model.js 15 KB

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