8
0

document.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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 CompressedHistory from './compressedhistory.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 graveyardName = '$graveyard';
  20. /**
  21. * Document tree model describes all editable data in the editor. It may contain multiple
  22. * {@link engine.model.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.model.operation.Operation operations}. To create operations in
  26. * the simple way use use the {@link engine.model.Batch} API, for example:
  27. *
  28. * doc.batch().insert( position, nodes ).split( otherPosition );
  29. *
  30. * @see engine.model.Document#batch
  31. *
  32. * @memberOf engine.model
  33. */
  34. export default class Document {
  35. /**
  36. * Creates an empty document instance with no {@link engine.model.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.model.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.model.Document#version
  46. */
  47. this.version = 0;
  48. /**
  49. * Selection done on this document.
  50. *
  51. * @readonly
  52. * @member {engine.model.Selection} engine.model.Document#selection
  53. */
  54. this.selection = new Selection( this );
  55. /**
  56. * Schema for this document.
  57. *
  58. * @member {engine.model.Schema} engine.model.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.model.composer.Composer} engine.model.Document#composer
  67. */
  68. this.composer = new Composer();
  69. /**
  70. * Array of pending changes. See: {@link engine.model.Document#enqueueChanges}.
  71. *
  72. * @private
  73. * @member {Array.<Function>} engine.model.Document#_pendingChanges
  74. */
  75. this._pendingChanges = [];
  76. /**
  77. * List of roots that are owned and managed by this document. Use {@link engine.model.document#createRoot} and
  78. * {@link engine.model.document#getRoot} to manipulate it.
  79. *
  80. * @readonly
  81. * @protected
  82. * @member {Map} engine.model.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( '$root', graveyardName );
  94. /**
  95. * Document's history.
  96. *
  97. * This is a compressed document history. It means that stored deltas might be removed or different
  98. * than originally applied deltas.
  99. *
  100. * @readonly
  101. * @member {engine.model.CompressedHistory} engine.model.Document#history
  102. */
  103. this.history = new CompressedHistory( this );
  104. }
  105. /**
  106. * Graveyard tree root. Document always have a graveyard root, which stores removed nodes.
  107. *
  108. * @readonly
  109. * @type {engine.model.RootElement}
  110. */
  111. get graveyard() {
  112. return this.getRoot( graveyardName );
  113. }
  114. /**
  115. * Gets names of all roots (without the {@link engine.model.Document#graveyard}).
  116. *
  117. * @readonly
  118. * @type {Iterable.<String>}
  119. */
  120. get rootNames() {
  121. return Array.from( this._roots.keys() ).filter( ( name ) => name != graveyardName );
  122. }
  123. /**
  124. * This is the entry point for all document changes. All changes on the document are done using
  125. * {@link engine.model.operation.Operation operations}. To create operations in the simple way use the
  126. * {@link engine.model.Batch} API available via {@link engine.model.Document#batch} method.
  127. *
  128. * @fires @link engine.model.Document#change
  129. * @param {engine.model.operation.Operation} operation Operation to be applied.
  130. */
  131. applyOperation( operation ) {
  132. if ( operation.baseVersion !== this.version ) {
  133. /**
  134. * Only operations with matching versions can be applied.
  135. *
  136. * @error document-applyOperation-wrong-version
  137. * @param {engine.model.operation.Operation} operation
  138. */
  139. throw new CKEditorError(
  140. 'document-applyOperation-wrong-version: Only operations with matching versions can be applied.',
  141. { operation: operation } );
  142. }
  143. let changes = operation._execute();
  144. this.version++;
  145. if ( operation.delta ) {
  146. // Right now I can't imagine operations without deltas, but let's be safe.
  147. this.history.addDelta( operation.delta );
  148. }
  149. const batch = operation.delta && operation.delta.batch;
  150. if ( changes ) {
  151. // `NoOperation` returns no changes, do not fire event for it.
  152. this.fire( 'change', operation.type, changes, batch );
  153. }
  154. }
  155. /**
  156. * Creates a {@link engine.model.Batch} instance which allows to change the document.
  157. *
  158. * @param {String} [type] Batch type. See {@link engine.model.Batch#type}.
  159. * @returns {engine.model.Batch} Batch instance.
  160. */
  161. batch( type ) {
  162. return new Batch( this, type );
  163. }
  164. /**
  165. * Creates a new top-level root.
  166. *
  167. * @param {String} [elementName='$root'] Element name. Defaults to `'$root'` which also have
  168. * some basic schema defined (`$block`s are allowed inside the `$root`). Make sure to define a proper
  169. * schema if you use a different name.
  170. * @param {String} [rootName='main'] Unique root name.
  171. * @returns {engine.model.RootElement} Created root.
  172. */
  173. createRoot( elementName = '$root', rootName = 'main' ) {
  174. if ( this._roots.has( rootName ) ) {
  175. /**
  176. * Root with specified name already exists.
  177. *
  178. * @error document-createRoot-name-exists
  179. * @param {engine.model.Document} doc
  180. * @param {String} name
  181. */
  182. throw new CKEditorError(
  183. 'document-createRoot-name-exists: Root with specified name already exists.',
  184. { name: rootName }
  185. );
  186. }
  187. const root = new RootElement( this, elementName, rootName );
  188. this._roots.set( rootName, root );
  189. return root;
  190. }
  191. /**
  192. * Removes all events listeners set by document instance.
  193. */
  194. destroy() {
  195. this.selection.destroy();
  196. this.stopListening();
  197. }
  198. /**
  199. * Enqueues document changes. Any changes to be done on document (mostly using {@link engine.model.Document#batch}
  200. * should be placed in the queued callback. If no other plugin is changing document at the moment, the callback will be
  201. * called immediately. Otherwise it will wait for all previously queued changes to finish happening. This way
  202. * queued callback will not interrupt other callbacks.
  203. *
  204. * When all queued changes are done {@link engine.model.Document#changesDone} event is fired.
  205. *
  206. * @fires @link engine.model.Document#changesDone
  207. * @param {Function} callback Callback to enqueue.
  208. */
  209. enqueueChanges( callback ) {
  210. this._pendingChanges.push( callback );
  211. if ( this._pendingChanges.length == 1 ) {
  212. while ( this._pendingChanges.length ) {
  213. this._pendingChanges[ 0 ]();
  214. this._pendingChanges.shift();
  215. }
  216. this.fire( 'changesDone' );
  217. }
  218. }
  219. /**
  220. * Returns top-level root by its name.
  221. *
  222. * @param {String} [name='main'] Unique root name.
  223. * @returns {engine.model.RootElement} Root registered under given name.
  224. */
  225. getRoot( name = 'main' ) {
  226. if ( !this._roots.has( name ) ) {
  227. /**
  228. * Root with specified name does not exist.
  229. *
  230. * @error document-getRoot-root-not-exist
  231. * @param {String} name
  232. */
  233. throw new CKEditorError(
  234. 'document-getRoot-root-not-exist: Root with specified name does not exist.',
  235. { name: name }
  236. );
  237. }
  238. return this._roots.get( name );
  239. }
  240. /**
  241. * Checks if root with given name is defined.
  242. *
  243. * @param {String} name Name of root to check.
  244. * @returns {Boolean}
  245. */
  246. hasRoot( name ) {
  247. return this._roots.has( name );
  248. }
  249. /**
  250. * Custom toJSON method to solve child-parent circular dependencies.
  251. *
  252. * @returns {Object} Clone of this object with the document property changed to string.
  253. */
  254. toJSON() {
  255. const json = clone( this );
  256. // Due to circular references we need to remove parent reference.
  257. json.selection = '[engine.model.Selection]';
  258. return {};
  259. }
  260. /**
  261. * Returns default root for this document which is either the first root that was added to the the document using
  262. * {@link engine.model.Document#createRoot} or the {@link engine.model.Document#graveyard graveyard root} if
  263. * no other roots were created.
  264. *
  265. * @protected
  266. * @returns {engine.model.RootElement} The default root for this document.
  267. */
  268. _getDefaultRoot() {
  269. for ( let root of this._roots.values() ) {
  270. if ( root !== this.graveyard ) {
  271. return root;
  272. }
  273. }
  274. return this.graveyard;
  275. }
  276. /**
  277. * Fired when document changes by applying an operation.
  278. *
  279. * There are 5 types of change:
  280. *
  281. * * 'insert' when nodes are inserted,
  282. * * 'remove' when nodes are removed,
  283. * * 'reinsert' when remove is undone,
  284. * * 'move' when nodes are moved,
  285. * * 'addAttribute' when attributes are added,
  286. * * 'removeAttribute' when attributes are removed,
  287. * * 'changeAttribute' when attributes change,
  288. * * 'addRootAttribute' when attribute for root is added,
  289. * * 'removeRootAttribute' when attribute for root is removed,
  290. * * 'changeRootAttribute' when attribute for root changes.
  291. *
  292. * @event engine.model.Document#change
  293. * @param {String} type Change type, possible option: 'insert', 'remove', 'reinsert', 'move', 'attribute'.
  294. * @param {Object} data Additional information about the change.
  295. * @param {engine.model.Range} data.range Range in model containing changed nodes. Note that the range state is
  296. * after changes has been done, i.e. for 'remove' the range will be in the {@link engine.model.Document#graveyard graveyard root}.
  297. * This is `undefined` for "...root..." types.
  298. * @param {engine.model.Position} [data.sourcePosition] Change source position. Exists for 'remove', 'reinsert' and 'move'.
  299. * Note that this position state is before changes has been done, i.e. for 'reinsert' the source position will be in the
  300. * {@link engine.model.Document#graveyard graveyard root}.
  301. * @param {String} [data.key] Only for attribute types. Key of changed / inserted / removed attribute.
  302. * @param {*} [data.oldValue] Only for 'removeAttribute', 'removeRootAttribute', 'changeAttribute' or
  303. * 'changeRootAttribute' type.
  304. * @param {*} [data.newValue] Only for 'addAttribute', 'addRootAttribute', 'changeAttribute' or
  305. * 'changeRootAttribute' type.
  306. * @param {engine.model.RootElement} [changeInfo.root] Root element which attributes got changed. This is defined
  307. * only for root types.
  308. * @param {engine.model.Batch} batch A {@link engine.model.Batch batch} of changes which this change is a part of.
  309. */
  310. /**
  311. * Fired when all queued document changes are done. See {@link engine.model.Document#enqueueChanges}.
  312. *
  313. * @event engine.model.Document#changesDone
  314. */
  315. }
  316. mix( Document, EmitterMixin );