document.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/model/document
  7. */
  8. // Load all basic deltas and transformations, they register themselves.
  9. import './delta/basic-deltas';
  10. import './delta/basic-transformations';
  11. import Range from './range';
  12. import Position from './position';
  13. import RootElement from './rootelement';
  14. import History from './history';
  15. import DocumentSelection from './documentselection';
  16. import TreeWalker from './treewalker';
  17. import deltaTransform from './delta/transform';
  18. import clone from '@ckeditor/ckeditor5-utils/src/lib/lodash/clone';
  19. import EmitterMixin from '@ckeditor/ckeditor5-utils/src/emittermixin';
  20. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  21. import mix from '@ckeditor/ckeditor5-utils/src/mix';
  22. import { isInsideSurrogatePair, isInsideCombinedSymbol } from '@ckeditor/ckeditor5-utils/src/unicode';
  23. const graveyardName = '$graveyard';
  24. /**
  25. * Document tree model describes all editable data in the editor. It may contain multiple
  26. * {@link module:engine/model/document~Document#roots root elements}, for example if the editor have multiple editable areas,
  27. * each area will be represented by the separate root.
  28. *
  29. * All changes in the document are done by {@link module:engine/model/operation/operation~Operation operations}. To create operations in
  30. * a simple way, use the {@link module:engine/model/batch~Batch} API, for example:
  31. *
  32. * const batch = doc.batch();
  33. * batch.insert( node, position );
  34. * batch.split( otherPosition );
  35. *
  36. * @see module:engine/model/document~Document#batch
  37. * @mixes module:utils/emittermixin~EmitterMixin
  38. */
  39. export default class Document {
  40. /**
  41. * Creates an empty document instance with no {@link #roots} (other than
  42. * the {@link #graveyard graveyard root}).
  43. */
  44. constructor( model ) {
  45. this.model = model;
  46. /**
  47. * Document version. It starts from `0` and every operation increases the version number. It is used to ensure that
  48. * operations are applied on the proper document version.
  49. * If the {@link module:engine/model/operation/operation~Operation#baseVersion} will not match document version the
  50. * {@link module:utils/ckeditorerror~CKEditorError model-document-applyOperation-wrong-version} error is thrown.
  51. *
  52. * @readonly
  53. * @member {Number}
  54. */
  55. this.version = 0;
  56. /**
  57. * Document's history.
  58. *
  59. * **Note:** Be aware that deltas applied to the document might get removed or changed.
  60. *
  61. * @readonly
  62. * @member {module:engine/model/history~History}
  63. */
  64. this.history = new History( this );
  65. /**
  66. * Selection done on this document.
  67. *
  68. * @readonly
  69. * @member {module:engine/model/documentselection~DocumentSelection}
  70. */
  71. this.selection = new DocumentSelection( this, this.model );
  72. /**
  73. * List of roots that are owned and managed by this document. Use {@link #createRoot} and
  74. * {@link #getRoot} to manipulate it.
  75. *
  76. * @readonly
  77. * @member {Map}
  78. */
  79. this.roots = new Map();
  80. // Add events that will ensure selection correctness.
  81. this.selection.on( 'change:range', () => {
  82. for ( const range of this.selection.getRanges() ) {
  83. if ( !this._validateSelectionRange( range ) ) {
  84. /**
  85. * Range from {@link module:engine/model/documentselection~DocumentSelection document selection}
  86. * starts or ends at incorrect position.
  87. *
  88. * @error document-selection-wrong-position
  89. * @param {module:engine/model/range~Range} range
  90. */
  91. throw new CKEditorError( 'document-selection-wrong-position: ' +
  92. 'Range from document selection starts or ends at incorrect position.', { range } );
  93. }
  94. }
  95. } );
  96. // Graveyard tree root. Document always have a graveyard root, which stores removed nodes.
  97. this.createRoot( '$root', graveyardName );
  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. }, { priority: 'high' } );
  112. this.listenTo( model, 'applyOperation', ( evt, args ) => {
  113. const operation = args[ 0 ];
  114. if ( operation.isDocumentOperation ) {
  115. this.version++;
  116. this.history.addDelta( operation.delta );
  117. this.fire( 'change', operation.type, evt.return, operation.delta.batch, operation.delta.type );
  118. }
  119. }, { priority: 'low' } );
  120. // Temporary compatibility.
  121. model.delegate( 'changesDone' ).to( this );
  122. }
  123. /**
  124. * Graveyard tree root. Document always have a graveyard root, which stores removed nodes.
  125. *
  126. * @readonly
  127. * @member {module:engine/model/rootelement~RootElement}
  128. */
  129. get graveyard() {
  130. return this.getRoot( graveyardName );
  131. }
  132. /**
  133. * Creates a new top-level root.
  134. *
  135. * @param {String} [elementName='$root'] Element name. Defaults to `'$root'` which also have
  136. * some basic schema defined (`$block`s are allowed inside the `$root`). Make sure to define a proper
  137. * schema if you use a different name.
  138. * @param {String} [rootName='main'] Unique root name.
  139. * @returns {module:engine/model/rootelement~RootElement} Created root.
  140. */
  141. createRoot( elementName = '$root', rootName = 'main' ) {
  142. if ( this.roots.has( rootName ) ) {
  143. /**
  144. * Root with specified name already exists.
  145. *
  146. * @error model-document-createRoot-name-exists
  147. * @param {module:engine/model/document~Document} doc
  148. * @param {String} name
  149. */
  150. throw new CKEditorError(
  151. 'model-document-createRoot-name-exists: Root with specified name already exists.',
  152. { name: rootName }
  153. );
  154. }
  155. const root = new RootElement( this, elementName, rootName );
  156. this.roots.set( rootName, root );
  157. return root;
  158. }
  159. /**
  160. * Removes all events listeners set by document instance.
  161. */
  162. destroy() {
  163. this.selection.destroy();
  164. this.stopListening();
  165. }
  166. /**
  167. * Returns top-level root by its name.
  168. *
  169. * @param {String} [name='main'] Unique root name.
  170. * @returns {module:engine/model/rootelement~RootElement} Root registered under given name.
  171. */
  172. getRoot( name = 'main' ) {
  173. if ( !this.roots.has( name ) ) {
  174. /**
  175. * Root with specified name does not exist.
  176. *
  177. * @error model-document-getRoot-root-not-exist
  178. * @param {String} name
  179. */
  180. throw new CKEditorError(
  181. 'model-document-getRoot-root-not-exist: Root with specified name does not exist.',
  182. { name }
  183. );
  184. }
  185. return this.roots.get( name );
  186. }
  187. /**
  188. * Checks if root with given name is defined.
  189. *
  190. * @param {String} name Name of root to check.
  191. * @returns {Boolean}
  192. */
  193. hasRoot( name ) {
  194. return this.roots.has( name );
  195. }
  196. /**
  197. * Returns array with names of all roots (without the {@link #graveyard}) added to the document.
  198. *
  199. * @returns {Array.<String>} Roots names.
  200. */
  201. getRootNames() {
  202. return Array.from( this.roots.keys() ).filter( name => name != graveyardName );
  203. }
  204. /**
  205. * Basing on given `position`, finds and returns a {@link module:engine/model/range~Range Range} instance that is
  206. * nearest to that `position` and is a correct range for selection.
  207. *
  208. * Correct selection range might be collapsed - when it's located in position where text node can be placed.
  209. * Non-collapsed range is returned when selection can be placed around element marked as "object" in
  210. * {@link module:engine/model/schema~Schema schema}.
  211. *
  212. * Direction of searching for nearest correct selection range can be specified as:
  213. * * `both` - searching will be performed in both ways,
  214. * * `forward` - searching will be performed only forward,
  215. * * `backward` - searching will be performed only backward.
  216. *
  217. * When valid selection range cannot be found, `null` is returned.
  218. *
  219. * @param {module:engine/model/position~Position} position Reference position where new selection range should be looked for.
  220. * @param {'both'|'forward'|'backward'} [direction='both'] Search direction.
  221. * @returns {module:engine/model/range~Range|null} Nearest selection range or `null` if one cannot be found.
  222. */
  223. getNearestSelectionRange( position, direction = 'both' ) {
  224. const schema = this.model.schema;
  225. // Return collapsed range if provided position is valid.
  226. if ( schema.check( { name: '$text', inside: position } ) ) {
  227. return new Range( position );
  228. }
  229. let backwardWalker, forwardWalker;
  230. if ( direction == 'both' || direction == 'backward' ) {
  231. backwardWalker = new TreeWalker( { startPosition: position, direction: 'backward' } );
  232. }
  233. if ( direction == 'both' || direction == 'forward' ) {
  234. forwardWalker = new TreeWalker( { startPosition: position } );
  235. }
  236. for ( const data of combineWalkers( backwardWalker, forwardWalker ) ) {
  237. const type = ( data.walker == backwardWalker ? 'elementEnd' : 'elementStart' );
  238. const value = data.value;
  239. if ( value.type == type && schema.objects.has( value.item.name ) ) {
  240. return Range.createOn( value.item );
  241. }
  242. if ( schema.check( { name: '$text', inside: value.nextPosition } ) ) {
  243. return new Range( value.nextPosition );
  244. }
  245. }
  246. return null;
  247. }
  248. /**
  249. * Transforms two sets of deltas by themselves. Returns both transformed sets.
  250. *
  251. * @param {Array.<module:engine/model/delta/delta~Delta>} deltasA Array with the first set of deltas to transform. These
  252. * deltas are considered more important (than `deltasB`) when resolving conflicts.
  253. * @param {Array.<module:engine/model/delta/delta~Delta>} deltasB Array with the second set of deltas to transform. These
  254. * deltas are considered less important (than `deltasA`) when resolving conflicts.
  255. * @param {Boolean} [useContext=false] When set to `true`, transformation will store and use additional context
  256. * information to guarantee more expected results. Should be used whenever deltas related to already applied
  257. * deltas are transformed (for example when undoing changes).
  258. * @returns {Object}
  259. * @returns {Array.<module:engine/model/delta/delta~Delta>} return.deltasA The first set of deltas transformed
  260. * by the second set of deltas.
  261. * @returns {Array.<module:engine/model/delta/delta~Delta>} return.deltasB The second set of deltas transformed
  262. * by the first set of deltas.
  263. */
  264. transformDeltas( deltasA, deltasB, useContext = false ) {
  265. return deltaTransform.transformDeltaSets( deltasA, deltasB, useContext ? this : null );
  266. }
  267. /**
  268. * Custom toJSON method to solve child-parent circular dependencies.
  269. *
  270. * @returns {Object} Clone of this object with the document property changed to string.
  271. */
  272. toJSON() {
  273. const json = clone( this );
  274. // Due to circular references we need to remove parent reference.
  275. json.selection = '[engine.model.DocumentSelection]';
  276. json.model = '[engine.model.Model]';
  277. return json;
  278. }
  279. /**
  280. * Returns default root for this document which is either the first root that was added to the the document using
  281. * {@link #createRoot} or the {@link #graveyard graveyard root} if no other roots were created.
  282. *
  283. * @protected
  284. * @returns {module:engine/model/rootelement~RootElement} The default root for this document.
  285. */
  286. _getDefaultRoot() {
  287. for ( const root of this.roots.values() ) {
  288. if ( root !== this.graveyard ) {
  289. return root;
  290. }
  291. }
  292. return this.graveyard;
  293. }
  294. /**
  295. * Returns a default range for this selection. The default range is a collapsed range that starts and ends
  296. * at the beginning of this selection's document's {@link #_getDefaultRoot default root}.
  297. *
  298. * @protected
  299. * @returns {module:engine/model/range~Range}
  300. */
  301. _getDefaultRange() {
  302. const defaultRoot = this._getDefaultRoot();
  303. // Find the first position where the selection can be put.
  304. const position = new Position( defaultRoot, [ 0 ] );
  305. const nearestRange = this.getNearestSelectionRange( position );
  306. // If valid selection range is not found - return range collapsed at the beginning of the root.
  307. return nearestRange || new Range( position );
  308. }
  309. /**
  310. * Checks whether given {@link module:engine/model/range~Range range} is a valid range for
  311. * {@link #selection document's selection}.
  312. *
  313. * @private
  314. * @param {module:engine/model/range~Range} range Range to check.
  315. * @returns {Boolean} `true` if `range` is valid, `false` otherwise.
  316. */
  317. _validateSelectionRange( range ) {
  318. return validateTextNodePosition( range.start ) && validateTextNodePosition( range.end );
  319. }
  320. /**
  321. * Fired when document changes by applying an operation.
  322. *
  323. * There are a few types of change:
  324. *
  325. * * 'insert' when nodes are inserted,
  326. * * 'remove' when nodes are removed,
  327. * * 'reinsert' when remove is undone,
  328. * * 'move' when nodes are moved,
  329. * * 'rename' when element is renamed,
  330. * * 'marker' when a marker changes (added, removed or its range is changed),
  331. * * 'addAttribute' when attributes are added,
  332. * * 'removeAttribute' when attributes are removed,
  333. * * 'changeAttribute' when attributes change,
  334. * * 'addRootAttribute' when attribute for root is added,
  335. * * 'removeRootAttribute' when attribute for root is removed,
  336. * * 'changeRootAttribute' when attribute for root changes.
  337. *
  338. * @event change
  339. * @param {String} type Change type, possible option: 'insert', 'remove', 'reinsert', 'move', 'attribute'.
  340. * @param {Object} data Additional information about the change.
  341. * @param {module:engine/model/range~Range} [data.range] Range in model containing changed nodes. Note that the range state is
  342. * after changes has been done, i.e. for 'remove' the range will be in the {@link #graveyard graveyard root}.
  343. * The range is not defined for root, rename and marker types.
  344. * @param {module:engine/model/position~Position} [data.sourcePosition] Change source position.
  345. * Exists for 'remove', 'reinsert' and 'move'.
  346. * Note that this position state is before changes has been done, i.e. for 'reinsert' the source position will be in the
  347. * {@link #graveyard graveyard root}.
  348. * @param {String} [data.key] Only for attribute types. Key of changed / inserted / removed attribute.
  349. * @param {*} [data.oldValue] Only for 'removeAttribute', 'removeRootAttribute', 'changeAttribute' or
  350. * 'changeRootAttribute' type.
  351. * @param {*} [data.newValue] Only for 'addAttribute', 'addRootAttribute', 'changeAttribute' or
  352. * 'changeRootAttribute' type.
  353. * @param {module:engine/model/rootelement~RootElement} [data.root] Root element which attributes got changed. This is defined
  354. * only for root types.
  355. * @param {module:engine/model/batch~Batch} batch A {@link module:engine/model/batch~Batch batch}
  356. * of changes which this change is a part of.
  357. */
  358. /**
  359. * Fired when all queued document changes are done. See {@link #enqueueChanges}.
  360. *
  361. * @event changesDone
  362. */
  363. }
  364. mix( Document, EmitterMixin );
  365. // Checks whether given range boundary position is valid for document selection, meaning that is not between
  366. // unicode surrogate pairs or base character and combining marks.
  367. function validateTextNodePosition( rangeBoundary ) {
  368. const textNode = rangeBoundary.textNode;
  369. if ( textNode ) {
  370. const data = textNode.data;
  371. const offset = rangeBoundary.offset - textNode.startOffset;
  372. return !isInsideSurrogatePair( data, offset ) && !isInsideCombinedSymbol( data, offset );
  373. }
  374. return true;
  375. }
  376. // Generator function returning values from provided walkers, switching between them at each iteration. If only one walker
  377. // is provided it will return data only from that walker.
  378. //
  379. // @param {module:engine/module/treewalker~TreeWalker} [backward] Walker iterating in backward direction.
  380. // @param {module:engine/module/treewalker~TreeWalker} [forward] Walker iterating in forward direction.
  381. // @returns {Iterable.<Object>} Object returned at each iteration contains `value` and `walker` (informing which walker returned
  382. // given value) fields.
  383. function* combineWalkers( backward, forward ) {
  384. let done = false;
  385. while ( !done ) {
  386. done = true;
  387. if ( backward ) {
  388. const step = backward.next();
  389. if ( !step.done ) {
  390. done = false;
  391. yield {
  392. walker: backward,
  393. value: step.value
  394. };
  395. }
  396. }
  397. if ( forward ) {
  398. const step = forward.next();
  399. if ( !step.done ) {
  400. done = false;
  401. yield {
  402. walker: forward,
  403. value: step.value
  404. };
  405. }
  406. }
  407. }
  408. }