differ.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/model/differ
  7. */
  8. import Position from './position';
  9. import Range from './range';
  10. /**
  11. * Calculates the difference between two model states.
  12. *
  13. * Receives operations that are to be applied on the model document. Marks parts of the model document tree which
  14. * are changed and saves the state of these elements before the change. Then, it compares saved elements with the
  15. * changed elements, after all changes are applied on the model document. Calculates the diff between saved
  16. * elements and new ones and returns a change set.
  17. */
  18. export default class Differ {
  19. /**
  20. * Creates a `Differ` instance.
  21. *
  22. * @param {module:engine/model/markercollection~MarkerCollection} markerCollection Model's marker collection.
  23. */
  24. constructor( markerCollection ) {
  25. /**
  26. * Reference to the model's marker collection.
  27. *
  28. * @private
  29. * @type {module:engine/model/markercollection~MarkerCollection}
  30. */
  31. this._markerCollection = markerCollection;
  32. /**
  33. * A map that stores changes that happened in a given element.
  34. *
  35. * The keys of the map are references to the model elements.
  36. * The values of the map are arrays with changes that were done on this element.
  37. *
  38. * @private
  39. * @type {Map}
  40. */
  41. this._changesInElement = new Map();
  42. /**
  43. * A map that stores "element's children snapshots". A snapshot is representing children of a given element before
  44. * the first change was applied on that element. Snapshot items are objects with two properties: `name`,
  45. * containing the element name (or `'$text'` for a text node) and `attributes` which is a map of the node's attributes.
  46. *
  47. * @private
  48. * @type {Map}
  49. */
  50. this._elementSnapshots = new Map();
  51. /**
  52. * A map that stores all changed markers.
  53. *
  54. * The keys of the map are marker names.
  55. * The values of the map are objects with the `oldRange` and `newRange` properties. They store the marker range
  56. * state before and after the change.
  57. *
  58. * @private
  59. * @type {Map}
  60. */
  61. this._changedMarkers = new Map();
  62. /**
  63. * Stores the number of changes that were processed. Used to order the changes chronologically. It is important
  64. * when changes are sorted.
  65. *
  66. * @private
  67. * @type {Number}
  68. */
  69. this._changeCount = 0;
  70. /**
  71. * For efficiency purposes, `Differ` stores the change set returned by the differ after {@link #getChanges} call.
  72. * Cache is reset each time a new operation is buffered. If the cache has not been reset, {@link #getChanges} will
  73. * return the cached value instead of calculating it again.
  74. *
  75. * This property stores those changes that did not take place in graveyard root.
  76. *
  77. * @private
  78. * @type {Array.<Object>|null}
  79. */
  80. this._cachedChanges = null;
  81. /**
  82. * For efficiency purposes, `Differ` stores the change set returned by the differ after the {@link #getChanges} call.
  83. * The cache is reset each time a new operation is buffered. If the cache has not been reset, {@link #getChanges} will
  84. * return the cached value instead of calculating it again.
  85. *
  86. * This property stores all changes evaluated by `Differ`, including those that took place in the graveyard.
  87. *
  88. * @private
  89. * @type {Array.<Object>|null}
  90. */
  91. this._cachedChangesWithGraveyard = null;
  92. }
  93. /**
  94. * Informs whether there are any changes buffered in `Differ`.
  95. *
  96. * @readonly
  97. * @type {Boolean}
  98. */
  99. get isEmpty() {
  100. return this._changesInElement.size == 0 && this._changedMarkers.size == 0;
  101. }
  102. /**
  103. * Buffers the given operation. An operation has to be buffered before it is executed.
  104. *
  105. * Operation type is checked and it is checked which nodes it will affect. These nodes are then stored in `Differ`
  106. * in the state before the operation is executed.
  107. *
  108. * @param {module:engine/model/operation/operation~Operation} operation An operation to buffer.
  109. */
  110. bufferOperation( operation ) {
  111. // Below we take an operation, check its type, then use its parameters in marking (private) methods.
  112. // The general rule is to not mark elements inside inserted element. All inserted elements are re-rendered.
  113. // Marking changes in them would cause a "double" changing then.
  114. //
  115. switch ( operation.type ) {
  116. case 'insert': {
  117. if ( this._isInInsertedElement( operation.position.parent ) ) {
  118. return;
  119. }
  120. this._markInsert( operation.position.parent, operation.position.offset, operation.nodes.maxOffset );
  121. break;
  122. }
  123. case 'addAttribute':
  124. case 'removeAttribute':
  125. case 'changeAttribute': {
  126. for ( const item of operation.range.getItems() ) {
  127. if ( this._isInInsertedElement( item.parent ) ) {
  128. continue;
  129. }
  130. this._markAttribute( item );
  131. }
  132. break;
  133. }
  134. case 'remove':
  135. case 'move':
  136. case 'reinsert': {
  137. const sourceParentInserted = this._isInInsertedElement( operation.sourcePosition.parent );
  138. const targetParentInserted = this._isInInsertedElement( operation.targetPosition.parent );
  139. if ( !sourceParentInserted ) {
  140. this._markRemove( operation.sourcePosition.parent, operation.sourcePosition.offset, operation.howMany );
  141. }
  142. if ( !targetParentInserted ) {
  143. this._markInsert( operation.targetPosition.parent, operation.getMovedRangeStart().offset, operation.howMany );
  144. }
  145. break;
  146. }
  147. case 'rename': {
  148. if ( this._isInInsertedElement( operation.position.parent ) ) {
  149. return;
  150. }
  151. this._markRemove( operation.position.parent, operation.position.offset, 1 );
  152. this._markInsert( operation.position.parent, operation.position.offset, 1 );
  153. const range = Range.createFromPositionAndShift( operation.position, 1 );
  154. for ( const marker of this._markerCollection.getMarkersIntersectingRange( range ) ) {
  155. const markerRange = marker.getRange();
  156. this.bufferMarkerChange( marker.name, markerRange, markerRange, marker.affectsData );
  157. }
  158. break;
  159. }
  160. case 'split': {
  161. const splitElement = operation.splitPosition.parent;
  162. // Mark that children of the split element were removed.
  163. if ( !this._isInInsertedElement( splitElement ) ) {
  164. this._markRemove( splitElement, operation.splitPosition.offset, operation.howMany );
  165. }
  166. // Mark that the new element (split copy) was inserted.
  167. if ( !this._isInInsertedElement( operation.insertionPosition.parent ) ) {
  168. this._markInsert( operation.insertionPosition.parent, operation.insertionPosition.offset, 1 );
  169. }
  170. // If the split took the element from the graveyard, mark that the element from the graveyard was removed.
  171. if ( operation.graveyardPosition ) {
  172. this._markRemove( operation.graveyardPosition.parent, operation.graveyardPosition.offset, 1 );
  173. }
  174. break;
  175. }
  176. case 'merge': {
  177. // Mark that the merged element was removed.
  178. const mergedElement = operation.sourcePosition.parent;
  179. if ( !this._isInInsertedElement( mergedElement.parent ) ) {
  180. this._markRemove( mergedElement.parent, mergedElement.startOffset, 1 );
  181. }
  182. // Mark that the merged element was inserted into graveyard.
  183. const graveyardParent = operation.graveyardPosition.parent;
  184. this._markInsert( graveyardParent, operation.graveyardPosition.offset, 1 );
  185. // Mark that children of merged element were inserted at new parent.
  186. const mergedIntoElement = operation.targetPosition.parent;
  187. if ( !this._isInInsertedElement( mergedIntoElement ) ) {
  188. this._markInsert( mergedIntoElement, operation.targetPosition.offset, mergedElement.maxOffset );
  189. }
  190. break;
  191. }
  192. }
  193. // Clear cache after each buffered operation as it is no longer valid.
  194. this._cachedChanges = null;
  195. }
  196. /**
  197. * Buffers a marker change.
  198. *
  199. * @param {String} markerName The name of the marker that changed.
  200. * @param {module:engine/model/range~Range|null} oldRange Marker range before the change or `null` if the marker has just
  201. * been created.
  202. * @param {module:engine/model/range~Range|null} newRange Marker range after the change or `null` if the marker was removed.
  203. * @param {Boolean} affectsData Flag indicating whether marker affects the editor data.
  204. */
  205. bufferMarkerChange( markerName, oldRange, newRange, affectsData ) {
  206. const buffered = this._changedMarkers.get( markerName );
  207. if ( !buffered ) {
  208. this._changedMarkers.set( markerName, {
  209. oldRange,
  210. newRange,
  211. affectsData
  212. } );
  213. } else {
  214. buffered.newRange = newRange;
  215. buffered.affectsData = affectsData;
  216. if ( buffered.oldRange == null && buffered.newRange == null ) {
  217. // The marker is going to be removed (`newRange == null`) but it did not exist before the first buffered change
  218. // (`buffered.oldRange == null`). In this case, do not keep the marker in buffer at all.
  219. this._changedMarkers.delete( markerName );
  220. }
  221. }
  222. }
  223. /**
  224. * Returns all markers that should be removed as a result of buffered changes.
  225. *
  226. * @returns {Array.<Object>} Markers to remove. Each array item is an object containing the `name` and `range` properties.
  227. */
  228. getMarkersToRemove() {
  229. const result = [];
  230. for ( const [ name, change ] of this._changedMarkers ) {
  231. if ( change.oldRange != null ) {
  232. result.push( { name, range: change.oldRange } );
  233. }
  234. }
  235. return result;
  236. }
  237. /**
  238. * Returns all markers which should be added as a result of buffered changes.
  239. *
  240. * @returns {Array.<Object>} Markers to add. Each array item is an object containing the `name` and `range` properties.
  241. */
  242. getMarkersToAdd() {
  243. const result = [];
  244. for ( const [ name, change ] of this._changedMarkers ) {
  245. if ( change.newRange != null ) {
  246. result.push( { name, range: change.newRange } );
  247. }
  248. }
  249. return result;
  250. }
  251. /**
  252. * Checks whether some of the buffered changes affect the editor data.
  253. *
  254. * Types of changes which affect the editor data:
  255. *
  256. * * model structure changes,
  257. * * attribute changes,
  258. * * changes of markers which were defined as `affectingData`.
  259. *
  260. * @returns {Boolean}
  261. */
  262. hasDataChanges() {
  263. for ( const [ , change ] of this._changedMarkers ) {
  264. if ( change.affectsData ) {
  265. return true;
  266. }
  267. }
  268. // If markers do not affect the data, check whether there are some changes in elements.
  269. return this._changesInElement.size > 0;
  270. }
  271. /**
  272. * Calculates the diff between the old model tree state (the state before the first buffered operations since the last {@link #reset}
  273. * call) and the new model tree state (actual one). It should be called after all buffered operations are executed.
  274. *
  275. * The diff set is returned as an array of diff items, each describing a change done on the model. The items are sorted by
  276. * the position on which the change happened. If a position {@link module:engine/model/position~Position#isBefore is before}
  277. * another one, it will be on an earlier index in the diff set.
  278. *
  279. * Because calculating the diff is a costly operation, the result is cached. If no new operation was buffered since the
  280. * previous {@link #getChanges} call, the next call will return the cached value.
  281. *
  282. * @param {Object} options Additional options.
  283. * @param {Boolean} [options.includeChangesInGraveyard=false] If set to `true`, also changes that happened
  284. * in the graveyard root will be returned. By default, changes in the graveyard root are not returned.
  285. * @returns {Array.<Object>} Diff between the old and the new model tree state.
  286. */
  287. getChanges( options = { includeChangesInGraveyard: false } ) {
  288. // If there are cached changes, just return them instead of calculating changes again.
  289. if ( this._cachedChanges ) {
  290. if ( options.includeChangesInGraveyard ) {
  291. return this._cachedChangesWithGraveyard.slice();
  292. } else {
  293. return this._cachedChanges.slice();
  294. }
  295. }
  296. // Will contain returned results.
  297. const diffSet = [];
  298. // Check all changed elements.
  299. for ( const element of this._changesInElement.keys() ) {
  300. // Get changes for this element and sort them.
  301. const changes = this._changesInElement.get( element ).sort( ( a, b ) => {
  302. if ( a.offset === b.offset ) {
  303. if ( a.type != b.type ) {
  304. // If there are multiple changes at the same position, "remove" change should be first.
  305. // If the order is different, for example, we would first add some nodes and then removed them
  306. // (instead of the nodes that we should remove).
  307. return a.type == 'remove' ? -1 : 1;
  308. }
  309. return 0;
  310. }
  311. return a.offset < b.offset ? -1 : 1;
  312. } );
  313. // Get children of this element before any change was applied on it.
  314. const snapshotChildren = this._elementSnapshots.get( element );
  315. // Get snapshot of current element's children.
  316. const elementChildren = _getChildrenSnapshot( element.getChildren() );
  317. // Generate actions basing on changes done on element.
  318. const actions = _generateActionsFromChanges( snapshotChildren.length, changes );
  319. let i = 0; // Iterator in `elementChildren` array -- iterates through current children of element.
  320. let j = 0; // Iterator in `snapshotChildren` array -- iterates through old children of element.
  321. // Process every action.
  322. for ( const action of actions ) {
  323. if ( action === 'i' ) {
  324. // Generate diff item for this element and insert it into the diff set.
  325. diffSet.push( this._getInsertDiff( element, i, elementChildren[ i ].name ) );
  326. i++;
  327. } else if ( action === 'r' ) {
  328. // Generate diff item for this element and insert it into the diff set.
  329. diffSet.push( this._getRemoveDiff( element, i, snapshotChildren[ j ].name ) );
  330. j++;
  331. } else if ( action === 'a' ) {
  332. // Take attributes from saved and current children.
  333. const elementAttributes = elementChildren[ i ].attributes;
  334. const snapshotAttributes = snapshotChildren[ j ].attributes;
  335. let range;
  336. if ( elementChildren[ i ].name == '$text' ) {
  337. range = Range.createFromParentsAndOffsets( element, i, element, i + 1 );
  338. } else {
  339. const index = element.offsetToIndex( i );
  340. range = Range.createFromParentsAndOffsets( element, i, element.getChild( index ), 0 );
  341. }
  342. // Generate diff items for this change (there might be multiple attributes changed and
  343. // there is a single diff for each of them) and insert them into the diff set.
  344. diffSet.push( ...this._getAttributesDiff( range, snapshotAttributes, elementAttributes ) );
  345. i++;
  346. j++;
  347. } else {
  348. // `action` is 'equal'. Child not changed.
  349. i++;
  350. j++;
  351. }
  352. }
  353. }
  354. // Then, sort the changes by the position (change at position before other changes is first).
  355. diffSet.sort( ( a, b ) => {
  356. // If the change is in different root, we don't care much, but we'd like to have all changes in given
  357. // root "together" in the array. So let's just sort them by the root name. It does not matter which root
  358. // will be processed first.
  359. if ( a.position.root != b.position.root ) {
  360. return a.position.root.rootName < b.position.root.rootName ? -1 : 1;
  361. }
  362. // If change happens at the same position...
  363. if ( a.position.isEqual( b.position ) ) {
  364. // Keep chronological order of operations.
  365. return a.changeCount - b.changeCount;
  366. }
  367. // If positions differ, position "on the left" should be earlier in the result.
  368. return a.position.isBefore( b.position ) ? -1 : 1;
  369. } );
  370. // Glue together multiple changes (mostly on text nodes).
  371. for ( let i = 1; i < diffSet.length; i++ ) {
  372. const prevDiff = diffSet[ i - 1 ];
  373. const thisDiff = diffSet[ i ];
  374. // Glue remove changes if they happen on text on same position.
  375. const isConsecutiveTextRemove =
  376. prevDiff.type == 'remove' && thisDiff.type == 'remove' &&
  377. prevDiff.name == '$text' && thisDiff.name == '$text' &&
  378. prevDiff.position.isEqual( thisDiff.position );
  379. // Glue insert changes if they happen on text on consecutive fragments.
  380. const isConsecutiveTextAdd =
  381. prevDiff.type == 'insert' && thisDiff.type == 'insert' &&
  382. prevDiff.name == '$text' && thisDiff.name == '$text' &&
  383. prevDiff.position.parent == thisDiff.position.parent &&
  384. prevDiff.position.offset + prevDiff.length == thisDiff.position.offset;
  385. // Glue attribute changes if they happen on consecutive fragments and have same key, old value and new value.
  386. const isConsecutiveAttributeChange =
  387. prevDiff.type == 'attribute' && thisDiff.type == 'attribute' &&
  388. prevDiff.position.parent == thisDiff.position.parent &&
  389. prevDiff.range.isFlat && thisDiff.range.isFlat &&
  390. prevDiff.position.offset + prevDiff.length == thisDiff.position.offset &&
  391. prevDiff.attributeKey == thisDiff.attributeKey &&
  392. prevDiff.attributeOldValue == thisDiff.attributeOldValue &&
  393. prevDiff.attributeNewValue == thisDiff.attributeNewValue;
  394. if ( isConsecutiveTextRemove || isConsecutiveTextAdd || isConsecutiveAttributeChange ) {
  395. diffSet[ i - 1 ].length++;
  396. if ( isConsecutiveAttributeChange ) {
  397. diffSet[ i - 1 ].range.end = diffSet[ i - 1 ].range.end.getShiftedBy( 1 );
  398. }
  399. diffSet.splice( i, 1 );
  400. i--;
  401. }
  402. }
  403. // Remove `changeCount` property from diff items. It is used only for sorting and is internal thing.
  404. for ( const item of diffSet ) {
  405. delete item.changeCount;
  406. if ( item.type == 'attribute' ) {
  407. delete item.position;
  408. delete item.length;
  409. }
  410. }
  411. this._changeCount = 0;
  412. // Cache changes.
  413. this._cachedChangesWithGraveyard = diffSet.slice();
  414. this._cachedChanges = diffSet.slice().filter( _changesInGraveyardFilter );
  415. if ( options.includeChangesInGraveyard ) {
  416. return this._cachedChangesWithGraveyard;
  417. } else {
  418. return this._cachedChanges;
  419. }
  420. }
  421. /**
  422. * Resets `Differ`. Removes all buffered changes.
  423. */
  424. reset() {
  425. this._changesInElement.clear();
  426. this._elementSnapshots.clear();
  427. this._changedMarkers.clear();
  428. this._cachedChanges = null;
  429. }
  430. /**
  431. * Saves and handles an insert change.
  432. *
  433. * @private
  434. * @param {module:engine/model/element~Element} parent
  435. * @param {Number} offset
  436. * @param {Number} howMany
  437. */
  438. _markInsert( parent, offset, howMany ) {
  439. const changeItem = { type: 'insert', offset, howMany, count: this._changeCount++ };
  440. this._markChange( parent, changeItem );
  441. }
  442. /**
  443. * Saves and handles a remove change.
  444. *
  445. * @private
  446. * @param {module:engine/model/element~Element} parent
  447. * @param {Number} offset
  448. * @param {Number} howMany
  449. */
  450. _markRemove( parent, offset, howMany ) {
  451. const changeItem = { type: 'remove', offset, howMany, count: this._changeCount++ };
  452. this._markChange( parent, changeItem );
  453. this._removeAllNestedChanges( parent, offset, howMany );
  454. }
  455. /**
  456. * Saves and handles an attribute change.
  457. *
  458. * @private
  459. * @param {module:engine/model/item~Item} item
  460. */
  461. _markAttribute( item ) {
  462. const changeItem = { type: 'attribute', offset: item.startOffset, howMany: item.offsetSize, count: this._changeCount++ };
  463. this._markChange( item.parent, changeItem );
  464. }
  465. /**
  466. * Saves and handles a model change.
  467. *
  468. * @private
  469. * @param {module:engine/model/element~Element} parent
  470. * @param {Object} changeItem
  471. */
  472. _markChange( parent, changeItem ) {
  473. // First, make a snapshot of this parent's children (it will be made only if it was not made before).
  474. this._makeSnapshot( parent );
  475. // Then, get all changes that already were done on the element (empty array if this is the first change).
  476. const changes = this._getChangesForElement( parent );
  477. // Then, look through all the changes, and transform them or the new change.
  478. this._handleChange( changeItem, changes );
  479. // Add the new change.
  480. changes.push( changeItem );
  481. // Remove incorrect changes. During transformation some change might be, for example, included in another.
  482. // In that case, the change will have `howMany` property set to `0` or less. We need to remove those changes.
  483. for ( let i = 0; i < changes.length; i++ ) {
  484. if ( changes[ i ].howMany < 1 ) {
  485. changes.splice( i, 1 );
  486. i--;
  487. }
  488. }
  489. }
  490. /**
  491. * Gets an array of changes that have already been saved for a given element.
  492. *
  493. * @private
  494. * @param {module:engine/model/element~Element} element
  495. * @returns {Array.<Object>}
  496. */
  497. _getChangesForElement( element ) {
  498. let changes;
  499. if ( this._changesInElement.has( element ) ) {
  500. changes = this._changesInElement.get( element );
  501. } else {
  502. changes = [];
  503. this._changesInElement.set( element, changes );
  504. }
  505. return changes;
  506. }
  507. /**
  508. * Saves a children snapshot for a given element.
  509. *
  510. * @private
  511. * @param {module:engine/model/element~Element} element
  512. */
  513. _makeSnapshot( element ) {
  514. if ( !this._elementSnapshots.has( element ) ) {
  515. this._elementSnapshots.set( element, _getChildrenSnapshot( element.getChildren() ) );
  516. }
  517. }
  518. /**
  519. * For a given newly saved change, compares it with a change already done on the element and modifies the incoming
  520. * change and/or the old change.
  521. *
  522. * @private
  523. * @param {Object} inc Incoming (new) change.
  524. * @param {Array.<Object>} changes An array containing all the changes done on that element.
  525. */
  526. _handleChange( inc, changes ) {
  527. // We need a helper variable that will store how many nodes are to be still handled for this change item.
  528. // `nodesToHandle` (how many nodes still need to be handled) and `howMany` (how many nodes were affected)
  529. // needs to be differentiated.
  530. //
  531. // This comes up when there are multiple changes that are affected by `inc` change item.
  532. //
  533. // For example: assume two insert changes: `{ offset: 2, howMany: 1 }` and `{ offset: 5, howMany: 1 }`.
  534. // Assume that `inc` change is remove `{ offset: 2, howMany: 2, nodesToHandle: 2 }`.
  535. //
  536. // Then, we:
  537. // - "forget" about first insert change (it is "eaten" by remove),
  538. // - because of that, at the end we will want to remove only one node (`nodesToHandle = 1`),
  539. // - but still we have to change offset of the second insert change from `5` to `3`!
  540. //
  541. // So, `howMany` does not change throughout items transformation and keeps information about how many nodes were affected,
  542. // while `nodesToHandle` means how many nodes need to be handled after the change item is transformed by other changes.
  543. inc.nodesToHandle = inc.howMany;
  544. for ( const old of changes ) {
  545. const incEnd = inc.offset + inc.howMany;
  546. const oldEnd = old.offset + old.howMany;
  547. if ( inc.type == 'insert' ) {
  548. if ( old.type == 'insert' ) {
  549. if ( inc.offset <= old.offset ) {
  550. old.offset += inc.howMany;
  551. } else if ( inc.offset < oldEnd ) {
  552. old.howMany += inc.nodesToHandle;
  553. inc.nodesToHandle = 0;
  554. }
  555. }
  556. if ( old.type == 'remove' ) {
  557. if ( inc.offset < old.offset ) {
  558. old.offset += inc.howMany;
  559. }
  560. }
  561. if ( old.type == 'attribute' ) {
  562. if ( inc.offset <= old.offset ) {
  563. old.offset += inc.howMany;
  564. } else if ( inc.offset < oldEnd ) {
  565. // This case is more complicated, because attribute change has to be split into two.
  566. // Example (assume that uppercase and lowercase letters mean different attributes):
  567. //
  568. // initial state: abcxyz
  569. // attribute change: aBCXYz
  570. // incoming insert: aBCfooXYz
  571. //
  572. // Change ranges cannot intersect because each item has to be described exactly (it was either
  573. // not changed, inserted, removed, or its attribute was changed). That's why old attribute
  574. // change has to be split and both parts has to be handled separately from now on.
  575. const howMany = old.howMany;
  576. old.howMany = inc.offset - old.offset;
  577. // Add the second part of attribute change to the beginning of processed array so it won't
  578. // be processed again in this loop.
  579. changes.unshift( {
  580. type: 'attribute',
  581. offset: incEnd,
  582. howMany: howMany - old.howMany,
  583. count: this._changeCount++
  584. } );
  585. }
  586. }
  587. }
  588. if ( inc.type == 'remove' ) {
  589. if ( old.type == 'insert' ) {
  590. if ( incEnd <= old.offset ) {
  591. old.offset -= inc.howMany;
  592. } else if ( incEnd <= oldEnd ) {
  593. if ( inc.offset < old.offset ) {
  594. const intersectionLength = incEnd - old.offset;
  595. old.offset = inc.offset;
  596. old.howMany -= intersectionLength;
  597. inc.nodesToHandle -= intersectionLength;
  598. } else {
  599. old.howMany -= inc.nodesToHandle;
  600. inc.nodesToHandle = 0;
  601. }
  602. } else {
  603. if ( inc.offset <= old.offset ) {
  604. inc.nodesToHandle -= old.howMany;
  605. old.howMany = 0;
  606. } else if ( inc.offset < oldEnd ) {
  607. const intersectionLength = oldEnd - inc.offset;
  608. old.howMany -= intersectionLength;
  609. inc.nodesToHandle -= intersectionLength;
  610. }
  611. }
  612. }
  613. if ( old.type == 'remove' ) {
  614. if ( incEnd <= old.offset ) {
  615. old.offset -= inc.howMany;
  616. } else if ( inc.offset < old.offset ) {
  617. inc.nodesToHandle += old.howMany;
  618. old.howMany = 0;
  619. }
  620. }
  621. if ( old.type == 'attribute' ) {
  622. if ( incEnd <= old.offset ) {
  623. old.offset -= inc.howMany;
  624. } else if ( inc.offset < old.offset ) {
  625. const intersectionLength = incEnd - old.offset;
  626. old.offset = inc.offset;
  627. old.howMany -= intersectionLength;
  628. } else if ( inc.offset < oldEnd ) {
  629. if ( incEnd <= oldEnd ) {
  630. // On first sight in this case we don't need to split attribute operation into two.
  631. // However the changes set is later converted to actions (see `_generateActionsFromChanges`).
  632. // For that reason, no two changes may intersect.
  633. // So we cannot have an attribute change that "contains" remove change.
  634. // Attribute change needs to be split.
  635. const howMany = old.howMany;
  636. old.howMany = inc.offset - old.offset;
  637. const howManyAfter = howMany - old.howMany - inc.nodesToHandle;
  638. // Add the second part of attribute change to the beginning of processed array so it won't
  639. // be processed again in this loop.
  640. changes.unshift( {
  641. type: 'attribute',
  642. offset: inc.offset,
  643. howMany: howManyAfter,
  644. count: this._changeCount++
  645. } );
  646. } else {
  647. old.howMany -= oldEnd - inc.offset;
  648. }
  649. }
  650. }
  651. }
  652. if ( inc.type == 'attribute' ) {
  653. // In case of attribute change, `howMany` should be kept same as `nodesToHandle`. It's not an error.
  654. if ( old.type == 'insert' ) {
  655. if ( inc.offset < old.offset && incEnd > old.offset ) {
  656. if ( incEnd > oldEnd ) {
  657. // This case is similar to a case described when incoming change was insert and old change was attribute.
  658. // See comment above.
  659. //
  660. // This time incoming change is attribute. We need to split incoming change in this case too.
  661. // However this time, the second part of the attribute change needs to be processed further
  662. // because there might be other changes that it collides with.
  663. const attributePart = {
  664. type: 'attribute',
  665. offset: oldEnd,
  666. howMany: incEnd - oldEnd,
  667. count: this._changeCount++
  668. };
  669. this._handleChange( attributePart, changes );
  670. changes.push( attributePart );
  671. }
  672. inc.nodesToHandle = old.offset - inc.offset;
  673. inc.howMany = inc.nodesToHandle;
  674. } else if ( inc.offset >= old.offset && inc.offset < oldEnd ) {
  675. if ( incEnd > oldEnd ) {
  676. inc.nodesToHandle = incEnd - oldEnd;
  677. inc.offset = oldEnd;
  678. } else {
  679. inc.nodesToHandle = 0;
  680. }
  681. }
  682. }
  683. if ( old.type == 'attribute' ) {
  684. // There are only two conflicting scenarios possible here:
  685. if ( inc.offset >= old.offset && incEnd <= oldEnd ) {
  686. // `old` change includes `inc` change, or they are the same.
  687. inc.nodesToHandle = 0;
  688. inc.howMany = 0;
  689. inc.offset = 0;
  690. } else if ( inc.offset <= old.offset && incEnd >= oldEnd ) {
  691. // `inc` change includes `old` change.
  692. old.howMany = 0;
  693. }
  694. }
  695. }
  696. }
  697. inc.howMany = inc.nodesToHandle;
  698. delete inc.nodesToHandle;
  699. }
  700. /**
  701. * Returns an object with a single insert change description.
  702. *
  703. * @private
  704. * @param {module:engine/model/element~Element} parent The element in which the change happened.
  705. * @param {Number} offset The offset at which change happened.
  706. * @param {String} name The name of the removed element or `'$text'` for a character.
  707. * @returns {Object} The diff item.
  708. */
  709. _getInsertDiff( parent, offset, name ) {
  710. return {
  711. type: 'insert',
  712. position: Position.createFromParentAndOffset( parent, offset ),
  713. name,
  714. length: 1,
  715. changeCount: this._changeCount++
  716. };
  717. }
  718. /**
  719. * Returns an object with a single remove change description.
  720. *
  721. * @private
  722. * @param {module:engine/model/element~Element} parent The element in which change happened.
  723. * @param {Number} offset The offset at which change happened.
  724. * @param {String} name The name of the removed element or `'$text'` for a character.
  725. * @returns {Object} The diff item.
  726. */
  727. _getRemoveDiff( parent, offset, name ) {
  728. return {
  729. type: 'remove',
  730. position: Position.createFromParentAndOffset( parent, offset ),
  731. name,
  732. length: 1,
  733. changeCount: this._changeCount++
  734. };
  735. }
  736. /**
  737. * Returns an array of objects where each one is a single attribute change description.
  738. *
  739. * @private
  740. * @param {module:engine/model/range~Range} range The range where the change happened.
  741. * @param {Map} oldAttributes A map, map iterator or compatible object that contains attributes before the change.
  742. * @param {Map} newAttributes A map, map iterator or compatible object that contains attributes after the change.
  743. * @returns {Array.<Object>} An array containing one or more diff items.
  744. */
  745. _getAttributesDiff( range, oldAttributes, newAttributes ) {
  746. // Results holder.
  747. const diffs = [];
  748. // Clone new attributes as we will be performing changes on this object.
  749. newAttributes = new Map( newAttributes );
  750. // Look through old attributes.
  751. for ( const [ key, oldValue ] of oldAttributes ) {
  752. // Check what is the new value of the attribute (or if it was removed).
  753. const newValue = newAttributes.has( key ) ? newAttributes.get( key ) : null;
  754. // If values are different (or attribute was removed)...
  755. if ( newValue !== oldValue ) {
  756. // Add diff item.
  757. diffs.push( {
  758. type: 'attribute',
  759. position: range.start,
  760. range: Range.createFromRange( range ),
  761. length: 1,
  762. attributeKey: key,
  763. attributeOldValue: oldValue,
  764. attributeNewValue: newValue,
  765. changeCount: this._changeCount++
  766. } );
  767. }
  768. // Prevent returning two diff items for the same change.
  769. newAttributes.delete( key );
  770. }
  771. // Look through new attributes that weren't handled above.
  772. for ( const [ key, newValue ] of newAttributes ) {
  773. // Each of them is a new attribute. Add diff item.
  774. diffs.push( {
  775. type: 'attribute',
  776. position: range.start,
  777. range: Range.createFromRange( range ),
  778. length: 1,
  779. attributeKey: key,
  780. attributeOldValue: null,
  781. attributeNewValue: newValue,
  782. changeCount: this._changeCount++
  783. } );
  784. }
  785. return diffs;
  786. }
  787. /**
  788. * Checks whether given element or any of its parents is an element that is buffered as an inserted element.
  789. *
  790. * @private
  791. * @param {module:engine/model/element~Element} element Element to check.
  792. * @returns {Boolean}
  793. */
  794. _isInInsertedElement( element ) {
  795. const parent = element.parent;
  796. if ( !parent ) {
  797. return false;
  798. }
  799. const changes = this._changesInElement.get( parent );
  800. const offset = element.startOffset;
  801. if ( changes ) {
  802. for ( const change of changes ) {
  803. if ( change.type == 'insert' && offset >= change.offset && offset < change.offset + change.howMany ) {
  804. return true;
  805. }
  806. }
  807. }
  808. return this._isInInsertedElement( parent );
  809. }
  810. /**
  811. * Removes deeply all buffered changes that are registered in elements from range specified by `parent`, `offset`
  812. * and `howMany`.
  813. *
  814. * @private
  815. * @param {module:engine/model/element~Element} parent
  816. * @param {Number} offset
  817. * @param {Number} howMany
  818. */
  819. _removeAllNestedChanges( parent, offset, howMany ) {
  820. const range = Range.createFromParentsAndOffsets( parent, offset, parent, offset + howMany );
  821. for ( const item of range.getItems( { shallow: true } ) ) {
  822. if ( item.is( 'element' ) ) {
  823. this._elementSnapshots.delete( item );
  824. this._changesInElement.delete( item );
  825. this._removeAllNestedChanges( item, 0, item.maxOffset );
  826. }
  827. }
  828. }
  829. }
  830. // Returns an array that is a copy of passed child list with the exception that text nodes are split to one or more
  831. // objects, each representing one character and attributes set on that character.
  832. function _getChildrenSnapshot( children ) {
  833. const snapshot = [];
  834. for ( const child of children ) {
  835. if ( child.is( 'text' ) ) {
  836. for ( let i = 0; i < child.data.length; i++ ) {
  837. snapshot.push( {
  838. name: '$text',
  839. attributes: new Map( child.getAttributes() )
  840. } );
  841. }
  842. } else {
  843. snapshot.push( {
  844. name: child.name,
  845. attributes: new Map( child.getAttributes() )
  846. } );
  847. }
  848. }
  849. return snapshot;
  850. }
  851. // Generates array of actions for given changes set.
  852. // It simulates what `diff` function does.
  853. // Generated actions are:
  854. // - 'e' for 'equal' - when item at that position did not change,
  855. // - 'i' for 'insert' - when item at that position was inserted,
  856. // - 'r' for 'remove' - when item at that position was removed,
  857. // - 'a' for 'attribute' - when item at that position has it attributes changed.
  858. //
  859. // Example (assume that uppercase letters have bold attribute, compare with function code):
  860. //
  861. // children before: fooBAR
  862. // children after: foxybAR
  863. //
  864. // changes: type: remove, offset: 1, howMany: 1
  865. // type: insert, offset: 2, howMany: 2
  866. // type: attribute, offset: 4, howMany: 1
  867. //
  868. // expected actions: equal (f), remove (o), equal (o), insert (x), insert (y), attribute (b), equal (A), equal (R)
  869. //
  870. // steps taken by th script:
  871. //
  872. // 1. change = "type: remove, offset: 1, howMany: 1"; offset = 0; oldChildrenHandled = 0
  873. // 1.1 between this change and the beginning is one not-changed node, fill with one equal action, one old child has been handled
  874. // 1.2 this change removes one node, add one remove action
  875. // 1.3 change last visited `offset` to 1
  876. // 1.4 since an old child has been removed, one more old child has been handled
  877. // 1.5 actions at this point are: equal, remove
  878. //
  879. // 2. change = "type: insert, offset: 2, howMany: 2"; offset = 1; oldChildrenHandled = 2
  880. // 2.1 between this change and previous change is one not-changed node, add equal action, another one old children has been handled
  881. // 2.2 this change inserts two nodes, add two insert actions
  882. // 2.3 change last visited offset to the end of the inserted range, that is 4
  883. // 2.4 actions at this point are: equal, remove, equal, insert, insert
  884. //
  885. // 3. change = "type: attribute, offset: 4, howMany: 1"; offset = 4, oldChildrenHandled = 3
  886. // 3.1 between this change and previous change are no not-changed nodes
  887. // 3.2 this change changes one node, add one attribute action
  888. // 3.3 change last visited `offset` to the end of change range, that is 5
  889. // 3.4 since an old child has been changed, one more old child has been handled
  890. // 3.5 actions at this point are: equal, remove, equal, insert, insert, attribute
  891. //
  892. // 4. after loop oldChildrenHandled = 4, oldChildrenLength = 6 (fooBAR is 6 characters)
  893. // 4.1 fill up with two equal actions
  894. //
  895. // The result actions are: equal, remove, equal, insert, insert, attribute, equal, equal.
  896. function _generateActionsFromChanges( oldChildrenLength, changes ) {
  897. const actions = [];
  898. let offset = 0;
  899. let oldChildrenHandled = 0;
  900. // Go through all buffered changes.
  901. for ( const change of changes ) {
  902. // First, fill "holes" between changes with "equal" actions.
  903. if ( change.offset > offset ) {
  904. actions.push( ...'e'.repeat( change.offset - offset ).split( '' ) );
  905. oldChildrenHandled += change.offset - offset;
  906. }
  907. // Then, fill up actions accordingly to change type.
  908. if ( change.type == 'insert' ) {
  909. actions.push( ...'i'.repeat( change.howMany ).split( '' ) );
  910. // The last handled offset is after inserted range.
  911. offset = change.offset + change.howMany;
  912. } else if ( change.type == 'remove' ) {
  913. actions.push( ...'r'.repeat( change.howMany ).split( '' ) );
  914. // The last handled offset is at the position where the nodes were removed.
  915. offset = change.offset;
  916. // We removed `howMany` old nodes, update `oldChildrenHandled`.
  917. oldChildrenHandled += change.howMany;
  918. } else {
  919. actions.push( ...'a'.repeat( change.howMany ).split( '' ) );
  920. // The last handled offset isa at the position after the changed range.
  921. offset = change.offset + change.howMany;
  922. // We changed `howMany` old nodes, update `oldChildrenHandled`.
  923. oldChildrenHandled += change.howMany;
  924. }
  925. }
  926. // Fill "equal" actions at the end of actions set. Use `oldChildrenHandled` to see how many children
  927. // has not been changed / removed at the end of their parent.
  928. if ( oldChildrenHandled < oldChildrenLength ) {
  929. actions.push( ...'e'.repeat( oldChildrenLength - oldChildrenHandled ).split( '' ) );
  930. }
  931. return actions;
  932. }
  933. // Filter callback for Array.filter that filters out change entries that are in graveyard.
  934. function _changesInGraveyardFilter( entry ) {
  935. const posInGy = entry.position && entry.position.root.rootName == '$graveyard';
  936. const rangeInGy = entry.range && entry.range.root.rootName == '$graveyard';
  937. return !posInGy && !rangeInGy;
  938. }