8
0

document.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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 LiveSelection from './liveselection.js';
  13. import Schema from './schema.js';
  14. import Composer from './composer/composer.js';
  15. import clone from '../../utils/lib/lodash/clone.js';
  16. import EmitterMixin from '../../utils/emittermixin.js';
  17. import CKEditorError from '../../utils/ckeditorerror.js';
  18. import mix from '../../utils/mix.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. * a simple way, 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
  37. * a {@link engine.model.Document#graveyard graveyard root}).
  38. */
  39. constructor() {
  40. /**
  41. * Document version. It starts from `0` and every operation increases the version number. It is used to ensure that
  42. * operations are applied on the proper document version. If the {@link engine.model.operation.Operation#baseVersion} will
  43. * not match document version the {@link document-applyOperation-wrong-version} error is thrown.
  44. *
  45. * @readonly
  46. * @member {Number} engine.model.Document#version
  47. */
  48. this.version = 0;
  49. /**
  50. * Selection done on this document.
  51. *
  52. * @readonly
  53. * @member {engine.model.LiveSelection} engine.model.Document#selection
  54. */
  55. this.selection = new LiveSelection( this );
  56. /**
  57. * Schema for this document.
  58. *
  59. * @member {engine.model.Schema} engine.model.Document#schema
  60. */
  61. this.schema = new Schema();
  62. /**
  63. * Composer for this document. Set of tools to work with the document.
  64. *
  65. * The features can tune up these tools to better work on their specific cases.
  66. *
  67. * @member {engine.model.composer.Composer} engine.model.Document#composer
  68. */
  69. this.composer = new Composer();
  70. /**
  71. * Array of pending changes. See: {@link engine.model.Document#enqueueChanges}.
  72. *
  73. * @private
  74. * @member {Array.<Function>} engine.model.Document#_pendingChanges
  75. */
  76. this._pendingChanges = [];
  77. /**
  78. * List of roots that are owned and managed by this document. Use {@link engine.model.document#createRoot} and
  79. * {@link engine.model.document#getRoot} to manipulate it.
  80. *
  81. * @readonly
  82. * @protected
  83. * @member {Map} engine.model.Document#roots
  84. */
  85. this._roots = new Map();
  86. // Add events that will update selection attributes.
  87. this.selection.on( 'change:range', () => {
  88. this.selection._updateAttributes();
  89. } );
  90. this.on( 'changesDone', () => {
  91. this.selection._updateAttributes();
  92. } );
  93. // Graveyard tree root. Document always have a graveyard root, which stores removed nodes.
  94. this.createRoot( '$root', graveyardName );
  95. /**
  96. * Document's history.
  97. *
  98. * **Note:** Be aware that deltas applied to the stored deltas might be removed or changed.
  99. *
  100. * @readonly
  101. * @member {engine.model.History} engine.model.Document#history
  102. */
  103. this.history = new History( 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. this.history.addDelta( operation.delta );
  146. const batch = operation.delta && operation.delta.batch;
  147. if ( changes ) {
  148. // `NoOperation` returns no changes, do not fire event for it.
  149. this.fire( 'change', operation.type, changes, batch );
  150. }
  151. }
  152. /**
  153. * Creates a {@link engine.model.Batch} instance which allows to change the document.
  154. *
  155. * @param {String} [type] Batch type. See {@link engine.model.Batch#type}.
  156. * @returns {engine.model.Batch} Batch instance.
  157. */
  158. batch( type ) {
  159. return new Batch( this, type );
  160. }
  161. /**
  162. * Creates a new top-level root.
  163. *
  164. * @param {String} [elementName='$root'] Element name. Defaults to `'$root'` which also have
  165. * some basic schema defined (`$block`s are allowed inside the `$root`). Make sure to define a proper
  166. * schema if you use a different name.
  167. * @param {String} [rootName='main'] Unique root name.
  168. * @returns {engine.model.RootElement} Created root.
  169. */
  170. createRoot( elementName = '$root', rootName = 'main' ) {
  171. if ( this._roots.has( rootName ) ) {
  172. /**
  173. * Root with specified name already exists.
  174. *
  175. * @error document-createRoot-name-exists
  176. * @param {engine.model.Document} doc
  177. * @param {String} name
  178. */
  179. throw new CKEditorError(
  180. 'document-createRoot-name-exists: Root with specified name already exists.',
  181. { name: rootName }
  182. );
  183. }
  184. const root = new RootElement( this, elementName, rootName );
  185. this._roots.set( rootName, root );
  186. return root;
  187. }
  188. /**
  189. * Removes all events listeners set by document instance.
  190. */
  191. destroy() {
  192. this.selection.destroy();
  193. this.stopListening();
  194. }
  195. /**
  196. * Enqueues document changes. Any changes to be done on document (mostly using {@link engine.model.Document#batch}
  197. * should be placed in the queued callback. If no other plugin is changing document at the moment, the callback will be
  198. * called immediately. Otherwise it will wait for all previously queued changes to finish happening. This way
  199. * queued callback will not interrupt other callbacks.
  200. *
  201. * When all queued changes are done {@link engine.model.Document#changesDone} event is fired.
  202. *
  203. * @fires @link engine.model.Document#changesDone
  204. * @param {Function} callback Callback to enqueue.
  205. */
  206. enqueueChanges( callback ) {
  207. this._pendingChanges.push( callback );
  208. if ( this._pendingChanges.length == 1 ) {
  209. while ( this._pendingChanges.length ) {
  210. this._pendingChanges[ 0 ]();
  211. this._pendingChanges.shift();
  212. }
  213. this.fire( 'changesDone' );
  214. }
  215. }
  216. /**
  217. * Returns top-level root by its name.
  218. *
  219. * @param {String} [name='main'] Unique root name.
  220. * @returns {engine.model.RootElement} Root registered under given name.
  221. */
  222. getRoot( name = 'main' ) {
  223. if ( !this._roots.has( name ) ) {
  224. /**
  225. * Root with specified name does not exist.
  226. *
  227. * @error document-getRoot-root-not-exist
  228. * @param {String} name
  229. */
  230. throw new CKEditorError(
  231. 'document-getRoot-root-not-exist: Root with specified name does not exist.',
  232. { name: name }
  233. );
  234. }
  235. return this._roots.get( name );
  236. }
  237. /**
  238. * Checks if root with given name is defined.
  239. *
  240. * @param {String} name Name of root to check.
  241. * @returns {Boolean}
  242. */
  243. hasRoot( name ) {
  244. return this._roots.has( name );
  245. }
  246. /**
  247. * Custom toJSON method to solve child-parent circular dependencies.
  248. *
  249. * @returns {Object} Clone of this object with the document property changed to string.
  250. */
  251. toJSON() {
  252. const json = clone( this );
  253. // Due to circular references we need to remove parent reference.
  254. json.selection = '[engine.model.LiveSelection]';
  255. return json;
  256. }
  257. /**
  258. * Returns default root for this document which is either the first root that was added to the the document using
  259. * {@link engine.model.Document#createRoot} or the {@link engine.model.Document#graveyard graveyard root} if
  260. * no other roots were created.
  261. *
  262. * @protected
  263. * @returns {engine.model.RootElement} The default root for this document.
  264. */
  265. _getDefaultRoot() {
  266. for ( let root of this._roots.values() ) {
  267. if ( root !== this.graveyard ) {
  268. return root;
  269. }
  270. }
  271. return this.graveyard;
  272. }
  273. /**
  274. * Fired when document changes by applying an operation.
  275. *
  276. * There are 5 types of change:
  277. *
  278. * * 'insert' when nodes are inserted,
  279. * * 'remove' when nodes are removed,
  280. * * 'reinsert' when remove is undone,
  281. * * 'move' when nodes are moved,
  282. * * 'addAttribute' when attributes are added,
  283. * * 'removeAttribute' when attributes are removed,
  284. * * 'changeAttribute' when attributes change,
  285. * * 'addRootAttribute' when attribute for root is added,
  286. * * 'removeRootAttribute' when attribute for root is removed,
  287. * * 'changeRootAttribute' when attribute for root changes.
  288. *
  289. * @event engine.model.Document#change
  290. * @param {String} type Change type, possible option: 'insert', 'remove', 'reinsert', 'move', 'attribute'.
  291. * @param {Object} data Additional information about the change.
  292. * @param {engine.model.Range} data.range Range in model containing changed nodes. Note that the range state is
  293. * after changes has been done, i.e. for 'remove' the range will be in the {@link engine.model.Document#graveyard graveyard root}.
  294. * This is `undefined` for "...root..." types.
  295. * @param {engine.model.Position} [data.sourcePosition] Change source position. Exists for 'remove', 'reinsert' and 'move'.
  296. * Note that this position state is before changes has been done, i.e. for 'reinsert' the source position will be in the
  297. * {@link engine.model.Document#graveyard graveyard root}.
  298. * @param {String} [data.key] Only for attribute types. Key of changed / inserted / removed attribute.
  299. * @param {*} [data.oldValue] Only for 'removeAttribute', 'removeRootAttribute', 'changeAttribute' or
  300. * 'changeRootAttribute' type.
  301. * @param {*} [data.newValue] Only for 'addAttribute', 'addRootAttribute', 'changeAttribute' or
  302. * 'changeRootAttribute' type.
  303. * @param {engine.model.RootElement} [changeInfo.root] Root element which attributes got changed. This is defined
  304. * only for root types.
  305. * @param {engine.model.Batch} batch A {@link engine.model.Batch batch} of changes which this change is a part of.
  306. */
  307. /**
  308. * Fired when all queued document changes are done. See {@link engine.model.Document#enqueueChanges}.
  309. *
  310. * @event engine.model.Document#changesDone
  311. */
  312. }
  313. mix( Document, EmitterMixin );