8
0

document.js 17 KB

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