document.js 16 KB

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