8
0

differ.js 35 KB

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