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