@ckeditor/ckeditor5-engine 30.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/LICENSE.md +17 -0
  2. package/README.md +30 -0
  3. package/package.json +70 -0
  4. package/src/controller/datacontroller.js +563 -0
  5. package/src/controller/editingcontroller.js +149 -0
  6. package/src/conversion/conversion.js +644 -0
  7. package/src/conversion/conversionhelpers.js +40 -0
  8. package/src/conversion/downcastdispatcher.js +914 -0
  9. package/src/conversion/downcasthelpers.js +1706 -0
  10. package/src/conversion/mapper.js +696 -0
  11. package/src/conversion/modelconsumable.js +329 -0
  12. package/src/conversion/upcastdispatcher.js +807 -0
  13. package/src/conversion/upcasthelpers.js +997 -0
  14. package/src/conversion/viewconsumable.js +623 -0
  15. package/src/dataprocessor/basichtmlwriter.js +32 -0
  16. package/src/dataprocessor/dataprocessor.jsdoc +64 -0
  17. package/src/dataprocessor/htmldataprocessor.js +159 -0
  18. package/src/dataprocessor/htmlwriter.js +22 -0
  19. package/src/dataprocessor/xmldataprocessor.js +161 -0
  20. package/src/dev-utils/model.js +482 -0
  21. package/src/dev-utils/operationreplayer.js +140 -0
  22. package/src/dev-utils/utils.js +103 -0
  23. package/src/dev-utils/view.js +1091 -0
  24. package/src/index.js +52 -0
  25. package/src/model/batch.js +82 -0
  26. package/src/model/differ.js +1282 -0
  27. package/src/model/document.js +483 -0
  28. package/src/model/documentfragment.js +390 -0
  29. package/src/model/documentselection.js +1261 -0
  30. package/src/model/element.js +438 -0
  31. package/src/model/history.js +138 -0
  32. package/src/model/item.jsdoc +14 -0
  33. package/src/model/liveposition.js +182 -0
  34. package/src/model/liverange.js +221 -0
  35. package/src/model/markercollection.js +553 -0
  36. package/src/model/model.js +934 -0
  37. package/src/model/node.js +507 -0
  38. package/src/model/nodelist.js +217 -0
  39. package/src/model/operation/attributeoperation.js +202 -0
  40. package/src/model/operation/detachoperation.js +103 -0
  41. package/src/model/operation/insertoperation.js +188 -0
  42. package/src/model/operation/markeroperation.js +154 -0
  43. package/src/model/operation/mergeoperation.js +216 -0
  44. package/src/model/operation/moveoperation.js +209 -0
  45. package/src/model/operation/nooperation.js +58 -0
  46. package/src/model/operation/operation.js +139 -0
  47. package/src/model/operation/operationfactory.js +49 -0
  48. package/src/model/operation/renameoperation.js +155 -0
  49. package/src/model/operation/rootattributeoperation.js +211 -0
  50. package/src/model/operation/splitoperation.js +254 -0
  51. package/src/model/operation/transform.js +2389 -0
  52. package/src/model/operation/utils.js +292 -0
  53. package/src/model/position.js +1164 -0
  54. package/src/model/range.js +1049 -0
  55. package/src/model/rootelement.js +111 -0
  56. package/src/model/schema.js +1851 -0
  57. package/src/model/selection.js +902 -0
  58. package/src/model/text.js +138 -0
  59. package/src/model/textproxy.js +279 -0
  60. package/src/model/treewalker.js +414 -0
  61. package/src/model/utils/autoparagraphing.js +77 -0
  62. package/src/model/utils/deletecontent.js +528 -0
  63. package/src/model/utils/getselectedcontent.js +150 -0
  64. package/src/model/utils/insertcontent.js +824 -0
  65. package/src/model/utils/modifyselection.js +229 -0
  66. package/src/model/utils/selection-post-fixer.js +297 -0
  67. package/src/model/writer.js +1574 -0
  68. package/src/view/attributeelement.js +274 -0
  69. package/src/view/containerelement.js +123 -0
  70. package/src/view/document.js +221 -0
  71. package/src/view/documentfragment.js +273 -0
  72. package/src/view/documentselection.js +387 -0
  73. package/src/view/domconverter.js +1437 -0
  74. package/src/view/downcastwriter.js +2121 -0
  75. package/src/view/editableelement.js +118 -0
  76. package/src/view/element.js +945 -0
  77. package/src/view/elementdefinition.jsdoc +59 -0
  78. package/src/view/emptyelement.js +119 -0
  79. package/src/view/filler.js +161 -0
  80. package/src/view/item.jsdoc +14 -0
  81. package/src/view/matcher.js +776 -0
  82. package/src/view/node.js +391 -0
  83. package/src/view/observer/arrowkeysobserver.js +58 -0
  84. package/src/view/observer/bubblingemittermixin.js +307 -0
  85. package/src/view/observer/bubblingeventinfo.js +71 -0
  86. package/src/view/observer/clickobserver.js +46 -0
  87. package/src/view/observer/compositionobserver.js +79 -0
  88. package/src/view/observer/domeventdata.js +82 -0
  89. package/src/view/observer/domeventobserver.js +99 -0
  90. package/src/view/observer/fakeselectionobserver.js +118 -0
  91. package/src/view/observer/focusobserver.js +106 -0
  92. package/src/view/observer/inputobserver.js +44 -0
  93. package/src/view/observer/keyobserver.js +83 -0
  94. package/src/view/observer/mouseobserver.js +56 -0
  95. package/src/view/observer/mutationobserver.js +345 -0
  96. package/src/view/observer/observer.js +118 -0
  97. package/src/view/observer/selectionobserver.js +242 -0
  98. package/src/view/placeholder.js +285 -0
  99. package/src/view/position.js +426 -0
  100. package/src/view/range.js +533 -0
  101. package/src/view/rawelement.js +148 -0
  102. package/src/view/renderer.js +1037 -0
  103. package/src/view/rooteditableelement.js +107 -0
  104. package/src/view/selection.js +718 -0
  105. package/src/view/styles/background.js +73 -0
  106. package/src/view/styles/border.js +362 -0
  107. package/src/view/styles/margin.js +41 -0
  108. package/src/view/styles/padding.js +40 -0
  109. package/src/view/styles/utils.js +277 -0
  110. package/src/view/stylesmap.js +938 -0
  111. package/src/view/text.js +147 -0
  112. package/src/view/textproxy.js +199 -0
  113. package/src/view/treewalker.js +496 -0
  114. package/src/view/uielement.js +238 -0
  115. package/src/view/upcastwriter.js +484 -0
  116. package/src/view/view.js +721 -0
  117. package/theme/placeholder.css +27 -0
