document.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. /**
  2. * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. 'use strict';
  6. // Load all basic deltas and transformations, they register themselves, but they need to be imported somewhere.
  7. import deltas from './delta/basic-deltas.js'; // jshint ignore:line
  8. import transformations from './delta/basic-transformations.js'; // jshint ignore:line
  9. import RootElement from './rootelement.js';
  10. import Batch from './batch.js';
  11. import History from './history.js';
  12. import Selection from './selection.js';
  13. import EmitterMixin from '../../utils/emittermixin.js';
  14. import CKEditorError from '../../utils/ckeditorerror.js';
  15. import mix from '../../utils/mix.js';
  16. import Schema from './schema.js';
  17. import Composer from './composer/composer.js';
  18. import clone from '../../utils/lib/lodash/clone.js';
  19. const graveyardSymbol = Symbol( 'graveyard' );
  20. /**
  21. * Document tree model describes all editable data in the editor. It may contain multiple
  22. * {@link engine.treeModel.Document#roots root elements}, for example if the editor have multiple editable areas, each area will be
  23. * represented by the separate root.
  24. *
  25. * All changes in the document are done by {@link engine.treeModel.operation.Operation operations}. To create operations in
  26. * the simple way use use the {@link engine.treeModel.Batch} API, for example:
  27. *
  28. * doc.batch().insert( position, nodes ).split( otherPosition );
  29. *
  30. * @see engine.treeModel.Document#batch
  31. *
  32. * @memberOf engine.treeModel
  33. */
  34. export default class Document {
  35. /**
  36. * Creates an empty document instance with no {@link engine.treeModel.Document#roots} (other than graveyard).
  37. */
  38. constructor() {
  39. /**
  40. * Document version. It starts from `0` and every operation increases the version number. It is used to ensure that
  41. * operations are applied on the proper document version. If the {@link engine.treeModel.operation.Operation#baseVersion} will
  42. * not match document version the {@link document-applyOperation-wrong-version} error is thrown.
  43. *
  44. * @readonly
  45. * @member {Number} engine.treeModel.Document#version
  46. */
  47. this.version = 0;
  48. /**
  49. * Selection done on this document.
  50. *
  51. * @readonly
  52. * @member {engine.treeModel.Selection} engine.treeModel.Document#selection
  53. */
  54. this.selection = new Selection( this );
  55. /**
  56. * Schema for this document.
  57. *
  58. * @member {engine.treeModel.Schema} engine.treeModel.Document#schema
  59. */
  60. this.schema = new Schema();
  61. /**
  62. * Composer for this document. Set of tools to work with the document.
  63. *
  64. * The features can tune up these tools to better work on their specific cases.
  65. *
  66. * @member {engine.treeModel.composer.Composer} engine.treeModel.Document#composer
  67. */
  68. this.composer = new Composer();
  69. /**
  70. * Array of pending changes. See: {@link engine.treeModel.Document#enqueueChanges}.
  71. *
  72. * @private
  73. * @member {Array.<Function>} engine.treeModel.Document#_pendingChanges
  74. */
  75. this._pendingChanges = [];
  76. /**
  77. * List of roots that are owned and managed by this document. Use {@link engine.treeModel.document#createRoot} and
  78. * {@link engine.treeModel.document#getRoot} to manipulate it.
  79. *
  80. * @readonly
  81. * @protected
  82. * @member {Map} engine.treeModel.Document#roots
  83. */
  84. this._roots = new Map();
  85. // Add events that will update selection attributes.
  86. this.selection.on( 'change:range', () => {
  87. this.selection._updateAttributes();
  88. } );
  89. this.on( 'changesDone', () => {
  90. this.selection._updateAttributes();
  91. } );
  92. // Graveyard tree root. Document always have a graveyard root, which stores removed nodes.
  93. this.createRoot( graveyardSymbol );
  94. /**
  95. * Document's history.
  96. *
  97. * @readonly
  98. * @member {engine.treeModel.History} engine.treeModel.Document#history
  99. */
  100. this.history = new History();
  101. }
  102. /**
  103. * Graveyard tree root. Document always have a graveyard root, which stores removed nodes.
  104. *
  105. * @readonly
  106. * @type {engine.treeModel.RootElement}
  107. */
  108. get graveyard() {
  109. return this.getRoot( graveyardSymbol );
  110. }
  111. /**
  112. * Gets names of all roots (without the {@link engine.treeModel.Document#graveyard}).
  113. *
  114. * @readonly
  115. * @type {Iterable.<String>}
  116. */
  117. get rootNames() {
  118. return Array.from( this._roots.keys() ).filter( ( name ) => name != graveyardSymbol );
  119. }
  120. /**
  121. * This is the entry point for all document changes. All changes on the document are done using
  122. * {@link engine.treeModel.operation.Operation operations}. To create operations in the simple way use the
  123. * {@link engine.treeModel.Batch} API available via {@link engine.treeModel.Document#batch} method.
  124. *
  125. * @fires @link engine.treeModel.Document#change
  126. * @param {engine.treeModel.operation.Operation} operation Operation to be applied.
  127. */
  128. applyOperation( operation ) {
  129. if ( operation.baseVersion !== this.version ) {
  130. /**
  131. * Only operations with matching versions can be applied.
  132. *
  133. * @error document-applyOperation-wrong-version
  134. * @param {engine.treeModel.operation.Operation} operation
  135. */
  136. throw new CKEditorError(
  137. 'document-applyOperation-wrong-version: Only operations with matching versions can be applied.',
  138. { operation: operation } );
  139. }
  140. let changes = operation._execute();
  141. this.version++;
  142. this.history.addOperation( operation );
  143. const batch = operation.delta && operation.delta.batch;
  144. if ( changes ) {
  145. // `NoOperation` returns no changes, do not fire event for it.
  146. this.fire( 'change', operation.type, changes, batch );
  147. }
  148. }
  149. /**
  150. * Creates a {@link engine.treeModel.Batch} instance which allows to change the document.
  151. *
  152. * @returns {engine.treeModel.Batch} Batch instance.
  153. */
  154. batch() {
  155. return new Batch( this );
  156. }
  157. /**
  158. * Creates a new top-level root.
  159. *
  160. * @param {String|Symbol} rootName Unique root name.
  161. * @param {String} [elementName='$root'] Element name. Defaults to `'$root'` which also have
  162. * some basic schema defined (`$block`s are allowed inside the `$root`). Make sure to define a proper
  163. * schema if you use a different name.
  164. * @returns {engine.treeModel.RootElement} Created root.
  165. */
  166. createRoot( rootName, elementName = '$root' ) {
  167. if ( this._roots.has( rootName ) ) {
  168. /**
  169. * Root with specified name already exists.
  170. *
  171. * @error document-createRoot-name-exists
  172. * @param {engine.treeModel.Document} doc
  173. * @param {String} name
  174. */
  175. throw new CKEditorError(
  176. 'document-createRoot-name-exists: Root with specified name already exists.',
  177. { name: rootName }
  178. );
  179. }
  180. const root = new RootElement( this, elementName );
  181. this._roots.set( rootName, root );
  182. return root;
  183. }
  184. /**
  185. * Removes all events listeners set by document instance.
  186. */
  187. destroy() {
  188. this.selection.destroy();
  189. this.stopListening();
  190. }
  191. /**
  192. * Enqueues document changes. Any changes to be done on document (mostly using {@link engine.treeModel.Document#batch}
  193. * should be placed in the queued callback. If no other plugin is changing document at the moment, the callback will be
  194. * called immediately. Otherwise it will wait for all previously queued changes to finish happening. This way
  195. * queued callback will not interrupt other callbacks.
  196. *
  197. * When all queued changes are done {@link engine.treeModel.Document#changesDone} event is fired.
  198. *
  199. * @fires @link engine.treeModel.Document#changesDone
  200. * @param {Function} callback Callback to enqueue.
  201. */
  202. enqueueChanges( callback ) {
  203. this._pendingChanges.push( callback );
  204. if ( this._pendingChanges.length == 1 ) {
  205. while ( this._pendingChanges.length ) {
  206. this._pendingChanges[ 0 ]();
  207. this._pendingChanges.shift();
  208. }
  209. this.fire( 'changesDone' );
  210. }
  211. }
  212. /**
  213. * Returns top-level root by its name.
  214. *
  215. * @param {String|Symbol} name Unique root name.
  216. * @returns {engine.treeModel.RootElement} Root registered under given name.
  217. */
  218. getRoot( name ) {
  219. if ( !this._roots.has( name ) ) {
  220. /**
  221. * Root with specified name does not exist.
  222. *
  223. * @error document-getRoot-root-not-exist
  224. * @param {String} name
  225. */
  226. throw new CKEditorError(
  227. 'document-getRoot-root-not-exist: Root with specified name does not exist.',
  228. { name: name }
  229. );
  230. }
  231. return this._roots.get( name );
  232. }
  233. /**
  234. * Custom toJSON method to solve child-parent circular dependencies.
  235. *
  236. * @returns {Object} Clone of this object with the document property changed to string.
  237. */
  238. toJSON() {
  239. const json = clone( this );
  240. // Due to circular references we need to remove parent reference.
  241. json.selection = '[engine.treeModel.Selection]';
  242. return {};
  243. }
  244. /**
  245. * Returns default root for this document which is either the first root that was added to the the document using
  246. * {@link engine.treeModel.Document#createRoot} or the {@link engine.treeModel.Document#graveyard graveyard root} if
  247. * no other roots were created.
  248. *
  249. * @protected
  250. * @returns {engine.treeModel.RootElement} The default root for this document.
  251. */
  252. _getDefaultRoot() {
  253. for ( let root of this._roots.values() ) {
  254. if ( root !== this.graveyard ) {
  255. return root;
  256. }
  257. }
  258. return this.graveyard;
  259. }
  260. /**
  261. * Fired when document changes by applying an operation.
  262. *
  263. * There are 5 types of change:
  264. *
  265. * * 'insert' when nodes are inserted,
  266. * * 'remove' when nodes are removed,
  267. * * 'reinsert' when remove is undone,
  268. * * 'move' when nodes are moved,
  269. * * 'addAttribute' when attributes are added,
  270. * * 'removeAttribute' when attributes are removed,
  271. * * 'changeAttribute' when attributes change,
  272. * * 'addRootAttribute' when attribute for root is added,
  273. * * 'removeRootAttribute' when attribute for root is removed,
  274. * * 'changeRootAttribute' when attribute for root changes.
  275. *
  276. * @event engine.treeModel.Document.change
  277. * @param {String} type Change type, possible option: 'insert', 'remove', 'reinsert', 'move', 'attribute'.
  278. * @param {Object} data Additional information about the change.
  279. * @param {engine.treeModel.Range} data.range Range in model containing changed nodes. Note that the range state is
  280. * after changes has been done, i.e. for 'remove' the range will be in the {@link engine.treeModel.Document#graveyard graveyard root}.
  281. * This is `undefined` for "...root..." types.
  282. * @param {engine.treeModel.Position} [data.sourcePosition] Change source position. Exists for 'remove', 'reinsert' and 'move'.
  283. * Note that this position state is before changes has been done, i.e. for 'reinsert' the source position will be in the
  284. * {@link engine.treeModel.Document#graveyard graveyard root}.
  285. * @param {String} [data.key] Only for attribute types. Key of changed / inserted / removed attribute.
  286. * @param {*} [data.oldValue] Only for 'removeAttribute', 'removeRootAttribute', 'changeAttribute' or
  287. * 'changeRootAttribute' type.
  288. * @param {*} [data.newValue] Only for 'addAttribute', 'addRootAttribute', 'changeAttribute' or
  289. * 'changeRootAttribute' type.
  290. * @param {engine.treeModel.RootElement} [changeInfo.root] Root element which attributes got changed. This is defined
  291. * only for root types.
  292. * @param {engine.treeModel.Batch} batch A {@link engine.treeModel.Batch batch} of changes which this change is a part of.
  293. */
  294. /**
  295. * Fired when all queued document changes are done. See {@link engine.treeModel.Document#enqueueChanges}.
  296. *
  297. * @event engine.treeModel.Document#changesDone
  298. */
  299. }
  300. mix( Document, EmitterMixin );