document.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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/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. * @member {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. * @member {Number}
  57. */
  58. this.version = 0;
  59. /**
  60. * The document's history.
  61. *
  62. * @readonly
  63. * @member {module:engine/model/history~History}
  64. */
  65. this.history = new History( this );
  66. /**
  67. * The selection in this document.
  68. *
  69. * @readonly
  70. * @member {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. * @member {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. * @member {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. * @member {Set}
  93. */
  94. this._postFixers = new Set();
  95. // Graveyard tree root. Document always have a graveyard root, which stores removed nodes.
  96. this.createRoot( '$root', graveyardName );
  97. // First, if the operation is a document operation check if it's base version is correct.
  98. this.listenTo( model, 'applyOperation', ( evt, args ) => {
  99. const operation = args[ 0 ];
  100. if ( operation.isDocumentOperation && operation.baseVersion !== this.version ) {
  101. /**
  102. * Only operations with matching versions can be applied.
  103. *
  104. * @error document-applyOperation-wrong-version
  105. * @param {module:engine/model/operation/operation~Operation} operation
  106. */
  107. throw new CKEditorError(
  108. 'model-document-applyOperation-wrong-version: Only operations with matching versions can be applied.',
  109. { operation }
  110. );
  111. }
  112. }, { priority: 'highest' } );
  113. // Then, still before an operation is applied on model, buffer the change in differ.
  114. this.listenTo( model, 'applyOperation', ( evt, args ) => {
  115. const operation = args[ 0 ];
  116. if ( operation.isDocumentOperation ) {
  117. this.differ.bufferOperation( operation );
  118. }
  119. }, { priority: 'high' } );
  120. // After the operation is applied, bump document's version and add the operation to the history.
  121. this.listenTo( model, 'applyOperation', ( evt, args ) => {
  122. const operation = args[ 0 ];
  123. if ( operation.isDocumentOperation ) {
  124. this.version++;
  125. this.history.addOperation( operation );
  126. }
  127. }, { priority: 'low' } );
  128. // Listen to selection changes. If selection changed, mark it.
  129. let hasSelectionChanged = false;
  130. this.listenTo( this.selection, 'change', () => {
  131. hasSelectionChanged = true;
  132. } );
  133. // Wait for `_change` event from model, which signalizes that outermost change block has finished.
  134. // When this happens, check if there were any changes done on document, and if so, call post-fixers,
  135. // fire `change` event for features and conversion and then reset the differ.
  136. // Fire `change:data` event when at least one operation or buffered marker changes the data.
  137. this.listenTo( model, '_change', ( evt, writer ) => {
  138. if ( !this.differ.isEmpty || hasSelectionChanged ) {
  139. this._callPostFixers( writer );
  140. if ( this.differ.hasDataChanges() ) {
  141. this.fire( 'change:data', writer.batch );
  142. } else {
  143. this.fire( 'change', writer.batch );
  144. }
  145. this.differ.reset();
  146. hasSelectionChanged = false;
  147. }
  148. } );
  149. // Buffer marker changes.
  150. // This is not covered in buffering operations because markers may change outside of them (when they
  151. // are modified using `model.markers` collection, not through `MarkerOperation`).
  152. this.listenTo( model.markers, 'update', ( evt, marker, oldRange, newRange ) => {
  153. // Whenever marker is updated, buffer that change.
  154. this.differ.bufferMarkerChange( marker.name, oldRange, newRange, marker.affectsData );
  155. if ( oldRange === null ) {
  156. // If this is a new marker, add a listener that will buffer change whenever marker changes.
  157. marker.on( 'change', ( evt, oldRange ) => {
  158. this.differ.bufferMarkerChange( marker.name, oldRange, marker.getRange(), marker.affectsData );
  159. } );
  160. }
  161. } );
  162. }
  163. /**
  164. * The graveyard tree root. A document always has a graveyard root that stores removed nodes.
  165. *
  166. * @readonly
  167. * @member {module:engine/model/rootelement~RootElement}
  168. */
  169. get graveyard() {
  170. return this.getRoot( graveyardName );
  171. }
  172. /**
  173. * Creates a new root.
  174. *
  175. * @param {String} [elementName='$root'] The element name. Defaults to `'$root'` which also has some basic schema defined
  176. * (`$block`s are allowed inside the `$root`). Make sure to define a proper schema if you use a different name.
  177. * @param {String} [rootName='main'] A unique root name.
  178. * @returns {module:engine/model/rootelement~RootElement} The created root.
  179. */
  180. createRoot( elementName = '$root', rootName = 'main' ) {
  181. if ( this.roots.get( rootName ) ) {
  182. /**
  183. * A root with the specified name already exists.
  184. *
  185. * @error model-document-createRoot-name-exists
  186. * @param {module:engine/model/document~Document} doc
  187. * @param {String} name
  188. */
  189. throw new CKEditorError(
  190. 'model-document-createRoot-name-exists: Root with specified name already exists.',
  191. { name: rootName }
  192. );
  193. }
  194. const root = new RootElement( this, elementName, rootName );
  195. this.roots.add( root );
  196. return root;
  197. }
  198. /**
  199. * Removes all event listeners set by the document instance.
  200. */
  201. destroy() {
  202. this.selection.destroy();
  203. this.stopListening();
  204. }
  205. /**
  206. * Returns a root by its name.
  207. *
  208. * @param {String} [name='main'] A unique root name.
  209. * @returns {module:engine/model/rootelement~RootElement|null} The root registered under a given name or `null` when
  210. * there is no root with the given name.
  211. */
  212. getRoot( name = 'main' ) {
  213. return this.roots.get( name );
  214. }
  215. /**
  216. * Returns an array with names of all roots (without the {@link #graveyard}) added to the document.
  217. *
  218. * @returns {Array.<String>} Roots names.
  219. */
  220. getRootNames() {
  221. return Array.from( this.roots, root => root.rootName ).filter( name => name != graveyardName );
  222. }
  223. /**
  224. * Used to register a post-fixer callback. A post-fixer mechanism guarantees that the features that listen to
  225. * the {@link module:engine/model/model~Model#event:_change model's change event} will operate on a correct model state.
  226. *
  227. * An execution of a feature may lead to an incorrect document tree state. The callbacks are used to fix the document tree after
  228. * it has changed. Post-fixers are fired just after all changes from the outermost change block were applied but
  229. * before the {@link module:engine/model/document~Document#event:change change event} is fired. If a post-fixer callback made
  230. * a change, it should return `true`. When this happens, all post-fixers are fired again to check if something else should
  231. * not be fixed in the new document tree state.
  232. *
  233. * As a parameter, a post-fixer callback receives a {@link module:engine/model/writer~Writer writer} instance connected with the
  234. * executed changes block. Thanks to that, all changes done by the callback will be added to the same
  235. * {@link module:engine/model/batch~Batch batch} (and undo step) as the original changes. This makes post-fixer changes transparent
  236. * for the user.
  237. *
  238. * An example of a post-fixer is a callback that checks if all the data were removed from the editor. If so, the
  239. * callback should add an empty paragraph so that the editor is never empty:
  240. *
  241. * document.registerPostFixer( writer => {
  242. * const changes = document.differ.getChanges();
  243. *
  244. * // Check if the changes lead to an empty root in the editor.
  245. * for ( const entry of changes ) {
  246. * if ( entry.type == 'remove' && entry.position.root.isEmpty ) {
  247. * writer.insertElement( 'paragraph', entry.position.root, 0 );
  248. *
  249. * // It is fine to return early, even if multiple roots would need to be fixed.
  250. * // All post-fixers will be fired again, so if there are more empty roots, those will be fixed, too.
  251. * return true;
  252. * }
  253. * }
  254. * } );
  255. *
  256. * @param {Function} postFixer
  257. */
  258. registerPostFixer( postFixer ) {
  259. this._postFixers.add( postFixer );
  260. }
  261. /**
  262. * A custom `toJSON()` method to solve child-parent circular dependencies.
  263. *
  264. * @returns {Object} A clone of this object with the document property changed to a string.
  265. */
  266. toJSON() {
  267. const json = clone( this );
  268. // Due to circular references we need to remove parent reference.
  269. json.selection = '[engine.model.DocumentSelection]';
  270. json.model = '[engine.model.Model]';
  271. return json;
  272. }
  273. /**
  274. * Returns the default root for this document which is either the first root that was added to the document using
  275. * {@link #createRoot} or the {@link #graveyard graveyard root} if no other roots were created.
  276. *
  277. * @protected
  278. * @returns {module:engine/model/rootelement~RootElement} The default root for this document.
  279. */
  280. _getDefaultRoot() {
  281. for ( const root of this.roots ) {
  282. if ( root !== this.graveyard ) {
  283. return root;
  284. }
  285. }
  286. return this.graveyard;
  287. }
  288. /**
  289. * Returns the default range for this selection. The default range is a collapsed range that starts and ends
  290. * at the beginning of this selection's document {@link #_getDefaultRoot default root}.
  291. *
  292. * @protected
  293. * @returns {module:engine/model/range~Range}
  294. */
  295. _getDefaultRange() {
  296. const defaultRoot = this._getDefaultRoot();
  297. const model = this.model;
  298. const schema = model.schema;
  299. // Find the first position where the selection can be put.
  300. const position = model.createPositionFromPath( defaultRoot, [ 0 ] );
  301. const nearestRange = schema.getNearestSelectionRange( position );
  302. // If valid selection range is not found - return range collapsed at the beginning of the root.
  303. return nearestRange || model.createRange( position );
  304. }
  305. /**
  306. * Checks whether a given {@link module:engine/model/range~Range range} is a valid range for
  307. * the {@link #selection document's selection}.
  308. *
  309. * @private
  310. * @param {module:engine/model/range~Range} range A range to check.
  311. * @returns {Boolean} `true` if `range` is valid, `false` otherwise.
  312. */
  313. _validateSelectionRange( range ) {
  314. return validateTextNodePosition( range.start ) && validateTextNodePosition( range.end );
  315. }
  316. /**
  317. * Performs post-fixer loops. Executes post-fixer callbacks as long as none of them has done any changes to the model.
  318. *
  319. * @private
  320. */
  321. _callPostFixers( writer ) {
  322. let wasFixed = false;
  323. do {
  324. for ( const callback of this._postFixers ) {
  325. wasFixed = callback( writer );
  326. if ( wasFixed ) {
  327. break;
  328. }
  329. }
  330. } while ( wasFixed );
  331. }
  332. /**
  333. * Fired after each {@link module:engine/model/model~Model#enqueueChange `enqueueChange()` block} or the outermost
  334. * {@link module:engine/model/model~Model#change `change()` block} was executed and the document was changed
  335. * during that block's execution.
  336. *
  337. * The changes which this event will cover include:
  338. *
  339. * * document structure changes,
  340. * * selection changes,
  341. * * marker changes.
  342. *
  343. * If you want to be notified about all these changes, then simply listen to this event like this:
  344. *
  345. * model.document.on( 'change', () => {
  346. * console.log( 'The document has changed!' );
  347. * } );
  348. *
  349. * If, however, you only want to be notified about the data changes, then use the
  350. * {@link module:engine/model/document~Document#event:change:data change:data} event,
  351. * which is fired for document structure changes and marker changes (which affects the data).
  352. *
  353. * model.document.on( 'change:data', () => {
  354. * console.log( 'The data has changed!' );
  355. * } );
  356. *
  357. * @event change
  358. * @param {module:engine/model/batch~Batch} batch The batch that was used in the executed changes block.
  359. */
  360. /**
  361. * It is a narrower version of the {@link #event:change} event. It is fired for changes which
  362. * affect the editor data. This is:
  363. *
  364. * * document structure changes,
  365. * * marker changes (which affects the data).
  366. *
  367. * If you want to be notified about the data changes, then listen to this event:
  368. *
  369. * model.document.on( 'change:data', () => {
  370. * console.log( 'The data has changed!' );
  371. * } );
  372. *
  373. * If you would like to listen to all document changes, then check out the
  374. * {@link module:engine/model/document~Document#event:change change} event.
  375. *
  376. * @event change:data
  377. * @param {module:engine/model/batch~Batch} batch The batch that was used in the executed changes block.
  378. */
  379. }
  380. mix( Document, EmitterMixin );
  381. // Checks whether given range boundary position is valid for document selection, meaning that is not between
  382. // unicode surrogate pairs or base character and combining marks.
  383. function validateTextNodePosition( rangeBoundary ) {
  384. const textNode = rangeBoundary.textNode;
  385. if ( textNode ) {
  386. const data = textNode.data;
  387. const offset = rangeBoundary.offset - textNode.startOffset;
  388. return !isInsideSurrogatePair( data, offset ) && !isInsideCombinedSymbol( data, offset );
  389. }
  390. return true;
  391. }