@@ -0,0 +1,1282 @@
1
+ /**
2
+ * @license Copyright (c) 2003-2021, CKSource - Frederico Knabben. All rights reserved.
3
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4
+ */
5
+
6
+ /**
7
+ * @module engine/model/differ
8
+ */
9
+
10
+ import Position from './position';
11
+ import Range from './range';
12
+
13
+ /**
14
+ * Calculates the difference between two model states.
15
+ *
16
+ * Receives operations that are to be applied on the model document. Marks parts of the model document tree which
17
+ * are changed and saves the state of these elements before the change. Then, it compares saved elements with the
18
+ * changed elements, after all changes are applied on the model document. Calculates the diff between saved
19
+ * elements and new ones and returns a change set.
20
+ */
21
+ export default class Differ {
22
+ /**
23
+ * Creates a `Differ` instance.
24
+ *
25
+ * @param {module:engine/model/markercollection~MarkerCollection} markerCollection Model's marker collection.
26
+ */
27
+ constructor( markerCollection ) {
28
+ /**
29
+ * Reference to the model's marker collection.
30
+ *
31
+ * @private
32
+ * @type {module:engine/model/markercollection~MarkerCollection}
33
+ */
34
+ this._markerCollection = markerCollection;
35
+
36
+ /**
37
+ * A map that stores changes that happened in a given element.
38
+ *
39
+ * The keys of the map are references to the model elements.
40
+ * The values of the map are arrays with changes that were done on this element.
41
+ *
42
+ * @private
43
+ * @type {Map}
44
+ */
45
+ this._changesInElement = new Map();
46
+
47
+ /**
48
+ * A map that stores "element's children snapshots". A snapshot is representing children of a given element before
49
+ * the first change was applied on that element. Snapshot items are objects with two properties: `name`,
50
+ * containing the element name (or `'$text'` for a text node) and `attributes` which is a map of the node's attributes.
51
+ *
52
+ * @private
53
+ * @type {Map}
54
+ */
55
+ this._elementSnapshots = new Map();
56
+
57
+ /**
58
+ * A map that stores all changed markers.
59
+ *
60
+ * The keys of the map are marker names.
61
+ * The values of the map are objects with the `oldRange` and `newRange` properties. They store the marker range
62
+ * state before and after the change.
63
+ *
64
+ * @private
65
+ * @type {Map}
66
+ */
67
+ this._changedMarkers = new Map();
68
+
69
+ /**
70
+ * Stores the number of changes that were processed. Used to order the changes chronologically. It is important
71
+ * when changes are sorted.
72
+ *
73
+ * @private
74
+ * @type {Number}
75
+ */
76
+ this._changeCount = 0;
77
+
78
+ /**
79
+ * For efficiency purposes, `Differ` stores the change set returned by the differ after {@link #getChanges} call.
80
+ * Cache is reset each time a new operation is buffered. If the cache has not been reset, {@link #getChanges} will
81
+ * return the cached value instead of calculating it again.
82
+ *
83
+ * This property stores those changes that did not take place in graveyard root.
84
+ *
85
+ * @private
86
+ * @type {Array.<Object>|null}
87
+ */
88
+ this._cachedChanges = null;
89
+
90
+ /**
91
+ * For efficiency purposes, `Differ` stores the change set returned by the differ after the {@link #getChanges} call.
92
+ * The cache is reset each time a new operation is buffered. If the cache has not been reset, {@link #getChanges} will
93
+ * return the cached value instead of calculating it again.
94
+ *
95
+ * This property stores all changes evaluated by `Differ`, including those that took place in the graveyard.
96
+ *
97
+ * @private
98
+ * @type {Array.<Object>|null}
99
+ */
100
+ this._cachedChangesWithGraveyard = null;
101
+ }
102
+
103
+ /**
104
+ * Informs whether there are any changes buffered in `Differ`.
105
+ *
106
+ * @readonly
107
+ * @type {Boolean}
108
+ */
109
+ get isEmpty() {
110
+ return this._changesInElement.size == 0 && this._changedMarkers.size == 0;
111
+ }
112
+
113
+ /**
114
+ * Marks given `item` in differ to be "refreshed". It means that the item will be marked as removed and inserted in the differ changes
115
+ * set, so it will be effectively re-converted when differ changes will be handled by a dispatcher.
116
+ *
117
+ * @param {module:engine/model/item~Item} item Item to refresh.
118
+ */
119
+ refreshItem( item ) {
120
+ if ( this._isInInsertedElement( item.parent ) ) {
121
+ return;
122
+ }
123
+
124
+ this._markRemove( item.parent, item.startOffset, item.offsetSize );
125
+ this._markInsert( item.parent, item.startOffset, item.offsetSize );
126
+
127
+ const range = Range._createOn( item );
128
+
129
+ for ( const marker of this._markerCollection.getMarkersIntersectingRange( range ) ) {
130
+ const markerRange = marker.getRange();
131
+
132
+ this.bufferMarkerChange( marker.name, markerRange, markerRange, marker.affectsData );
133
+ }
134
+
135
+ // Clear cache after each buffered operation as it is no longer valid.
136
+ this._cachedChanges = null;
137
+ }
138
+
139
+ /**
140
+ * Buffers the given operation. An operation has to be buffered before it is executed.
141
+ *
142
+ * Operation type is checked and it is checked which nodes it will affect. These nodes are then stored in `Differ`
143
+ * in the state before the operation is executed.
144
+ *
145
+ * @param {module:engine/model/operation/operation~Operation} operation An operation to buffer.
146
+ */
147
+ bufferOperation( operation ) {
148
+ // Below we take an operation, check its type, then use its parameters in marking (private) methods.
149
+ // The general rule is to not mark elements inside inserted element. All inserted elements are re-rendered.
150
+ // Marking changes in them would cause a "double" changing then.
151
+ //
152
+ switch ( operation.type ) {
153
+ case 'insert': {
154
+ if ( this._isInInsertedElement( operation.position.parent ) ) {
155
+ return;
156
+ }
157
+
158
+ this._markInsert( operation.position.parent, operation.position.offset, operation.nodes.maxOffset );
159
+
160
+ break;
161
+ }
162
+ case 'addAttribute':
163
+ case 'removeAttribute':
164
+ case 'changeAttribute': {
165
+ for ( const item of operation.range.getItems( { shallow: true } ) ) {
166
+ if ( this._isInInsertedElement( item.parent ) ) {
167
+ continue;
168
+ }
169
+
170
+ this._markAttribute( item );
171
+ }
172
+
173
+ break;
174
+ }
175
+ case 'remove':
176
+ case 'move':
177
+ case 'reinsert': {
178
+ // When range is moved to the same position then not mark it as a change.
179
+ // See: https://github.com/ckeditor/ckeditor5-engine/issues/1664.
180
+ if (
181
+ operation.sourcePosition.isEqual( operation.targetPosition ) ||
182
+ operation.sourcePosition.getShiftedBy( operation.howMany ).isEqual( operation.targetPosition )
183
+ ) {
184
+ return;
185
+ }
186
+
187
+ const sourceParentInserted = this._isInInsertedElement( operation.sourcePosition.parent );
188
+ const targetParentInserted = this._isInInsertedElement( operation.targetPosition.parent );
189
+
190
+ if ( !sourceParentInserted ) {
191
+ this._markRemove( operation.sourcePosition.parent, operation.sourcePosition.offset, operation.howMany );
192
+ }
193
+
194
+ if ( !targetParentInserted ) {
195
+ this._markInsert( operation.targetPosition.parent, operation.getMovedRangeStart().offset, operation.howMany );
196
+ }
197
+
198
+ break;
199
+ }
200
+ case 'rename': {
201
+ if ( this._isInInsertedElement( operation.position.parent ) ) {
202
+ return;
203
+ }
204
+
205
+ this._markRemove( operation.position.parent, operation.position.offset, 1 );
206
+ this._markInsert( operation.position.parent, operation.position.offset, 1 );
207
+
208
+ const range = Range._createFromPositionAndShift( operation.position, 1 );
209
+
210
+ for ( const marker of this._markerCollection.getMarkersIntersectingRange( range ) ) {
211
+ const markerRange = marker.getRange();
212
+
213
+ this.bufferMarkerChange( marker.name, markerRange, markerRange, marker.affectsData );
214
+ }
215
+
216
+ break;
217
+ }
218
+ case 'split': {
219
+ const splitElement = operation.splitPosition.parent;
220
+
221
+ // Mark that children of the split element were removed.
222
+ if ( !this._isInInsertedElement( splitElement ) ) {
223
+ this._markRemove( splitElement, operation.splitPosition.offset, operation.howMany );
224
+ }
225
+
226
+ // Mark that the new element (split copy) was inserted.
227
+ if ( !this._isInInsertedElement( operation.insertionPosition.parent ) ) {
228
+ this._markInsert( operation.insertionPosition.parent, operation.insertionPosition.offset, 1 );
229
+ }
230
+
231
+ // If the split took the element from the graveyard, mark that the element from the graveyard was removed.
232
+ if ( operation.graveyardPosition ) {
233
+ this._markRemove( operation.graveyardPosition.parent, operation.graveyardPosition.offset, 1 );
234
+ }
235
+
236
+ break;
237
+ }
238
+ case 'merge': {
239
+ // Mark that the merged element was removed.
240
+ const mergedElement = operation.sourcePosition.parent;
241
+
242
+ if ( !this._isInInsertedElement( mergedElement.parent ) ) {
243
+ this._markRemove( mergedElement.parent, mergedElement.startOffset, 1 );
244
+ }
245
+
246
+ // Mark that the merged element was inserted into graveyard.
247
+ const graveyardParent = operation.graveyardPosition.parent;
248
+
249
+ this._markInsert( graveyardParent, operation.graveyardPosition.offset, 1 );
250
+
251
+ // Mark that children of merged element were inserted at new parent.
252
+ const mergedIntoElement = operation.targetPosition.parent;
253
+
254
+ if ( !this._isInInsertedElement( mergedIntoElement ) ) {
255
+ this._markInsert( mergedIntoElement, operation.targetPosition.offset, mergedElement.maxOffset );
256
+ }
257
+
258
+ break;
259
+ }
260
+ }
261
+
262
+ // Clear cache after each buffered operation as it is no longer valid.
263
+ this._cachedChanges = null;
264
+ }
265
+
266
+ /**
267
+ * Buffers a marker change.
268
+ *
269
+ * @param {String} markerName The name of the marker that changed.
270
+ * @param {module:engine/model/range~Range|null} oldRange Marker range before the change or `null` if the marker has just
271
+ * been created.
272
+ * @param {module:engine/model/range~Range|null} newRange Marker range after the change or `null` if the marker was removed.
273
+ * @param {Boolean} affectsData Flag indicating whether marker affects the editor data.
274
+ */
275
+ bufferMarkerChange( markerName, oldRange, newRange, affectsData ) {
276
+ const buffered = this._changedMarkers.get( markerName );
277
+
278
+ if ( !buffered ) {
279
+ this._changedMarkers.set( markerName, {
280
+ oldRange,
281
+ newRange,
282
+ affectsData
283
+ } );
284
+ } else {
285
+ buffered.newRange = newRange;
286
+ buffered.affectsData = affectsData;
287
+
288
+ if ( buffered.oldRange == null && buffered.newRange == null ) {
289
+ // The marker is going to be removed (`newRange == null`) but it did not exist before the first buffered change
290
+ // (`buffered.oldRange == null`). In this case, do not keep the marker in buffer at all.
291
+ this._changedMarkers.delete( markerName );
292
+ }
293
+ }
294
+ }
295
+
296
+ /**
297
+ * Returns all markers that should be removed as a result of buffered changes.
298
+ *
299
+ * @returns {Array.<Object>} Markers to remove. Each array item is an object containing the `name` and `range` properties.
300
+ */
301
+ getMarkersToRemove() {
302
+ const result = [];
303
+
304
+ for ( const [ name, change ] of this._changedMarkers ) {
305
+ if ( change.oldRange != null ) {
306
+ result.push( { name, range: change.oldRange } );
307
+ }
308
+ }
309
+
310
+ return result;
311
+ }
312
+
313
+ /**
314
+ * Returns all markers which should be added as a result of buffered changes.
315
+ *
316
+ * @returns {Array.<Object>} Markers to add. Each array item is an object containing the `name` and `range` properties.
317
+ */
318
+ getMarkersToAdd() {
319
+ const result = [];
320
+
321
+ for ( const [ name, change ] of this._changedMarkers ) {
322
+ if ( change.newRange != null ) {
323
+ result.push( { name, range: change.newRange } );
324
+ }
325
+ }
326
+
327
+ return result;
328
+ }
329
+
330
+ /**
331
+ * Returns all markers which changed.
332
+ *
333
+ * @returns {Array.<Object>}
334
+ */
335
+ getChangedMarkers() {
336
+ return Array.from( this._changedMarkers ).map( item => (
337
+ {
338
+ name: item[ 0 ],
339
+ data: {
340
+ oldRange: item[ 1 ].oldRange,
341
+ newRange: item[ 1 ].newRange
342
+ }
343
+ }
344
+ ) );
345
+ }
346
+
347
+ /**
348
+ * Checks whether some of the buffered changes affect the editor data.
349
+ *
350
+ * Types of changes which affect the editor data:
351
+ *
352
+ * * model structure changes,
353
+ * * attribute changes,
354
+ * * changes of markers which were defined as `affectingData`.
355
+ *
356
+ * @returns {Boolean}
357
+ */
358
+ hasDataChanges() {
359
+ for ( const [ , change ] of this._changedMarkers ) {
360
+ if ( change.affectsData ) {
361
+ return true;
362
+ }
363
+ }
364
+
365
+ // If markers do not affect the data, check whether there are some changes in elements.
366
+ return this._changesInElement.size > 0;
367
+ }
368
+
369
+ /**
370
+ * Calculates the diff between the old model tree state (the state before the first buffered operations since the last {@link #reset}
371
+ * call) and the new model tree state (actual one). It should be called after all buffered operations are executed.
372
+ *
373
+ * The diff set is returned as an array of {@link module:engine/model/differ~DiffItem diff items}, each describing a change done
374
+ * on the model. The items are sorted by the position on which the change happened. If a position
375
+ * {@link module:engine/model/position~Position#isBefore is before} another one, it will be on an earlier index in the diff set.
376
+ *
377
+ * **Note**: Elements inside inserted element will not have a separate diff item, only the top most element change will be reported.
378
+ *
379
+ * Because calculating the diff is a costly operation, the result is cached. If no new operation was buffered since the
380
+ * previous {@link #getChanges} call, the next call will return the cached value.
381
+ *
382
+ * @param {Object} options Additional options.
383
+ * @param {Boolean} [options.includeChangesInGraveyard=false] If set to `true`, also changes that happened
384
+ * in the graveyard root will be returned. By default, changes in the graveyard root are not returned.
385
+ * @returns {Array.<module:engine/model/differ~DiffItem>} Diff between the old and the new model tree state.
386
+ */
387
+ getChanges( options = { includeChangesInGraveyard: false } ) {
388
+ // If there are cached changes, just return them instead of calculating changes again.
389
+ if ( this._cachedChanges ) {
390
+ if ( options.includeChangesInGraveyard ) {
391
+ return this._cachedChangesWithGraveyard.slice();
392
+ } else {
393
+ return this._cachedChanges.slice();
394
+ }
395
+ }
396
+
397
+ // Will contain returned results.
398
+ let diffSet = [];
399
+
400
+ // Check all changed elements.
401
+ for ( const element of this._changesInElement.keys() ) {
402
+ // Get changes for this element and sort them.
403
+ const changes = this._changesInElement.get( element ).sort( ( a, b ) => {
404
+ if ( a.offset === b.offset ) {
405
+ if ( a.type != b.type ) {
406
+ // If there are multiple changes at the same position, "remove" change should be first.
407
+ // If the order is different, for example, we would first add some nodes and then removed them
408
+ // (instead of the nodes that we should remove).
409
+ return a.type == 'remove' ? -1 : 1;
410
+ }
411
+
412
+ return 0;
413
+ }
414
+
415
+ return a.offset < b.offset ? -1 : 1;
416
+ } );
417
+
418
+ // Get children of this element before any change was applied on it.
419
+ const snapshotChildren = this._elementSnapshots.get( element );
420
+ // Get snapshot of current element's children.
421
+ const elementChildren = _getChildrenSnapshot( element.getChildren() );
422
+
423
+ // Generate actions basing on changes done on element.
424
+ const actions = _generateActionsFromChanges( snapshotChildren.length, changes );
425
+
426
+ let i = 0; // Iterator in `elementChildren` array -- iterates through current children of element.
427
+ let j = 0; // Iterator in `snapshotChildren` array -- iterates through old children of element.
428
+
429
+ // Process every action.
430
+ for ( const action of actions ) {
431
+ if ( action === 'i' ) {
432
+ // Generate diff item for this element and insert it into the diff set.
433
+ diffSet.push( this._getInsertDiff( element, i, elementChildren[ i ].name ) );
434
+
435
+ i++;
436
+ } else if ( action === 'r' ) {
437
+ // Generate diff item for this element and insert it into the diff set.
438
+ diffSet.push( this._getRemoveDiff( element, i, snapshotChildren[ j ].name ) );
439
+
440
+ j++;
441
+ } else if ( action === 'a' ) {
442
+ // Take attributes from saved and current children.
443
+ const elementAttributes = elementChildren[ i ].attributes;
444
+ const snapshotAttributes = snapshotChildren[ j ].attributes;
445
+ let range;
446
+
447
+ if ( elementChildren[ i ].name == '$text' ) {
448
+ range = new Range( Position._createAt( element, i ), Position._createAt( element, i + 1 ) );
449
+ } else {
450
+ const index = element.offsetToIndex( i );
451
+ range = new Range( Position._createAt( element, i ), Position._createAt( element.getChild( index ), 0 ) );
452
+ }
453
+
454
+ // Generate diff items for this change (there might be multiple attributes changed and
455
+ // there is a single diff for each of them) and insert them into the diff set.
456
+ diffSet.push( ...this._getAttributesDiff( range, snapshotAttributes, elementAttributes ) );
457
+
458
+ i++;
459
+ j++;
460
+ } else {
461
+ // `action` is 'equal'. Child not changed.
462
+ i++;
463
+ j++;
464
+ }
465
+ }
466
+ }
467
+
468
+ // Then, sort the changes by the position (change at position before other changes is first).
469
+ diffSet.sort( ( a, b ) => {
470
+ // If the change is in different root, we don't care much, but we'd like to have all changes in given
471
+ // root "together" in the array. So let's just sort them by the root name. It does not matter which root
472
+ // will be processed first.
473
+ if ( a.position.root != b.position.root ) {
474
+ return a.position.root.rootName < b.position.root.rootName ? -1 : 1;
475
+ }
476
+
477
+ // If change happens at the same position...
478
+ if ( a.position.isEqual( b.position ) ) {
479
+ // Keep chronological order of operations.
480
+ return a.changeCount - b.changeCount;
481
+ }
482
+
483
+ // If positions differ, position "on the left" should be earlier in the result.
484
+ return a.position.isBefore( b.position ) ? -1 : 1;
485
+ } );
486
+
487
+ // Glue together multiple changes (mostly on text nodes).
488
+ for ( let i = 1, prevIndex = 0; i < diffSet.length; i++ ) {
489
+ const prevDiff = diffSet[ prevIndex ];
490
+ const thisDiff = diffSet[ i ];
491
+
492
+ // Glue remove changes if they happen on text on same position.
493
+ const isConsecutiveTextRemove =
494
+ prevDiff.type == 'remove' && thisDiff.type == 'remove' &&
495
+ prevDiff.name == '$text' && thisDiff.name == '$text' &&
496
+ prevDiff.position.isEqual( thisDiff.position );
497
+
498
+ // Glue insert changes if they happen on text on consecutive fragments.
499
+ const isConsecutiveTextAdd =
500
+ prevDiff.type == 'insert' && thisDiff.type == 'insert' &&
501
+ prevDiff.name == '$text' && thisDiff.name == '$text' &&
502
+ prevDiff.position.parent == thisDiff.position.parent &&
503
+ prevDiff.position.offset + prevDiff.length == thisDiff.position.offset;
504
+
505
+ // Glue attribute changes if they happen on consecutive fragments and have same key, old value and new value.
506
+ const isConsecutiveAttributeChange =
507
+ prevDiff.type == 'attribute' && thisDiff.type == 'attribute' &&
508
+ prevDiff.position.parent == thisDiff.position.parent &&
509
+ prevDiff.range.isFlat && thisDiff.range.isFlat &&
510
+ prevDiff.position.offset + prevDiff.length == thisDiff.position.offset &&
511
+ prevDiff.attributeKey == thisDiff.attributeKey &&
512
+ prevDiff.attributeOldValue == thisDiff.attributeOldValue &&
513
+ prevDiff.attributeNewValue == thisDiff.attributeNewValue;
514
+
515
+ if ( isConsecutiveTextRemove || isConsecutiveTextAdd || isConsecutiveAttributeChange ) {
516
+ prevDiff.length++;
517
+
518
+ if ( isConsecutiveAttributeChange ) {
519
+ prevDiff.range.end = prevDiff.range.end.getShiftedBy( 1 );
520
+ }
521
+
522
+ diffSet[ i ] = null;
523
+ } else {
524
+ prevIndex = i;
525
+ }
526
+ }
527
+
528
+ diffSet = diffSet.filter( v => v );
529
+
530
+ // Remove `changeCount` property from diff items. It is used only for sorting and is internal thing.
531
+ for ( const item of diffSet ) {
532
+ delete item.changeCount;
533
+
534
+ if ( item.type == 'attribute' ) {
535
+ delete item.position;
536
+ delete item.length;
537
+ }
538
+ }
539
+
540
+ this._changeCount = 0;
541
+
542
+ // Cache changes.
543
+ this._cachedChangesWithGraveyard = diffSet.slice();
544
+ this._cachedChanges = diffSet.filter( _changesInGraveyardFilter );
545
+
546
+ if ( options.includeChangesInGraveyard ) {
547
+ return this._cachedChangesWithGraveyard;
548
+ } else {
549
+ return this._cachedChanges;
550
+ }
551
+ }
552
+
553
+ /**
554
+ * Resets `Differ`. Removes all buffered changes.
555
+ */
556
+ reset() {
557
+ this._changesInElement.clear();
558
+ this._elementSnapshots.clear();
559
+ this._changedMarkers.clear();
560
+ this._cachedChanges = null;
561
+ }
562
+
563
+ /**
564
+ * Saves and handles an insert change.
565
+ *
566
+ * @private
567
+ * @param {module:engine/model/element~Element} parent
568
+ * @param {Number} offset
569
+ * @param {Number} howMany
570
+ */
571
+ _markInsert( parent, offset, howMany ) {
572
+ const changeItem = { type: 'insert', offset, howMany, count: this._changeCount++ };
573
+
574
+ this._markChange( parent, changeItem );
575
+ }
576
+
577
+ /**
578
+ * Saves and handles a remove change.
579
+ *
580
+ * @private
581
+ * @param {module:engine/model/element~Element} parent
582
+ * @param {Number} offset
583
+ * @param {Number} howMany
584
+ */
585
+ _markRemove( parent, offset, howMany ) {
586
+ const changeItem = { type: 'remove', offset, howMany, count: this._changeCount++ };
587
+
588
+ this._markChange( parent, changeItem );
589
+
590
+ this._removeAllNestedChanges( parent, offset, howMany );
591
+ }
592
+
593
+ /**
594
+ * Saves and handles an attribute change.
595
+ *
596
+ * @private
597
+ * @param {module:engine/model/item~Item} item
598
+ */
599
+ _markAttribute( item ) {
600
+ const changeItem = { type: 'attribute', offset: item.startOffset, howMany: item.offsetSize, count: this._changeCount++ };
601
+
602
+ this._markChange( item.parent, changeItem );
603
+ }
604
+
605
+ /**
606
+ * Saves and handles a model change.
607
+ *
608
+ * @private
609
+ * @param {module:engine/model/element~Element} parent
610
+ * @param {Object} changeItem
611
+ */
612
+ _markChange( parent, changeItem ) {
613
+ // First, make a snapshot of this parent's children (it will be made only if it was not made before).
614
+ this._makeSnapshot( parent );
615
+
616
+ // Then, get all changes that already were done on the element (empty array if this is the first change).
617
+ const changes = this._getChangesForElement( parent );
618
+
619
+ // Then, look through all the changes, and transform them or the new change.
620
+ this._handleChange( changeItem, changes );
621
+
622
+ // Add the new change.
623
+ changes.push( changeItem );
624
+
625
+ // Remove incorrect changes. During transformation some change might be, for example, included in another.
626
+ // In that case, the change will have `howMany` property set to `0` or less. We need to remove those changes.
627
+ for ( let i = 0; i < changes.length; i++ ) {
628
+ if ( changes[ i ].howMany < 1 ) {
629
+ changes.splice( i, 1 );
630
+
631
+ i--;
632
+ }
633
+ }
634
+ }
635
+
636
+ /**
637
+ * Gets an array of changes that have already been saved for a given element.
638
+ *
639
+ * @private
640
+ * @param {module:engine/model/element~Element} element
641
+ * @returns {Array.<Object>}
642
+ */
643
+ _getChangesForElement( element ) {
644
+ let changes;
645
+
646
+ if ( this._changesInElement.has( element ) ) {
647
+ changes = this._changesInElement.get( element );
648
+ } else {
649
+ changes = [];
650
+
651
+ this._changesInElement.set( element, changes );
652
+ }
653
+
654
+ return changes;
655
+ }
656
+
657
+ /**
658
+ * Saves a children snapshot for a given element.
659
+ *
660
+ * @private
661
+ * @param {module:engine/model/element~Element} element
662
+ */
663
+ _makeSnapshot( element ) {
664
+ if ( !this._elementSnapshots.has( element ) ) {
665
+ this._elementSnapshots.set( element, _getChildrenSnapshot( element.getChildren() ) );
666
+ }
667
+ }
668
+
669
+ /**
670
+ * For a given newly saved change, compares it with a change already done on the element and modifies the incoming
671
+ * change and/or the old change.
672
+ *
673
+ * @private
674
+ * @param {Object} inc Incoming (new) change.
675
+ * @param {Array.<Object>} changes An array containing all the changes done on that element.
676
+ */
677
+ _handleChange( inc, changes ) {
678
+ // We need a helper variable that will store how many nodes are to be still handled for this change item.
679
+ // `nodesToHandle` (how many nodes still need to be handled) and `howMany` (how many nodes were affected)
680
+ // needs to be differentiated.
681
+ //
682
+ // This comes up when there are multiple changes that are affected by `inc` change item.
683
+ //
684
+ // For example: assume two insert changes: `{ offset: 2, howMany: 1 }` and `{ offset: 5, howMany: 1 }`.
685
+ // Assume that `inc` change is remove `{ offset: 2, howMany: 2, nodesToHandle: 2 }`.
686
+ //
687
+ // Then, we:
688
+ // - "forget" about first insert change (it is "eaten" by remove),
689
+ // - because of that, at the end we will want to remove only one node (`nodesToHandle = 1`),
690
+ // - but still we have to change offset of the second insert change from `5` to `3`!
691
+ //
692
+ // So, `howMany` does not change throughout items transformation and keeps information about how many nodes were affected,
693
+ // while `nodesToHandle` means how many nodes need to be handled after the change item is transformed by other changes.
694
+ inc.nodesToHandle = inc.howMany;
695
+
696
+ for ( const old of changes ) {
697
+ const incEnd = inc.offset + inc.howMany;
698
+ const oldEnd = old.offset + old.howMany;
699
+
700
+ if ( inc.type == 'insert' ) {
701
+ if ( old.type == 'insert' ) {
702
+ if ( inc.offset <= old.offset ) {
703
+ old.offset += inc.howMany;
704
+ } else if ( inc.offset < oldEnd ) {
705
+ old.howMany += inc.nodesToHandle;
706
+ inc.nodesToHandle = 0;
707
+ }
708
+ }
709
+
710
+ if ( old.type == 'remove' ) {
711
+ if ( inc.offset < old.offset ) {
712
+ old.offset += inc.howMany;
713
+ }
714
+ }
715
+
716
+ if ( old.type == 'attribute' ) {
717
+ if ( inc.offset <= old.offset ) {
718
+ old.offset += inc.howMany;
719
+ } else if ( inc.offset < oldEnd ) {
720
+ // This case is more complicated, because attribute change has to be split into two.
721
+ // Example (assume that uppercase and lowercase letters mean different attributes):
722
+ //
723
+ // initial state: abcxyz
724
+ // attribute change: aBCXYz
725
+ // incoming insert: aBCfooXYz
726
+ //
727
+ // Change ranges cannot intersect because each item has to be described exactly (it was either
728
+ // not changed, inserted, removed, or its attribute was changed). That's why old attribute
729
+ // change has to be split and both parts has to be handled separately from now on.
730
+ const howMany = old.howMany;
731
+
732
+ old.howMany = inc.offset - old.offset;
733
+
734
+ // Add the second part of attribute change to the beginning of processed array so it won't
735
+ // be processed again in this loop.
736
+ changes.unshift( {
737
+ type: 'attribute',
738
+ offset: incEnd,
739
+ howMany: howMany - old.howMany,
740
+ count: this._changeCount++
741
+ } );
742
+ }
743
+ }
744
+ }
745
+
746
+ if ( inc.type == 'remove' ) {
747
+ if ( old.type == 'insert' ) {
748
+ if ( incEnd <= old.offset ) {
749
+ old.offset -= inc.howMany;
750
+ } else if ( incEnd <= oldEnd ) {
751
+ if ( inc.offset < old.offset ) {
752
+ const intersectionLength = incEnd - old.offset;
753
+
754
+ old.offset = inc.offset;
755
+
756
+ old.howMany -= intersectionLength;
757
+ inc.nodesToHandle -= intersectionLength;
758
+ } else {
759
+ old.howMany -= inc.nodesToHandle;
760
+ inc.nodesToHandle = 0;
761
+ }
762
+ } else {
763
+ if ( inc.offset <= old.offset ) {
764
+ inc.nodesToHandle -= old.howMany;
765
+ old.howMany = 0;
766
+ } else if ( inc.offset < oldEnd ) {
767
+ const intersectionLength = oldEnd - inc.offset;
768
+
769
+ old.howMany -= intersectionLength;
770
+ inc.nodesToHandle -= intersectionLength;
771
+ }
772
+ }
773
+ }
774
+
775
+ if ( old.type == 'remove' ) {
776
+ if ( incEnd <= old.offset ) {
777
+ old.offset -= inc.howMany;
778
+ } else if ( inc.offset < old.offset ) {
779
+ inc.nodesToHandle += old.howMany;
780
+ old.howMany = 0;
781
+ }
782
+ }
783
+
784
+ if ( old.type == 'attribute' ) {
785
+ if ( incEnd <= old.offset ) {
786
+ old.offset -= inc.howMany;
787
+ } else if ( inc.offset < old.offset ) {
788
+ const intersectionLength = incEnd - old.offset;
789
+
790
+ old.offset = inc.offset;
791
+ old.howMany -= intersectionLength;
792
+ } else if ( inc.offset < oldEnd ) {
793
+ if ( incEnd <= oldEnd ) {
794
+ // On first sight in this case we don't need to split attribute operation into two.
795
+ // However the changes set is later converted to actions (see `_generateActionsFromChanges`).
796
+ // For that reason, no two changes may intersect.
797
+ // So we cannot have an attribute change that "contains" remove change.
798
+ // Attribute change needs to be split.
799
+ const howMany = old.howMany;
800
+
801
+ old.howMany = inc.offset - old.offset;
802
+
803
+ const howManyAfter = howMany - old.howMany - inc.nodesToHandle;
804
+
805
+ // Add the second part of attribute change to the beginning of processed array so it won't
806
+ // be processed again in this loop.
807
+ changes.unshift( {
808
+ type: 'attribute',
809
+ offset: inc.offset,
810
+ howMany: howManyAfter,
811
+ count: this._changeCount++
812
+ } );
813
+ } else {
814
+ old.howMany -= oldEnd - inc.offset;
815
+ }
816
+ }
817
+ }
818
+ }
819
+
820
+ if ( inc.type == 'attribute' ) {
821
+ // In case of attribute change, `howMany` should be kept same as `nodesToHandle`. It's not an error.
822
+ if ( old.type == 'insert' ) {
823
+ if ( inc.offset < old.offset && incEnd > old.offset ) {
824
+ if ( incEnd > oldEnd ) {
825
+ // This case is similar to a case described when incoming change was insert and old change was attribute.
826
+ // See comment above.
827
+ //
828
+ // This time incoming change is attribute. We need to split incoming change in this case too.
829
+ // However this time, the second part of the attribute change needs to be processed further
830
+ // because there might be other changes that it collides with.
831
+ const attributePart = {
832
+ type: 'attribute',
833
+ offset: oldEnd,
834
+ howMany: incEnd - oldEnd,
835
+ count: this._changeCount++
836
+ };
837
+
838
+ this._handleChange( attributePart, changes );
839
+
840
+ changes.push( attributePart );
841
+ }
842
+
843
+ inc.nodesToHandle = old.offset - inc.offset;
844
+ inc.howMany = inc.nodesToHandle;
845
+ } else if ( inc.offset >= old.offset && inc.offset < oldEnd ) {
846
+ if ( incEnd > oldEnd ) {
847
+ inc.nodesToHandle = incEnd - oldEnd;
848
+ inc.offset = oldEnd;
849
+ } else {
850
+ inc.nodesToHandle = 0;
851
+ }
852
+ }
853
+ }
854
+
855
+ if ( old.type == 'remove' ) {
856
+ // This is a case when attribute change "contains" remove change.
857
+ // The attribute change needs to be split into two because changes cannot intersect.
858
+ if ( inc.offset < old.offset && incEnd > old.offset ) {
859
+ const attributePart = {
860
+ type: 'attribute',
861
+ offset: old.offset,
862
+ howMany: incEnd - old.offset,
863
+ count: this._changeCount++
864
+ };
865
+
866
+ this._handleChange( attributePart, changes );
867
+
868
+ changes.push( attributePart );
869
+
870
+ inc.nodesToHandle = old.offset - inc.offset;
871
+ inc.howMany = inc.nodesToHandle;
872
+ }
873
+ }
874
+
875
+ if ( old.type == 'attribute' ) {
876
+ // There are only two conflicting scenarios possible here:
877
+ if ( inc.offset >= old.offset && incEnd <= oldEnd ) {
878
+ // `old` change includes `inc` change, or they are the same.
879
+ inc.nodesToHandle = 0;
880
+ inc.howMany = 0;
881
+ inc.offset = 0;
882
+ } else if ( inc.offset <= old.offset && incEnd >= oldEnd ) {
883
+ // `inc` change includes `old` change.
884
+ old.howMany = 0;
885
+ }
886
+ }
887
+ }
888
+ }
889
+
890
+ inc.howMany = inc.nodesToHandle;
891
+ delete inc.nodesToHandle;
892
+ }
893
+
894
+ /**
895
+ * Returns an object with a single insert change description.
896
+ *
897
+ * @private
898
+ * @param {module:engine/model/element~Element} parent The element in which the change happened.
899
+ * @param {Number} offset The offset at which change happened.
900
+ * @param {String} name The name of the removed element or `'$text'` for a character.
901
+ * @returns {Object} The diff item.
902
+ */
903
+ _getInsertDiff( parent, offset, name ) {
904
+ return {
905
+ type: 'insert',
906
+ position: Position._createAt( parent, offset ),
907
+ name,
908
+ length: 1,
909
+ changeCount: this._changeCount++
910
+ };
911
+ }
912
+
913
+ /**
914
+ * Returns an object with a single remove change description.
915
+ *
916
+ * @private
917
+ * @param {module:engine/model/element~Element} parent The element in which change happened.
918
+ * @param {Number} offset The offset at which change happened.
919
+ * @param {String} name The name of the removed element or `'$text'` for a character.
920
+ * @returns {Object} The diff item.
921
+ */
922
+ _getRemoveDiff( parent, offset, name ) {
923
+ return {
924
+ type: 'remove',
925
+ position: Position._createAt( parent, offset ),
926
+ name,
927
+ length: 1,
928
+ changeCount: this._changeCount++
929
+ };
930
+ }
931
+
932
+ /**
933
+ * Returns an array of objects where each one is a single attribute change description.
934
+ *
935
+ * @private
936
+ * @param {module:engine/model/range~Range} range The range where the change happened.
937
+ * @param {Map} oldAttributes A map, map iterator or compatible object that contains attributes before the change.
938
+ * @param {Map} newAttributes A map, map iterator or compatible object that contains attributes after the change.
939
+ * @returns {Array.<Object>} An array containing one or more diff items.
940
+ */
941
+ _getAttributesDiff( range, oldAttributes, newAttributes ) {
942
+ // Results holder.
943
+ const diffs = [];
944
+
945
+ // Clone new attributes as we will be performing changes on this object.
946
+ newAttributes = new Map( newAttributes );
947
+
948
+ // Look through old attributes.
949
+ for ( const [ key, oldValue ] of oldAttributes ) {
950
+ // Check what is the new value of the attribute (or if it was removed).
951
+ const newValue = newAttributes.has( key ) ? newAttributes.get( key ) : null;
952
+
953
+ // If values are different (or attribute was removed)...
954
+ if ( newValue !== oldValue ) {
955
+ // Add diff item.
956
+ diffs.push( {
957
+ type: 'attribute',
958
+ position: range.start,
959
+ range: range.clone(),
960
+ length: 1,
961
+ attributeKey: key,
962
+ attributeOldValue: oldValue,
963
+ attributeNewValue: newValue,
964
+ changeCount: this._changeCount++
965
+ } );
966
+ }
967
+
968
+ // Prevent returning two diff items for the same change.
969
+ newAttributes.delete( key );
970
+ }
971
+
972
+ // Look through new attributes that weren't handled above.
973
+ for ( const [ key, newValue ] of newAttributes ) {
974
+ // Each of them is a new attribute. Add diff item.
975
+ diffs.push( {
976
+ type: 'attribute',
977
+ position: range.start,
978
+ range: range.clone(),
979
+ length: 1,
980
+ attributeKey: key,
981
+ attributeOldValue: null,
982
+ attributeNewValue: newValue,
983
+ changeCount: this._changeCount++
984
+ } );
985
+ }
986
+
987
+ return diffs;
988
+ }
989
+
990
+ /**
991
+ * Checks whether given element or any of its parents is an element that is buffered as an inserted element.
992
+ *
993
+ * @private
994
+ * @param {module:engine/model/element~Element} element Element to check.
995
+ * @returns {Boolean}
996
+ */
997
+ _isInInsertedElement( element ) {
998
+ const parent = element.parent;
999
+
1000
+ if ( !parent ) {
1001
+ return false;
1002
+ }
1003
+
1004
+ const changes = this._changesInElement.get( parent );
1005
+ const offset = element.startOffset;
1006
+
1007
+ if ( changes ) {
1008
+ for ( const change of changes ) {
1009
+ if ( change.type == 'insert' && offset >= change.offset && offset < change.offset + change.howMany ) {
1010
+ return true;
1011
+ }
1012
+ }
1013
+ }
1014
+
1015
+ return this._isInInsertedElement( parent );
1016
+ }
1017
+
1018
+ /**
1019
+ * Removes deeply all buffered changes that are registered in elements from range specified by `parent`, `offset`
1020
+ * and `howMany`.
1021
+ *
1022
+ * @private
1023
+ * @param {module:engine/model/element~Element} parent
1024
+ * @param {Number} offset
1025
+ * @param {Number} howMany
1026
+ */
1027
+ _removeAllNestedChanges( parent, offset, howMany ) {
1028
+ const range = new Range( Position._createAt( parent, offset ), Position._createAt( parent, offset + howMany ) );
1029
+
1030
+ for ( const item of range.getItems( { shallow: true } ) ) {
1031
+ if ( item.is( 'element' ) ) {
1032
+ this._elementSnapshots.delete( item );
1033
+ this._changesInElement.delete( item );
1034
+
1035
+ this._removeAllNestedChanges( item, 0, item.maxOffset );
1036
+ }
1037
+ }
1038
+ }
1039
+ }
1040
+
1041
+ // Returns an array that is a copy of passed child list with the exception that text nodes are split to one or more
1042
+ // objects, each representing one character and attributes set on that character.
1043
+ function _getChildrenSnapshot( children ) {
1044
+ const snapshot = [];
1045
+
1046
+ for ( const child of children ) {
1047
+ if ( child.is( '$text' ) ) {
1048
+ for ( let i = 0; i < child.data.length; i++ ) {
1049
+ snapshot.push( {
1050
+ name: '$text',
1051
+ attributes: new Map( child.getAttributes() )
1052
+ } );
1053
+ }
1054
+ } else {
1055
+ snapshot.push( {
1056
+ name: child.name,
1057
+ attributes: new Map( child.getAttributes() )
1058
+ } );
1059
+ }
1060
+ }
1061
+
1062
+ return snapshot;
1063
+ }
1064
+
1065
+ // Generates array of actions for given changes set.
1066
+ // It simulates what `diff` function does.
1067
+ // Generated actions are:
1068
+ // - 'e' for 'equal' - when item at that position did not change,
1069
+ // - 'i' for 'insert' - when item at that position was inserted,
1070
+ // - 'r' for 'remove' - when item at that position was removed,
1071
+ // - 'a' for 'attribute' - when item at that position has it attributes changed.
1072
+ //
1073
+ // Example (assume that uppercase letters have bold attribute, compare with function code):
1074
+ //
1075
+ // children before: fooBAR
1076
+ // children after: foxybAR
1077
+ //
1078
+ // changes: type: remove, offset: 1, howMany: 1
1079
+ // type: insert, offset: 2, howMany: 2
1080
+ // type: attribute, offset: 4, howMany: 1
1081
+ //
1082
+ // expected actions: equal (f), remove (o), equal (o), insert (x), insert (y), attribute (b), equal (A), equal (R)
1083
+ //
1084
+ // steps taken by th script:
1085
+ //
1086
+ // 1. change = "type: remove, offset: 1, howMany: 1"; offset = 0; oldChildrenHandled = 0
1087
+ // 1.1 between this change and the beginning is one not-changed node, fill with one equal action, one old child has been handled
1088
+ // 1.2 this change removes one node, add one remove action
1089
+ // 1.3 change last visited `offset` to 1
1090
+ // 1.4 since an old child has been removed, one more old child has been handled
1091
+ // 1.5 actions at this point are: equal, remove
1092
+ //
1093
+ // 2. change = "type: insert, offset: 2, howMany: 2"; offset = 1; oldChildrenHandled = 2
1094
+ // 2.1 between this change and previous change is one not-changed node, add equal action, another one old children has been handled
1095
+ // 2.2 this change inserts two nodes, add two insert actions
1096
+ // 2.3 change last visited offset to the end of the inserted range, that is 4
1097
+ // 2.4 actions at this point are: equal, remove, equal, insert, insert
1098
+ //
1099
+ // 3. change = "type: attribute, offset: 4, howMany: 1"; offset = 4, oldChildrenHandled = 3
1100
+ // 3.1 between this change and previous change are no not-changed nodes
1101
+ // 3.2 this change changes one node, add one attribute action
1102
+ // 3.3 change last visited `offset` to the end of change range, that is 5
1103
+ // 3.4 since an old child has been changed, one more old child has been handled
1104
+ // 3.5 actions at this point are: equal, remove, equal, insert, insert, attribute
1105
+ //
1106
+ // 4. after loop oldChildrenHandled = 4, oldChildrenLength = 6 (fooBAR is 6 characters)
1107
+ // 4.1 fill up with two equal actions
1108
+ //
1109
+ // The result actions are: equal, remove, equal, insert, insert, attribute, equal, equal.
1110
+ function _generateActionsFromChanges( oldChildrenLength, changes ) {
1111
+ const actions = [];
1112
+
1113
+ let offset = 0;
1114
+ let oldChildrenHandled = 0;
1115
+
1116
+ // Go through all buffered changes.
1117
+ for ( const change of changes ) {
1118
+ // First, fill "holes" between changes with "equal" actions.
1119
+ if ( change.offset > offset ) {
1120
+ for ( let i = 0; i < change.offset - offset; i++ ) {
1121
+ actions.push( 'e' );
1122
+ }
1123
+
1124
+ oldChildrenHandled += change.offset - offset;
1125
+ }
1126
+
1127
+ // Then, fill up actions accordingly to change type.
1128
+ if ( change.type == 'insert' ) {
1129
+ for ( let i = 0; i < change.howMany; i++ ) {
1130
+ actions.push( 'i' );
1131
+ }
1132
+
1133
+ // The last handled offset is after inserted range.
1134
+ offset = change.offset + change.howMany;
1135
+ } else if ( change.type == 'remove' ) {
1136
+ for ( let i = 0; i < change.howMany; i++ ) {
1137
+ actions.push( 'r' );
1138
+ }
1139
+
1140
+ // The last handled offset is at the position where the nodes were removed.
1141
+ offset = change.offset;
1142
+ // We removed `howMany` old nodes, update `oldChildrenHandled`.
1143
+ oldChildrenHandled += change.howMany;
1144
+ } else {
1145
+ actions.push( ...'a'.repeat( change.howMany ).split( '' ) );
1146
+
1147
+ // The last handled offset is at the position after the changed range.
1148
+ offset = change.offset + change.howMany;
1149
+ // We changed `howMany` old nodes, update `oldChildrenHandled`.
1150
+ oldChildrenHandled += change.howMany;
1151
+ }
1152
+ }
1153
+
1154
+ // Fill "equal" actions at the end of actions set. Use `oldChildrenHandled` to see how many children
1155
+ // has not been changed / removed at the end of their parent.
1156
+ if ( oldChildrenHandled < oldChildrenLength ) {
1157
+ for ( let i = 0; i < oldChildrenLength - oldChildrenHandled - offset; i++ ) {
1158
+ actions.push( 'e' );
1159
+ }
1160
+ }
1161
+
1162
+ return actions;
1163
+ }
1164
+
1165
+ // Filter callback for Array.filter that filters out change entries that are in graveyard.
1166
+ function _changesInGraveyardFilter( entry ) {
1167
+ const posInGy = entry.position && entry.position.root.rootName == '$graveyard';
1168
+ const rangeInGy = entry.range && entry.range.root.rootName == '$graveyard';
1169
+
1170
+ return !posInGy && !rangeInGy;
1171
+ }
1172
+
1173
+ /**
1174
+ * The single diff item.
1175
+ *
1176
+ * Could be one of:
1177
+ *
1178
+ * * {@link module:engine/model/differ~DiffItemInsert `DiffItemInsert`},
1179
+ * * {@link module:engine/model/differ~DiffItemRemove `DiffItemRemove`},
1180
+ * * {@link module:engine/model/differ~DiffItemAttribute `DiffItemAttribute`}.
1181
+ *
1182
+ * @interface DiffItem
1183
+ */
1184
+
1185
+ /**
1186
+ * The single diff item for inserted nodes.
1187
+ *
1188
+ * @class DiffItemInsert
1189
+ * @implements module:engine/model/differ~DiffItem
1190
+ */
1191
+
1192
+ /**
1193
+ * The type of diff item.
1194
+ *
1195
+ * @member {'insert'} module:engine/model/differ~DiffItemInsert#type
1196
+ */
1197
+
1198
+ /**
1199
+ * The name of the inserted elements or `'$text'` for a text node.
1200
+ *
1201
+ * @member {String} module:engine/model/differ~DiffItemInsert#name
1202
+ */
1203
+
1204
+ /**
1205
+ * The position where the node was inserted.
1206
+ *
1207
+ * @member {module:engine/model/position~Position} module:engine/model/differ~DiffItemInsert#position
1208
+ */
1209
+
1210
+ /**
1211
+ * The length of an inserted text node. For elements it is always 1 as each inserted element is counted as a one.
1212
+ *
1213
+ * @member {Number} module:engine/model/differ~DiffItemInsert#length
1214
+ */
1215
+
1216
+ /**
1217
+ * The single diff item for removed nodes.
1218
+ *
1219
+ * @class DiffItemRemove
1220
+ * @implements module:engine/model/differ~DiffItem
1221
+ */
1222
+
1223
+ /**
1224
+ * The type of diff item.
1225
+ *
1226
+ * @member {'remove'} module:engine/model/differ~DiffItemRemove#type
1227
+ */
1228
+
1229
+ /**
1230
+ * The name of the removed element or `'$text'` for a text node.
1231
+ *
1232
+ * @member {String} module:engine/model/differ~DiffItemRemove#name
1233
+ */
1234
+
1235
+ /**
1236
+ * The position where the node was removed.
1237
+ *
1238
+ * @member {module:engine/model/position~Position} module:engine/model/differ~DiffItemRemove#position
1239
+ */
1240
+
1241
+ /**
1242
+ * The length of a removed text node. For elements it is always 1 as each removed element is counted as a one.
1243
+ *
1244
+ * @member {Number} module:engine/model/differ~DiffItemRemove#length
1245
+ */
1246
+
1247
+ /**
1248
+ * The single diff item for attribute change.
1249
+ *
1250
+ * @class DiffItemAttribute
1251
+ * @implements module:engine/model/differ~DiffItem
1252
+ */
1253
+
1254
+ /**
1255
+ * The type of diff item.
1256
+ *
1257
+ * @member {'attribute'} module:engine/model/differ~DiffItemAttribute#type
1258
+ */
1259
+
1260
+ /**
1261
+ * The name of the changed attribute.
1262
+ *
1263
+ * @member {String} module:engine/model/differ~DiffItemAttribute#attributeKey
1264
+ */
1265
+
1266
+ /**
1267
+ * An attribute previous value (before change).
1268
+ *
1269
+ * @member {String} module:engine/model/differ~DiffItemAttribute#attributeOldValue
1270
+ */
1271
+
1272
+ /**
1273
+ * An attribute new value (after change).
1274
+ *
1275
+ * @member {String} module:engine/model/differ~DiffItemAttribute#attributeNewValue
1276
+ */
1277
+
1278
+ /**
1279
+ * The range where the change happened.
1280
+ *
1281
+ * @member {module:engine/model/range~Range} module:engine/model/differ~DiffItemAttribute#range
1282
+ */