@ckeditor/ckeditor5-engine 34.2.0 → 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 (125) hide show
  1. package/CHANGELOG.md +823 -0
  2. package/LICENSE.md +4 -0
  3. package/package.json +32 -25
  4. package/src/controller/datacontroller.js +467 -561
  5. package/src/controller/editingcontroller.js +168 -204
  6. package/src/conversion/conversion.js +541 -565
  7. package/src/conversion/conversionhelpers.js +24 -28
  8. package/src/conversion/downcastdispatcher.js +457 -686
  9. package/src/conversion/downcasthelpers.js +1583 -1965
  10. package/src/conversion/mapper.js +518 -707
  11. package/src/conversion/modelconsumable.js +240 -283
  12. package/src/conversion/upcastdispatcher.js +372 -718
  13. package/src/conversion/upcasthelpers.js +707 -818
  14. package/src/conversion/viewconsumable.js +524 -581
  15. package/src/dataprocessor/basichtmlwriter.js +12 -16
  16. package/src/dataprocessor/dataprocessor.js +5 -0
  17. package/src/dataprocessor/htmldataprocessor.js +101 -117
  18. package/src/dataprocessor/htmlwriter.js +1 -18
  19. package/src/dataprocessor/xmldataprocessor.js +117 -138
  20. package/src/dev-utils/model.js +260 -352
  21. package/src/dev-utils/operationreplayer.js +106 -126
  22. package/src/dev-utils/utils.js +34 -51
  23. package/src/dev-utils/view.js +632 -753
  24. package/src/index.js +0 -11
  25. package/src/model/batch.js +111 -127
  26. package/src/model/differ.js +988 -1233
  27. package/src/model/document.js +340 -449
  28. package/src/model/documentfragment.js +327 -364
  29. package/src/model/documentselection.js +996 -1189
  30. package/src/model/element.js +306 -410
  31. package/src/model/history.js +224 -262
  32. package/src/model/item.js +5 -0
  33. package/src/model/liveposition.js +84 -145
  34. package/src/model/liverange.js +108 -185
  35. package/src/model/markercollection.js +379 -480
  36. package/src/model/model.js +883 -1034
  37. package/src/model/node.js +419 -463
  38. package/src/model/nodelist.js +175 -201
  39. package/src/model/operation/attributeoperation.js +153 -182
  40. package/src/model/operation/detachoperation.js +64 -83
  41. package/src/model/operation/insertoperation.js +135 -166
  42. package/src/model/operation/markeroperation.js +114 -140
  43. package/src/model/operation/mergeoperation.js +163 -191
  44. package/src/model/operation/moveoperation.js +157 -187
  45. package/src/model/operation/nooperation.js +28 -38
  46. package/src/model/operation/operation.js +106 -125
  47. package/src/model/operation/operationfactory.js +30 -34
  48. package/src/model/operation/renameoperation.js +109 -135
  49. package/src/model/operation/rootattributeoperation.js +155 -188
  50. package/src/model/operation/splitoperation.js +196 -232
  51. package/src/model/operation/transform.js +1833 -2204
  52. package/src/model/operation/utils.js +140 -204
  53. package/src/model/position.js +899 -1053
  54. package/src/model/range.js +910 -1028
  55. package/src/model/rootelement.js +77 -97
  56. package/src/model/schema.js +1189 -1835
  57. package/src/model/selection.js +745 -862
  58. package/src/model/text.js +90 -114
  59. package/src/model/textproxy.js +204 -240
  60. package/src/model/treewalker.js +316 -397
  61. package/src/model/typecheckable.js +16 -0
  62. package/src/model/utils/autoparagraphing.js +32 -44
  63. package/src/model/utils/deletecontent.js +334 -418
  64. package/src/model/utils/findoptimalinsertionrange.js +25 -36
  65. package/src/model/utils/getselectedcontent.js +96 -118
  66. package/src/model/utils/insertcontent.js +654 -773
  67. package/src/model/utils/insertobject.js +96 -119
  68. package/src/model/utils/modifyselection.js +120 -158
  69. package/src/model/utils/selection-post-fixer.js +153 -201
  70. package/src/model/writer.js +1305 -1474
  71. package/src/view/attributeelement.js +189 -225
  72. package/src/view/containerelement.js +75 -85
  73. package/src/view/document.js +172 -215
  74. package/src/view/documentfragment.js +200 -249
  75. package/src/view/documentselection.js +338 -367
  76. package/src/view/domconverter.js +1371 -1613
  77. package/src/view/downcastwriter.js +1747 -2076
  78. package/src/view/editableelement.js +81 -97
  79. package/src/view/element.js +739 -890
  80. package/src/view/elementdefinition.js +5 -0
  81. package/src/view/emptyelement.js +82 -92
  82. package/src/view/filler.js +35 -50
  83. package/src/view/item.js +5 -0
  84. package/src/view/matcher.js +260 -559
  85. package/src/view/node.js +274 -360
  86. package/src/view/observer/arrowkeysobserver.js +19 -28
  87. package/src/view/observer/bubblingemittermixin.js +120 -263
  88. package/src/view/observer/bubblingeventinfo.js +47 -55
  89. package/src/view/observer/clickobserver.js +7 -13
  90. package/src/view/observer/compositionobserver.js +14 -24
  91. package/src/view/observer/domeventdata.js +57 -67
  92. package/src/view/observer/domeventobserver.js +40 -64
  93. package/src/view/observer/fakeselectionobserver.js +81 -96
  94. package/src/view/observer/focusobserver.js +45 -61
  95. package/src/view/observer/inputobserver.js +7 -13
  96. package/src/view/observer/keyobserver.js +17 -27
  97. package/src/view/observer/mouseobserver.js +7 -14
  98. package/src/view/observer/mutationobserver.js +220 -315
  99. package/src/view/observer/observer.js +81 -102
  100. package/src/view/observer/selectionobserver.js +191 -246
  101. package/src/view/observer/tabobserver.js +23 -36
  102. package/src/view/placeholder.js +128 -173
  103. package/src/view/position.js +350 -401
  104. package/src/view/range.js +453 -513
  105. package/src/view/rawelement.js +85 -112
  106. package/src/view/renderer.js +874 -1014
  107. package/src/view/rooteditableelement.js +80 -90
  108. package/src/view/selection.js +608 -689
  109. package/src/view/styles/background.js +43 -44
  110. package/src/view/styles/border.js +220 -276
  111. package/src/view/styles/margin.js +8 -17
  112. package/src/view/styles/padding.js +8 -16
  113. package/src/view/styles/utils.js +127 -160
  114. package/src/view/stylesmap.js +728 -905
  115. package/src/view/text.js +102 -126
  116. package/src/view/textproxy.js +144 -170
  117. package/src/view/treewalker.js +383 -479
  118. package/src/view/typecheckable.js +19 -0
  119. package/src/view/uielement.js +166 -187
  120. package/src/view/upcastwriter.js +395 -449
  121. package/src/view/view.js +569 -664
  122. package/src/dataprocessor/dataprocessor.jsdoc +0 -64
  123. package/src/model/item.jsdoc +0 -14
  124. package/src/view/elementdefinition.jsdoc +0 -59
  125. package/src/view/item.jsdoc +0 -14
@@ -2,16 +2,14 @@
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/range
8
7
  */
9
-
8
+ import TypeCheckable from './typecheckable';
10
9
  import Position from './position';
11
10
  import TreeWalker from './treewalker';
12
11
  import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
13
12
  import compareArrays from '@ckeditor/ckeditor5-utils/src/comparearrays';
14
-
15
13
  /**
16
14
  * Represents a range in the model tree.
17
15
  *
@@ -21,1029 +19,913 @@ import compareArrays from '@ckeditor/ckeditor5-utils/src/comparearrays';
21
19
  * You can create range instances via its constructor or the `createRange*()` factory methods of
22
20
  * {@link module:engine/model/model~Model} and {@link module:engine/model/writer~Writer}.
23
21
  */
