8
0

document.js 11 KB

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