8
0

document.js 16 KB

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