8
0

document.js 18 KB

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