8
0

model.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/model/model
  7. */
  8. // Load all basic deltas and transformations, they register themselves.
  9. import './delta/basic-deltas';
  10. import './delta/basic-transformations';
  11. import Batch from './batch';
  12. import Writer from './writer';
  13. import Schema from './schema';
  14. import Document from './document';
  15. import MarkerCollection from './markercollection';
  16. import ObservableMixin from '@ckeditor/ckeditor5-utils/src/observablemixin';
  17. import mix from '@ckeditor/ckeditor5-utils/src/mix';
  18. import deltaTransform from './delta/transform';
  19. import ModelElement from './element';
  20. import ModelRange from './range';
  21. import insertContent from './utils/insertcontent';
  22. import deleteContent from './utils/deletecontent';
  23. import modifySelection from './utils/modifyselection';
  24. import getSelectedContent from './utils/getselectedcontent';
  25. /**
  26. * Editor's data model class. Model defines all the data: both nodes that are attached to the roots of the
  27. * {@link module:engine/model/model~Model#document model document}, and also all detached nodes which has not been yet
  28. * added to the document.
  29. *
  30. * All those nodes are created and modified by the {@link module:engine/model/writer~Writer model writer}, which can be
  31. * accessed by using {@link module:engine/model/model~Model#change} or {@link module:engine/model/model~Model#enqueueChange} methods.
  32. *
  33. * @mixes module:utils/observablemixin~ObservableMixin
  34. */
  35. export default class Model {
  36. constructor() {
  37. /**
  38. * Models markers' collection.
  39. *
  40. * @readonly
  41. * @member {module:engine/model/markercollection~MarkerCollection}
  42. */
  43. this.markers = new MarkerCollection();
  44. /**
  45. * Editors document model.
  46. *
  47. * @readonly
  48. * @member {module:engine/model/document~Document}
  49. */
  50. this.document = new Document( this );
  51. /**
  52. * Schema for editors model.
  53. *
  54. * @readonly
  55. * @member {module:engine/model/schema~Schema}
  56. */
  57. this.schema = new Schema();
  58. /**
  59. * All callbacks added by {@link module:engine/model/model~Model#change} or
  60. * {@link module:engine/model/model~Model#enqueueChange} methods waiting to be executed.
  61. *
  62. * @private
  63. * @type {Array.<Function>}
  64. */
  65. this._pendingChanges = [];
  66. /**
  67. * The last created and currently used writer instance.
  68. *
  69. * @private
  70. * @member {module:engine/model/writer~Writer}
  71. */
  72. this._currentWriter = null;
  73. [ 'insertContent', 'deleteContent', 'modifySelection', 'getSelectedContent', 'applyOperation' ]
  74. .forEach( methodName => this.decorate( methodName ) );
  75. // Adding operation validation with `highest` priority, so it is called before any other feature would like
  76. // to do anything with the operation. If the operation has incorrect parameters it should throw on the earliest occasion.
  77. this.on( 'applyOperation', ( evt, args ) => {
  78. const operation = args[ 0 ];
  79. operation._validate();
  80. }, { priority: 'highest' } );
  81. // Register some default abstract entities.
  82. this.schema.register( '$root', {
  83. isLimit: true
  84. } );
  85. this.schema.register( '$block', {
  86. allowIn: '$root',
  87. isBlock: true
  88. } );
  89. this.schema.register( '$text', {
  90. allowIn: '$block'
  91. } );
  92. this.schema.register( '$clipboardHolder', {
  93. allowContentOf: '$root',
  94. isLimit: true
  95. } );
  96. this.schema.extend( '$text', { allowIn: '$clipboardHolder' } );
  97. // Element needed by `upcastElementToMarker` converter.
  98. // This element temporarily represents marker bound during conversion process and is removed
  99. // at the end of conversion. `UpcastDispatcher` or at least `Conversion` class looks like a better for this
  100. // registration but both know nothing about Schema.
  101. this.schema.register( '$marker', {
  102. allowIn: [ '$root', '$block' ]
  103. } );
  104. }
  105. /**
  106. * Change method is the primary way of changing the model. You should use it to modify any node, including detached
  107. * nodes (not added to the {@link module:engine/model/model~Model#document model document}).
  108. *
  109. * model.change( writer => {
  110. * writer.insertText( 'foo', paragraph, 'end' );
  111. * } );
  112. *
  113. * All changes inside the change block use the same {@link module:engine/model/batch~Batch} so they share the same
  114. * undo step.
  115. *
  116. * model.change( writer => {
  117. * writer.insertText( 'foo', paragraph, 'end' ); // foo.
  118. *
  119. * model.change( writer => {
  120. * writer.insertText( 'bar', paragraph, 'end' ); // foobar.
  121. * } );
  122. *
  123. * writer.insertText( 'bom', paragraph, 'end' ); // foobarbom.
  124. * } );
  125. *
  126. * Change block is executed immediately.
  127. *
  128. * You can also return a value from the change block.
  129. *
  130. * const img = model.change( writer => {
  131. * return writer.createElement( 'img' );
  132. * } );
  133. *
  134. * When the outermost block is done the {@link #event:_change} event is fired.
  135. *
  136. * @see #enqueueChange
  137. * @param {Function} callback Callback function which may modify the model.
  138. * @returns {*} Value returned by the callback.
  139. */
  140. change( callback ) {
  141. if ( this._pendingChanges.length === 0 ) {
  142. // If this is the outermost block, create a new batch and start `_runPendingChanges` execution flow.
  143. this._pendingChanges.push( { batch: new Batch(), callback } );
  144. return this._runPendingChanges()[ 0 ];
  145. } else {
  146. // If this is not the outermost block, just execute the callback.
  147. return callback( this._currentWriter );
  148. }
  149. }
  150. /**
  151. * `enqueueChange` method performs similar task as the {@link #change change method}, with two major differences.
  152. *
  153. * First, the callback of the `enqueueChange` is executed when all other changes are done. It might be executed
  154. * immediately if it is not nested in any other change block, but if it is nested in another (enqueue)change block,
  155. * it will be delayed and executed after the outermost block.
  156. *
  157. * model.change( writer => {
  158. * console.log( 1 );
  159. *
  160. * model.enqueueChange( writer => {
  161. * console.log( 2 );
  162. * } );
  163. *
  164. * console.log( 3 );
  165. * } ); // Will log: 1, 3, 2.
  166. *
  167. * Second, it lets you define the {@link module:engine/model/batch~Batch} into which you want to add your changes.
  168. * By default, a new batch is created. In the sample above, `change` and `enqueueChange` blocks use a different
  169. * batch (and different {@link module:engine/model/writer~Writer} since each of them operates on the separate batch).
  170. *
  171. * Using `enqueueChange` block you can also add some changes to the batch you used before.
  172. *
  173. * model.enqueueChange( batch, writer => {
  174. * writer.insertText( 'foo', paragraph, 'end' );
  175. * } );
  176. *
  177. * `Batch` instance can be obtained from {@link module:engine/model/writer~Writer#batch the writer}.
  178. *
  179. * @param {module:engine/model/batch~Batch|String} batchOrType Batch or batch type should be used in the callback.
  180. * If not defined, a new batch will be created.
  181. * @param {Function} callback Callback function which may modify the model.
  182. */
  183. enqueueChange( batchOrType, callback ) {
  184. if ( typeof batchOrType === 'string' ) {
  185. batchOrType = new Batch( batchOrType );
  186. } else if ( typeof batchOrType == 'function' ) {
  187. callback = batchOrType;
  188. batchOrType = new Batch();
  189. }
  190. this._pendingChanges.push( { batch: batchOrType, callback } );
  191. if ( this._pendingChanges.length == 1 ) {
  192. this._runPendingChanges();
  193. }
  194. }
  195. /**
  196. * Common part of {@link module:engine/model/model~Model#change} and {@link module:engine/model/model~Model#enqueueChange}
  197. * which calls callbacks and returns array of values returned by these callbacks.
  198. *
  199. * @private
  200. * @returns {Array.<*>} Array of values returned by callbacks.
  201. */
  202. _runPendingChanges() {
  203. const ret = [];
  204. while ( this._pendingChanges.length ) {
  205. // Create a new writer using batch instance created for this chain of changes.
  206. const currentBatch = this._pendingChanges[ 0 ].batch;
  207. this._currentWriter = new Writer( this, currentBatch );
  208. // Execute changes callback and gather the returned value.
  209. const callbackReturnValue = this._pendingChanges[ 0 ].callback( this._currentWriter );
  210. ret.push( callbackReturnValue );
  211. // Fire internal `_change` event.
  212. this.fire( '_change', this._currentWriter );
  213. this._pendingChanges.shift();
  214. this._currentWriter = null;
  215. }
  216. return ret;
  217. }
  218. /**
  219. * {@link module:utils/observablemixin~ObservableMixin#decorate Decorated} function to apply
  220. * {@link module:engine/model/operation/operation~Operation operations} on the model.
  221. *
  222. * @param {module:engine/model/operation/operation~Operation} operation Operation to apply
  223. */
  224. applyOperation( operation ) {
  225. operation._execute();
  226. }
  227. /**
  228. * Transforms two sets of deltas by themselves. Returns both transformed sets.
  229. *
  230. * @param {Array.<module:engine/model/delta/delta~Delta>} deltasA Array with the first set of deltas to transform. These
  231. * deltas are considered more important (than `deltasB`) when resolving conflicts.
  232. * @param {Array.<module:engine/model/delta/delta~Delta>} deltasB Array with the second set of deltas to transform. These
  233. * deltas are considered less important (than `deltasA`) when resolving conflicts.
  234. * @param {Boolean} [useContext=false] When set to `true`, transformation will store and use additional context
  235. * information to guarantee more expected results. Should be used whenever deltas related to already applied
  236. * deltas are transformed (for example when undoing changes).
  237. * @returns {Object}
  238. * @returns {Array.<module:engine/model/delta/delta~Delta>} return.deltasA The first set of deltas transformed
  239. * by the second set of deltas.
  240. * @returns {Array.<module:engine/model/delta/delta~Delta>} return.deltasB The second set of deltas transformed
  241. * by the first set of deltas.
  242. */
  243. transformDeltas( deltasA, deltasB, useContext = false ) {
  244. return deltaTransform.transformDeltaSets( deltasA, deltasB, useContext ? this.document : null );
  245. }
  246. /**
  247. * See {@link module:engine/model/utils/insertcontent~insertContent}.
  248. *
  249. * @fires insertContent
  250. * @param {module:engine/model/documentfragment~DocumentFragment|module:engine/model/item~Item} content The content to insert.
  251. * @param {module:engine/model/selection~Selection} selection Selection into which the content should be inserted.
  252. */
  253. insertContent( content, selection ) {
  254. insertContent( this, content, selection );
  255. }
  256. /**
  257. * See {@link module:engine/model/utils/deletecontent.deleteContent}.
  258. *
  259. * Note: For the sake of predictability, the resulting selection should always be collapsed.
  260. * In cases where a feature wants to modify deleting behavior so selection isn't collapsed
  261. * (e.g. a table feature may want to keep row selection after pressing <kbd>Backspace</kbd>),
  262. * then that behavior should be implemented in the view's listener. At the same time, the table feature
  263. * will need to modify this method's behavior too, e.g. to "delete contents and then collapse
  264. * the selection inside the last selected cell" or "delete the row and collapse selection somewhere near".
  265. * That needs to be done in order to ensure that other features which use `deleteContent()` will work well with tables.
  266. *
  267. * @fires deleteContent
  268. * @param {module:engine/model/selection~Selection} selection Selection of which the content should be deleted.
  269. * @param {Object} options See {@link module:engine/model/utils/deletecontent~deleteContent}'s options.
  270. */
  271. deleteContent( selection, options ) {
  272. deleteContent( this, selection, options );
  273. }
  274. /**
  275. * See {@link module:engine/model/utils/modifyselection~modifySelection}.
  276. *
  277. * @fires modifySelection
  278. * @param {module:engine/model/selection~Selection} selection The selection to modify.
  279. * @param {Object} options See {@link module:engine/model/utils/modifyselection.modifySelection}'s options.
  280. */
  281. modifySelection( selection, options ) {
  282. modifySelection( this, selection, options );
  283. }
  284. /**
  285. * See {@link module:engine/model/utils/getselectedcontent~getSelectedContent}.
  286. *
  287. * @fires getSelectedContent
  288. * @param {module:engine/model/selection~Selection} selection The selection of which content will be retrieved.
  289. * @returns {module:engine/model/documentfragment~DocumentFragment} Document fragment holding the clone of the selected content.
  290. */
  291. getSelectedContent( selection ) {
  292. return getSelectedContent( this, selection );
  293. }
  294. /**
  295. * Checks whether given {@link module:engine/model/range~Range range} or {@link module:engine/model/element~Element element}
  296. * has any content.
  297. *
  298. * Content is any text node or element which is registered in {@link module:engine/model/schema~Schema schema}.
  299. *
  300. * @param {module:engine/model/range~Range|module:engine/model/element~Element} rangeOrElement Range or element to check.
  301. * @returns {Boolean}
  302. */
  303. hasContent( rangeOrElement ) {
  304. if ( rangeOrElement instanceof ModelElement ) {
  305. rangeOrElement = ModelRange.createIn( rangeOrElement );
  306. }
  307. if ( rangeOrElement.isCollapsed ) {
  308. return false;
  309. }
  310. for ( const item of rangeOrElement.getItems() ) {
  311. // Remember, `TreeWalker` returns always `textProxy` nodes.
  312. if ( item.is( 'textProxy' ) || this.schema.isObject( item ) ) {
  313. return true;
  314. }
  315. }
  316. return false;
  317. }
  318. /**
  319. * Removes all events listeners set by model instance and destroys {@link module:engine/model/document~Document}.
  320. */
  321. destroy() {
  322. this.document.destroy();
  323. this.stopListening();
  324. }
  325. /**
  326. * Fired after leaving each {@link module:engine/model/model~Model#enqueueChange} block or outermost
  327. * {@link module:engine/model/model~Model#change} block.
  328. *
  329. * **Note:** This is an internal event! Use {@link module:engine/model/document~Document#event:change} instead.
  330. *
  331. * @protected
  332. * @event _change
  333. * @param {module:engine/model/writer~Writer} writer `Writer` instance that has been used in the change block.
  334. */
  335. /**
  336. * Fired every time any {@link module:engine/model/operation/operation~Operation operation} is applied on the model
  337. * using {@link #applyOperation}.
  338. *
  339. * Note that this event is suitable only for very specific use-cases. Use it if you need to listen to every single operation
  340. * applied on the document. However, in most cases {@link module:engine/model/document~Document#event:change} should
  341. * be used.
  342. *
  343. * A few callbacks are already added to this event by engine internal classes:
  344. *
  345. * * with `highest` priority operation is validated,
  346. * * with `normal` priority operation is executed,
  347. * * with `low` priority the {@link module:engine/model/document~Document} updates its version,
  348. * * with `low` priority {@link module:engine/model/liveposition~LivePosition} and {@link module:engine/model/liverange~LiveRange}
  349. * update themselves.
  350. *
  351. * @event applyOperation
  352. * @param {Array} args Arguments of the `applyOperation` which is an array with a single element - applied
  353. * {@link module:engine/model/operation/operation~Operation operation}.
  354. */
  355. /**
  356. * Event fired when {@link #insertContent} method is called.
  357. *
  358. * The {@link #insertContent default action of that method} is implemented as a
  359. * listener to this event so it can be fully customized by the features.
  360. *
  361. * @event insertContent
  362. * @param {Array} args The arguments passed to the original method.
  363. */
  364. /**
  365. * Event fired when {@link #deleteContent} method is called.
  366. *
  367. * The {@link #deleteContent default action of that method} is implemented as a
  368. * listener to this event so it can be fully customized by the features.
  369. *
  370. * @event deleteContent
  371. * @param {Array} args The arguments passed to the original method.
  372. */
  373. /**
  374. * Event fired when {@link #modifySelection} method is called.
  375. *
  376. * The {@link #modifySelection default action of that method} is implemented as a
  377. * listener to this event so it can be fully customized by the features.
  378. *
  379. * @event modifySelection
  380. * @param {Array} args The arguments passed to the original method.
  381. */
  382. /**
  383. * Event fired when {@link #getSelectedContent} method is called.
  384. *
  385. * The {@link #getSelectedContent default action of that method} is implemented as a
  386. * listener to this event so it can be fully customized by the features.
  387. *
  388. * @event getSelectedContent
  389. * @param {Array} args The arguments passed to the original method.
  390. */
  391. }
  392. mix( Model, ObservableMixin );