8
0

document.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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 LiveSelection from './liveselection';
  19. import Schema from './schema';
  20. import TreeWalker from './treewalker';
  21. import MarkerCollection from './markercollection';
  22. import clone from '@ckeditor/ckeditor5-utils/src/lib/lodash/clone';
  23. import EmitterMixin from '@ckeditor/ckeditor5-utils/src/emittermixin';
  24. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  25. import mix from '@ckeditor/ckeditor5-utils/src/mix';
  26. import { isInsideSurrogatePair, isInsideCombinedSymbol } from '@ckeditor/ckeditor5-utils/src/unicode';
  27. const graveyardName = '$graveyard';
  28. /**
  29. * Document tree model describes all editable data in the editor. It may contain multiple
  30. * {@link module:engine/model/document~Document#roots root elements}, for example if the editor have multiple editable areas,
  31. * each area will be represented by the separate root.
  32. *
  33. * All changes in the document are done by {@link module:engine/model/operation/operation~Operation operations}. To create operations in
  34. * a simple way, use the {@link module:engine/model/batch~Batch} API, for example:
  35. *
  36. * doc.batch().insert( position, nodes ).split( otherPosition );
  37. *
  38. * @see module:engine/model/document~Document#batch
  39. * @mixes module:utils/emittermixin~EmitterMixin
  40. */
  41. export default class Document {
  42. /**
  43. * Creates an empty document instance with no {@link #roots} (other than
  44. * the {@link #graveyard graveyard root}).
  45. */
  46. constructor() {
  47. /**
  48. * Document version. It starts from `0` and every operation increases the version number. It is used to ensure that
  49. * operations are applied on the proper document version.
  50. * If the {@link module:engine/model/operation/operation~Operation#baseVersion} will not match document version the
  51. * {@link module:utils/ckeditorerror~CKEditorError model-document-applyOperation-wrong-version} error is thrown.
  52. *
  53. * @readonly
  54. * @member {Number}
  55. */
  56. this.version = 0;
  57. /**
  58. * Schema for this document.
  59. *
  60. * @member {module:engine/model/schema~Schema}
  61. */
  62. this.schema = new Schema();
  63. /**
  64. * Document's history.
  65. *
  66. * **Note:** Be aware that deltas applied to the document might get removed or changed.
  67. *
  68. * @readonly
  69. * @member {module:engine/model/history~History}
  70. */
  71. this.history = new History( this );
  72. /**
  73. * Document's markers' collection.
  74. *
  75. * @readonly
  76. * @member {module:engine/model/markercollection~MarkerCollection}
  77. */
  78. this.markers = new MarkerCollection();
  79. /**
  80. * Selection done on this document.
  81. *
  82. * @readonly
  83. * @member {module:engine/model/liveselection~LiveSelection}
  84. */
  85. this.selection = new LiveSelection( this );
  86. /**
  87. * Array of pending changes. See: {@link #enqueueChanges}.
  88. *
  89. * @private
  90. * @member {Array.<Function>}
  91. */
  92. this._pendingChanges = [];
  93. /**
  94. * List of roots that are owned and managed by this document. Use {@link #createRoot} and
  95. * {@link #getRoot} to manipulate it.
  96. *
  97. * @readonly
  98. * @member {Map}
  99. */
  100. this.roots = new Map();
  101. // Add events that will ensure selection correctness.
  102. this.selection.on( 'change:range', () => {
  103. for ( const range of this.selection.getRanges() ) {
  104. if ( !this._validateSelectionRange( range ) ) {
  105. /**
  106. * Range from document selection 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. if ( changes ) {
  152. // `NoOperation` returns no changes, do not fire event for it.
  153. this.fire( 'change', operation.type, changes, operation.delta.batch, operation.delta.type );
  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 }
  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, forwardWalker;
  283. if ( direction == 'both' || direction == 'backward' ) {
  284. backwardWalker = new TreeWalker( { startPosition: position, direction: 'backward' } );
  285. }
  286. if ( direction == 'both' || direction == 'forward' ) {
  287. forwardWalker = new TreeWalker( { startPosition: position } );
  288. }
  289. for ( const data of combineWalkers( backwardWalker, forwardWalker ) ) {
  290. const type = ( data.walker == backwardWalker ? 'elementEnd' : 'elementStart' );
  291. const value = data.value;
  292. if ( value.type == type && this.schema.objects.has( value.item.name ) ) {
  293. return Range.createOn( value.item );
  294. }
  295. if ( this.schema.check( { name: '$text', inside: value.nextPosition } ) ) {
  296. return new Range( value.nextPosition );
  297. }
  298. }
  299. return null;
  300. }
  301. /**
  302. * Custom toJSON method to solve child-parent circular dependencies.
  303. *
  304. * @returns {Object} Clone of this object with the document property changed to string.
  305. */
  306. toJSON() {
  307. const json = clone( this );
  308. // Due to circular references we need to remove parent reference.
  309. json.selection = '[engine.model.LiveSelection]';
  310. return json;
  311. }
  312. /**
  313. * Returns default root for this document which is either the first root that was added to the the document using
  314. * {@link #createRoot} or the {@link #graveyard graveyard root} if no other roots were created.
  315. *
  316. * @protected
  317. * @returns {module:engine/model/rootelement~RootElement} The default root for this document.
  318. */
  319. _getDefaultRoot() {
  320. for ( const root of this.roots.values() ) {
  321. if ( root !== this.graveyard ) {
  322. return root;
  323. }
  324. }
  325. return this.graveyard;
  326. }
  327. /**
  328. * Returns a default range for this selection. The default range is a collapsed range that starts and ends
  329. * at the beginning of this selection's document's {@link #_getDefaultRoot default root}.
  330. *
  331. * @protected
  332. * @returns {module:engine/model/range~Range}
  333. */
  334. _getDefaultRange() {
  335. const defaultRoot = this._getDefaultRoot();
  336. // Find the first position where the selection can be put.
  337. const position = new Position( defaultRoot, [ 0 ] );
  338. const nearestRange = this.getNearestSelectionRange( position );
  339. // If valid selection range is not found - return range collapsed at the beginning of the root.
  340. return nearestRange || new Range( position );
  341. }
  342. /**
  343. * Checks whether given {@link module:engine/model/range~Range range} is a valid range for
  344. * {@link #selection document's selection}.
  345. *
  346. * @private
  347. * @param {module:engine/model/range~Range} range Range to check.
  348. * @returns {Boolean} `true` if `range` is valid, `false` otherwise.
  349. */
  350. _validateSelectionRange( range ) {
  351. return validateTextNodePosition( range.start ) && validateTextNodePosition( range.end );
  352. }
  353. /**
  354. * Fired when document changes by applying an operation.
  355. *
  356. * There are 5 types of change:
  357. *
  358. * * 'insert' when nodes are inserted,
  359. * * 'remove' when nodes are removed,
  360. * * 'reinsert' when remove is undone,
  361. * * 'move' when nodes are moved,
  362. * * 'addAttribute' when attributes are added,
  363. * * 'removeAttribute' when attributes are removed,
  364. * * 'changeAttribute' when attributes change,
  365. * * 'addRootAttribute' when attribute for root is added,
  366. * * 'removeRootAttribute' when attribute for root is removed,
  367. * * 'changeRootAttribute' when attribute for root changes.
  368. *
  369. * @event change
  370. * @param {String} type Change type, possible option: 'insert', 'remove', 'reinsert', 'move', 'attribute'.
  371. * @param {Object} data Additional information about the change.
  372. * @param {module:engine/model/range~Range} data.range Range in model containing changed nodes. Note that the range state is
  373. * after changes has been done, i.e. for 'remove' the range will be in the {@link #graveyard graveyard root}.
  374. * This is `undefined` for "...root..." types.
  375. * @param {module:engine/model/position~Position} [data.sourcePosition] Change source position.
  376. * Exists for 'remove', 'reinsert' and 'move'.
  377. * Note that this position state is before changes has been done, i.e. for 'reinsert' the source position will be in the
  378. * {@link #graveyard graveyard root}.
  379. * @param {String} [data.key] Only for attribute types. Key of changed / inserted / removed attribute.
  380. * @param {*} [data.oldValue] Only for 'removeAttribute', 'removeRootAttribute', 'changeAttribute' or
  381. * 'changeRootAttribute' type.
  382. * @param {*} [data.newValue] Only for 'addAttribute', 'addRootAttribute', 'changeAttribute' or
  383. * 'changeRootAttribute' type.
  384. * @param {module:engine/model/rootelement~RootElement} [changeInfo.root] Root element which attributes got changed. This is defined
  385. * only for root types.
  386. * @param {module:engine/model/batch~Batch} batch A {@link module:engine/model/batch~Batch batch}
  387. * of changes which this change is a part of.
  388. */
  389. /**
  390. * Fired when all queued document changes are done. See {@link #enqueueChanges}.
  391. *
  392. * @event changesDone
  393. */
  394. }
  395. mix( Document, EmitterMixin );
  396. // Checks whether given range boundary position is valid for document selection, meaning that is not between
  397. // unicode surrogate pairs or base character and combining marks.
  398. function validateTextNodePosition( rangeBoundary ) {
  399. const textNode = rangeBoundary.textNode;
  400. if ( textNode ) {
  401. const data = textNode.data;
  402. const offset = rangeBoundary.offset - textNode.startOffset;
  403. return !isInsideSurrogatePair( data, offset ) && !isInsideCombinedSymbol( data, offset );
  404. }
  405. return true;
  406. }
  407. // Generator function returning values from provided walkers, switching between them at each iteration. If only one walker
  408. // is provided it will return data only from that walker.
  409. //
  410. // @param {module:engine/module/treewalker~TreeWalker} [backward] Walker iterating in backward direction.
  411. // @param {module:engine/module/treewalker~TreeWalker} [forward] Walker iterating in forward direction.
  412. // @returns {Iterable.<Object>} Object returned at each iteration contains `value` and `walker` (informing which walker returned
  413. // given value) fields.
  414. function* combineWalkers( backward, forward ) {
  415. let done = false;
  416. while ( !done ) {
  417. done = true;
  418. if ( backward ) {
  419. const step = backward.next();
  420. if ( !step.done ) {
  421. done = false;
  422. yield{
  423. walker: backward,
  424. value: step.value
  425. };
  426. }
  427. }
  428. if ( forward ) {
  429. const step = forward.next();
  430. if ( !step.done ) {
  431. done = false;
  432. yield{
  433. walker: forward,
  434. value: step.value
  435. };
  436. }
  437. }
  438. }
  439. }