8
0

differ.js 31 KB

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