document.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. /**
  2. * @license Copyright (c) 2003-2020, 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/document
  7. */
  8. import Differ from './differ';
  9. import RootElement from './rootelement';
  10. import History from './history';
  11. import DocumentSelection from './documentselection';
  12. import Collection from '@ckeditor/ckeditor5-utils/src/collection';
  13. import EmitterMixin from '@ckeditor/ckeditor5-utils/src/emittermixin';
  14. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  15. import mix from '@ckeditor/ckeditor5-utils/src/mix';
  16. import { isInsideSurrogatePair, isInsideCombinedSymbol } from '@ckeditor/ckeditor5-utils/src/unicode';
  17. import { clone } from 'lodash-es';
  18. // @if CK_DEBUG_ENGINE // const { logDocument } = require( '../dev-utils/utils' );
  19. const graveyardName = '$graveyard';
  20. /**
  21. * Data model's document. It contains the model's structure, its selection and the history of changes.
  22. *
  23. * Read more about working with the model in
  24. * {@glink framework/guides/architecture/editing-engine#model introduction to the the editing engine's architecture}.
  25. *
  26. * Usually, the document contains just one {@link module:engine/model/document~Document#roots root element}, so
  27. * you can retrieve it by just calling {@link module:engine/model/document~Document#getRoot} without specifying its name:
  28. *
  29. * model.document.getRoot(); // -> returns the main root
  30. *
  31. * However, the document may contain multiple roots – e.g. when the editor has multiple editable areas
  32. * (e.g. a title and a body of a message).
  33. *
  34. * @mixes module:utils/emittermixin~EmitterMixin
  35. */
  36. export default class Document {
  37. /**
  38. * Creates an empty document instance with no {@link #roots} (other than
  39. * the {@link #graveyard graveyard root}).
  40. */
  41. constructor( model ) {
  42. /**
  43. * The {@link module:engine/model/model~Model model} that the document is a part of.
  44. *
  45. * @readonly
  46. * @type {module:engine/model/model~Model}
  47. */
  48. this.model = model;
  49. /**
  50. * The document version. It starts from `0` and every operation increases the version number. It is used to ensure that
  51. * operations are applied on a proper document version.
  52. *
  53. * If the {@link module:engine/model/operation/operation~Operation#baseVersion base version} does not match the document version,
  54. * a {@link module:utils/ckeditorerror~CKEditorError model-document-applyoperation-wrong-version} error is thrown.
  55. *
  56. * @type {Number}
  57. */
  58. this.version = 0;
  59. /**
  60. * The document's history.
  61. *
  62. * @readonly
  63. * @type {module:engine/model/history~History}
  64. */
  65. this.history = new History( this );
  66. /**
  67. * The selection in this document.
  68. *
  69. * @readonly
  70. * @type {module:engine/model/documentselection~DocumentSelection}
  71. */
  72. this.selection = new DocumentSelection( this );
  73. /**
  74. * A list of roots that are owned and managed by this document. Use {@link #createRoot} and
  75. * {@link #getRoot} to manipulate it.
  76. *
  77. * @readonly
  78. * @type {module:utils/collection~Collection}
  79. */
  80. this.roots = new Collection( { idProperty: 'rootName' } );
  81. /**
  82. * The model differ object. Its role is to buffer changes done on the model document and then calculate a diff of those changes.
  83. *
  84. * @readonly
  85. * @type {module:engine/model/differ~Differ}
  86. */
  87. this.differ = new Differ( model.markers );
  88. /**
  89. * Post-fixer callbacks registered to the model document.
  90. *
  91. * @private
  92. * @type {Set.<Function>}
  93. */
  94. this._postFixers = new Set();
  95. /**
  96. * A boolean indicates whether the selection has changed until
  97. *
  98. * @private
  99. * @type {Boolean}
  100. */
  101. this._hasSelectionChangedFromTheLastChangeBlock = false;
  102. // Graveyard tree root. Document always have a graveyard root, which stores removed nodes.
  103. this.createRoot( '$root', graveyardName );
  104. // First, if the operation is a document operation check if it's base version is correct.
  105. this.listenTo( model, 'applyOperation', ( evt, args ) => {
  106. const operation = args[ 0 ];
  107. if ( operation.isDocumentOperation && operation.baseVersion !== this.version ) {
  108. /**
  109. * Only operations with matching versions can be applied.
  110. *
  111. * @error model-document-applyoperation-wrong-version
  112. * @param {module:engine/model/operation/operation~Operation} operation
  113. */
  114. throw new CKEditorError( 'model-document-applyoperation-wrong-version', this, { operation } );
  115. }
  116. }, { priority: 'highest' } );
  117. // Then, still before an operation is applied on model, buffer the change in differ.
  118. this.listenTo( model, 'applyOperation', ( evt, args ) => {
  119. const operation = args[ 0 ];
  120. if ( operation.isDocumentOperation ) {
  121. this.differ.bufferOperation( operation );
  122. }
  123. }, { priority: 'high' } );
  124. // After the operation is applied, bump document's version and add the operation to the history.
  125. this.listenTo( model, 'applyOperation', ( evt, args ) => {
  126. const operation = args[ 0 ];
  127. if ( operation.isDocumentOperation ) {
  128. this.version++;
  129. this.history.addOperation( operation );
  130. }
  131. }, { priority: 'low' } );
  132. // Listen to selection changes. If selection changed, mark it.
  133. this.listenTo( this.selection, 'change', () => {
  134. this._hasSelectionChangedFromTheLastChangeBlock = true;
  135. } );
  136. // Buffer marker changes.
  137. // This is not covered in buffering operations because markers may change outside of them (when they
  138. // are modified using `model.markers` collection, not through `MarkerOperation`).
  139. this.listenTo( model.markers, 'update', ( evt, marker, oldRange, newRange ) => {
  140. // Whenever marker is updated, buffer that change.
  141. this.differ.bufferMarkerChange( marker.name, oldRange, newRange, marker.affectsData );
  142. if ( oldRange === null ) {
  143. // If this is a new marker, add a listener that will buffer change whenever marker changes.
  144. marker.on( 'change', ( evt, oldRange ) => {
  145. this.differ.bufferMarkerChange( marker.name, oldRange, marker.getRange(), marker.affectsData );
  146. } );
  147. }
  148. } );
  149. }
  150. /**
  151. * The graveyard tree root. A document always has a graveyard root that stores removed nodes.
  152. *
  153. * @readonly
  154. * @member {module:engine/model/rootelement~RootElement}
  155. */
  156. get graveyard() {
  157. return this.getRoot( graveyardName );
  158. }
  159. /**
  160. * Creates a new root.
  161. *
  162. * @param {String} [elementName='$root'] The element name. Defaults to `'$root'` which also has some basic schema defined
  163. * (`$block`s are allowed inside the `$root`). Make sure to define a proper schema if you use a different name.
  164. * @param {String} [rootName='main'] A unique root name.
  165. * @returns {module:engine/model/rootelement~RootElement} The created root.
  166. */
  167. createRoot( elementName = '$root', rootName = 'main' ) {
  168. if ( this.roots.get( rootName ) ) {
  169. /**
  170. * A root with the specified name already exists.
  171. *
  172. * @error model-document-createroot-name-exists
  173. * @param {module:engine/model/document~Document} doc
  174. * @param {String} name
  175. */
  176. throw new CKEditorError( 'model-document-createroot-name-exists', this, { name: rootName } );
  177. }
  178. const root = new RootElement( this, elementName, rootName );
  179. this.roots.add( root );
  180. return root;
  181. }
  182. /**
  183. * Removes all event listeners set by the document instance.
  184. */
  185. destroy() {
  186. this.selection.destroy();
  187. this.stopListening();
  188. }
  189. /**
  190. * Returns a root by its name.
  191. *
  192. * @param {String} [name='main'] A unique root name.
  193. * @returns {module:engine/model/rootelement~RootElement|null} The root registered under a given name or `null` when
  194. * there is no root with the given name.
  195. */
  196. getRoot( name = 'main' ) {
  197. return this.roots.get( name );
  198. }
  199. /**
  200. * Returns an array with names of all roots (without the {@link #graveyard}) added to the document.
  201. *
  202. * @returns {Array.<String>} Roots names.
  203. */
  204. getRootNames() {
  205. return Array.from( this.roots, root => root.rootName ).filter( name => name != graveyardName );
  206. }
  207. /**
  208. * Used to register a post-fixer callback. A post-fixer mechanism guarantees that the features
  209. * will operate on a correct model state.
  210. *
  211. * An execution of a feature may lead to an incorrect document tree state. The callbacks are used to fix the document tree after
  212. * it has changed. Post-fixers are fired just after all changes from the outermost change block were applied but
  213. * before the {@link module:engine/model/document~Document#event:change change event} is fired. If a post-fixer callback made
  214. * a change, it should return `true`. When this happens, all post-fixers are fired again to check if something else should
  215. * not be fixed in the new document tree state.
  216. *
  217. * As a parameter, a post-fixer callback receives a {@link module:engine/model/writer~Writer writer} instance connected with the
  218. * executed changes block. Thanks to that, all changes done by the callback will be added to the same
  219. * {@link module:engine/model/batch~Batch batch} (and undo step) as the original changes. This makes post-fixer changes transparent
  220. * for the user.
  221. *
  222. * An example of a post-fixer is a callback that checks if all the data were removed from the editor. If so, the
  223. * callback should add an empty paragraph so that the editor is never empty:
  224. *
  225. * document.registerPostFixer( writer => {
  226. * const changes = document.differ.getChanges();
  227. *
  228. * // Check if the changes lead to an empty root in the editor.
  229. * for ( const entry of changes ) {
  230. * if ( entry.type == 'remove' && entry.position.root.isEmpty ) {
  231. * writer.insertElement( 'paragraph', entry.position.root, 0 );
  232. *
  233. * // It is fine to return early, even if multiple roots would need to be fixed.
  234. * // All post-fixers will be fired again, so if there are more empty roots, those will be fixed, too.
  235. * return true;
  236. * }
  237. * }
  238. * } );
  239. *
  240. * @param {Function} postFixer
  241. */
  242. registerPostFixer( postFixer ) {
  243. this._postFixers.add( postFixer );
  244. }
  245. /**
  246. * A custom `toJSON()` method to solve child-parent circular dependencies.
  247. *
  248. * @returns {Object} A clone of this object with the document property changed to a string.
  249. */
  250. toJSON() {
  251. const json = clone( this );
  252. // Due to circular references we need to remove parent reference.
  253. json.selection = '[engine.model.DocumentSelection]';
  254. json.model = '[engine.model.Model]';
  255. return json;
  256. }
  257. /**
  258. * Check if there were any changes done on document, and if so, call post-fixers,
  259. * fire `change` event for features and conversion and then reset the differ.
  260. * Fire `change:data` event when at least one operation or buffered marker changes the data.
  261. *
  262. * @protected
  263. * @fires change
  264. * @fires change:data
  265. * @param {module:engine/model/writer~Writer} writer The writer on which post-fixers will be called.
  266. */
  267. _handleChangeBlock( writer ) {
  268. if ( this._hasDocumentChangedFromTheLastChangeBlock() ) {
  269. this._callPostFixers( writer );
  270. // Refresh selection attributes according to the final position in the model after the change.
  271. this.selection.refresh();
  272. if ( this.differ.hasDataChanges() ) {
  273. this.fire( 'change:data', writer.batch );
  274. } else {
  275. this.fire( 'change', writer.batch );
  276. }
  277. // Theoretically, it is not necessary to refresh selection after change event because
  278. // post-fixers are the last who should change the model, but just in case...
  279. this.selection.refresh();
  280. this.differ.reset();
  281. }
  282. this._hasSelectionChangedFromTheLastChangeBlock = false;
  283. }
  284. /**
  285. * Returns whether there is a buffered change or if the selection has changed from the last
  286. * {@link module:engine/model/model~Model#enqueueChange `enqueueChange()` block}
  287. * or {@link module:engine/model/model~Model#change `change()` block}.
  288. *
  289. * @protected
  290. * @returns {Boolean} Returns `true` if document has changed from the last `change()` or `enqueueChange()` block.
  291. */
  292. _hasDocumentChangedFromTheLastChangeBlock() {
  293. return !this.differ.isEmpty || this._hasSelectionChangedFromTheLastChangeBlock;
  294. }
  295. /**
  296. * Returns the default root for this document which is either the first root that was added to the document using
  297. * {@link #createRoot} or the {@link #graveyard graveyard root} if no other roots were created.
  298. *
  299. * @protected
  300. * @returns {module:engine/model/rootelement~RootElement} The default root for this document.
  301. */
  302. _getDefaultRoot() {
  303. for ( const root of this.roots ) {
  304. if ( root !== this.graveyard ) {
  305. return root;
  306. }
  307. }
  308. return this.graveyard;
  309. }
  310. /**
  311. * Returns the default range for this selection. The default range is a collapsed range that starts and ends
  312. * at the beginning of this selection's document {@link #_getDefaultRoot default root}.
  313. *
  314. * @protected
  315. * @returns {module:engine/model/range~Range}
  316. */
  317. _getDefaultRange() {
  318. const defaultRoot = this._getDefaultRoot();
  319. const model = this.model;
  320. const schema = model.schema;
  321. // Find the first position where the selection can be put.
  322. const position = model.createPositionFromPath( defaultRoot, [ 0 ] );
  323. const nearestRange = schema.getNearestSelectionRange( position );
  324. // If valid selection range is not found - return range collapsed at the beginning of the root.
  325. return nearestRange || model.createRange( position );
  326. }
  327. /**
  328. * Checks whether a given {@link module:engine/model/range~Range range} is a valid range for
  329. * the {@link #selection document's selection}.
  330. *
  331. * @private
  332. * @param {module:engine/model/range~Range} range A range to check.
  333. * @returns {Boolean} `true` if `range` is valid, `false` otherwise.
  334. */
  335. _validateSelectionRange( range ) {
  336. return validateTextNodePosition( range.start ) && validateTextNodePosition( range.end );
  337. }
  338. /**
  339. * Performs post-fixer loops. Executes post-fixer callbacks as long as none of them has done any changes to the model.
  340. *
  341. * @private
  342. * @param {module:engine/model/writer~Writer} writer The writer on which post-fixer callbacks will be called.
  343. */
  344. _callPostFixers( writer ) {
  345. let wasFixed = false;
  346. do {
  347. for ( const callback of this._postFixers ) {
  348. // Ensure selection attributes are up to date before each post-fixer.
  349. // https://github.com/ckeditor/ckeditor5-engine/issues/1673.
  350. //
  351. // It might be good to refresh the selection after each operation but at the moment it leads
  352. // to losing attributes for composition or and spell checking
  353. // https://github.com/ckeditor/ckeditor5-typing/issues/188
  354. this.selection.refresh();
  355. wasFixed = callback( writer );
  356. if ( wasFixed ) {
  357. break;
  358. }
  359. }
  360. } while ( wasFixed );
  361. }
  362. /**
  363. * Fired after each {@link module:engine/model/model~Model#enqueueChange `enqueueChange()` block} or the outermost
  364. * {@link module:engine/model/model~Model#change `change()` block} was executed and the document was changed
  365. * during that block's execution.
  366. *
  367. * The changes which this event will cover include:
  368. *
  369. * * document structure changes,
  370. * * selection changes,
  371. * * marker changes.
  372. *
  373. * If you want to be notified about all these changes, then simply listen to this event like this:
  374. *
  375. * model.document.on( 'change', () => {
  376. * console.log( 'The document has changed!' );
  377. * } );
  378. *
  379. * If, however, you only want to be notified about the data changes, then use the
  380. * {@link module:engine/model/document~Document#event:change:data change:data} event,
  381. * which is fired for document structure changes and marker changes (which affects the data).
  382. *
  383. * model.document.on( 'change:data', () => {
  384. * console.log( 'The data has changed!' );
  385. * } );
  386. *
  387. * @event change
  388. * @param {module:engine/model/batch~Batch} batch The batch that was used in the executed changes block.
  389. */
  390. /**
  391. * It is a narrower version of the {@link #event:change} event. It is fired for changes which
  392. * affect the editor data. This is:
  393. *
  394. * * document structure changes,
  395. * * marker changes (which affects the data).
  396. *
  397. * If you want to be notified about the data changes, then listen to this event:
  398. *
  399. * model.document.on( 'change:data', () => {
  400. * console.log( 'The data has changed!' );
  401. * } );
  402. *
  403. * If you would like to listen to all document changes, then check out the
  404. * {@link module:engine/model/document~Document#event:change change} event.
  405. *
  406. * @event change:data
  407. * @param {module:engine/model/batch~Batch} batch The batch that was used in the executed changes block.
  408. */
  409. // @if CK_DEBUG_ENGINE // log( version = null ) {
  410. // @if CK_DEBUG_ENGINE // version = version === null ? this.version : version;
  411. // @if CK_DEBUG_ENGINE // logDocument( this, version );
  412. // @if CK_DEBUG_ENGINE // }
  413. }
  414. mix( Document, EmitterMixin );
  415. // Checks whether given range boundary position is valid for document selection, meaning that is not between
  416. // unicode surrogate pairs or base character and combining marks.
  417. function validateTextNodePosition( rangeBoundary ) {
  418. const textNode = rangeBoundary.textNode;
  419. if ( textNode ) {
  420. const data = textNode.data;
  421. const offset = rangeBoundary.offset - textNode.startOffset;
  422. return !isInsideSurrogatePair( data, offset ) && !isInsideCombinedSymbol( data, offset );
  423. }
  424. return true;
  425. }