model.js 33 KB

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