8
0

document.js 14 KB

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