document.js 18 KB

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