8
0

differ.js 31 KB

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