document.js 15 KB

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