document.js 16 KB

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