8
0

document.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. /**
  2. * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. // Load all basic deltas and transformations, they register themselves, but they need to be imported somewhere.
  6. import deltas from './delta/basic-deltas.js'; // jshint ignore:line
  7. import transformations from './delta/basic-transformations.js'; // jshint ignore:line
  8. import RootElement from './rootelement.js';
  9. import Batch from './batch.js';
  10. import History from './history.js';
  11. import LiveSelection from './liveselection.js';
  12. import Schema from './schema.js';
  13. import Composer from './composer/composer.js';
  14. import clone from '../../utils/lib/lodash/clone.js';
  15. import EmitterMixin from '../../utils/emittermixin.js';
  16. import CKEditorError from '../../utils/ckeditorerror.js';
  17. import mix from '../../utils/mix.js';
  18. const graveyardName = '$graveyard';
  19. /**
  20. * Document tree model describes all editable data in the editor. It may contain multiple
  21. * {@link engine.model.Document#roots root elements}, for example if the editor have multiple editable areas, each area will be
  22. * represented by the separate root.
  23. *
  24. * All changes in the document are done by {@link engine.model.operation.Operation operations}. To create operations in
  25. * a simple way, use the {@link engine.model.Batch} API, for example:
  26. *
  27. * doc.batch().insert( position, nodes ).split( otherPosition );
  28. *
  29. * @see engine.model.Document#batch
  30. *
  31. * @memberOf engine.model
  32. */
  33. export default class Document {
  34. /**
  35. * Creates an empty document instance with no {@link engine.model.Document#roots} (other than
  36. * a {@link engine.model.Document#graveyard graveyard root}).
  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.LiveSelection} engine.model.Document#selection
  53. */
  54. this.selection = new LiveSelection( 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. * Document's history.
  63. *
  64. * **Note:** Be aware that deltas applied to the stored deltas might be removed or changed.
  65. *
  66. * @readonly
  67. * @member {engine.model.History} engine.model.Document#history
  68. */
  69. this.history = new History( this );
  70. /**
  71. * Composer for this document. Set of tools to work with the document.
  72. *
  73. * The features can tune up these tools to better work on their specific cases.
  74. *
  75. * @member {engine.model.composer.Composer} engine.model.Document#composer
  76. */
  77. this.composer = new Composer();
  78. /**
  79. * Array of pending changes. See: {@link engine.model.Document#enqueueChanges}.
  80. *
  81. * @private
  82. * @member {Array.<Function>} engine.model.Document#_pendingChanges
  83. */
  84. this._pendingChanges = [];
  85. /**
  86. * List of roots that are owned and managed by this document. Use {@link engine.model.document#createRoot} and
  87. * {@link engine.model.document#getRoot} to manipulate it.
  88. *
  89. * @readonly
  90. * @protected
  91. * @member {Map} engine.model.Document#roots
  92. */
  93. this._roots = new Map();
  94. // Add events that will update selection attributes.
  95. this.selection.on( 'change:range', () => {
  96. this.selection._updateAttributes();
  97. } );
  98. this.on( 'changesDone', () => {
  99. this.selection._updateAttributes();
  100. } );
  101. // Graveyard tree root. Document always have a graveyard root, which stores removed nodes.
  102. this.createRoot( '$root', graveyardName );
  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. * This is the entry point for all document changes. All changes on the document are done using
  115. * {@link engine.model.operation.Operation operations}. To create operations in the simple way use the
  116. * {@link engine.model.Batch} API available via {@link engine.model.Document#batch} method.
  117. *
  118. * @fires @link engine.model.Document#change
  119. * @param {engine.model.operation.Operation} operation Operation to be applied.
  120. */
  121. applyOperation( operation ) {
  122. if ( operation.baseVersion !== this.version ) {
  123. /**
  124. * Only operations with matching versions can be applied.
  125. *
  126. * @error document-applyOperation-wrong-version
  127. * @param {engine.model.operation.Operation} operation
  128. */
  129. throw new CKEditorError(
  130. 'document-applyOperation-wrong-version: Only operations with matching versions can be applied.',
  131. { operation: operation } );
  132. }
  133. let changes = operation._execute();
  134. this.version++;
  135. this.history.addDelta( operation.delta );
  136. const batch = operation.delta && operation.delta.batch;
  137. if ( changes ) {
  138. // `NoOperation` returns no changes, do not fire event for it.
  139. this.fire( 'change', operation.type, changes, batch );
  140. }
  141. }
  142. /**
  143. * Creates a {@link engine.model.Batch} instance which allows to change the document.
  144. *
  145. * @param {String} [type] Batch type. See {@link engine.model.Batch#type}.
  146. * @returns {engine.model.Batch} Batch instance.
  147. */
  148. batch( type ) {
  149. return new Batch( this, type );
  150. }
  151. /**
  152. * Creates a new top-level root.
  153. *
  154. * @param {String} [elementName='$root'] Element name. Defaults to `'$root'` which also have
  155. * some basic schema defined (`$block`s are allowed inside the `$root`). Make sure to define a proper
  156. * schema if you use a different name.
  157. * @param {String} [rootName='main'] Unique root name.
  158. * @returns {engine.model.RootElement} Created root.
  159. */
  160. createRoot( elementName = '$root', rootName = 'main' ) {
  161. if ( this._roots.has( rootName ) ) {
  162. /**
  163. * Root with specified name already exists.
  164. *
  165. * @error document-createRoot-name-exists
  166. * @param {engine.model.Document} doc
  167. * @param {String} name
  168. */
  169. throw new CKEditorError(
  170. 'document-createRoot-name-exists: Root with specified name already exists.',
  171. { name: rootName }
  172. );
  173. }
  174. const root = new RootElement( this, elementName, rootName );
  175. this._roots.set( rootName, root );
  176. return root;
  177. }
  178. /**
  179. * Removes all events listeners set by document instance.
  180. */
  181. destroy() {
  182. this.selection.destroy();
  183. this.stopListening();
  184. }
  185. /**
  186. * Enqueues document changes. Any changes to be done on document (mostly using {@link engine.model.Document#batch}
  187. * should be placed in the queued callback. If no other plugin is changing document at the moment, the callback will be
  188. * called immediately. Otherwise it will wait for all previously queued changes to finish happening. This way
  189. * queued callback will not interrupt other callbacks.
  190. *
  191. * When all queued changes are done {@link engine.model.Document#changesDone} event is fired.
  192. *
  193. * @fires @link engine.model.Document#changesDone
  194. * @param {Function} callback Callback to enqueue.
  195. */
  196. enqueueChanges( callback ) {
  197. this._pendingChanges.push( callback );
  198. if ( this._pendingChanges.length == 1 ) {
  199. while ( this._pendingChanges.length ) {
  200. this._pendingChanges[ 0 ]();
  201. this._pendingChanges.shift();
  202. }
  203. this.fire( 'changesDone' );
  204. }
  205. }
  206. /**
  207. * Returns top-level root by its name.
  208. *
  209. * @param {String} [name='main'] Unique root name.
  210. * @returns {engine.model.RootElement} Root registered under given name.
  211. */
  212. getRoot( name = 'main' ) {
  213. if ( !this._roots.has( name ) ) {
  214. /**
  215. * Root with specified name does not exist.
  216. *
  217. * @error document-getRoot-root-not-exist
  218. * @param {String} name
  219. */
  220. throw new CKEditorError(
  221. 'document-getRoot-root-not-exist: Root with specified name does not exist.',
  222. { name: name }
  223. );
  224. }
  225. return this._roots.get( name );
  226. }
  227. /**
  228. * Gets names of all roots (without the {@link engine.model.Document#graveyard}).
  229. *
  230. * @readonly
  231. * @type {Iterable.<String>}
  232. */
  233. getRootNames() {
  234. return Array.from( this._roots.keys() ).filter( ( name ) => name != graveyardName );
  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.LiveSelection]';
  254. return json;
  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 );