model.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  1. /**
  2. * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /**
  6. * @module engine/model/model
  7. */
  8. import Batch from './batch';
  9. import Writer from './writer';
  10. import Schema from './schema';
  11. import Document from './document';
  12. import MarkerCollection from './markercollection';
  13. import ObservableMixin from '@ckeditor/ckeditor5-utils/src/observablemixin';
  14. import mix from '@ckeditor/ckeditor5-utils/src/mix';
  15. import ModelElement from './element';
  16. import ModelRange from './range';
  17. import ModelPosition from './position';
  18. import ModelSelection from './selection';
  19. import insertContent from './utils/insertcontent';
  20. import deleteContent from './utils/deletecontent';
  21. import modifySelection from './utils/modifyselection';
  22. import getSelectedContent from './utils/getselectedcontent';
  23. import { injectSelectionPostFixer } from './utils/selection-post-fixer';
  24. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  25. // @if CK_DEBUG_ENGINE // const { dumpTrees } = require( '../dev-utils/utils' );
  26. // @if CK_DEBUG_ENGINE // const { OperationReplayer } = require( '../dev-utils/operationreplayer' ).default;
  27. /**
  28. * Editor's data model. Read about the model in the
  29. * {@glink framework/guides/architecture/editing-engine engine architecture guide}.
  30. *
  31. * @mixes module:utils/observablemixin~ObservableMixin
  32. */
  33. export default class Model {
  34. constructor() {
  35. /**
  36. * Model's marker collection.
  37. *
  38. * @readonly
  39. * @member {module:engine/model/markercollection~MarkerCollection}
  40. */
  41. this.markers = new MarkerCollection();
  42. /**
  43. * Model's document.
  44. *
  45. * @readonly
  46. * @member {module:engine/model/document~Document}
  47. */
  48. this.document = new Document( this );
  49. /**
  50. * Model's schema.
  51. *
  52. * @readonly
  53. * @member {module:engine/model/schema~Schema}
  54. */
  55. this.schema = new Schema();
  56. /**
  57. * All callbacks added by {@link module:engine/model/model~Model#change} or
  58. * {@link module:engine/model/model~Model#enqueueChange} methods waiting to be executed.
  59. *
  60. * @private
  61. * @type {Array.<Function>}
  62. */
  63. this._pendingChanges = [];
  64. /**
  65. * The last created and currently used writer instance.
  66. *
  67. * @private
  68. * @member {module:engine/model/writer~Writer}
  69. */
  70. this._currentWriter = null;
  71. [ 'insertContent', 'deleteContent', 'modifySelection', 'getSelectedContent', 'applyOperation' ]
  72. .forEach( methodName => this.decorate( methodName ) );
  73. // Adding operation validation with `highest` priority, so it is called before any other feature would like
  74. // to do anything with the operation. If the operation has incorrect parameters it should throw on the earliest occasion.
  75. this.on( 'applyOperation', ( evt, args ) => {
  76. const operation = args[ 0 ];
  77. operation._validate();
  78. }, { priority: 'highest' } );
  79. // Register some default abstract entities.
  80. this.schema.register( '$root', {
  81. isLimit: true
  82. } );
  83. this.schema.register( '$block', {
  84. allowIn: '$root',
  85. isBlock: true
  86. } );
  87. this.schema.register( '$text', {
  88. allowIn: '$block',
  89. isInline: true
  90. } );
  91. this.schema.register( '$clipboardHolder', {
  92. allowContentOf: '$root',
  93. isLimit: true
  94. } );
  95. this.schema.extend( '$text', { allowIn: '$clipboardHolder' } );
  96. // An element needed by the `upcastElementToMarker` converter.
  97. // This element temporarily represents a marker boundary during the conversion process and is removed
  98. // at the end of the conversion. `UpcastDispatcher` or at least `Conversion` class looks like a
  99. // better place for this registration but both know nothing about `Schema`.
  100. this.schema.register( '$marker' );
  101. this.schema.addChildCheck( ( context, childDefinition ) => {
  102. if ( childDefinition.name === '$marker' ) {
  103. return true;
  104. }
  105. } );
  106. injectSelectionPostFixer( this );
  107. // @if CK_DEBUG_ENGINE // this.on( 'applyOperation', () => {
  108. // @if CK_DEBUG_ENGINE // dumpTrees( this.document, this.document.version );
  109. // @if CK_DEBUG_ENGINE // }, { priority: 'lowest' } );
  110. }
  111. /**
  112. * The `change()` method is the primary way of changing the model. You should use it to modify all document nodes
  113. * (including detached nodes – i.e. nodes not added to the {@link module:engine/model/model~Model#document model document}),
  114. * the {@link module:engine/model/document~Document#selection document's selection}, and
  115. * {@link module:engine/model/model~Model#markers model markers}.
  116. *
  117. * model.change( writer => {
  118. * writer.insertText( 'foo', paragraph, 'end' );
  119. * } );
  120. *
  121. * All changes inside the change block use the same {@link module:engine/model/batch~Batch} so they are combined
  122. * into a single undo step.
  123. *
  124. * model.change( writer => {
  125. * writer.insertText( 'foo', paragraph, 'end' ); // foo.
  126. *
  127. * model.change( writer => {
  128. * writer.insertText( 'bar', paragraph, 'end' ); // foobar.
  129. * } );
  130. *
  131. * writer.insertText( 'bom', paragraph, 'end' ); // foobarbom.
  132. * } );
  133. *
  134. * The callback of the `change()` block is executed synchronously.
  135. *
  136. * You can also return a value from the change block.
  137. *
  138. * const img = model.change( writer => {
  139. * return writer.createElement( 'img' );
  140. * } );
  141. *
  142. * @see #enqueueChange
  143. * @param {Function} callback Callback function which may modify the model.
  144. * @returns {*} Value returned by the callback.
  145. */
  146. change( callback ) {
  147. try {
  148. if ( this._pendingChanges.length === 0 ) {
  149. // If this is the outermost block, create a new batch and start `_runPendingChanges` execution flow.
  150. this._pendingChanges.push( { batch: new Batch(), callback } );
  151. return this._runPendingChanges()[ 0 ];
  152. } else {
  153. // If this is not the outermost block, just execute the callback.
  154. return callback( this._currentWriter );
  155. }
  156. } catch ( err ) {
  157. CKEditorError.rethrowUnexpectedError( err, this );
  158. }
  159. }
  160. /**
  161. * The `enqueueChange()` method performs similar task as the {@link #change `change()` method}, with two major differences.
  162. *
  163. * First, the callback of `enqueueChange()` is executed when all other enqueued changes are done. It might be executed
  164. * immediately if it is not nested in any other change block, but if it is nested in another (enqueue)change block,
  165. * it will be delayed and executed after the outermost block.
  166. *
  167. * model.change( writer => {
  168. * console.log( 1 );
  169. *
  170. * model.enqueueChange( writer => {
  171. * console.log( 2 );
  172. * } );
  173. *
  174. * console.log( 3 );
  175. * } ); // Will log: 1, 3, 2.
  176. *
  177. * Second, it lets you define the {@link module:engine/model/batch~Batch} into which you want to add your changes.
  178. * By default, a new batch is created. In the sample above, `change` and `enqueueChange` blocks use a different
  179. * batch (and different {@link module:engine/model/writer~Writer} since each of them operates on the separate batch).
  180. *
  181. * When using the `enqueueChange()` block you can also add some changes to the batch you used before.
  182. *
  183. * model.enqueueChange( batch, writer => {
  184. * writer.insertText( 'foo', paragraph, 'end' );
  185. * } );
  186. *
  187. * The batch instance can be obtained from {@link module:engine/model/writer~Writer#batch the writer}.
  188. *
  189. * @param {module:engine/model/batch~Batch|'transparent'|'default'} batchOrType Batch or batch type should be used in the callback.
  190. * If not defined, a new batch will be created.
  191. * @param {Function} callback Callback function which may modify the model.
  192. */
  193. enqueueChange( batchOrType, callback ) {
  194. try {
  195. if ( typeof batchOrType === 'string' ) {
  196. batchOrType = new Batch( batchOrType );
  197. } else if ( typeof batchOrType == 'function' ) {
  198. callback = batchOrType;
  199. batchOrType = new Batch();
  200. }
  201. this._pendingChanges.push( { batch: batchOrType, callback } );
  202. if ( this._pendingChanges.length == 1 ) {
  203. this._runPendingChanges();
  204. }
  205. } catch ( err ) {
  206. CKEditorError.rethrowUnexpectedError( err, this );
  207. }
  208. }
  209. /**
  210. * {@link module:utils/observablemixin~ObservableMixin#decorate Decorated} function for applying
  211. * {@link module:engine/model/operation/operation~Operation operations} to the model.
  212. *
  213. * This is a low-level way of changing the model. It is exposed for very specific use cases (like the undo feature).
  214. * Normally, to modify the model, you will want to use {@link module:engine/model/writer~Writer `Writer`}.
  215. * See also {@glink framework/guides/architecture/editing-engine#changing-the-model Changing the model} section
  216. * of the {@glink framework/guides/architecture/editing-engine Editing architecture} guide.
  217. *
  218. * @param {module:engine/model/operation/operation~Operation} operation The operation to apply.
  219. */
  220. applyOperation( operation ) {
  221. // @if CK_DEBUG_ENGINE // console.log( 'Applying ' + operation );
  222. // @if CK_DEBUG_ENGINE // if ( !this._operationLogs ) {
  223. // @if CK_DEBUG_ENGINE // this._operationLogs = [];
  224. // @if CK_DEBUG_ENGINE // }
  225. // @if CK_DEBUG_ENGINE // this._operationLogs.push( JSON.stringify( operation ) );
  226. // @if CK_DEBUG_ENGINE //if ( !this._appliedOperations ) {
  227. // @if CK_DEBUG_ENGINE // this._appliedOperations = [];
  228. // @if CK_DEBUG_ENGINE //}
  229. // @if CK_DEBUG_ENGINE //this._appliedOperations.push( operation );
  230. operation._execute();
  231. }
  232. // @if CK_DEBUG_ENGINE // getAppliedOperation() {
  233. // @if CK_DEBUG_ENGINE // if ( !this._appliedOperations ) {
  234. // @if CK_DEBUG_ENGINE // return '';
  235. // @if CK_DEBUG_ENGINE // }
  236. // @if CK_DEBUG_ENGINE // return this._appliedOperations.map( JSON.stringify ).join( '-------' );
  237. // @if CK_DEBUG_ENGINE // }
  238. // @if CK_DEBUG_ENGINE // createReplayer( stringifiedOperations ) {
  239. // @if CK_DEBUG_ENGINE // return new OperationReplayer( this, '-------', stringifiedOperations );
  240. // @if CK_DEBUG_ENGINE // }
  241. /**
  242. * Inserts content at the position in the editor specified by the selection, as one would expect the paste
  243. * functionality to work.
  244. *
  245. * This is a high-level method. It takes the {@link #schema schema} into consideration when inserting
  246. * the content, clears the given selection's content before inserting nodes and moves the selection
  247. * to its target position at the end of the process.
  248. * It can split elements, merge them, wrap bare text nodes with paragraphs, etc. &mdash; just like the
  249. * pasting feature should do.
  250. *
  251. * For lower-level methods see {@link module:engine/model/writer~Writer `Writer`}.
  252. *
  253. * This method, unlike {@link module:engine/model/writer~Writer `Writer`}'s methods, does not have to be used
  254. * inside a {@link #change `change()` block}.
  255. *
  256. * # Conversion and schema
  257. *
  258. * Inserting elements and text nodes into the model is not enough to make CKEditor 5 render that content
  259. * to the user. CKEditor 5 implements a model-view-controller architecture and what `model.insertContent()` does
  260. * is only adding nodes to the model. Additionally, you need to define
  261. * {@glink framework/guides/architecture/editing-engine#conversion converters} between the model and view
  262. * and define those nodes in the {@glink framework/guides/architecture/editing-engine#schema schema}.
  263. *
  264. * So, while this method may seem similar to CKEditor 4 `editor.insertHtml()` (in fact, both methods
  265. * are used for paste-like content insertion), the CKEditor 5 method cannot be use to insert arbitrary HTML
  266. * unless converters are defined for all elements and attributes in that HTML.
  267. *
  268. * # Examples
  269. *
  270. * Using `insertContent()` with a manually created model structure:
  271. *
  272. * // Let's create a document fragment containing such content as:
  273. * //
  274. * // <paragraph>foo</paragraph>
  275. * // <blockQuote>
  276. * // <paragraph>bar</paragraph>
  277. * // </blockQuote>
  278. * const docFrag = editor.model.change( writer => {
  279. * const p1 = writer.createElement( 'paragraph' );
  280. * const p2 = writer.createElement( 'paragraph' );
  281. * const blockQuote = writer.createElement( 'blockQuote' );
  282. * const docFrag = writer.createDocumentFragment();
  283. *
  284. * writer.append( p1, docFrag );
  285. * writer.append( blockQuote, docFrag );
  286. * writer.append( p2, blockQuote );
  287. * writer.insertText( 'foo', p1 );
  288. * writer.insertText( 'bar', p2 );
  289. *
  290. * return docFrag;
  291. * } );
  292. *
  293. * // insertContent() does not have to be used in a change() block. It can, though,
  294. * // so this code could be moved to the callback defined above.
  295. * editor.model.insertContent( docFrag );
  296. *
  297. * Using `insertContent()` with an HTML string converted to a model document fragment (similar to the pasting mechanism):
  298. *
  299. * // You can create your own HtmlDataProcessor instance or use editor.data.processor
  300. * // if you have not overridden the default one (which is the HtmlDataProcessor instance).
  301. * const htmlDP = new HtmlDataProcessor();
  302. *
  303. * // Convert an HTML string to a view document fragment:
  304. * const viewFragment = htmlDP.toView( htmlString );
  305. *
  306. * // Convert the view document fragment to a model document fragment
  307. * // in the context of $root. This conversion takes the schema into
  308. * // account so if, for example, the view document fragment contained a bare text node,
  309. * // this text node cannot be a child of $root, so it will be automatically
  310. * // wrapped with a <paragraph>. You can define the context yourself (in the second parameter),
  311. * // and e.g. convert the content like it would happen in a <paragraph>.
  312. * // Note: The clipboard feature uses a custom context called $clipboardHolder
  313. * // which has a loosened schema.
  314. * const modelFragment = editor.data.toModel( viewFragment );
  315. *
  316. * editor.model.insertContent( modelFragment );
  317. *
  318. * By default this method will use the document selection but it can also be used with a position, range or selection instance.
  319. *
  320. * // Insert text at the current document selection position.
  321. * editor.model.change( writer => {
  322. * editor.model.insertContent( writer.createText( 'x' ) );
  323. * } );
  324. *
  325. * // Insert text at a given position - the document selection will not be modified.
  326. * editor.model.change( writer => {
  327. * editor.model.insertContent( writer.createText( 'x' ), doc.getRoot(), 2 );
  328. *
  329. * // Which is a shorthand for:
  330. * editor.model.insertContent( writer.createText( 'x' ), writer.createPositionAt( doc.getRoot(), 2 ) );
  331. * } );
  332. *
  333. * If an instance of {@link module:engine/model/selection~Selection} is passed as `selectable`
  334. * it will be moved to the target position (where the document selection should be moved after the insertion).
  335. *
  336. * editor.model.change( writer => {
  337. * // Insert text replacing the given selection instance.
  338. * const selection = writer.createSelection( paragraph, 'in' );
  339. *
  340. * editor.model.insertContent( writer.createText( 'x' ), selection );
  341. *
  342. * // insertContent() modifies the passed selection instance so it can be used to set the document selection.
  343. * // Note: This is not necessary when you passed the document selection to insertContent().
  344. * writer.setSelection( selection );
  345. * } );
  346. *
  347. * @fires insertContent
  348. * @param {module:engine/model/documentfragment~DocumentFragment|module:engine/model/item~Item} content The content to insert.
  349. * @param {module:engine/model/selection~Selectable} [selectable=model.document.selection]
  350. * The selection into which the content should be inserted. If not provided the current model document selection will be used.
  351. * @param {Number|'before'|'end'|'after'|'on'|'in'} [placeOrOffset] To be used when a model item was passed as `selectable`.
  352. * This param defines a position in relation to that item.
  353. * @returns {module:engine/model/range~Range} Range which contains all the performed changes. This is a range that, if removed,
  354. * would return the model to the state before the insertion. If no changes were preformed by `insertContent`, returns a range collapsed
  355. * at the insertion position.
  356. */
  357. insertContent( content, selectable, placeOrOffset ) {
  358. return insertContent( this, content, selectable, placeOrOffset );
  359. }
  360. /**
  361. * Deletes content of the selection and merge siblings. The resulting selection is always collapsed.
  362. *
  363. * **Note:** For the sake of predictability, the resulting selection should always be collapsed.
  364. * In cases where a feature wants to modify deleting behavior so selection isn't collapsed
  365. * (e.g. a table feature may want to keep row selection after pressing <kbd>Backspace</kbd>),
  366. * then that behavior should be implemented in the view's listener. At the same time, the table feature
  367. * will need to modify this method's behavior too, e.g. to "delete contents and then collapse
  368. * the selection inside the last selected cell" or "delete the row and collapse selection somewhere near".
  369. * That needs to be done in order to ensure that other features which use `deleteContent()` will work well with tables.
  370. *
  371. * @fires deleteContent
  372. * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection} selection
  373. * Selection of which the content should be deleted.
  374. * @param {Object} [options]
  375. * @param {Boolean} [options.leaveUnmerged=false] Whether to merge elements after removing the content of the selection.
  376. *
  377. * For example `<heading1>x[x</heading1><paragraph>y]y</paragraph>` will become:
  378. *
  379. * * `<heading1>x^y</heading1>` with the option disabled (`leaveUnmerged == false`)
  380. * * `<heading1>x^</heading1><paragraph>y</paragraph>` with enabled (`leaveUnmerged == true`).
  381. *
  382. * Note: {@link module:engine/model/schema~Schema#isObject object} and {@link module:engine/model/schema~Schema#isLimit limit}
  383. * elements will not be merged.
  384. *
  385. * @param {Boolean} [options.doNotResetEntireContent=false] Whether to skip replacing the entire content with a
  386. * paragraph when the entire content was selected.
  387. *
  388. * For example `<heading1>[x</heading1><paragraph>y]</paragraph>` will become:
  389. *
  390. * * `<paragraph>^</paragraph>` with the option disabled (`doNotResetEntireContent == false`)
  391. * * `<heading1>^</heading1>` with enabled (`doNotResetEntireContent == true`)
  392. *
  393. * @param {Boolean} [options.doNotAutoparagraph=false] Whether to create a paragraph if after content deletion selection is moved
  394. * to a place where text cannot be inserted.
  395. *
  396. * For example `<paragraph>x</paragraph>[<image src="foo.jpg"></image>]` will become:
  397. *
  398. * * `<paragraph>x</paragraph><paragraph>[]</paragraph>` with the option disabled (`doNotAutoparagraph == false`)
  399. * * `<paragraph>x[]</paragraph>` with the option enabled (`doNotAutoparagraph == true`).
  400. *
  401. * **Note:** if there is no valid position for the selection, the paragraph will always be created:
  402. *
  403. * `[<image src="foo.jpg"></image>]` -> `<paragraph>[]</paragraph>`.
  404. */
  405. deleteContent( selection, options ) {
  406. deleteContent( this, selection, options );
  407. }
  408. /**
  409. * Modifies the selection. Currently, the supported modifications are:
  410. *
  411. * * Extending. The selection focus is moved in the specified `options.direction` with a step specified in `options.unit`.
  412. * Possible values for `unit` are:
  413. * * `'character'` (default) - moves selection by one user-perceived character. In most cases this means moving by one
  414. * character in `String` sense. However, unicode also defines "combing marks". These are special symbols, that combines
  415. * with a symbol before it ("base character") to create one user-perceived character. For example, `q̣̇` is a normal
  416. * letter `q` with two "combining marks": upper dot (`Ux0307`) and lower dot (`Ux0323`). For most actions, i.e. extending
  417. * selection by one position, it is correct to include both "base character" and all of it's "combining marks". That is
  418. * why `'character'` value is most natural and common method of modifying selection.
  419. * * `'codePoint'` - moves selection by one unicode code point. In contrary to, `'character'` unit, this will insert
  420. * selection between "base character" and "combining mark", because "combining marks" have their own unicode code points.
  421. * However, for technical reasons, unicode code points with values above `UxFFFF` are represented in native `String` by
  422. * two characters, called "surrogate pairs". Halves of "surrogate pairs" have a meaning only when placed next to each other.
  423. * For example `𨭎` is represented in `String` by `\uD862\uDF4E`. Both `\uD862` and `\uDF4E` do not have any meaning
  424. * outside the pair (are rendered as ? when alone). Position between them would be incorrect. In this case, selection
  425. * extension will include whole "surrogate pair".
  426. * * `'word'` - moves selection by a whole word.
  427. *
  428. * **Note:** if you extend a forward selection in a backward direction you will in fact shrink it.
  429. *
  430. * @fires modifySelection
  431. * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection} selection
  432. * The selection to modify.
  433. * @param {Object} [options]
  434. * @param {'forward'|'backward'} [options.direction='forward'] The direction in which the selection should be modified.
  435. * @param {'character'|'codePoint'|'word'} [options.unit='character'] The unit by which selection should be modified.
  436. */
  437. modifySelection( selection, options ) {
  438. modifySelection( this, selection, options );
  439. }
  440. /**
  441. * Gets a clone of the selected content.
  442. *
  443. * For example, for the following selection:
  444. *
  445. * ```html
  446. * <paragraph>x</paragraph>
  447. * <blockQuote>
  448. * <paragraph>y</paragraph>
  449. * <heading1>fir[st</heading1>
  450. * </blockQuote>
  451. * <paragraph>se]cond</paragraph>
  452. * <paragraph>z</paragraph>
  453. * ```
  454. *
  455. * It will return a document fragment with such a content:
  456. *
  457. * ```html
  458. * <blockQuote>
  459. * <heading1>st</heading1>
  460. * </blockQuote>
  461. * <paragraph>se</paragraph>
  462. * ```
  463. *
  464. * @fires getSelectedContent
  465. * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection} selection
  466. * The selection of which content will be returned.
  467. * @returns {module:engine/model/documentfragment~DocumentFragment}
  468. */
  469. getSelectedContent( selection ) {
  470. return getSelectedContent( this, selection );
  471. }
  472. /**
  473. * Checks whether the given {@link module:engine/model/range~Range range} or
  474. * {@link module:engine/model/element~Element element} has any meaningful content.
  475. *
  476. * Meaningful content is:
  477. *
  478. * * any text node (`options.ignoreWhitespaces` allows controlling whether this text node must also contain
  479. * any non-whitespace characters),
  480. * * or any {@link module:engine/model/schema~Schema#isObject object element},
  481. * * or any {@link module:engine/model/markercollection~Marker marker} which
  482. * {@link module:engine/model/markercollection~Marker#_affectsData affects data}.
  483. *
  484. * This means that a range containing an empty `<paragraph></paragraph>` is not considered to have a meaningful content.
  485. * However, a range containing an `<image></image>` (which would normally be marked in the schema as an object element)
  486. * is considered non-empty.
  487. *
  488. * @param {module:engine/model/range~Range|module:engine/model/element~Element} rangeOrElement Range or element to check.
  489. * @param {Object} [options]
  490. * @param {Boolean} [options.ignoreWhitespaces] Whether text node with whitespaces only should be considered empty.
  491. * @returns {Boolean}
  492. */
  493. hasContent( rangeOrElement, options ) {
  494. const range = rangeOrElement instanceof ModelElement ? ModelRange._createIn( rangeOrElement ) : rangeOrElement;
  495. if ( range.isCollapsed ) {
  496. return false;
  497. }
  498. // Check if there are any markers which affects data in this given range.
  499. for ( const intersectingMarker of this.markers.getMarkersIntersectingRange( range ) ) {
  500. if ( intersectingMarker.affectsData ) {
  501. return true;
  502. }
  503. }
  504. const { ignoreWhitespaces = false } = options || {};
  505. for ( const item of range.getItems() ) {
  506. if ( item.is( 'textProxy' ) ) {
  507. if ( !ignoreWhitespaces ) {
  508. return true;
  509. } else if ( item.data.search( /\S/ ) !== -1 ) {
  510. return true;
  511. }
  512. } else if ( this.schema.isObject( item ) ) {
  513. return true;
  514. }
  515. }
  516. return false;
  517. }
  518. /**
  519. * Creates a position from the given root and path in that root.
  520. *
  521. * Note: This method is also available as
  522. * {@link module:engine/model/writer~Writer#createPositionFromPath `Writer#createPositionFromPath()`}.
  523. *
  524. * @param {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment} root Root of the position.
  525. * @param {Array.<Number>} path Position path. See {@link module:engine/model/position~Position#path}.
  526. * @param {module:engine/model/position~PositionStickiness} [stickiness='toNone'] Position stickiness.
  527. * See {@link module:engine/model/position~PositionStickiness}.
  528. * @returns {module:engine/model/position~Position}
  529. */
  530. createPositionFromPath( root, path, stickiness ) {
  531. return new ModelPosition( root, path, stickiness );
  532. }
  533. /**
  534. * Creates position at the given location. The location can be specified as:
  535. *
  536. * * a {@link module:engine/model/position~Position position},
  537. * * a parent element and offset in that element,
  538. * * a parent element and `'end'` (the position will be set at the end of that element),
  539. * * a {@link module:engine/model/item~Item model item} and `'before'` or `'after'`
  540. * (the position will be set before or after the given model item).
  541. *
  542. * This method is a shortcut to other factory methods such as:
  543. *
  544. * * {@link module:engine/model/model~Model#createPositionBefore `createPositionBefore()`},
  545. * * {@link module:engine/model/model~Model#createPositionAfter `createPositionAfter()`}.
  546. *
  547. * Note: This method is also available as
  548. * {@link module:engine/model/writer~Writer#createPositionAt `Writer#createPositionAt()`},
  549. *
  550. * @param {module:engine/model/item~Item|module:engine/model/position~Position} itemOrPosition
  551. * @param {Number|'end'|'before'|'after'} [offset] Offset or one of the flags. Used only when
  552. * first parameter is a {@link module:engine/model/item~Item model item}.
  553. */
  554. createPositionAt( itemOrPosition, offset ) {
  555. return ModelPosition._createAt( itemOrPosition, offset );
  556. }
  557. /**
  558. * Creates a new position after the given {@link module:engine/model/item~Item model item}.
  559. *
  560. * Note: This method is also available as
  561. * {@link module:engine/model/writer~Writer#createPositionAfter `Writer#createPositionAfter()`}.
  562. *
  563. * @param {module:engine/model/item~Item} item Item after which the position should be placed.
  564. * @returns {module:engine/model/position~Position}
  565. */
  566. createPositionAfter( item ) {
  567. return ModelPosition._createAfter( item );
  568. }
  569. /**
  570. * Creates a new position before the given {@link module:engine/model/item~Item model item}.
  571. *
  572. * Note: This method is also available as
  573. * {@link module:engine/model/writer~Writer#createPositionBefore `Writer#createPositionBefore()`}.
  574. *
  575. * @param {module:engine/model/item~Item} item Item before which the position should be placed.
  576. * @returns {module:engine/model/position~Position}
  577. */
  578. createPositionBefore( item ) {
  579. return ModelPosition._createBefore( item );
  580. }
  581. /**
  582. * Creates a range spanning from the `start` position to the `end` position.
  583. *
  584. * Note: This method is also available as
  585. * {@link module:engine/model/writer~Writer#createRange `Writer#createRange()`}:
  586. *
  587. * model.change( writer => {
  588. * const range = writer.createRange( start, end );
  589. * } );
  590. *
  591. * @param {module:engine/model/position~Position} start Start position.
  592. * @param {module:engine/model/position~Position} [end] End position. If not set, the range will be collapsed
  593. * to the `start` position.
  594. * @returns {module:engine/model/range~Range}
  595. */
  596. createRange( start, end ) {
  597. return new ModelRange( start, end );
  598. }
  599. /**
  600. * Creates a range inside the given element which starts before the first child of
  601. * that element and ends after the last child of that element.
  602. *
  603. * Note: This method is also available as
  604. * {@link module:engine/model/writer~Writer#createRangeIn `Writer#createRangeIn()`}:
  605. *
  606. * model.change( writer => {
  607. * const range = writer.createRangeIn( paragraph );
  608. * } );
  609. *
  610. * @param {module:engine/model/element~Element} element Element which is a parent for the range.
  611. * @returns {module:engine/model/range~Range}
  612. */
  613. createRangeIn( element ) {
  614. return ModelRange._createIn( element );
  615. }
  616. /**
  617. * Creates a range that starts before the given {@link module:engine/model/item~Item model item} and ends after it.
  618. *
  619. * Note: This method is also available on `writer` instance as
  620. * {@link module:engine/model/writer~Writer#createRangeOn `Writer.createRangeOn()`}:
  621. *
  622. * model.change( writer => {
  623. * const range = writer.createRangeOn( paragraph );
  624. * } );
  625. *
  626. * @param {module:engine/model/item~Item} item
  627. * @returns {module:engine/model/range~Range}
  628. */
  629. createRangeOn( item ) {
  630. return ModelRange._createOn( item );
  631. }
  632. /**
  633. * Creates a new selection instance based on the given {@link module:engine/model/selection~Selectable selectable}
  634. * or creates an empty selection if no arguments were passed.
  635. *
  636. * Note: This method is also available as
  637. * {@link module:engine/model/writer~Writer#createSelection `Writer#createSelection()`}.
  638. *
  639. * // Creates empty selection without ranges.
  640. * const selection = writer.createSelection();
  641. *
  642. * // Creates selection at the given range.
  643. * const range = writer.createRange( start, end );
  644. * const selection = writer.createSelection( range );
  645. *
  646. * // Creates selection at the given ranges
  647. * const ranges = [ writer.createRange( start1, end2 ), writer.createRange( star2, end2 ) ];
  648. * const selection = writer.createSelection( ranges );
  649. *
  650. * // Creates selection from the other selection.
  651. * // Note: It doesn't copies selection attributes.
  652. * const otherSelection = writer.createSelection();
  653. * const selection = writer.createSelection( otherSelection );
  654. *
  655. * // Creates selection from the given document selection.
  656. * // Note: It doesn't copies selection attributes.
  657. * const documentSelection = model.document.selection;
  658. * const selection = writer.createSelection( documentSelection );
  659. *
  660. * // Creates selection at the given position.
  661. * const position = writer.createPositionFromPath( root, path );
  662. * const selection = writer.createSelection( position );
  663. *
  664. * // Creates selection at the given offset in the given element.
  665. * const paragraph = writer.createElement( 'paragraph' );
  666. * const selection = writer.createSelection( paragraph, offset );
  667. *
  668. * // Creates a range inside an {@link module:engine/model/element~Element element} which starts before the
  669. * // first child of that element and ends after the last child of that element.
  670. * const selection = writer.createSelection( paragraph, 'in' );
  671. *
  672. * // Creates a range on an {@link module:engine/model/item~Item item} which starts before the item and ends
  673. * // just after the item.
  674. * const selection = writer.createSelection( paragraph, 'on' );
  675. *
  676. * // Additional options (`'backward'`) can be specified as the last argument.
  677. *
  678. * // Creates backward selection.
  679. * const selection = writer.createSelection( range, { backward: true } );
  680. *
  681. * @param {module:engine/model/selection~Selectable} selectable
  682. * @param {Number|'before'|'end'|'after'|'on'|'in'} [placeOrOffset] Sets place or offset of the selection.
  683. * @param {Object} [options]
  684. * @param {Boolean} [options.backward] Sets this selection instance to be backward.
  685. * @returns {module:engine/model/selection~Selection}
  686. */
  687. createSelection( selectable, placeOrOffset, options ) {
  688. return new ModelSelection( selectable, placeOrOffset, options );
  689. }
  690. /**
  691. * Creates a {@link module:engine/model/batch~Batch} instance.
  692. *
  693. * **Note:** In most cases creating a batch instance is not necessary as they are created when using:
  694. *
  695. * * {@link #change `change()`},
  696. * * {@link #enqueueChange `enqueueChange()`}.
  697. *
  698. * @param {'transparent'|'default'} [type='default'] The type of the batch.
  699. * @returns {module:engine/model/batch~Batch}
  700. */
  701. createBatch( type ) {
  702. return new Batch( type );
  703. }
  704. /**
  705. * Removes all events listeners set by model instance and destroys {@link module:engine/model/document~Document}.
  706. */
  707. destroy() {
  708. this.document.destroy();
  709. this.stopListening();
  710. }
  711. /**
  712. * Common part of {@link module:engine/model/model~Model#change} and {@link module:engine/model/model~Model#enqueueChange}
  713. * which calls callbacks and returns array of values returned by these callbacks.
  714. *
  715. * @private
  716. * @returns {Array.<*>} Array of values returned by callbacks.
  717. */
  718. _runPendingChanges() {
  719. const ret = [];
  720. this.fire( '_beforeChanges' );
  721. while ( this._pendingChanges.length ) {
  722. // Create a new writer using batch instance created for this chain of changes.
  723. const currentBatch = this._pendingChanges[ 0 ].batch;
  724. this._currentWriter = new Writer( this, currentBatch );
  725. // Execute changes callback and gather the returned value.
  726. const callbackReturnValue = this._pendingChanges[ 0 ].callback( this._currentWriter );
  727. ret.push( callbackReturnValue );
  728. this.document._handleChangeBlock( this._currentWriter );
  729. this._pendingChanges.shift();
  730. this._currentWriter = null;
  731. }
  732. this.fire( '_afterChanges' );
  733. return ret;
  734. }
  735. /**
  736. * Fired when entering the outermost {@link module:engine/model/model~Model#enqueueChange} or
  737. * {@link module:engine/model/model~Model#change} block.
  738. *
  739. * @protected
  740. * @event _beforeChanges
  741. */
  742. /**
  743. * Fired when leaving the outermost {@link module:engine/model/model~Model#enqueueChange} or
  744. * {@link module:engine/model/model~Model#change} block.
  745. *
  746. * @protected
  747. * @event _afterChanges
  748. */
  749. /**
  750. * Fired every time any {@link module:engine/model/operation/operation~Operation operation} is applied on the model
  751. * using {@link #applyOperation}.
  752. *
  753. * Note that this event is suitable only for very specific use-cases. Use it if you need to listen to every single operation
  754. * applied on the document. However, in most cases {@link module:engine/model/document~Document#event:change} should
  755. * be used.
  756. *
  757. * A few callbacks are already added to this event by engine internal classes:
  758. *
  759. * * with `highest` priority operation is validated,
  760. * * with `normal` priority operation is executed,
  761. * * with `low` priority the {@link module:engine/model/document~Document} updates its version,
  762. * * with `low` priority {@link module:engine/model/liveposition~LivePosition} and {@link module:engine/model/liverange~LiveRange}
  763. * update themselves.
  764. *
  765. * @event applyOperation
  766. * @param {Array} args Arguments of the `applyOperation` which is an array with a single element - applied
  767. * {@link module:engine/model/operation/operation~Operation operation}.
  768. */
  769. /**
  770. * Event fired when {@link #insertContent} method is called.
  771. *
  772. * The {@link #insertContent default action of that method} is implemented as a
  773. * listener to this event so it can be fully customized by the features.
  774. *
  775. * **Note** The `selectable` parameter for the {@link #insertContent} is optional. When `undefined` value is passed the method uses
  776. * `model.document.selection`.
  777. *
  778. * @event insertContent
  779. * @param {Array} args The arguments passed to the original method.
  780. */
  781. /**
  782. * Event fired when {@link #deleteContent} method is called.
  783. *
  784. * The {@link #deleteContent default action of that method} is implemented as a
  785. * listener to this event so it can be fully customized by the features.
  786. *
  787. * @event deleteContent
  788. * @param {Array} args The arguments passed to the original method.
  789. */
  790. /**
  791. * Event fired when {@link #modifySelection} method is called.
  792. *
  793. * The {@link #modifySelection default action of that method} is implemented as a
  794. * listener to this event so it can be fully customized by the features.
  795. *
  796. * @event modifySelection
  797. * @param {Array} args The arguments passed to the original method.
  798. */
  799. /**
  800. * Event fired when {@link #getSelectedContent} method is called.
  801. *
  802. * The {@link #getSelectedContent default action of that method} is implemented as a
  803. * listener to this event so it can be fully customized by the features.
  804. *
  805. * @event getSelectedContent
  806. * @param {Array} args The arguments passed to the original method.
  807. */
  808. }
  809. mix( Model, ObservableMixin );