document.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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';
  8. import transformations from './delta/basic-transformations.js';
  9. /*jshint unused: false*/
  10. import RootElement from './rootelement.js';
  11. import Batch from './batch.js';
  12. import Selection from './selection.js';
  13. import EmitterMixin from '../emittermixin.js';
  14. import CKEditorError from '../ckeditorerror.js';
  15. import utils from '../utils.js';
  16. import CharacterProxy from './characterproxy.js';
  17. import Schema from './schema.js';
  18. const graveyardSymbol = Symbol( 'graveyard' );
  19. /**
  20. * Document tree model describes all editable data in the editor. It may contain multiple
  21. * {@link core.treeModel.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 core.treeModel.operation.Operation operations}. To create operations in
  25. * the simple way use use the {@link core.treeModel.Batch} API, for example:
  26. *
  27. * doc.batch().insert( position, nodes ).split( otherPosition );
  28. *
  29. * @see core.treeModel.Document#batch
  30. *
  31. * @memberOf core.treeModel
  32. */
  33. export default class Document {
  34. /**
  35. * Creates an empty document instance with no {@link core.treeModel.Document#roots} (other than graveyard).
  36. */
  37. constructor() {
  38. /**
  39. * List of roots that are owned and managed by this document.
  40. *
  41. * @readonly
  42. * @member {Map} core.treeModel.Document#roots
  43. */
  44. this.roots = new Map();
  45. /**
  46. * Document version. It starts from `0` and every operation increases the version number. It is used to ensure that
  47. * operations are applied on the proper document version. If the {@link core.treeModel.operation.Operation#baseVersion} will
  48. * not match document version the {@link document-applyOperation-wrong-version} error is thrown.
  49. *
  50. * @readonly
  51. * @member {Number} core.treeModel.Document#version
  52. */
  53. this.version = 0;
  54. /**
  55. * Array of pending changes. See: {@link core.treeModel.Document#enqueueChanges}.
  56. *
  57. * @private
  58. * @member {Array.<Function>} core.treeModel.Document#_pendingChanges
  59. */
  60. this._pendingChanges = [];
  61. /**
  62. * Selection done on this document.
  63. *
  64. * @readonly
  65. * @member {core.treeModel.Selection} core.treeModel.Document#selection
  66. */
  67. this.selection = new Selection();
  68. /**
  69. * Schema for this document.
  70. *
  71. * @member {core.treeModel.Schema} core.treeModel.Document#schema
  72. */
  73. this.schema = new Schema();
  74. // Add events that will update selection attributes.
  75. this.selection.on( 'update', () => {
  76. this._updateSelectionAttributes();
  77. } );
  78. this.on( 'changesDone', () => {
  79. this._updateSelectionAttributes();
  80. } );
  81. // Graveyard tree root. Document always have a graveyard root, which stores removed nodes.
  82. this.createRoot( graveyardSymbol );
  83. }
  84. /**
  85. * Graveyard tree root. Document always have a graveyard root, which stores removed nodes.
  86. *
  87. * @readonly
  88. * @type {core.treeModel.RootElement}
  89. */
  90. get graveyard() {
  91. return this.getRoot( graveyardSymbol );
  92. }
  93. /**
  94. * This is the entry point for all document changes. All changes on the document are done using
  95. * {@link core.treeModel.operation.Operation operations}. To create operations in the simple way use the
  96. * {@link core.treeModel.Batch} API available via {@link core.treeModel.Document#batch} method.
  97. *
  98. * This method calls {@link core.treeModel.Document#change} event.
  99. *
  100. * @param {core.treeModel.operation.Operation} operation Operation to be applied.
  101. */
  102. applyOperation( operation ) {
  103. if ( operation.baseVersion !== this.version ) {
  104. /**
  105. * Only operations with matching versions can be applied.
  106. *
  107. * @error document-applyOperation-wrong-version
  108. * @param {core.treeModel.operation.Operation} operation
  109. */
  110. throw new CKEditorError(
  111. 'document-applyOperation-wrong-version: Only operations with matching versions can be applied.',
  112. { operation: operation } );
  113. }
  114. let changes = operation._execute();
  115. this.version++;
  116. const batch = operation.delta && operation.delta.batch;
  117. this.fire( 'change', operation.type, changes, batch );
  118. }
  119. /**
  120. * Creates a {@link core.treeModel.Batch} instance which allows to change the document.
  121. *
  122. * @returns {core.treeModel.Batch} Batch instance.
  123. */
  124. batch() {
  125. return new Batch( this );
  126. }
  127. /**
  128. * Creates a new top-level root.
  129. *
  130. * @param {String|Symbol} id Unique root id.
  131. * @param {String|Symbol} name Unique root name.
  132. * @returns {core.treeModel.RootElement} Created root.
  133. */
  134. createRoot( id, name ) {
  135. if ( this.roots.has( id ) ) {
  136. /**
  137. * Root with specified id already exists.
  138. *
  139. * @error document-createRoot-id-exists
  140. * @param {core.treeModel.Document} doc
  141. * @param {String} id
  142. */
  143. throw new CKEditorError(
  144. 'document-createRoot-id-exists: Root with specified id already exists.',
  145. { id: id }
  146. );
  147. }
  148. const root = new RootElement( this, name || id );
  149. this.roots.set( id, root );
  150. return root;
  151. }
  152. /**
  153. * Enqueue a callback with document changes. Any changes to be done on document (mostly using {@link core.treeModel.Document#batch}
  154. * should be placed in the queued callback. If no other plugin is changing document at the moment, the callback will be
  155. * called immediately. Otherwise it will wait for all previously queued changes to finish happening. This way
  156. * queued callback will not interrupt other callbacks.
  157. *
  158. * When all queued changes are done {@link core.treeModel.Document.changesDone} event is fired.
  159. *
  160. * @fires {@link core.treeModel.Document.changesDone}
  161. * @param {Function} callback Callback to enqueue.
  162. */
  163. enqueueChanges( callback ) {
  164. this._pendingChanges.push( callback );
  165. if ( this._pendingChanges.length == 1 ) {
  166. while ( this._pendingChanges.length ) {
  167. this._pendingChanges[ 0 ]();
  168. this._pendingChanges.shift();
  169. }
  170. this.fire( 'changesDone' );
  171. }
  172. }
  173. /**
  174. * Returns top-level root by it's id.
  175. *
  176. * @param {String|Symbol} id Unique root id.
  177. * @returns {core.treeModel.RootElement} Root registered under given id.
  178. */
  179. getRoot( id ) {
  180. if ( !this.roots.has( id ) ) {
  181. /**
  182. * Root with specified id does not exist.
  183. *
  184. * @error document-getRoot-root-not-exist
  185. * @param {String} id
  186. */
  187. throw new CKEditorError(
  188. 'document-getRoot-root-not-exist: Root with specified id does not exist.',
  189. { id: id }
  190. );
  191. }
  192. return this.roots.get( id );
  193. }
  194. /**
  195. * Updates this document's {@link core.treeModel.Document#selection selection} attributes. Should be fired
  196. * whenever selection attributes might have changed (i.e. when selection ranges change or document is changed).
  197. *
  198. * @private
  199. */
  200. _updateSelectionAttributes() {
  201. if ( !this.selection.hasAnyRange ) {
  202. this.selection.clearAttributes();
  203. } else {
  204. const position = this.selection.getFirstPosition();
  205. const positionParent = position.parent;
  206. let attrs = null;
  207. if ( this.selection.isCollapsed === false ) {
  208. // 1. If selection is a range...
  209. const range = this.selection.getFirstRange();
  210. // ...look for a first character node in that range and take attributes from it.
  211. for ( let item of range ) {
  212. if ( item.type == 'TEXT' ) {
  213. attrs = item.item.getAttributes();
  214. break;
  215. }
  216. }
  217. }
  218. // 2. If the selection is a caret or the range does not contain a character node...
  219. if ( !attrs && this.selection.isCollapsed === true ) {
  220. const nodeBefore = positionParent.getChild( position.offset - 1 );
  221. const nodeAfter = positionParent.getChild( position.offset );
  222. // ...look at the node before caret and take attributes from it if it is a character node.
  223. attrs = getAttrsIfCharacter( nodeBefore );
  224. // 3. If not, look at the node after caret...
  225. if ( !attrs ) {
  226. attrs = getAttrsIfCharacter( nodeAfter );
  227. }
  228. // 4. If not, try to find the first character on the left, that is in the same node.
  229. if ( !attrs ) {
  230. let node = nodeBefore;
  231. while ( node && !attrs ) {
  232. node = node.previousSibling;
  233. attrs = getAttrsIfCharacter( node );
  234. }
  235. }
  236. // 5. If not found, try to find the first character on the right, that is in the same node.
  237. if ( !attrs ) {
  238. let node = nodeAfter;
  239. while ( node && !attrs ) {
  240. node = node.nextSibling;
  241. attrs = getAttrsIfCharacter( node );
  242. }
  243. }
  244. // 6. If not found, selection should retrieve attributes from parent.
  245. if ( !attrs ) {
  246. attrs = Selection.filterStoreAttributes( positionParent.getAttributes() );
  247. }
  248. }
  249. if ( attrs ) {
  250. this.selection.setAttributesTo( attrs );
  251. } else {
  252. this.selection.clearAttributes();
  253. }
  254. }
  255. function getAttrsIfCharacter( node ) {
  256. if ( node instanceof CharacterProxy ) {
  257. return node.getAttributes();
  258. }
  259. return null;
  260. }
  261. }
  262. /**
  263. * Fired when document changes by applying an operation.
  264. *
  265. * There are 5 types of change:
  266. *
  267. * * 'insert' when nodes are inserted,
  268. * * 'remove' when nodes are removed,
  269. * * 'reinsert' when remove is undone,
  270. * * 'move' when nodes are moved,
  271. * * 'attribute' when attributes change.
  272. *
  273. * Change event is fired after the change is done. This means that any ranges or positions passed in
  274. * `changeInfo` are referencing nodes and paths in updated tree model.
  275. *
  276. * @event core.treeModel.Document#change
  277. * @param {String} type Change type, possible option: `'insert'`, `'remove'`, `'reinsert'`, `'move'`, `'attribute'`.
  278. * @param {Object} changeInfo Additional information about the change.
  279. * @param {core.treeModel.Range} changeInfo.range Range containing changed nodes. Note that for `'remove'` the range will be in the
  280. * {@link core.treeModel.Document#graveyard graveyard root}.
  281. * @param {core.treeModel.Position} [changeInfo.sourcePosition] Change source position. Exists for `'remove'`, `'reinsert'` and `'move'`.
  282. * Note that for 'reinsert' the source position will be in the {@link core.treeModel.Document#graveyard graveyard root}.
  283. * @param {String} [changeInfo.key] Only for `'attribute'` type. Key of changed / inserted / removed attribute.
  284. * @param {*} [changeInfo.oldValue] Only for `'attribute'` type. If the type is `'attribute'` and `oldValue`
  285. * is `undefined` it means that new attribute was inserted. Otherwise it contains changed or removed attribute value.
  286. * @param {*} [changeInfo.newValue] Only for `'attribute'` type. If the type is `'attribute'` and `newValue`
  287. * is `undefined` it means that attribute was removed. Otherwise it contains changed or inserted attribute value.
  288. * @param {core.treeModel.Batch} batch A batch of changes which this change is a part of.
  289. */
  290. /**
  291. * Fired when all queued document changes are done. See {@link core.treeModel.Document#enqueueChanges}.
  292. *
  293. * @event core.treeModel.Document#changesDone
  294. */
  295. }
  296. utils.mix( Document, EmitterMixin );