24
- export default class Range {
25
- /**
26
- * Creates a range spanning from `start` position to `end` position.
27
- *
28
- * @param {module:engine/model/position~Position} start The start position.
29
- * @param {module:engine/model/position~Position} [end] The end position. If not set,
30
- * the range will be collapsed at the `start` position.
31
- */
32
- constructor( start, end = null ) {
33
- /**
34
- * Start position.
35
- *
36
- * @readonly
37
- * @member {module:engine/model/position~Position}
38
- */
39
- this.start = Position._createAt( start );
40
-
41
- /**
42
- * End position.
43
- *
44
- * @readonly
45
- * @member {module:engine/model/position~Position}
46
- */
47
- this.end = end ? Position._createAt( end ) : Position._createAt( start );
48
-
49
- // If the range is collapsed, treat in a similar way as a position and set its boundaries stickiness to 'toNone'.
50
- // In other case, make the boundaries stick to the "inside" of the range.
51
- this.start.stickiness = this.isCollapsed ? 'toNone' : 'toNext';
52
- this.end.stickiness = this.isCollapsed ? 'toNone' : 'toPrevious';
53
- }
54
-
55
- /**
56
- * Iterable interface.
57
- *
58
- * Iterates over all {@link module:engine/model/item~Item items} that are in this range and returns
59
- * them together with additional information like length or {@link module:engine/model/position~Position positions},
60
- * grouped as {@link module:engine/model/treewalker~TreeWalkerValue}.
61
- * It iterates over all {@link module:engine/model/textproxy~TextProxy text contents} that are inside the range
62
- * and all the {@link module:engine/model/element~Element}s that are entered into when iterating over this range.
63
- *
64
- * This iterator uses {@link module:engine/model/treewalker~TreeWalker} with `boundaries` set to this range
65
- * and `ignoreElementEnd` option set to `true`.
66
- *
67
- * @returns {Iterable.<module:engine/model/treewalker~TreeWalkerValue>}
68
- */
69
- * [ Symbol.iterator ]() {
70
- yield* new TreeWalker( { boundaries: this, ignoreElementEnd: true } );
71
- }
72
-
73
- /**
74
- * Returns whether the range is collapsed, that is if {@link #start} and
75
- * {@link #end} positions are equal.
76
- *
77
- * @type {Boolean}
78
- */
79
- get isCollapsed() {
80
- return this.start.isEqual( this.end );
81
- }
82
-
83
- /**
84
- * Returns whether this range is flat, that is if {@link #start} position and
85
- * {@link #end} position are in the same {@link module:engine/model/position~Position#parent}.
86
- *
87
- * @type {Boolean}
88
- */
89
- get isFlat() {
90
- const startParentPath = this.start.getParentPath();
91
- const endParentPath = this.end.getParentPath();
92
-
93
- return compareArrays( startParentPath, endParentPath ) == 'same';
94
- }
95
-
96
- /**
97
- * Range root element.
98
- *
99
- * @type {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment}
100
- */
101
- get root() {
102
- return this.start.root;
103
- }
104
-
105
- /**
106
- * Checks whether this range contains given {@link module:engine/model/position~Position position}.
107
- *
108
- * @param {module:engine/model/position~Position} position Position to check.
109
- * @returns {Boolean} `true` if given {@link module:engine/model/position~Position position} is contained
110
- * in this range,`false` otherwise.
111
- */
112
- containsPosition( position ) {
113
- return position.isAfter( this.start ) && position.isBefore( this.end );
114
- }
115
-
116
- /**
117
- * Checks whether this range contains given {@link ~Range range}.
118
- *
119
- * @param {module:engine/model/range~Range} otherRange Range to check.
120
- * @param {Boolean} [loose=false] Whether the check is loose or strict. If the check is strict (`false`), compared range cannot
121
- * start or end at the same position as this range boundaries. If the check is loose (`true`), compared range can start, end or
122
- * even be equal to this range. Note that collapsed ranges are always compared in strict mode.
123
- * @returns {Boolean} `true` if given {@link ~Range range} boundaries are contained by this range, `false` otherwise.
124
- */
125
- containsRange( otherRange, loose = false ) {
126
- if ( otherRange.isCollapsed ) {
127
- loose = false;
128
- }
129
-
130
- const containsStart = this.containsPosition( otherRange.start ) || ( loose && this.start.isEqual( otherRange.start ) );
131
- const containsEnd = this.containsPosition( otherRange.end ) || ( loose && this.end.isEqual( otherRange.end ) );
132
-
133
- return containsStart && containsEnd;
134
- }
135
-
136
- /**
137
- * Checks whether given {@link module:engine/model/item~Item} is inside this range.
138
- *
139
- * @param {module:engine/model/item~Item} item Model item to check.
140
- */
141
- containsItem( item ) {
142
- const pos = Position._createBefore( item );
143
-
144
- return this.containsPosition( pos ) || this.start.isEqual( pos );
145
- }
146
-
147
- /**
148
- * Checks whether this object is of the given.
149
- *
150
- * range.is( 'range' ); // -> true
151
- * range.is( 'model:range' ); // -> true
152
- *
153
- * range.is( 'view:range' ); // -> false
154
- * range.is( 'documentSelection' ); // -> false
155
- *
156
- * {@link module:engine/model/node~Node#is Check the entire list of model objects} which implement the `is()` method.
157
- *
158
- * @param {String} type
159
- * @returns {Boolean}
160
- */
161
- is( type ) {
162
- return type === 'range' || type === 'model:range';
163
- }
164
-
165
- /**
166
- * Two ranges are equal if their {@link #start} and {@link #end} positions are equal.
167
- *
168
- * @param {module:engine/model/range~Range} otherRange Range to compare with.
169
- * @returns {Boolean} `true` if ranges are equal, `false` otherwise.
170
- */
171
- isEqual( otherRange ) {
172
- return this.start.isEqual( otherRange.start ) && this.end.isEqual( otherRange.end );
173
- }
174
-
175
- /**
176
- * Checks and returns whether this range intersects with given range.
177
- *
178
- * @param {module:engine/model/range~Range} otherRange Range to compare with.
179
- * @returns {Boolean} `true` if ranges intersect, `false` otherwise.
180
- */
181
- isIntersecting( otherRange ) {
182
- return this.start.isBefore( otherRange.end ) && this.end.isAfter( otherRange.start );
183
- }
184
-
185
- /**
186
- * Computes which part(s) of this {@link ~Range range} is not a part of given {@link ~Range range}.
187
- * Returned array contains zero, one or two {@link ~Range ranges}.
188
- *
189
- * Examples:
190
- *
191
- * let range = model.createRange(
192
- * model.createPositionFromPath( root, [ 2, 7 ] ),
193
- * model.createPositionFromPath( root, [ 4, 0, 1 ] )
194
- * );
195
- * let otherRange = model.createRange( model.createPositionFromPath( root, [ 1 ] ), model.createPositionFromPath( root, [ 5 ] ) );
196
- * let transformed = range.getDifference( otherRange );
197
- * // transformed array has no ranges because `otherRange` contains `range`
198
- *
199
- * otherRange = model.createRange( model.createPositionFromPath( root, [ 1 ] ), model.createPositionFromPath( root, [ 3 ] ) );
200
- * transformed = range.getDifference( otherRange );
201
- * // transformed array has one range: from [ 3 ] to [ 4, 0, 1 ]
202
- *
203
- * otherRange = model.createRange( model.createPositionFromPath( root, [ 3 ] ), model.createPositionFromPath( root, [ 4 ] ) );
204
- * transformed = range.getDifference( otherRange );
205
- * // transformed array has two ranges: from [ 2, 7 ] to [ 3 ] and from [ 4 ] to [ 4, 0, 1 ]
206
- *
207
- * @param {module:engine/model/range~Range} otherRange Range to differentiate against.
208
- * @returns {Array.<module:engine/model/range~Range>} The difference between ranges.
209
- */
210
- getDifference( otherRange ) {
211
- const ranges = [];
212
-
213
- if ( this.isIntersecting( otherRange ) ) {
214
- // Ranges intersect.
215
-
216
- if ( this.containsPosition( otherRange.start ) ) {
217
- // Given range start is inside this range. This means that we have to
218
- // add shrunken range - from the start to the middle of this range.
219
- ranges.push( new Range( this.start, otherRange.start ) );
220
- }
221
-
222
- if ( this.containsPosition( otherRange.end ) ) {
223
- // Given range end is inside this range. This means that we have to
224
- // add shrunken range - from the middle of this range to the end.
225
- ranges.push( new Range( otherRange.end, this.end ) );
226
- }
227
- } else {
228
- // Ranges do not intersect, return the original range.
229
- ranges.push( new Range( this.start, this.end ) );
230
- }
231
-
232
- return ranges;
233
- }
234
-
235
- /**
236
- * Returns an intersection of this {@link ~Range range} and given {@link ~Range range}.
237
- * Intersection is a common part of both of those ranges. If ranges has no common part, returns `null`.
238
- *
239
- * Examples:
240
- *
241
- * let range = model.createRange(
242
- * model.createPositionFromPath( root, [ 2, 7 ] ),
243
- * model.createPositionFromPath( root, [ 4, 0, 1 ] )
244
- * );
245
- * let otherRange = model.createRange( model.createPositionFromPath( root, [ 1 ] ), model.createPositionFromPath( root, [ 2 ] ) );
246
- * let transformed = range.getIntersection( otherRange ); // null - ranges have no common part
247
- *
248
- * otherRange = model.createRange( model.createPositionFromPath( root, [ 3 ] ), model.createPositionFromPath( root, [ 5 ] ) );
249
- * transformed = range.getIntersection( otherRange ); // range from [ 3 ] to [ 4, 0, 1 ]
250
- *
251
- * @param {module:engine/model/range~Range} otherRange Range to check for intersection.
252
- * @returns {module:engine/model/range~Range|null} A common part of given ranges or `null` if ranges have no common part.
253
- */
254
- getIntersection( otherRange ) {
255
- if ( this.isIntersecting( otherRange ) ) {
256
- // Ranges intersect, so a common range will be returned.
257
- // At most, it will be same as this range.
258
- let commonRangeStart = this.start;
259
- let commonRangeEnd = this.end;
260
-
261
- if ( this.containsPosition( otherRange.start ) ) {
262
- // Given range start is inside this range. This means thaNt we have to
263
- // shrink common range to the given range start.
264
- commonRangeStart = otherRange.start;
265
- }
266
-
267
- if ( this.containsPosition( otherRange.end ) ) {
268
- // Given range end is inside this range. This means that we have to
269
- // shrink common range to the given range end.
270
- commonRangeEnd = otherRange.end;
271
- }
272
-
273
- return new Range( commonRangeStart, commonRangeEnd );
274
- }
275
-
276
- // Ranges do not intersect, so they do not have common part.
277
- return null;
278
- }
279
-
280
- /**
281
- * Returns a range created by joining this {@link ~Range range} with the given {@link ~Range range}.
282
- * If ranges have no common part, returns `null`.
283
- *
284
- * Examples:
285
- *
286
- * let range = model.createRange(
287
- * model.createPositionFromPath( root, [ 2, 7 ] ),
288
- * model.createPositionFromPath( root, [ 4, 0, 1 ] )
289
- * );
290
- * let otherRange = model.createRange(
291
- * model.createPositionFromPath( root, [ 1 ] ),
292
- * model.createPositionFromPath( root, [ 2 ] )
293
- * );
294
- * let transformed = range.getJoined( otherRange ); // null - ranges have no common part
295
- *
296
- * otherRange = model.createRange(
297
- * model.createPositionFromPath( root, [ 3 ] ),
298
- * model.createPositionFromPath( root, [ 5 ] )
299
- * );
300
- * transformed = range.getJoined( otherRange ); // range from [ 2, 7 ] to [ 5 ]
301
- *
302
- * @param {module:engine/model/range~Range} otherRange Range to be joined.
303
- * @param {Boolean} [loose=false] Whether the intersection check is loose or strict. If the check is strict (`false`),
304
- * ranges are tested for intersection or whether start/end positions are equal. If the check is loose (`true`),
305
- * compared range is also checked if it's {@link module:engine/model/position~Position#isTouching touching} current range.
306
- * @returns {module:engine/model/range~Range|null} A sum of given ranges or `null` if ranges have no common part.
307
- */
308
- getJoined( otherRange, loose = false ) {
309
- let shouldJoin = this.isIntersecting( otherRange );
310
-
311
- if ( !shouldJoin ) {
312
- if ( this.start.isBefore( otherRange.start ) ) {
313
- shouldJoin = loose ? this.end.isTouching( otherRange.start ) : this.end.isEqual( otherRange.start );
314
- } else {
315
- shouldJoin = loose ? otherRange.end.isTouching( this.start ) : otherRange.end.isEqual( this.start );
316
- }
317
- }
318
-
319
- if ( !shouldJoin ) {
320
- return null;
321
- }
322
-
323
- let startPosition = this.start;
324
- let endPosition = this.end;
325
-
326
- if ( otherRange.start.isBefore( startPosition ) ) {
327
- startPosition = otherRange.start;
328
- }
329
-
330
- if ( otherRange.end.isAfter( endPosition ) ) {
331
- endPosition = otherRange.end;
332
- }
333
-
334
- return new Range( startPosition, endPosition );
335
- }
336
-
337
- /**
338
- * Computes and returns the smallest set of {@link #isFlat flat} ranges, that covers this range in whole.
339
- *
340
- * See an example of a model structure (`[` and `]` are range boundaries):
341
- *
342
- * root root
343
- * |- element DIV DIV P2 P3 DIV
344
- * | |- element H H P1 f o o b a r H P4
345
- * | | |- "fir[st" fir[st lorem se]cond ipsum
346
- * | |- element P1
347
- * | | |- "lorem" ||
348
- * |- element P2 ||
349
- * | |- "foo" VV
350
- * |- element P3
351
- * | |- "bar" root
352
- * |- element DIV DIV [P2 P3] DIV
353
- * | |- element H H [P1] f o o b a r H P4
354
- * | | |- "se]cond" fir[st] lorem [se]cond ipsum
355
- * | |- element P4
356
- * | | |- "ipsum"
357
- *
358
- * As it can be seen, letters contained in the range are: `stloremfoobarse`, spread across different parents.
359
- * We are looking for minimal set of flat ranges that contains the same nodes.
360
- *
361
- * Minimal flat ranges for above range `( [ 0, 0, 3 ], [ 3, 0, 2 ] )` will be:
362
- *
363
- * ( [ 0, 0, 3 ], [ 0, 0, 5 ] ) = "st"
364
- * ( [ 0, 1 ], [ 0, 2 ] ) = element P1 ("lorem")
365
- * ( [ 1 ], [ 3 ] ) = element P2, element P3 ("foobar")
366
- * ( [ 3, 0, 0 ], [ 3, 0, 2 ] ) = "se"
367
- *
368
- * **Note:** if an {@link module:engine/model/element~Element element} is not wholly contained in this range, it won't be returned
369
- * in any of the returned flat ranges. See in the example how `H` elements at the beginning and at the end of the range
370
- * were omitted. Only their parts that were wholly in the range were returned.
371
- *
372
- * **Note:** this method is not returning flat ranges that contain no nodes.
373
- *
374
- * @returns {Array.<module:engine/model/range~Range>} Array of flat ranges covering this range.
375
- */
376
- getMinimalFlatRanges() {
377
- const ranges = [];
378
- const diffAt = this.start.getCommonPath( this.end ).length;
379
-
380
- const pos = Position._createAt( this.start );
381
- let posParent = pos.parent;
382
-
383
- // Go up.
384
- while ( pos.path.length > diffAt + 1 ) {
385
- const howMany = posParent.maxOffset - pos.offset;
386
-
387
- if ( howMany !== 0 ) {
388
- ranges.push( new Range( pos, pos.getShiftedBy( howMany ) ) );
389
- }
390
-
391
- pos.path = pos.path.slice( 0, -1 );
392
- pos.offset++;
393
- posParent = posParent.parent;
394
- }
395
-
396
- // Go down.
397
- while ( pos.path.length <= this.end.path.length ) {
398
- const offset = this.end.path[ pos.path.length - 1 ];
399
- const howMany = offset - pos.offset;
400
-
401
- if ( howMany !== 0 ) {
402
- ranges.push( new Range( pos, pos.getShiftedBy( howMany ) ) );
403
- }
404
-
405
- pos.offset = offset;
406
- pos.path.push( 0 );
407
- }
408
-
409
- return ranges;
410
- }
411
-
412
- /**
413
- * Creates a {@link module:engine/model/treewalker~TreeWalker TreeWalker} instance with this range as a boundary.
414
- *
415
- * For example, to iterate over all items in the entire document root:
416
- *
417
- * // Create a range spanning over the entire root content:
418
- * const range = editor.model.createRangeIn( editor.model.document.getRoot() );
419
- *
420
- * // Iterate over all items in this range:
421
- * for ( const value of range.getWalker() ) {
422
- * console.log( value.item );
423
- * }
424
- *
425
- * @param {Object} options Object with configuration options. See {@link module:engine/model/treewalker~TreeWalker}.
426
- * @param {module:engine/model/position~Position} [options.startPosition]
427
- * @param {Boolean} [options.singleCharacters=false]
428
- * @param {Boolean} [options.shallow=false]
429
- * @param {Boolean} [options.ignoreElementEnd=false]
430
- * @returns {module:engine/model/treewalker~TreeWalker}
431
- */
432
- getWalker( options = {} ) {
433
- options.boundaries = this;
434
-
435
- return new TreeWalker( options );
436
- }
437
-
438
- /**
439
- * Returns an iterator that iterates over all {@link module:engine/model/item~Item items} that are in this range and returns
440
- * them.
441
- *
442
- * This method uses {@link module:engine/model/treewalker~TreeWalker} with `boundaries` set to this range and `ignoreElementEnd` option
443
- * set to `true`. However it returns only {@link module:engine/model/item~Item model items},
444
- * not {@link module:engine/model/treewalker~TreeWalkerValue}.
445
- *
446
- * You may specify additional options for the tree walker. See {@link module:engine/model/treewalker~TreeWalker} for
447
- * a full list of available options.
448
- *
449
- * @param {Object} [options] Object with configuration options. See {@link module:engine/model/treewalker~TreeWalker}.
450
- * @returns {Iterable.<module:engine/model/item~Item>}
451
- */
452
- * getItems( options = {} ) {
453
- options.boundaries = this;
454
- options.ignoreElementEnd = true;
455
-
456
- const treeWalker = new TreeWalker( options );
457
-
458
- for ( const value of treeWalker ) {
459
- yield value.item;
460
- }
461
- }
462
-
463
- /**
464
- * Returns an iterator that iterates over all {@link module:engine/model/position~Position positions} that are boundaries or
465
- * contained in this range.
466
- *
467
- * This method uses {@link module:engine/model/treewalker~TreeWalker} with `boundaries` set to this range. However it returns only
468
- * {@link module:engine/model/position~Position positions}, not {@link module:engine/model/treewalker~TreeWalkerValue}.
469
- *
470
- * You may specify additional options for the tree walker. See {@link module:engine/model/treewalker~TreeWalker} for
471
- * a full list of available options.
472
- *
473
- * @param {Object} options Object with configuration options. See {@link module:engine/model/treewalker~TreeWalker}.
474
- * @returns {Iterable.<module:engine/model/position~Position>}
475
- */
476
- * getPositions( options = {} ) {
477
- options.boundaries = this;
478
-
479
- const treeWalker = new TreeWalker( options );
480
-
481
- yield treeWalker.position;
482
-
483
- for ( const value of treeWalker ) {
484
- yield value.nextPosition;
485
- }
486
- }
487
-
488
- /**
489
- * Returns a range that is a result of transforming this range by given `operation`.
490
- *
491
- * **Note:** transformation may break one range into multiple ranges (for example, when a part of the range is
492
- * moved to a different part of document tree). For this reason, an array is returned by this method and it
493
- * may contain one or more `Range` instances.
494
- *
495
- * @param {module:engine/model/operation/operation~Operation} operation Operation to transform range by.
496
- * @returns {Array.<module:engine/model/range~Range>} Range which is the result of transformation.
497
- */
498
- getTransformedByOperation( operation ) {
499
- switch ( operation.type ) {
500
- case 'insert':
501
- return this._getTransformedByInsertOperation( operation );
502
- case 'move':
503
- case 'remove':
504
- case 'reinsert':
505
- return this._getTransformedByMoveOperation( operation );
506
- case 'split':
507
- return [ this._getTransformedBySplitOperation( operation ) ];
508
- case 'merge':
509
- return [ this._getTransformedByMergeOperation( operation ) ];
510
- }
511
-
512
- return [ new Range( this.start, this.end ) ];
513
- }
514
-
515
- /**
516
- * Returns a range that is a result of transforming this range by multiple `operations`.
517
- *
518
- * @see ~Range#getTransformedByOperation
519
- * @param {Iterable.<module:engine/model/operation/operation~Operation>} operations Operations to transform the range by.
520
- * @returns {Array.<module:engine/model/range~Range>} Range which is the result of transformation.
521
- */
522
- getTransformedByOperations( operations ) {
523
- const ranges = [ new Range( this.start, this.end ) ];
524
-
525
- for ( const operation of operations ) {
526
- for ( let i = 0; i < ranges.length; i++ ) {
527
- const result = ranges[ i ].getTransformedByOperation( operation );
528
-
529
- ranges.splice( i, 1, ...result );
530
- i += result.length - 1;
531
- }
532
- }
533
-
534
- // It may happen that a range is split into two, and then the part of second "piece" is moved into first
535
- // "piece". In this case we will have incorrect third range, which should not be included in the result --
536
- // because it is already included in the first "piece". In this loop we are looking for all such ranges that
537
- // are inside other ranges and we simply remove them.
538
- for ( let i = 0; i < ranges.length; i++ ) {
539
- const range = ranges[ i ];
540
-
541
- for ( let j = i + 1; j < ranges.length; j++ ) {
542
- const next = ranges[ j ];
543
-
544
- if ( range.containsRange( next ) || next.containsRange( range ) || range.isEqual( next ) ) {
545
- ranges.splice( j, 1 );
546
- }
547
- }
548
- }
549
-
550
- return ranges;
551
- }
552
-
553
- /**
554
- * Returns an {@link module:engine/model/element~Element} or {@link module:engine/model/documentfragment~DocumentFragment}
555
- * which is a common ancestor of the range's both ends (in which the entire range is contained).
556
- *
557
- * @returns {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment|null}
558
- */
559
- getCommonAncestor() {
560
- return this.start.getCommonAncestor( this.end );
561
- }
562
-
563
- /**
564
- * Returns an {@link module:engine/model/element~Element Element} contained by the range.
565
- * The element will be returned when it is the **only** node within the range and **fully–contained**
566
- * at the same time.
567
- *
568
- * @returns {module:engine/model/element~Element|null}
569
- */
570
- getContainedElement() {
571
- if ( this.isCollapsed ) {
572
- return null;
573
- }
574
-
575
- const nodeAfterStart = this.start.nodeAfter;
576
- const nodeBeforeEnd = this.end.nodeBefore;
577
-
578
- if ( nodeAfterStart && nodeAfterStart.is( 'element' ) && nodeAfterStart === nodeBeforeEnd ) {
579
- return nodeAfterStart;
580
- }
581
-
582
- return null;
583
- }
584
-
585
- /**
586
- * Converts `Range` to plain object and returns it.
587
- *
588
- * @returns {Object} `Node` converted to plain object.
589
- */
590
- toJSON() {
591
- return {
592
- start: this.start.toJSON(),
593
- end: this.end.toJSON()
594
- };
595
- }
596
-
597
- /**
598
- * Returns a new range that is equal to current range.
599
- *
600
- * @returns {module:engine/model/range~Range}
601
- */
602
- clone() {
603
- return new this.constructor( this.start, this.end );
604
- }
605
-
606
- /**
607
- * Returns a result of transforming a copy of this range by insert operation.
608
- *
609
- * One or more ranges may be returned as a result of this transformation.
610
- *
611
- * @protected
612
- * @param {module:engine/model/operation/insertoperation~InsertOperation} operation
613
- * @returns {Array.<module:engine/model/range~Range>}
614
- */
615
- _getTransformedByInsertOperation( operation, spread = false ) {
616
- return this._getTransformedByInsertion( operation.position, operation.howMany, spread );
617
- }
618
-
619
- /**
620
- * Returns a result of transforming a copy of this range by move operation.
621
- *
622
- * One or more ranges may be returned as a result of this transformation.
623
- *
624
- * @protected
625
- * @param {module:engine/model/operation/moveoperation~MoveOperation} operation
626
- * @returns {Array.<module:engine/model/range~Range>}
627
- */
628
- _getTransformedByMoveOperation( operation, spread = false ) {
629
- const sourcePosition = operation.sourcePosition;
630
- const howMany = operation.howMany;
631
- const targetPosition = operation.targetPosition;
632
-
633
- return this._getTransformedByMove( sourcePosition, targetPosition, howMany, spread );
634
- }
635
-
636
- /**
637
- * Returns a result of transforming a copy of this range by split operation.
638
- *
639
- * Always one range is returned. The transformation is done in a way to not break the range.
640
- *
641
- * @protected
642
- * @param {module:engine/model/operation/splitoperation~SplitOperation} operation
643
- * @returns {module:engine/model/range~Range}
644
- */
645
- _getTransformedBySplitOperation( operation ) {
646
- const start = this.start._getTransformedBySplitOperation( operation );
647
- let end = this.end._getTransformedBySplitOperation( operation );
648
-
649
- if ( this.end.isEqual( operation.insertionPosition ) ) {
650
- end = this.end.getShiftedBy( 1 );
651
- }
652
-
653
- // Below may happen when range contains graveyard element used by split operation.
654
- if ( start.root != end.root ) {
655
- // End position was next to the moved graveyard element and was moved with it.
656
- // Fix it by using old `end` which has proper `root`.
657
- end = this.end.getShiftedBy( -1 );
658
- }
659
-
660
- return new Range( start, end );
661
- }
662
-
663
- /**
664
- * Returns a result of transforming a copy of this range by merge operation.
665
- *
666
- * Always one range is returned. The transformation is done in a way to not break the range.
667
- *
668
- * @protected
669
- * @param {module:engine/model/operation/mergeoperation~MergeOperation} operation
670
- * @returns {module:engine/model/range~Range}
671
- */
672
- _getTransformedByMergeOperation( operation ) {
673
- // Special case when the marker is set on "the closing tag" of an element. Marker can be set like that during
674
- // transformations, especially when a content of a few block elements were removed. For example:
675
- //
676
- // {} is the transformed range, [] is the removed range.
677
- // <p>F[o{o</p><p>B}ar</p><p>Xy]z</p>
678
- //
679
- // <p>Fo{o</p><p>B}ar</p><p>z</p>
680
- // <p>F{</p><p>B}ar</p><p>z</p>
681
- // <p>F{</p>}<p>z</p>
682
- // <p>F{}z</p>
683
- //
684
- if ( this.start.isEqual( operation.targetPosition ) && this.end.isEqual( operation.deletionPosition ) ) {
685
- return new Range( this.start );
686
- }
687
-
688
- let start = this.start._getTransformedByMergeOperation( operation );
689
- let end = this.end._getTransformedByMergeOperation( operation );
690
-
691
- if ( start.root != end.root ) {
692
- // This happens when the end position was next to the merged (deleted) element.
693
- // Then, the end position was moved to the graveyard root. In this case we need to fix
694
- // the range cause its boundaries would be in different roots.
695
- end = this.end.getShiftedBy( -1 );
696
- }
697
-
698
- if ( start.isAfter( end ) ) {
699
- // This happens in three following cases:
700
- //
701
- // Case 1: Merge operation source position is before the target position (due to some transformations, OT, etc.)
702
- // This means that start can be moved before the end of the range.
703
- //
704
- // Before: <p>a{a</p><p>b}b</p><p>cc</p>
705
- // Merge: <p>b}b</p><p>cca{a</p>
706
- // Fix: <p>{b}b</p><p>ccaa</p>
707
- //
708
- // Case 2: Range start is before merged node but not directly.
709
- // Result should include all nodes that were in the original range.
710
- //
711
- // Before: <p>aa</p>{<p>cc</p><p>b}b</p>
712
- // Merge: <p>aab}b</p>{<p>cc</p>
713
- // Fix: <p>aa{bb</p><p>cc</p>}
714
- //
715
- // The range is expanded by an additional `b` letter but it is better than dropping the whole `cc` paragraph.
716
- //
717
- // Case 3: Range start is directly before merged node.
718
- // Resulting range should include only nodes from the merged element:
719
- //
720
- // Before: <p>aa</p>{<p>b}b</p><p>cc</p>
721
- // Merge: <p>aab}b</p>{<p>cc</p>
722
- // Fix: <p>aa{b}b</p><p>cc</p>
723
- //
724
-
725
- if ( operation.sourcePosition.isBefore( operation.targetPosition ) ) {
726
- // Case 1.
727
- start = Position._createAt( end );
728
- start.offset = 0;
729
- } else {
730
- if ( !operation.deletionPosition.isEqual( start ) ) {
731
- // Case 2.
732
- end = operation.deletionPosition;
733
- }
734
-
735
- // In both case 2 and 3 start is at the end of the merge-to element.
736
- start = operation.targetPosition;
737
- }
738
-
739
- return new Range( start, end );
740
- }
741
-
742
- return new Range( start, end );
743
- }
744
-
745
- /**
746
- * Returns an array containing one or two {@link ~Range ranges} that are a result of transforming this
747
- * {@link ~Range range} by inserting `howMany` nodes at `insertPosition`. Two {@link ~Range ranges} are
748
- * returned if the insertion was inside this {@link ~Range range} and `spread` is set to `true`.
749
- *
750
- * Examples:
751
- *
752
- * let range = model.createRange(
753
- * model.createPositionFromPath( root, [ 2, 7 ] ),
754
- * model.createPositionFromPath( root, [ 4, 0, 1 ] )
755
- * );
756
- * let transformed = range._getTransformedByInsertion( model.createPositionFromPath( root, [ 1 ] ), 2 );
757
- * // transformed array has one range from [ 4, 7 ] to [ 6, 0, 1 ]
758
- *
759
- * transformed = range._getTransformedByInsertion( model.createPositionFromPath( root, [ 4, 0, 0 ] ), 4 );
760
- * // transformed array has one range from [ 2, 7 ] to [ 4, 0, 5 ]
761
- *
762
- * transformed = range._getTransformedByInsertion( model.createPositionFromPath( root, [ 3, 2 ] ), 4 );
763
- * // transformed array has one range, which is equal to original range
764
- *
765
- * transformed = range._getTransformedByInsertion( model.createPositionFromPath( root, [ 3, 2 ] ), 4, true );
766
- * // transformed array has two ranges: from [ 2, 7 ] to [ 3, 2 ] and from [ 3, 6 ] to [ 4, 0, 1 ]
767
- *
768
- * @protected
769
- * @param {module:engine/model/position~Position} insertPosition Position where nodes are inserted.
770
- * @param {Number} howMany How many nodes are inserted.
771
- * @param {Boolean} [spread] Flag indicating whether this {~Range range} should be spread if insertion
772
- * was inside the range. Defaults to `false`.
773
- * @returns {Array.<module:engine/model/range~Range>} Result of the transformation.
774
- */
775
- _getTransformedByInsertion( insertPosition, howMany, spread = false ) {
776
- if ( spread && this.containsPosition( insertPosition ) ) {
777
- // Range has to be spread. The first part is from original start to the spread point.
778
- // The other part is from spread point to the original end, but transformed by
779
- // insertion to reflect insertion changes.
780
-
781
- return [
782
- new Range( this.start, insertPosition ),
783
- new Range(
784
- insertPosition.getShiftedBy( howMany ),
785
- this.end._getTransformedByInsertion( insertPosition, howMany )
786
- )
787
- ];
788
- } else {
789
- const range = new Range( this.start, this.end );
790
-
791
- range.start = range.start._getTransformedByInsertion( insertPosition, howMany );
792
- range.end = range.end._getTransformedByInsertion( insertPosition, howMany );
793
-
794
- return [ range ];
795
- }
796
- }
797
-
798
- /**
799
- * Returns an array containing {@link ~Range ranges} that are a result of transforming this
800
- * {@link ~Range range} by moving `howMany` nodes from `sourcePosition` to `targetPosition`.
801
- *
802
- * @protected
803
- * @param {module:engine/model/position~Position} sourcePosition Position from which nodes are moved.
804
- * @param {module:engine/model/position~Position} targetPosition Position to where nodes are moved.
805
- * @param {Number} howMany How many nodes are moved.
806
- * @param {Boolean} [spread=false] Whether the range should be spread if the move points inside the range.
807
- * @returns {Array.<module:engine/model/range~Range>} Result of the transformation.
808
- */
809
- _getTransformedByMove( sourcePosition, targetPosition, howMany, spread = false ) {
810
- // Special case for transforming a collapsed range. Just transform it like a position.
811
- if ( this.isCollapsed ) {
812
- const newPos = this.start._getTransformedByMove( sourcePosition, targetPosition, howMany );
813
-
814
- return [ new Range( newPos ) ];
815
- }
816
-
817
- // Special case for transformation when a part of the range is moved towards the range.
818
- //
819
- // Examples:
820
- //
821
- // <div><p>ab</p><p>c[d</p></div><p>e]f</p> --> <div><p>ab</p></div><p>c[d</p><p>e]f</p>
822
- // <p>e[f</p><div><p>a]b</p><p>cd</p></div> --> <p>e[f</p><p>a]b</p><div><p>cd</p></div>
823
- //
824
- // Without this special condition, the default algorithm leaves an "artifact" range from one of `differenceSet` parts:
825
- //
826
- // <div><p>ab</p><p>c[d</p></div><p>e]f</p> --> <div><p>ab</p>{</div>}<p>c[d</p><p>e]f</p>
827
- //
828
- // This special case is applied only if the range is to be kept together (not spread).
829
- const moveRange = Range._createFromPositionAndShift( sourcePosition, howMany );
830
- const insertPosition = targetPosition._getTransformedByDeletion( sourcePosition, howMany );
831
-
832
- if ( this.containsPosition( targetPosition ) && !spread ) {
833
- if ( moveRange.containsPosition( this.start ) || moveRange.containsPosition( this.end ) ) {
834
- const start = this.start._getTransformedByMove( sourcePosition, targetPosition, howMany );
835
- const end = this.end._getTransformedByMove( sourcePosition, targetPosition, howMany );
836
-
837
- return [ new Range( start, end ) ];
838
- }
839
- }
840
-
841
- // Default algorithm.
842
- let result;
843
-
844
- const differenceSet = this.getDifference( moveRange );
845
- let difference = null;
846
-
847
- const common = this.getIntersection( moveRange );
848
-
849
- if ( differenceSet.length == 1 ) {
850
- // `moveRange` and this range may intersect but may be separate.
851
- difference = new Range(
852
- differenceSet[ 0 ].start._getTransformedByDeletion( sourcePosition, howMany ),
853
- differenceSet[ 0 ].end._getTransformedByDeletion( sourcePosition, howMany )
854
- );
855
- } else if ( differenceSet.length == 2 ) {
856
- // `moveRange` is inside this range.
857
- difference = new Range(
858
- this.start,
859
- this.end._getTransformedByDeletion( sourcePosition, howMany )
860
- );
861
- } // else, `moveRange` contains this range.
862
-
863
- if ( difference ) {
864
- result = difference._getTransformedByInsertion( insertPosition, howMany, common !== null || spread );
865
- } else {
866
- result = [];
867
- }
868
-
869
- if ( common ) {
870
- const transformedCommon = new Range(
871
- common.start._getCombined( moveRange.start, insertPosition ),
872
- common.end._getCombined( moveRange.start, insertPosition )
873
- );
874
-
875
- if ( result.length == 2 ) {
876
- result.splice( 1, 0, transformedCommon );
877
- } else {
878
- result.push( transformedCommon );
879
- }
880
- }
881
-
882
- return result;
883
- }
884
-
885
- /**
886
- * Returns a copy of this range that is transformed by deletion of `howMany` nodes from `deletePosition`.
887
- *
888
- * If the deleted range is intersecting with the transformed range, the transformed range will be shrank.
889
- *
890
- * If the deleted range contains transformed range, `null` will be returned.
891
- *
892
- * @protected
893
- * @param {module:engine/model/position~Position} deletionPosition Position from which nodes are removed.
894
- * @param {Number} howMany How many nodes are removed.
895
- * @returns {module:engine/model/range~Range|null} Result of the transformation.
896
- */
897
- _getTransformedByDeletion( deletePosition, howMany ) {
898
- let newStart = this.start._getTransformedByDeletion( deletePosition, howMany );
899
- let newEnd = this.end._getTransformedByDeletion( deletePosition, howMany );
900
-
901
- if ( newStart == null && newEnd == null ) {
902
- return null;
903
- }
904
-
905
- if ( newStart == null ) {
906
- newStart = deletePosition;
907
- }
908
-
909
- if ( newEnd == null ) {
910
- newEnd = deletePosition;
911
- }
912
-
913
- return new Range( newStart, newEnd );
914
- }
915
-
916
- /**
917
- * Creates a new range, spreading from specified {@link module:engine/model/position~Position position} to a position moved by
918
- * given `shift`. If `shift` is a negative value, shifted position is treated as the beginning of the range.
919
- *
920
- * @protected
921
- * @param {module:engine/model/position~Position} position Beginning of the range.
922
- * @param {Number} shift How long the range should be.
923
- * @returns {module:engine/model/range~Range}
924
- */
925
- static _createFromPositionAndShift( position, shift ) {
926
- const start = position;
927
- const end = position.getShiftedBy( shift );
928
-
929
- return shift > 0 ? new this( start, end ) : new this( end, start );
930
- }
931
-
932
- /**
933
- * Creates a range inside an {@link module:engine/model/element~Element element} which starts before the first child of
934
- * that element and ends after the last child of that element.
935
- *
936
- * @protected
937
- * @param {module:engine/model/element~Element} element Element which is a parent for the range.
938
- * @returns {module:engine/model/range~Range}
939
- */
940
- static _createIn( element ) {
941
- return new this( Position._createAt( element, 0 ), Position._createAt( element, element.maxOffset ) );
942
- }
943
-
944
- /**
945
- * Creates a range that starts before given {@link module:engine/model/item~Item model item} and ends after it.
946
- *
947
- * @protected
948
- * @param {module:engine/model/item~Item} item
949
- * @returns {module:engine/model/range~Range}
950
- */
951
- static _createOn( item ) {
952
- return this._createFromPositionAndShift( Position._createBefore( item ), item.offsetSize );
953
- }
954
-
955
- /**
956
- * Combines all ranges from the passed array into a one range. At least one range has to be passed.
957
- * Passed ranges must not have common parts.
958
- *
959
- * The first range from the array is a reference range. If other ranges start or end on the exactly same position where
960
- * the reference range, they get combined into one range.
961
- *
962
- * [ ][] [ ][ ][ ][ ][] [ ] // Passed ranges, shown sorted
963
- * [ ] // The result of the function if the first range was a reference range.
964
- * [ ] // The result of the function if the third-to-seventh range was a reference range.
965
- * [ ] // The result of the function if the last range was a reference range.
966
- *
967
- * @param {Array.<module:engine/model/range~Range>} ranges Ranges to combine.
968
- * @returns {module:engine/model/range~Range} Combined range.
969
- */
970
- static _createFromRanges( ranges ) {
971
- if ( ranges.length === 0 ) {
972
- /**
973
- * At least one range has to be passed to
974
- * {@link module:engine/model/range~Range._createFromRanges `Range._createFromRanges()`}.
975
- *
976
- * @error range-create-from-ranges-empty-array
977
- */
978
- throw new CKEditorError(
979
- 'range-create-from-ranges-empty-array',
980
- null
981
- );
982
- } else if ( ranges.length == 1 ) {
983
- return ranges[ 0 ].clone();
984
- }
985
-
986
- // 1. Set the first range in `ranges` array as a reference range.
987
- // If we are going to return just a one range, one of the ranges need to be the reference one.
988
- // Other ranges will be stuck to that range, if possible.
989
- const ref = ranges[ 0 ];
990
-
991
- // 2. Sort all the ranges so it's easier to process them.
992
- ranges.sort( ( a, b ) => {
993
- return a.start.isAfter( b.start ) ? 1 : -1;
994
- } );
995
-
996
- // 3. Check at which index the reference range is now.
997
- const refIndex = ranges.indexOf( ref );
998
-
999
- // 4. At this moment we don't need the original range.
1000
- // We are going to modify the result and we need to return a new instance of Range.
1001
- // We have to create a copy of the reference range.
1002
- const result = new this( ref.start, ref.end );
1003
-
1004
- // 5. Ranges should be checked and glued starting from the range that is closest to the reference range.
1005
- // Since ranges are sorted, start with the range with index that is closest to reference range index.
1006
- if ( refIndex > 0 ) {
1007
- for ( let i = refIndex - 1; true; i++ ) {
1008
- if ( ranges[ i ].end.isEqual( result.start ) ) {
1009
- result.start = Position._createAt( ranges[ i ].start );
1010
- } else {
1011
- // If ranges are not starting/ending at the same position there is no point in looking further.
1012
- break;
1013
- }
1014
- }
1015
- }
1016
-
1017
- // 6. Ranges should be checked and glued starting from the range that is closest to the reference range.
1018
- // Since ranges are sorted, start with the range with index that is closest to reference range index.
1019
- for ( let i = refIndex + 1; i < ranges.length; i++ ) {
1020
- if ( ranges[ i ].start.isEqual( result.end ) ) {
1021
- result.end = Position._createAt( ranges[ i ].end );
1022
- } else {
1023
- // If ranges are not starting/ending at the same position there is no point in looking further.
1024
- break;
1025
- }
1026
- }
1027
-
1028
- return result;
1029
- }
1030
-
1031
- /**
1032
- * Creates a `Range` instance from given plain object (i.e. parsed JSON string).
1033
- *
1034
- * @param {Object} json Plain object to be converted to `Range`.
1035
- * @param {module:engine/model/document~Document} doc Document object that will be range owner.
1036
- * @returns {module:engine/model/range~Range} `Range` instance created using given plain object.
1037
- */
1038
- static fromJSON( json, doc ) {
1039
- return new this( Position.fromJSON( json.start, doc ), Position.fromJSON( json.end, doc ) );
1040
- }
1041
-
1042
- // @if CK_DEBUG_ENGINE // toString() {
1043
- // @if CK_DEBUG_ENGINE // return `${ this.root } [ ${ this.start.path.join( ', ' ) } ] - [ ${ this.end.path.join( ', ' ) } ]`;
1044
- // @if CK_DEBUG_ENGINE // }
1045
-
1046
- // @if CK_DEBUG_ENGINE // log() {
1047
- // @if CK_DEBUG_ENGINE // console.log( 'ModelPosition: ' + this );
1048
- // @if CK_DEBUG_ENGINE // }
22
+ export default class Range extends TypeCheckable {
23
+ /**
24
+ * Creates a range spanning from `start` position to `end` position.
25
+ *
26
+ * @param {module:engine/model/position~Position} start The start position.
27
+ * @param {module:engine/model/position~Position|null} [end] The end position. If not set,
28
+ * the range will be collapsed at the `start` position.
29
+ */
30
+ constructor(start, end) {
31
+ super();
32
+ /**
33
+ * Start position.
34
+ *
35
+ * @readonly
36
+ * @member {module:engine/model/position~Position}
37
+ */
38
+ this.start = Position._createAt(start);
39
+ /**
40
+ * End position.
41
+ *
42
+ * @readonly
43
+ * @member {module:engine/model/position~Position}
44
+ */
45
+ this.end = end ? Position._createAt(end) : Position._createAt(start);
46
+ // If the range is collapsed, treat in a similar way as a position and set its boundaries stickiness to 'toNone'.
47
+ // In other case, make the boundaries stick to the "inside" of the range.
48
+ this.start.stickiness = this.isCollapsed ? 'toNone' : 'toNext';
49
+ this.end.stickiness = this.isCollapsed ? 'toNone' : 'toPrevious';
50
+ }
51
+ /**
52
+ * Iterable interface.
53
+ *
54
+ * Iterates over all {@link module:engine/model/item~Item items} that are in this range and returns
55
+ * them together with additional information like length or {@link module:engine/model/position~Position positions},
56
+ * grouped as {@link module:engine/model/treewalker~TreeWalkerValue}.
57
+ * It iterates over all {@link module:engine/model/textproxy~TextProxy text contents} that are inside the range
58
+ * and all the {@link module:engine/model/element~Element}s that are entered into when iterating over this range.
59
+ *
60
+ * This iterator uses {@link module:engine/model/treewalker~TreeWalker} with `boundaries` set to this range
61
+ * and `ignoreElementEnd` option set to `true`.
62
+ *
63
+ * @returns {Iterator.<module:engine/model/treewalker~TreeWalkerValue>}
64
+ */
65
+ *[Symbol.iterator]() {
66
+ yield* new TreeWalker({ boundaries: this, ignoreElementEnd: true });
67
+ }
68
+ /**
69
+ * Returns whether the range is collapsed, that is if {@link #start} and
70
+ * {@link #end} positions are equal.
71
+ *
72
+ * @type {Boolean}
73
+ */
74
+ get isCollapsed() {
75
+ return this.start.isEqual(this.end);
76
+ }
77
+ /**
78
+ * Returns whether this range is flat, that is if {@link #start} position and
79
+ * {@link #end} position are in the same {@link module:engine/model/position~Position#parent}.
80
+ *
81
+ * @type {Boolean}
82
+ */
83
+ get isFlat() {
84
+ const startParentPath = this.start.getParentPath();
85
+ const endParentPath = this.end.getParentPath();
86
+ return compareArrays(startParentPath, endParentPath) == 'same';
87
+ }
88
+ /**
89
+ * Range root element.
90
+ *
91
+ * @type {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment}
92
+ */
93
+ get root() {
94
+ return this.start.root;
95
+ }
96
+ /**
97
+ * Checks whether this range contains given {@link module:engine/model/position~Position position}.
98
+ *
99
+ * @param {module:engine/model/position~Position} position Position to check.
100
+ * @returns {Boolean} `true` if given {@link module:engine/model/position~Position position} is contained
101
+ * in this range,`false` otherwise.
102
+ */
103
+ containsPosition(position) {
104
+ return position.isAfter(this.start) && position.isBefore(this.end);
105
+ }
106
+ /**
107
+ * Checks whether this range contains given {@link ~Range range}.
108
+ *
109
+ * @param {module:engine/model/range~Range} otherRange Range to check.
110
+ * @param {Boolean} [loose=false] Whether the check is loose or strict. If the check is strict (`false`), compared range cannot
111
+ * start or end at the same position as this range boundaries. If the check is loose (`true`), compared range can start, end or
112
+ * even be equal to this range. Note that collapsed ranges are always compared in strict mode.
113
+ * @returns {Boolean} `true` if given {@link ~Range range} boundaries are contained by this range, `false` otherwise.
114
+ */
115
+ containsRange(otherRange, loose = false) {
116
+ if (otherRange.isCollapsed) {
117
+ loose = false;
118
+ }
119
+ const containsStart = this.containsPosition(otherRange.start) || (loose && this.start.isEqual(otherRange.start));
120
+ const containsEnd = this.containsPosition(otherRange.end) || (loose && this.end.isEqual(otherRange.end));
121
+ return containsStart && containsEnd;
122
+ }
123
+ /**
124
+ * Checks whether given {@link module:engine/model/item~Item} is inside this range.
125
+ *
126
+ * @param {module:engine/model/item~Item} item Model item to check.
127
+ */
128
+ containsItem(item) {
129
+ const pos = Position._createBefore(item);
130
+ return this.containsPosition(pos) || this.start.isEqual(pos);
131
+ }
132
+ /**
133
+ * Two ranges are equal if their {@link #start} and {@link #end} positions are equal.
134
+ *
135
+ * @param {module:engine/model/range~Range} otherRange Range to compare with.
136
+ * @returns {Boolean} `true` if ranges are equal, `false` otherwise.
137
+ */
138
+ isEqual(otherRange) {
139
+ return this.start.isEqual(otherRange.start) && this.end.isEqual(otherRange.end);
140
+ }
141
+ /**
142
+ * Checks and returns whether this range intersects with given range.
143
+ *
144
+ * @param {module:engine/model/range~Range} otherRange Range to compare with.
145
+ * @returns {Boolean} `true` if ranges intersect, `false` otherwise.
146
+ */
147
+ isIntersecting(otherRange) {
148
+ return this.start.isBefore(otherRange.end) && this.end.isAfter(otherRange.start);
149
+ }
150
+ /**
151
+ * Computes which part(s) of this {@link ~Range range} is not a part of given {@link ~Range range}.
152
+ * Returned array contains zero, one or two {@link ~Range ranges}.
153
+ *
154
+ * Examples:
155
+ *
156
+ * let range = model.createRange(
157
+ * model.createPositionFromPath( root, [ 2, 7 ] ),
158
+ * model.createPositionFromPath( root, [ 4, 0, 1 ] )
159
+ * );
160
+ * let otherRange = model.createRange( model.createPositionFromPath( root, [ 1 ] ), model.createPositionFromPath( root, [ 5 ] ) );
161
+ * let transformed = range.getDifference( otherRange );
162
+ * // transformed array has no ranges because `otherRange` contains `range`
163
+ *
164
+ * otherRange = model.createRange( model.createPositionFromPath( root, [ 1 ] ), model.createPositionFromPath( root, [ 3 ] ) );
165
+ * transformed = range.getDifference( otherRange );
166
+ * // transformed array has one range: from [ 3 ] to [ 4, 0, 1 ]
167
+ *
168
+ * otherRange = model.createRange( model.createPositionFromPath( root, [ 3 ] ), model.createPositionFromPath( root, [ 4 ] ) );
169
+ * transformed = range.getDifference( otherRange );
170
+ * // transformed array has two ranges: from [ 2, 7 ] to [ 3 ] and from [ 4 ] to [ 4, 0, 1 ]
171
+ *
172
+ * @param {module:engine/model/range~Range} otherRange Range to differentiate against.
173
+ * @returns {Array.<module:engine/model/range~Range>} The difference between ranges.
174
+ */
175
+ getDifference(otherRange) {
176
+ const ranges = [];
177
+ if (this.isIntersecting(otherRange)) {
178
+ // Ranges intersect.
179
+ if (this.containsPosition(otherRange.start)) {
180
+ // Given range start is inside this range. This means that we have to
181
+ // add shrunken range - from the start to the middle of this range.
182
+ ranges.push(new Range(this.start, otherRange.start));
183
+ }
184
+ if (this.containsPosition(otherRange.end)) {
185
+ // Given range end is inside this range. This means that we have to
186
+ // add shrunken range - from the middle of this range to the end.
187
+ ranges.push(new Range(otherRange.end, this.end));
188
+ }
189
+ }
190
+ else {
191
+ // Ranges do not intersect, return the original range.
192
+ ranges.push(new Range(this.start, this.end));
193
+ }
194
+ return ranges;
195
+ }
196
+ /**
197
+ * Returns an intersection of this {@link ~Range range} and given {@link ~Range range}.
198
+ * Intersection is a common part of both of those ranges. If ranges has no common part, returns `null`.
199
+ *
200
+ * Examples:
201
+ *
202
+ * let range = model.createRange(
203
+ * model.createPositionFromPath( root, [ 2, 7 ] ),
204
+ * model.createPositionFromPath( root, [ 4, 0, 1 ] )
205
+ * );
206
+ * let otherRange = model.createRange( model.createPositionFromPath( root, [ 1 ] ), model.createPositionFromPath( root, [ 2 ] ) );
207
+ * let transformed = range.getIntersection( otherRange ); // null - ranges have no common part
208
+ *
209
+ * otherRange = model.createRange( model.createPositionFromPath( root, [ 3 ] ), model.createPositionFromPath( root, [ 5 ] ) );
210
+ * transformed = range.getIntersection( otherRange ); // range from [ 3 ] to [ 4, 0, 1 ]
211
+ *
212
+ * @param {module:engine/model/range~Range} otherRange Range to check for intersection.
213
+ * @returns {module:engine/model/range~Range|null} A common part of given ranges or `null` if ranges have no common part.
214
+ */
215
+ getIntersection(otherRange) {
216
+ if (this.isIntersecting(otherRange)) {
217
+ // Ranges intersect, so a common range will be returned.
218
+ // At most, it will be same as this range.
219
+ let commonRangeStart = this.start;
220
+ let commonRangeEnd = this.end;
221
+ if (this.containsPosition(otherRange.start)) {
222
+ // Given range start is inside this range. This means thaNt we have to
223
+ // shrink common range to the given range start.
224
+ commonRangeStart = otherRange.start;
225
+ }
226
+ if (this.containsPosition(otherRange.end)) {
227
+ // Given range end is inside this range. This means that we have to
228
+ // shrink common range to the given range end.
229
+ commonRangeEnd = otherRange.end;
230
+ }
231
+ return new Range(commonRangeStart, commonRangeEnd);
232
+ }
233
+ // Ranges do not intersect, so they do not have common part.
234
+ return null;
235
+ }
236
+ /**
237
+ * Returns a range created by joining this {@link ~Range range} with the given {@link ~Range range}.
238
+ * If ranges have no common part, returns `null`.
239
+ *
240
+ * Examples:
241
+ *
242
+ * let range = model.createRange(
243
+ * model.createPositionFromPath( root, [ 2, 7 ] ),
244
+ * model.createPositionFromPath( root, [ 4, 0, 1 ] )
245
+ * );
246
+ * let otherRange = model.createRange(
247
+ * model.createPositionFromPath( root, [ 1 ] ),
248
+ * model.createPositionFromPath( root, [ 2 ] )
249
+ * );
250
+ * let transformed = range.getJoined( otherRange ); // null - ranges have no common part
251
+ *
252
+ * otherRange = model.createRange(
253
+ * model.createPositionFromPath( root, [ 3 ] ),
254
+ * model.createPositionFromPath( root, [ 5 ] )
255
+ * );
256
+ * transformed = range.getJoined( otherRange ); // range from [ 2, 7 ] to [ 5 ]
257
+ *
258
+ * @param {module:engine/model/range~Range} otherRange Range to be joined.
259
+ * @param {Boolean} [loose=false] Whether the intersection check is loose or strict. If the check is strict (`false`),
260
+ * ranges are tested for intersection or whether start/end positions are equal. If the check is loose (`true`),
261
+ * compared range is also checked if it's {@link module:engine/model/position~Position#isTouching touching} current range.
262
+ * @returns {module:engine/model/range~Range|null} A sum of given ranges or `null` if ranges have no common part.
263
+ */
264
+ getJoined(otherRange, loose = false) {
265
+ let shouldJoin = this.isIntersecting(otherRange);
266
+ if (!shouldJoin) {
267
+ if (this.start.isBefore(otherRange.start)) {
268
+ shouldJoin = loose ? this.end.isTouching(otherRange.start) : this.end.isEqual(otherRange.start);
269
+ }
270
+ else {
271
+ shouldJoin = loose ? otherRange.end.isTouching(this.start) : otherRange.end.isEqual(this.start);
272
+ }
273
+ }
274
+ if (!shouldJoin) {
275
+ return null;
276
+ }
277
+ let startPosition = this.start;
278
+ let endPosition = this.end;
279
+ if (otherRange.start.isBefore(startPosition)) {
280
+ startPosition = otherRange.start;
281
+ }
282
+ if (otherRange.end.isAfter(endPosition)) {
283
+ endPosition = otherRange.end;
284
+ }
285
+ return new Range(startPosition, endPosition);
286
+ }
287
+ /**
288
+ * Computes and returns the smallest set of {@link #isFlat flat} ranges, that covers this range in whole.
289
+ *
290
+ * See an example of a model structure (`[` and `]` are range boundaries):
291
+ *
292
+ * root root
293
+ * |- element DIV DIV P2 P3 DIV
294
+ * | |- element H H P1 f o o b a r H P4
295
+ * | | |- "fir[st" fir[st lorem se]cond ipsum
296
+ * | |- element P1
297
+ * | | |- "lorem" ||
298
+ * |- element P2 ||
299
+ * | |- "foo" VV
300
+ * |- element P3
301
+ * | |- "bar" root
302
+ * |- element DIV DIV [P2 P3] DIV
303
+ * | |- element H H [P1] f o o b a r H P4
304
+ * | | |- "se]cond" fir[st] lorem [se]cond ipsum
305
+ * | |- element P4
306
+ * | | |- "ipsum"
307
+ *
308
+ * As it can be seen, letters contained in the range are: `stloremfoobarse`, spread across different parents.
309
+ * We are looking for minimal set of flat ranges that contains the same nodes.
310
+ *
311
+ * Minimal flat ranges for above range `( [ 0, 0, 3 ], [ 3, 0, 2 ] )` will be:
312
+ *
313
+ * ( [ 0, 0, 3 ], [ 0, 0, 5 ] ) = "st"
314
+ * ( [ 0, 1 ], [ 0, 2 ] ) = element P1 ("lorem")
315
+ * ( [ 1 ], [ 3 ] ) = element P2, element P3 ("foobar")
316
+ * ( [ 3, 0, 0 ], [ 3, 0, 2 ] ) = "se"
317
+ *
318
+ * **Note:** if an {@link module:engine/model/element~Element element} is not wholly contained in this range, it won't be returned
319
+ * in any of the returned flat ranges. See in the example how `H` elements at the beginning and at the end of the range
320
+ * were omitted. Only their parts that were wholly in the range were returned.
321
+ *
322
+ * **Note:** this method is not returning flat ranges that contain no nodes.
323
+ *
324
+ * @returns {Array.<module:engine/model/range~Range>} Array of flat ranges covering this range.
325
+ */
326
+ getMinimalFlatRanges() {
327
+ const ranges = [];
328
+ const diffAt = this.start.getCommonPath(this.end).length;
329
+ const pos = Position._createAt(this.start);
330
+ let posParent = pos.parent;
331
+ // Go up.
332
+ while (pos.path.length > diffAt + 1) {
333
+ const howMany = posParent.maxOffset - pos.offset;
334
+ if (howMany !== 0) {
335
+ ranges.push(new Range(pos, pos.getShiftedBy(howMany)));
336
+ }
337
+ pos.path = pos.path.slice(0, -1);
338
+ pos.offset++;
339
+ posParent = posParent.parent;
340
+ }
341
+ // Go down.
342
+ while (pos.path.length <= this.end.path.length) {
343
+ const offset = this.end.path[pos.path.length - 1];
344
+ const howMany = offset - pos.offset;
345
+ if (howMany !== 0) {
346
+ ranges.push(new Range(pos, pos.getShiftedBy(howMany)));
347
+ }
348
+ pos.offset = offset;
349
+ pos.path.push(0);
350
+ }
351
+ return ranges;
352
+ }
353
+ /**
354
+ * Creates a {@link module:engine/model/treewalker~TreeWalker TreeWalker} instance with this range as a boundary.
355
+ *
356
+ * For example, to iterate over all items in the entire document root:
357
+ *
358
+ * // Create a range spanning over the entire root content:
359
+ * const range = editor.model.createRangeIn( editor.model.document.getRoot() );
360
+ *
361
+ * // Iterate over all items in this range:
362
+ * for ( const value of range.getWalker() ) {
363
+ * console.log( value.item );
364
+ * }
365
+ *
366
+ * @param {Object} options Object with configuration options. See {@link module:engine/model/treewalker~TreeWalker}.
367
+ * @param {module:engine/model/position~Position} [options.startPosition]
368
+ * @param {Boolean} [options.singleCharacters=false]
369
+ * @param {Boolean} [options.shallow=false]
370
+ * @param {Boolean} [options.ignoreElementEnd=false]
371
+ * @returns {module:engine/model/treewalker~TreeWalker}
372
+ */
373
+ getWalker(options = {}) {
374
+ options.boundaries = this;
375
+ return new TreeWalker(options);
376
+ }
377
+ /**
378
+ * Returns an iterator that iterates over all {@link module:engine/model/item~Item items} that are in this range and returns
379
+ * them.
380
+ *
381
+ * This method uses {@link module:engine/model/treewalker~TreeWalker} with `boundaries` set to this range and `ignoreElementEnd` option
382
+ * set to `true`. However it returns only {@link module:engine/model/item~Item model items},
383
+ * not {@link module:engine/model/treewalker~TreeWalkerValue}.
384
+ *
385
+ * You may specify additional options for the tree walker. See {@link module:engine/model/treewalker~TreeWalker} for
386
+ * a full list of available options.
387
+ *
388
+ * @param {Object} [options] Object with configuration options. See {@link module:engine/model/treewalker~TreeWalker}.
389
+ * @returns {Iterable.<module:engine/model/item~Item>}
390
+ */
391
+ *getItems(options = {}) {
392
+ options.boundaries = this;
393
+ options.ignoreElementEnd = true;
394
+ const treeWalker = new TreeWalker(options);
395
+ for (const value of treeWalker) {
396
+ yield value.item;
397
+ }
398
+ }
399
+ /**
400
+ * Returns an iterator that iterates over all {@link module:engine/model/position~Position positions} that are boundaries or
401
+ * contained in this range.
402
+ *
403
+ * This method uses {@link module:engine/model/treewalker~TreeWalker} with `boundaries` set to this range. However it returns only
404
+ * {@link module:engine/model/position~Position positions}, not {@link module:engine/model/treewalker~TreeWalkerValue}.
405
+ *
406
+ * You may specify additional options for the tree walker. See {@link module:engine/model/treewalker~TreeWalker} for
407
+ * a full list of available options.
408
+ *
409
+ * @param {Object} options Object with configuration options. See {@link module:engine/model/treewalker~TreeWalker}.
410
+ * @returns {Iterable.<module:engine/model/position~Position>}
411
+ */
412
+ *getPositions(options = {}) {
413
+ options.boundaries = this;
414
+ const treeWalker = new TreeWalker(options);
415
+ yield treeWalker.position;
416
+ for (const value of treeWalker) {
417
+ yield value.nextPosition;
418
+ }
419
+ }
420
+ /**
421
+ * Returns a range that is a result of transforming this range by given `operation`.
422
+ *
423
+ * **Note:** transformation may break one range into multiple ranges (for example, when a part of the range is
424
+ * moved to a different part of document tree). For this reason, an array is returned by this method and it
425
+ * may contain one or more `Range` instances.
426
+ *
427
+ * @param {module:engine/model/operation/operation~Operation} operation Operation to transform range by.
428
+ * @returns {Array.<module:engine/model/range~Range>} Range which is the result of transformation.
429
+ */
430
+ getTransformedByOperation(operation) {
431
+ switch (operation.type) {
432
+ case 'insert':
433
+ return this._getTransformedByInsertOperation(operation);
434
+ case 'move':
435
+ case 'remove':
436
+ case 'reinsert':
437
+ return this._getTransformedByMoveOperation(operation);
438
+ case 'split':
439
+ return [this._getTransformedBySplitOperation(operation)];
440
+ case 'merge':
441
+ return [this._getTransformedByMergeOperation(operation)];
442
+ }
443
+ return [new Range(this.start, this.end)];
444
+ }
445
+ /**
446
+ * Returns a range that is a result of transforming this range by multiple `operations`.
447
+ *
448
+ * @see ~Range#getTransformedByOperation
449
+ * @param {Iterable.<module:engine/model/operation/operation~Operation>} operations Operations to transform the range by.
450
+ * @returns {Array.<module:engine/model/range~Range>} Range which is the result of transformation.
451
+ */
452
+ getTransformedByOperations(operations) {
453
+ const ranges = [new Range(this.start, this.end)];
454
+ for (const operation of operations) {
455
+ for (let i = 0; i < ranges.length; i++) {
456
+ const result = ranges[i].getTransformedByOperation(operation);
457
+ ranges.splice(i, 1, ...result);
458
+ i += result.length - 1;
459
+ }
460
+ }
461
+ // It may happen that a range is split into two, and then the part of second "piece" is moved into first
462
+ // "piece". In this case we will have incorrect third range, which should not be included in the result --
463
+ // because it is already included in the first "piece". In this loop we are looking for all such ranges that
464
+ // are inside other ranges and we simply remove them.
465
+ for (let i = 0; i < ranges.length; i++) {
466
+ const range = ranges[i];
467
+ for (let j = i + 1; j < ranges.length; j++) {
468
+ const next = ranges[j];
469
+ if (range.containsRange(next) || next.containsRange(range) || range.isEqual(next)) {
470
+ ranges.splice(j, 1);
471
+ }
472
+ }
473
+ }
474
+ return ranges;
475
+ }
476
+ /**
477
+ * Returns an {@link module:engine/model/element~Element} or {@link module:engine/model/documentfragment~DocumentFragment}
478
+ * which is a common ancestor of the range's both ends (in which the entire range is contained).
479
+ *
480
+ * @returns {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment|null}
481
+ */
482
+ getCommonAncestor() {
483
+ return this.start.getCommonAncestor(this.end);
484
+ }
485
+ /**
486
+ * Returns an {@link module:engine/model/element~Element Element} contained by the range.
487
+ * The element will be returned when it is the **only** node within the range and **fully–contained**
488
+ * at the same time.
489
+ *
490
+ * @returns {module:engine/model/element~Element|null}
491
+ */
492
+ getContainedElement() {
493
+ if (this.isCollapsed) {
494
+ return null;
495
+ }
496
+ const nodeAfterStart = this.start.nodeAfter;
497
+ const nodeBeforeEnd = this.end.nodeBefore;
498
+ if (nodeAfterStart && nodeAfterStart.is('element') && nodeAfterStart === nodeBeforeEnd) {
499
+ return nodeAfterStart;
500
+ }
501
+ return null;
502
+ }
503
+ /**
504
+ * Converts `Range` to plain object and returns it.
505
+ *
506
+ * @returns {Object} `Node` converted to plain object.
507
+ */
508
+ toJSON() {
509
+ return {
510
+ start: this.start.toJSON(),
511
+ end: this.end.toJSON()
512
+ };
513
+ }
514
+ /**
515
+ * Returns a new range that is equal to current range.
516
+ *
517
+ * @returns {module:engine/model/range~Range}
518
+ */
519
+ clone() {
520
+ return new this.constructor(this.start, this.end);
521
+ }
522
+ /**
523
+ * Returns a result of transforming a copy of this range by insert operation.
524
+ *
525
+ * One or more ranges may be returned as a result of this transformation.
526
+ *
527
+ * @internal
528
+ * @protected
529
+ * @param {module:engine/model/operation/insertoperation~InsertOperation} operation
530
+ * @returns {Array.<module:engine/model/range~Range>}
531
+ */
532
+ _getTransformedByInsertOperation(operation, spread = false) {
533
+ return this._getTransformedByInsertion(operation.position, operation.howMany, spread);
534
+ }
535
+ /**
536
+ * Returns a result of transforming a copy of this range by move operation.
537
+ *
538
+ * One or more ranges may be returned as a result of this transformation.
539
+ *
540
+ * @internal
541
+ * @protected
542
+ * @param {module:engine/model/operation/moveoperation~MoveOperation} operation
543
+ * @returns {Array.<module:engine/model/range~Range>}
544
+ */
545
+ _getTransformedByMoveOperation(operation, spread = false) {
546
+ const sourcePosition = operation.sourcePosition;
547
+ const howMany = operation.howMany;
548
+ const targetPosition = operation.targetPosition;
549
+ return this._getTransformedByMove(sourcePosition, targetPosition, howMany, spread);
550
+ }
551
+ /**
552
+ * Returns a result of transforming a copy of this range by split operation.
553
+ *
554
+ * Always one range is returned. The transformation is done in a way to not break the range.
555
+ *
556
+ * @internal
557
+ * @protected
558
+ * @param {module:engine/model/operation/splitoperation~SplitOperation} operation
559
+ * @returns {module:engine/model/range~Range}
560
+ */
561
+ _getTransformedBySplitOperation(operation) {
562
+ const start = this.start._getTransformedBySplitOperation(operation);
563
+ let end = this.end._getTransformedBySplitOperation(operation);
564
+ if (this.end.isEqual(operation.insertionPosition)) {
565
+ end = this.end.getShiftedBy(1);
566
+ }
567
+ // Below may happen when range contains graveyard element used by split operation.
568
+ if (start.root != end.root) {
569
+ // End position was next to the moved graveyard element and was moved with it.
570
+ // Fix it by using old `end` which has proper `root`.
571
+ end = this.end.getShiftedBy(-1);
572
+ }
573
+ return new Range(start, end);
574
+ }
575
+ /**
576
+ * Returns a result of transforming a copy of this range by merge operation.
577
+ *
578
+ * Always one range is returned. The transformation is done in a way to not break the range.
579
+ *
580
+ * @internal
581
+ * @protected
582
+ * @param {module:engine/model/operation/mergeoperation~MergeOperation} operation
583
+ * @returns {module:engine/model/range~Range}
584
+ */
585
+ _getTransformedByMergeOperation(operation) {
586
+ // Special case when the marker is set on "the closing tag" of an element. Marker can be set like that during
587
+ // transformations, especially when a content of a few block elements were removed. For example:
588
+ //
589
+ // {} is the transformed range, [] is the removed range.
590
+ // <p>F[o{o</p><p>B}ar</p><p>Xy]z</p>
591
+ //
592
+ // <p>Fo{o</p><p>B}ar</p><p>z</p>
593
+ // <p>F{</p><p>B}ar</p><p>z</p>
594
+ // <p>F{</p>}<p>z</p>
595
+ // <p>F{}z</p>
596
+ //
597
+ if (this.start.isEqual(operation.targetPosition) && this.end.isEqual(operation.deletionPosition)) {
598
+ return new Range(this.start);
599
+ }
600
+ let start = this.start._getTransformedByMergeOperation(operation);
601
+ let end = this.end._getTransformedByMergeOperation(operation);
602
+ if (start.root != end.root) {
603
+ // This happens when the end position was next to the merged (deleted) element.
604
+ // Then, the end position was moved to the graveyard root. In this case we need to fix
605
+ // the range cause its boundaries would be in different roots.
606
+ end = this.end.getShiftedBy(-1);
607
+ }
608
+ if (start.isAfter(end)) {
609
+ // This happens in three following cases:
610
+ //
611
+ // Case 1: Merge operation source position is before the target position (due to some transformations, OT, etc.)
612
+ // This means that start can be moved before the end of the range.
613
+ //
614
+ // Before: <p>a{a</p><p>b}b</p><p>cc</p>
615
+ // Merge: <p>b}b</p><p>cca{a</p>
616
+ // Fix: <p>{b}b</p><p>ccaa</p>
617
+ //
618
+ // Case 2: Range start is before merged node but not directly.
619
+ // Result should include all nodes that were in the original range.
620
+ //
621
+ // Before: <p>aa</p>{<p>cc</p><p>b}b</p>
622
+ // Merge: <p>aab}b</p>{<p>cc</p>
623
+ // Fix: <p>aa{bb</p><p>cc</p>}
624
+ //
625
+ // The range is expanded by an additional `b` letter but it is better than dropping the whole `cc` paragraph.
626
+ //
627
+ // Case 3: Range start is directly before merged node.
628
+ // Resulting range should include only nodes from the merged element:
629
+ //
630
+ // Before: <p>aa</p>{<p>b}b</p><p>cc</p>
631
+ // Merge: <p>aab}b</p>{<p>cc</p>
632
+ // Fix: <p>aa{b}b</p><p>cc</p>
633
+ //
634
+ if (operation.sourcePosition.isBefore(operation.targetPosition)) {
635
+ // Case 1.
636
+ start = Position._createAt(end);
637
+ start.offset = 0;
638
+ }
639
+ else {
640
+ if (!operation.deletionPosition.isEqual(start)) {
641
+ // Case 2.
642
+ end = operation.deletionPosition;
643
+ }
644
+ // In both case 2 and 3 start is at the end of the merge-to element.
645
+ start = operation.targetPosition;
646
+ }
647
+ return new Range(start, end);
648
+ }
649
+ return new Range(start, end);
650
+ }
651
+ /**
652
+ * Returns an array containing one or two {@link ~Range ranges} that are a result of transforming this
653
+ * {@link ~Range range} by inserting `howMany` nodes at `insertPosition`. Two {@link ~Range ranges} are
654
+ * returned if the insertion was inside this {@link ~Range range} and `spread` is set to `true`.
655
+ *
656
+ * Examples:
657
+ *
658
+ * let range = model.createRange(
659
+ * model.createPositionFromPath( root, [ 2, 7 ] ),
660
+ * model.createPositionFromPath( root, [ 4, 0, 1 ] )
661
+ * );
662
+ * let transformed = range._getTransformedByInsertion( model.createPositionFromPath( root, [ 1 ] ), 2 );
663
+ * // transformed array has one range from [ 4, 7 ] to [ 6, 0, 1 ]
664
+ *
665
+ * transformed = range._getTransformedByInsertion( model.createPositionFromPath( root, [ 4, 0, 0 ] ), 4 );
666
+ * // transformed array has one range from [ 2, 7 ] to [ 4, 0, 5 ]
667
+ *
668
+ * transformed = range._getTransformedByInsertion( model.createPositionFromPath( root, [ 3, 2 ] ), 4 );
669
+ * // transformed array has one range, which is equal to original range
670
+ *
671
+ * transformed = range._getTransformedByInsertion( model.createPositionFromPath( root, [ 3, 2 ] ), 4, true );
672
+ * // transformed array has two ranges: from [ 2, 7 ] to [ 3, 2 ] and from [ 3, 6 ] to [ 4, 0, 1 ]
673
+ *
674
+ * @internal
675
+ * @protected
676
+ * @param {module:engine/model/position~Position} insertPosition Position where nodes are inserted.
677
+ * @param {Number} howMany How many nodes are inserted.
678
+ * @param {Boolean} [spread] Flag indicating whether this {~Range range} should be spread if insertion
679
+ * was inside the range. Defaults to `false`.
680
+ * @returns {Array.<module:engine/model/range~Range>} Result of the transformation.
681
+ */
682
+ _getTransformedByInsertion(insertPosition, howMany, spread = false) {
683
+ if (spread && this.containsPosition(insertPosition)) {
684
+ // Range has to be spread. The first part is from original start to the spread point.
685
+ // The other part is from spread point to the original end, but transformed by
686
+ // insertion to reflect insertion changes.
687
+ return [
688
+ new Range(this.start, insertPosition),
689
+ new Range(insertPosition.getShiftedBy(howMany), this.end._getTransformedByInsertion(insertPosition, howMany))
690
+ ];
691
+ }
692
+ else {
693
+ const range = new Range(this.start, this.end);
694
+ range.start = range.start._getTransformedByInsertion(insertPosition, howMany);
695
+ range.end = range.end._getTransformedByInsertion(insertPosition, howMany);
696
+ return [range];
697
+ }
698
+ }
699
+ /**
700
+ * Returns an array containing {@link ~Range ranges} that are a result of transforming this
701
+ * {@link ~Range range} by moving `howMany` nodes from `sourcePosition` to `targetPosition`.
702
+ *
703
+ * @internal
704
+ * @protected
705
+ * @param {module:engine/model/position~Position} sourcePosition Position from which nodes are moved.
706
+ * @param {module:engine/model/position~Position} targetPosition Position to where nodes are moved.
707
+ * @param {Number} howMany How many nodes are moved.
708
+ * @param {Boolean} [spread=false] Whether the range should be spread if the move points inside the range.
709
+ * @returns {Array.<module:engine/model/range~Range>} Result of the transformation.
710
+ */
711
+ _getTransformedByMove(sourcePosition, targetPosition, howMany, spread = false) {
712
+ // Special case for transforming a collapsed range. Just transform it like a position.
713
+ if (this.isCollapsed) {
714
+ const newPos = this.start._getTransformedByMove(sourcePosition, targetPosition, howMany);
715
+ return [new Range(newPos)];
716
+ }
717
+ // Special case for transformation when a part of the range is moved towards the range.
718
+ //
719
+ // Examples:
720
+ //
721
+ // <div><p>ab</p><p>c[d</p></div><p>e]f</p> --> <div><p>ab</p></div><p>c[d</p><p>e]f</p>
722
+ // <p>e[f</p><div><p>a]b</p><p>cd</p></div> --> <p>e[f</p><p>a]b</p><div><p>cd</p></div>
723
+ //
724
+ // Without this special condition, the default algorithm leaves an "artifact" range from one of `differenceSet` parts:
725
+ //
726
+ // <div><p>ab</p><p>c[d</p></div><p>e]f</p> --> <div><p>ab</p>{</div>}<p>c[d</p><p>e]f</p>
727
+ //
728
+ // This special case is applied only if the range is to be kept together (not spread).
729
+ const moveRange = Range._createFromPositionAndShift(sourcePosition, howMany);
730
+ const insertPosition = targetPosition._getTransformedByDeletion(sourcePosition, howMany);
731
+ if (this.containsPosition(targetPosition) && !spread) {
732
+ if (moveRange.containsPosition(this.start) || moveRange.containsPosition(this.end)) {
733
+ const start = this.start._getTransformedByMove(sourcePosition, targetPosition, howMany);
734
+ const end = this.end._getTransformedByMove(sourcePosition, targetPosition, howMany);
735
+ return [new Range(start, end)];
736
+ }
737
+ }
738
+ // Default algorithm.
739
+ let result;
740
+ const differenceSet = this.getDifference(moveRange);
741
+ let difference = null;
742
+ const common = this.getIntersection(moveRange);
743
+ if (differenceSet.length == 1) {
744
+ // `moveRange` and this range may intersect but may be separate.
745
+ difference = new Range(differenceSet[0].start._getTransformedByDeletion(sourcePosition, howMany), differenceSet[0].end._getTransformedByDeletion(sourcePosition, howMany));
746
+ }
747
+ else if (differenceSet.length == 2) {
748
+ // `moveRange` is inside this range.
749
+ difference = new Range(this.start, this.end._getTransformedByDeletion(sourcePosition, howMany));
750
+ } // else, `moveRange` contains this range.
751
+ if (difference) {
752
+ result = difference._getTransformedByInsertion(insertPosition, howMany, common !== null || spread);
753
+ }
754
+ else {
755
+ result = [];
756
+ }
757
+ if (common) {
758
+ const transformedCommon = new Range(common.start._getCombined(moveRange.start, insertPosition), common.end._getCombined(moveRange.start, insertPosition));
759
+ if (result.length == 2) {
760
+ result.splice(1, 0, transformedCommon);
761
+ }
762
+ else {
763
+ result.push(transformedCommon);
764
+ }
765
+ }
766
+ return result;
767
+ }
768
+ /**
769
+ * Returns a copy of this range that is transformed by deletion of `howMany` nodes from `deletePosition`.
770
+ *
771
+ * If the deleted range is intersecting with the transformed range, the transformed range will be shrank.
772
+ *
773
+ * If the deleted range contains transformed range, `null` will be returned.
774
+ *
775
+ * @internal
776
+ * @protected
777
+ * @param {module:engine/model/position~Position} deletionPosition Position from which nodes are removed.
778
+ * @param {Number} howMany How many nodes are removed.
779
+ * @returns {module:engine/model/range~Range|null} Result of the transformation.
780
+ */
781
+ _getTransformedByDeletion(deletePosition, howMany) {
782
+ let newStart = this.start._getTransformedByDeletion(deletePosition, howMany);
783
+ let newEnd = this.end._getTransformedByDeletion(deletePosition, howMany);
784
+ if (newStart == null && newEnd == null) {
785
+ return null;
786
+ }
787
+ if (newStart == null) {
788
+ newStart = deletePosition;
789
+ }
790
+ if (newEnd == null) {
791
+ newEnd = deletePosition;
792
+ }
793
+ return new Range(newStart, newEnd);
794
+ }
795
+ /**
796
+ * Creates a new range, spreading from specified {@link module:engine/model/position~Position position} to a position moved by
797
+ * given `shift`. If `shift` is a negative value, shifted position is treated as the beginning of the range.
798
+ *
799
+ * @internal
800
+ * @protected
801
+ * @param {module:engine/model/position~Position} position Beginning of the range.
802
+ * @param {Number} shift How long the range should be.
803
+ * @returns {module:engine/model/range~Range}
804
+ */
805
+ static _createFromPositionAndShift(position, shift) {
806
+ const start = position;
807
+ const end = position.getShiftedBy(shift);
808
+ return shift > 0 ? new this(start, end) : new this(end, start);
809
+ }
810
+ /**
811
+ * Creates a range inside an {@link module:engine/model/element~Element element} which starts before the first child of
812
+ * that element and ends after the last child of that element.
813
+ *
814
+ * @internal
815
+ * @protected
816
+ * @param {module:engine/model/element~Element} element Element which is a parent for the range.
817
+ * @returns {module:engine/model/range~Range}
818
+ */
819
+ static _createIn(element) {
820
+ return new this(Position._createAt(element, 0), Position._createAt(element, element.maxOffset));
821
+ }
822
+ /**
823
+ * Creates a range that starts before given {@link module:engine/model/item~Item model item} and ends after it.
824
+ *
825
+ * @internal
826
+ * @protected
827
+ * @param {module:engine/model/item~Item} item
828
+ * @returns {module:engine/model/range~Range}
829
+ */
830
+ static _createOn(item) {
831
+ return this._createFromPositionAndShift(Position._createBefore(item), item.offsetSize);
832
+ }
833
+ /**
834
+ * Combines all ranges from the passed array into a one range. At least one range has to be passed.
835
+ * Passed ranges must not have common parts.
836
+ *
837
+ * The first range from the array is a reference range. If other ranges start or end on the exactly same position where
838
+ * the reference range, they get combined into one range.
839
+ *
840
+ * [ ][] [ ][ ][ ][ ][] [ ] // Passed ranges, shown sorted
841
+ * [ ] // The result of the function if the first range was a reference range.
842
+ * [ ] // The result of the function if the third-to-seventh range was a reference range.
843
+ * [ ] // The result of the function if the last range was a reference range.
844
+ *
845
+ * @internal
846
+ * @protected
847
+ * @param {Array.<module:engine/model/range~Range>} ranges Ranges to combine.
848
+ * @returns {module:engine/model/range~Range} Combined range.
849
+ */
850
+ static _createFromRanges(ranges) {
851
+ if (ranges.length === 0) {
852
+ /**
853
+ * At least one range has to be passed to
854
+ * {@link module:engine/model/range~Range._createFromRanges `Range._createFromRanges()`}.
855
+ *
856
+ * @error range-create-from-ranges-empty-array
857
+ */
858
+ throw new CKEditorError('range-create-from-ranges-empty-array', null);
859
+ }
860
+ else if (ranges.length == 1) {
861
+ return ranges[0].clone();
862
+ }
863
+ // 1. Set the first range in `ranges` array as a reference range.
864
+ // If we are going to return just a one range, one of the ranges need to be the reference one.
865
+ // Other ranges will be stuck to that range, if possible.
866
+ const ref = ranges[0];
867
+ // 2. Sort all the ranges so it's easier to process them.
868
+ ranges.sort((a, b) => {
869
+ return a.start.isAfter(b.start) ? 1 : -1;
870
+ });
871
+ // 3. Check at which index the reference range is now.
872
+ const refIndex = ranges.indexOf(ref);
873
+ // 4. At this moment we don't need the original range.
874
+ // We are going to modify the result and we need to return a new instance of Range.
875
+ // We have to create a copy of the reference range.
876
+ const result = new this(ref.start, ref.end);
877
+ // 5. Ranges should be checked and glued starting from the range that is closest to the reference range.
878
+ // Since ranges are sorted, start with the range with index that is closest to reference range index.
879
+ if (refIndex > 0) {
880
+ // eslint-disable-next-line no-constant-condition
881
+ for (let i = refIndex - 1; true; i++) {
882
+ if (ranges[i].end.isEqual(result.start)) {
883
+ result.start = Position._createAt(ranges[i].start);
884
+ }
885
+ else {
886
+ // If ranges are not starting/ending at the same position there is no point in looking further.
887
+ break;
888
+ }
889
+ }
890
+ }
891
+ // 6. Ranges should be checked and glued starting from the range that is closest to the reference range.
892
+ // Since ranges are sorted, start with the range with index that is closest to reference range index.
893
+ for (let i = refIndex + 1; i < ranges.length; i++) {
894
+ if (ranges[i].start.isEqual(result.end)) {
895
+ result.end = Position._createAt(ranges[i].end);
896
+ }
897
+ else {
898
+ // If ranges are not starting/ending at the same position there is no point in looking further.
899
+ break;
900
+ }
901
+ }
902
+ return result;
903
+ }
904
+ /**
905
+ * Creates a `Range` instance from given plain object (i.e. parsed JSON string).
906
+ *
907
+ * @param {Object} json Plain object to be converted to `Range`.
908
+ * @param {module:engine/model/document~Document} doc Document object that will be range owner.
909
+ * @returns {module:engine/model/range~Range} `Range` instance created using given plain object.
910
+ */
911
+ static fromJSON(json, doc) {
912
+ return new this(Position.fromJSON(json.start, doc), Position.fromJSON(json.end, doc));
913
+ }
1049
914
  }
915
+ /**
916
+ * Checks whether this object is of the given.
917
+ *
918
+ * range.is( 'range' ); // -> true
919
+ * range.is( 'model:range' ); // -> true
920
+ *
921
+ * range.is( 'view:range' ); // -> false
922
+ * range.is( 'documentSelection' ); // -> false
923
+ *
924
+ * {@link module:engine/model/node~Node#is Check the entire list of model objects} which implement the `is()` method.
925
+ *
926
+ * @param {String} type
927
+ * @returns {Boolean}
928
+ */
929
+ Range.prototype.is = function (type) {
930
+ return type === 'range' || type === 'model:range';
931
+ };