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