@ckeditor/ckeditor5-engine 35.0.1 → 35.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/CHANGELOG.md +4 -4
  2. package/package.json +30 -24
  3. package/src/controller/datacontroller.js +467 -561
  4. package/src/controller/editingcontroller.js +168 -204
  5. package/src/conversion/conversion.js +541 -565
  6. package/src/conversion/conversionhelpers.js +24 -28
  7. package/src/conversion/downcastdispatcher.js +457 -686
  8. package/src/conversion/downcasthelpers.js +1583 -1965
  9. package/src/conversion/mapper.js +518 -707
  10. package/src/conversion/modelconsumable.js +240 -283
  11. package/src/conversion/upcastdispatcher.js +372 -718
  12. package/src/conversion/upcasthelpers.js +707 -818
  13. package/src/conversion/viewconsumable.js +524 -581
  14. package/src/dataprocessor/basichtmlwriter.js +12 -16
  15. package/src/dataprocessor/dataprocessor.js +5 -0
  16. package/src/dataprocessor/htmldataprocessor.js +100 -116
  17. package/src/dataprocessor/htmlwriter.js +1 -18
  18. package/src/dataprocessor/xmldataprocessor.js +116 -137
  19. package/src/dev-utils/model.js +260 -352
  20. package/src/dev-utils/operationreplayer.js +106 -126
  21. package/src/dev-utils/utils.js +34 -51
  22. package/src/dev-utils/view.js +632 -753
  23. package/src/index.js +0 -11
  24. package/src/model/batch.js +111 -127
  25. package/src/model/differ.js +988 -1233
  26. package/src/model/document.js +340 -449
  27. package/src/model/documentfragment.js +327 -364
  28. package/src/model/documentselection.js +996 -1189
  29. package/src/model/element.js +306 -410
  30. package/src/model/history.js +224 -262
  31. package/src/model/item.js +5 -0
  32. package/src/model/liveposition.js +84 -145
  33. package/src/model/liverange.js +108 -185
  34. package/src/model/markercollection.js +379 -480
  35. package/src/model/model.js +883 -1034
  36. package/src/model/node.js +419 -463
  37. package/src/model/nodelist.js +176 -201
  38. package/src/model/operation/attributeoperation.js +153 -182
  39. package/src/model/operation/detachoperation.js +64 -83
  40. package/src/model/operation/insertoperation.js +135 -166
  41. package/src/model/operation/markeroperation.js +114 -140
  42. package/src/model/operation/mergeoperation.js +163 -191
  43. package/src/model/operation/moveoperation.js +157 -187
  44. package/src/model/operation/nooperation.js +28 -38
  45. package/src/model/operation/operation.js +106 -125
  46. package/src/model/operation/operationfactory.js +30 -34
  47. package/src/model/operation/renameoperation.js +109 -135
  48. package/src/model/operation/rootattributeoperation.js +155 -188
  49. package/src/model/operation/splitoperation.js +196 -232
  50. package/src/model/operation/transform.js +1833 -2204
  51. package/src/model/operation/utils.js +140 -204
  52. package/src/model/position.js +980 -1053
  53. package/src/model/range.js +910 -1028
  54. package/src/model/rootelement.js +77 -97
  55. package/src/model/schema.js +1189 -1835
  56. package/src/model/selection.js +745 -862
  57. package/src/model/text.js +90 -114
  58. package/src/model/textproxy.js +204 -240
  59. package/src/model/treewalker.js +316 -397
  60. package/src/model/typecheckable.js +16 -0
  61. package/src/model/utils/autoparagraphing.js +32 -44
  62. package/src/model/utils/deletecontent.js +334 -418
  63. package/src/model/utils/findoptimalinsertionrange.js +25 -36
  64. package/src/model/utils/getselectedcontent.js +96 -118
  65. package/src/model/utils/insertcontent.js +757 -773
  66. package/src/model/utils/insertobject.js +96 -119
  67. package/src/model/utils/modifyselection.js +120 -158
  68. package/src/model/utils/selection-post-fixer.js +153 -201
  69. package/src/model/writer.js +1305 -1474
  70. package/src/view/attributeelement.js +189 -225
  71. package/src/view/containerelement.js +75 -85
  72. package/src/view/document.js +172 -215
  73. package/src/view/documentfragment.js +200 -249
  74. package/src/view/documentselection.js +338 -367
  75. package/src/view/domconverter.js +1370 -1617
  76. package/src/view/downcastwriter.js +1747 -2076
  77. package/src/view/editableelement.js +81 -97
  78. package/src/view/element.js +739 -890
  79. package/src/view/elementdefinition.js +5 -0
  80. package/src/view/emptyelement.js +82 -92
  81. package/src/view/filler.js +35 -50
  82. package/src/view/item.js +5 -0
  83. package/src/view/matcher.js +260 -559
  84. package/src/view/node.js +274 -360
  85. package/src/view/observer/arrowkeysobserver.js +19 -28
  86. package/src/view/observer/bubblingemittermixin.js +120 -263
  87. package/src/view/observer/bubblingeventinfo.js +47 -55
  88. package/src/view/observer/clickobserver.js +7 -13
  89. package/src/view/observer/compositionobserver.js +14 -24
  90. package/src/view/observer/domeventdata.js +57 -67
  91. package/src/view/observer/domeventobserver.js +40 -64
  92. package/src/view/observer/fakeselectionobserver.js +81 -96
  93. package/src/view/observer/focusobserver.js +45 -61
  94. package/src/view/observer/inputobserver.js +7 -13
  95. package/src/view/observer/keyobserver.js +17 -27
  96. package/src/view/observer/mouseobserver.js +7 -14
  97. package/src/view/observer/mutationobserver.js +220 -315
  98. package/src/view/observer/observer.js +81 -102
  99. package/src/view/observer/selectionobserver.js +199 -246
  100. package/src/view/observer/tabobserver.js +23 -36
  101. package/src/view/placeholder.js +128 -173
  102. package/src/view/position.js +350 -401
  103. package/src/view/range.js +453 -513
  104. package/src/view/rawelement.js +85 -112
  105. package/src/view/renderer.js +874 -1018
  106. package/src/view/rooteditableelement.js +80 -90
  107. package/src/view/selection.js +608 -689
  108. package/src/view/styles/background.js +43 -44
  109. package/src/view/styles/border.js +220 -276
  110. package/src/view/styles/margin.js +8 -17
  111. package/src/view/styles/padding.js +8 -16
  112. package/src/view/styles/utils.js +127 -160
  113. package/src/view/stylesmap.js +728 -905
  114. package/src/view/text.js +102 -126
  115. package/src/view/textproxy.js +144 -170
  116. package/src/view/treewalker.js +383 -479
  117. package/src/view/typecheckable.js +19 -0
  118. package/src/view/uielement.js +166 -187
  119. package/src/view/upcastwriter.js +395 -449
  120. package/src/view/view.js +569 -664
  121. package/src/dataprocessor/dataprocessor.jsdoc +0 -64
  122. package/src/model/item.jsdoc +0 -14
  123. package/src/view/elementdefinition.jsdoc +0 -59
  124. package/src/view/item.jsdoc +0 -14
@@ -2,18 +2,15 @@
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/position
8
7
  */
9
-
8
+ import TypeCheckable from './typecheckable';
10
9
  import TreeWalker from './treewalker';
11
10
  import compareArrays from '@ckeditor/ckeditor5-utils/src/comparearrays';
12
11
  import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
13
-
14
12
  // To check if component is loaded more than once.
15
13
  import '@ckeditor/ckeditor5-utils/src/version';
16
-
17
14
  /**
18
15
  * Represents a position in the model tree.
19
16
  *
@@ -41,1040 +38,893 @@ import '@ckeditor/ckeditor5-utils/src/version';
41
38
  *
42
39
  * In most cases, position with wrong path is caused by an error in code, but it is sometimes needed, as described above.
43
40
  */
44
- export default class Position {
45
- /**
46
- * Creates a position.
47
- *
48
- * @param {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment} root Root of the position.
49
- * @param {Array.<Number>} path Position path. See {@link module:engine/model/position~Position#path}.
50
- * @param {module:engine/model/position~PositionStickiness} [stickiness='toNone'] Position stickiness.
51
- * See {@link module:engine/model/position~PositionStickiness}.
52
- */
53
- constructor( root, path, stickiness = 'toNone' ) {
54
- if ( !root.is( 'element' ) && !root.is( 'documentFragment' ) ) {
55
- /**
56
- * Position root is invalid.
57
- *
58
- * Positions can only be anchored in elements or document fragments.
59
- *
60
- * @error model-position-root-invalid
61
- */
62
- throw new CKEditorError(
63
- 'model-position-root-invalid',
64
- root
65
- );
66
- }
67
-
68
- if ( !( path instanceof Array ) || path.length === 0 ) {
69
- /**
70
- * Position path must be an array with at least one item.
71
- *
72
- * @error model-position-path-incorrect-format
73
- * @param path
74
- */
75
- throw new CKEditorError(
76
- 'model-position-path-incorrect-format',
77
- root,
78
- { path }
79
- );
80
- }
81
-
82
- // Normalize the root and path when element (not root) is passed.
83
- if ( root.is( 'rootElement' ) ) {
84
- path = path.slice();
85
- } else {
86
- path = [ ...root.getPath(), ...path ];
87
- root = root.root;
88
- }
89
-
90
- /**
91
- * Root of the position path.
92
- *
93
- * @readonly
94
- * @member {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment}
95
- * module:engine/model/position~Position#root
96
- */
97
- this.root = root;
98
-
99
- /**
100
- * Position of the node in the tree. **Path contains offsets, not indexes.**
101
- *
102
- * Position can be placed before, after or in a {@link module:engine/model/node~Node node} if that node has
103
- * {@link module:engine/model/node~Node#offsetSize} greater than `1`. Items in position path are
104
- * {@link module:engine/model/node~Node#startOffset starting offsets} of position ancestors, starting from direct root children,
105
- * down to the position offset in it's parent.
106
- *
107
- * ROOT
108
- * |- P before: [ 0 ] after: [ 1 ]
109
- * |- UL before: [ 1 ] after: [ 2 ]
110
- * |- LI before: [ 1, 0 ] after: [ 1, 1 ]
111
- * | |- foo before: [ 1, 0, 0 ] after: [ 1, 0, 3 ]
112
- * |- LI before: [ 1, 1 ] after: [ 1, 2 ]
113
- * |- bar before: [ 1, 1, 0 ] after: [ 1, 1, 3 ]
114
- *
115
- * `foo` and `bar` are representing {@link module:engine/model/text~Text text nodes}. Since text nodes has offset size
116
- * greater than `1` you can place position offset between their start and end:
117
- *
118
- * ROOT
119
- * |- P
120
- * |- UL
121
- * |- LI
122
- * | |- f^o|o ^ has path: [ 1, 0, 1 ] | has path: [ 1, 0, 2 ]
123
- * |- LI
124
- * |- b^a|r ^ has path: [ 1, 1, 1 ] | has path: [ 1, 1, 2 ]
125
- *
126
- * @readonly
127
- * @member {Array.<Number>} module:engine/model/position~Position#path
128
- */
129
- this.path = path;
130
-
131
- /**
132
- * Position stickiness. See {@link module:engine/model/position~PositionStickiness}.
133
- *
134
- * @member {module:engine/model/position~PositionStickiness} module:engine/model/position~Position#stickiness
135
- */
136
- this.stickiness = stickiness;
137
- }
138
-
139
- /**
140
- * Offset at which this position is located in its {@link module:engine/model/position~Position#parent parent}. It is equal
141
- * to the last item in position {@link module:engine/model/position~Position#path path}.
142
- *
143
- * @type {Number}
144
- */
145
- get offset() {
146
- return this.path[ this.path.length - 1 ];
147
- }
148
-
149
- set offset( newOffset ) {
150
- this.path[ this.path.length - 1 ] = newOffset;
151
- }
152
-
153
- /**
154
- * Parent element of this position.
155
- *
156
- * Keep in mind that `parent` value is calculated when the property is accessed.
157
- * If {@link module:engine/model/position~Position#path position path}
158
- * leads to a non-existing element, `parent` property will throw error.
159
- *
160
- * Also it is a good idea to cache `parent` property if it is used frequently in an algorithm (i.e. in a long loop).
161
- *
162
- * @readonly
163
- * @type {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment}
164
- */
165
- get parent() {
166
- let parent = this.root;
167
-
168
- for ( let i = 0; i < this.path.length - 1; i++ ) {
169
- parent = parent.getChild( parent.offsetToIndex( this.path[ i ] ) );
170
-
171
- if ( !parent ) {
172
- /**
173
- * The position's path is incorrect. This means that a position does not point to
174
- * a correct place in the tree and hence, some of its methods and getters cannot work correctly.
175
- *
176
- * **Note**: Unlike DOM and view positions, in the model, the
177
- * {@link module:engine/model/position~Position#parent position's parent} is always an element or a document fragment.
178
- * The last offset in the {@link module:engine/model/position~Position#path position's path} is the point in this element
179
- * where this position points.
180
- *
181
- * Read more about model positions and offsets in
182
- * the {@glink framework/guides/architecture/editing-engine#indexes-and-offsets Editing engine architecture guide}.
183
- *
184
- * @error model-position-path-incorrect
185
- * @param {module:engine/model/position~Position} position The incorrect position.
186
- */
187
- throw new CKEditorError( 'model-position-path-incorrect', this, { position: this } );
188
- }
189
- }
190
-
191
- if ( parent.is( '$text' ) ) {
192
- throw new CKEditorError( 'model-position-path-incorrect', this, { position: this } );
193
- }
194
-
195
- return parent;
196
- }
197
-
198
- /**
199
- * Position {@link module:engine/model/position~Position#offset offset} converted to an index in position's parent node. It is
200
- * equal to the {@link module:engine/model/node~Node#index index} of a node after this position. If position is placed
201
- * in text node, position index is equal to the index of that text node.
202
- *
203
- * @readonly
204
- * @type {Number}
205
- */
206
- get index() {
207
- return this.parent.offsetToIndex( this.offset );
208
- }
209
-
210
- /**
211
- * Returns {@link module:engine/model/text~Text text node} instance in which this position is placed or `null` if this
212
- * position is not in a text node.
213
- *
214
- * @readonly
215
- * @type {module:engine/model/text~Text|null}
216
- */
217
- get textNode() {
218
- return getTextNodeAtPosition( this, this.parent );
219
- }
220
-
221
- /**
222
- * Node directly after this position or `null` if this position is in text node.
223
- *
224
- * @readonly
225
- * @type {module:engine/model/node~Node|null}
226
- */
227
- get nodeAfter() {
228
- // Cache the parent and reuse for performance reasons. See #6579 and #6582.
229
- const parent = this.parent;
230
-
231
- return getNodeAfterPosition( this, parent, getTextNodeAtPosition( this, parent ) );
232
- }
233
-
234
- /**
235
- * Node directly before this position or `null` if this position is in text node.
236
- *
237
- * @readonly
238
- * @type {module:engine/model/node~Node|null}
239
- */
240
- get nodeBefore() {
241
- // Cache the parent and reuse for performance reasons. See #6579 and #6582.
242
- const parent = this.parent;
243
-
244
- return getNodeBeforePosition( this, parent, getTextNodeAtPosition( this, parent ) );
245
- }
246
-
247
- /**
248
- * Is `true` if position is at the beginning of its {@link module:engine/model/position~Position#parent parent}, `false` otherwise.
249
- *
250
- * @readonly
251
- * @type {Boolean}
252
- */
253
- get isAtStart() {
254
- return this.offset === 0;
255
- }
256
-
257
- /**
258
- * Is `true` if position is at the end of its {@link module:engine/model/position~Position#parent parent}, `false` otherwise.
259
- *
260
- * @readonly
261
- * @type {Boolean}
262
- */
263
- get isAtEnd() {
264
- return this.offset == this.parent.maxOffset;
265
- }
266
-
267
- /**
268
- * Checks whether this position is before or after given position.
269
- *
270
- * This method is safe to use it on non-existing positions (for example during operational transformation).
271
- *
272
- * @param {module:engine/model/position~Position} otherPosition Position to compare with.
273
- * @returns {module:engine/model/position~PositionRelation}
274
- */
275
- compareWith( otherPosition ) {
276
- if ( this.root != otherPosition.root ) {
277
- return 'different';
278
- }
279
-
280
- const result = compareArrays( this.path, otherPosition.path );
281
-
282
- switch ( result ) {
283
- case 'same':
284
- return 'same';
285
-
286
- case 'prefix':
287
- return 'before';
288
-
289
- case 'extension':
290
- return 'after';
291
-
292
- default:
293
- return this.path[ result ] < otherPosition.path[ result ] ? 'before' : 'after';
294
- }
295
- }
296
-
297
- /**
298
- * Gets the farthest position which matches the callback using
299
- * {@link module:engine/model/treewalker~TreeWalker TreeWalker}.
300
- *
301
- * For example:
302
- *
303
- * getLastMatchingPosition( value => value.type == 'text' );
304
- * // <paragraph>[]foo</paragraph> -> <paragraph>foo[]</paragraph>
305
- *
306
- * getLastMatchingPosition( value => value.type == 'text', { direction: 'backward' } );
307
- * // <paragraph>foo[]</paragraph> -> <paragraph>[]foo</paragraph>
308
- *
309
- * getLastMatchingPosition( value => false );
310
- * // Do not move the position.
311
- *
312
- * @param {Function} skip Callback function. Gets {@link module:engine/model/treewalker~TreeWalkerValue} and should
313
- * return `true` if the value should be skipped or `false` if not.
314
- * @param {Object} options Object with configuration options. See {@link module:engine/model/treewalker~TreeWalker}.
315
- *
316
- * @returns {module:engine/model/position~Position} The position after the last item which matches the `skip` callback test.
317
- */
318
- getLastMatchingPosition( skip, options = {} ) {
319
- options.startPosition = this;
320
-
321
- const treeWalker = new TreeWalker( options );
322
- treeWalker.skip( skip );
323
-
324
- return treeWalker.position;
325
- }
326
-
327
- /**
328
- * Returns a path to this position's parent. Parent path is equal to position {@link module:engine/model/position~Position#path path}
329
- * but without the last item.
330
- *
331
- * This method is safe to use it on non-existing positions (for example during operational transformation).
332
- *
333
- * @returns {Array.<Number>} Path to the parent.
334
- */
335
- getParentPath() {
336
- return this.path.slice( 0, -1 );
337
- }
338
-
339
- /**
340
- * Returns ancestors array of this position, that is this position's parent and its ancestors.
341
- *
342
- * @returns {Array.<module:engine/model/item~Item>} Array with ancestors.
343
- */
344
- getAncestors() {
345
- const parent = this.parent;
346
-
347
- if ( parent.is( 'documentFragment' ) ) {
348
- return [ parent ];
349
- } else {
350
- return parent.getAncestors( { includeSelf: true } );
351
- }
352
- }
353
-
354
- /**
355
- * Returns the parent element of the given name. Returns null if the position is not inside the desired parent.
356
- *
357
- * @param {String} parentName The name of the parent element to find.
358
- * @returns {module:engine/model/element~Element|null}
359
- */
360
- findAncestor( parentName ) {
361
- const parent = this.parent;
362
-
363
- if ( parent.is( 'element' ) ) {
364
- return parent.findAncestor( parentName, { includeSelf: true } );
365
- }
366
-
367
- return null;
368
- }
369
-
370
- /**
371
- * Returns the slice of two position {@link #path paths} which is identical. The {@link #root roots}
372
- * of these two paths must be identical.
373
- *
374
- * This method is safe to use it on non-existing positions (for example during operational transformation).
375
- *
376
- * @param {module:engine/model/position~Position} position The second position.
377
- * @returns {Array.<Number>} The common path.
378
- */
379
- getCommonPath( position ) {
380
- if ( this.root != position.root ) {
381
- return [];
382
- }
383
-
384
- // We find on which tree-level start and end have the lowest common ancestor
385
- const cmp = compareArrays( this.path, position.path );
386
- // If comparison returned string it means that arrays are same.
387
- const diffAt = ( typeof cmp == 'string' ) ? Math.min( this.path.length, position.path.length ) : cmp;
388
-
389
- return this.path.slice( 0, diffAt );
390
- }
391
-
392
- /**
393
- * Returns an {@link module:engine/model/element~Element} or {@link module:engine/model/documentfragment~DocumentFragment}
394
- * which is a common ancestor of both positions. The {@link #root roots} of these two positions must be identical.
395
- *
396
- * @param {module:engine/model/position~Position} position The second position.
397
- * @returns {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment|null}
398
- */
399
- getCommonAncestor( position ) {
400
- const ancestorsA = this.getAncestors();
401
- const ancestorsB = position.getAncestors();
402
-
403
- let i = 0;
404
-
405
- while ( ancestorsA[ i ] == ancestorsB[ i ] && ancestorsA[ i ] ) {
406
- i++;
407
- }
408
-
409
- return i === 0 ? null : ancestorsA[ i - 1 ];
410
- }
411
-
412
- /**
413
- * Returns a new instance of `Position`, that has same {@link #parent parent} but it's offset
414
- * is shifted by `shift` value (can be a negative value).
415
- *
416
- * This method is safe to use it on non-existing positions (for example during operational transformation).
417
- *
418
- * @param {Number} shift Offset shift. Can be a negative value.
419
- * @returns {module:engine/model/position~Position} Shifted position.
420
- */
421
- getShiftedBy( shift ) {
422
- const shifted = this.clone();
423
-
424
- const offset = shifted.offset + shift;
425
- shifted.offset = offset < 0 ? 0 : offset;
426
-
427
- return shifted;
428
- }
429
-
430
- /**
431
- * Checks whether this position is after given position.
432
- *
433
- * This method is safe to use it on non-existing positions (for example during operational transformation).
434
- *
435
- * @see module:engine/model/position~Position#isBefore
436
- * @param {module:engine/model/position~Position} otherPosition Position to compare with.
437
- * @returns {Boolean} True if this position is after given position.
438
- */
439
- isAfter( otherPosition ) {
440
- return this.compareWith( otherPosition ) == 'after';
441
- }
442
-
443
- /**
444
- * Checks whether this position is before given position.
445
- *
446
- * **Note:** watch out when using negation of the value returned by this method, because the negation will also
447
- * be `true` if positions are in different roots and you might not expect this. You should probably use
448
- * `a.isAfter( b ) || a.isEqual( b )` or `!a.isBefore( p ) && a.root == b.root` in most scenarios. If your
449
- * condition uses multiple `isAfter` and `isBefore` checks, build them so they do not use negated values, i.e.:
450
- *
451
- * if ( a.isBefore( b ) && c.isAfter( d ) ) {
452
- * // do A.
453
- * } else {
454
- * // do B.
455
- * }
456
- *
457
- * or, if you have only one if-branch:
458
- *
459
- * if ( !( a.isBefore( b ) && c.isAfter( d ) ) {
460
- * // do B.
461
- * }
462
- *
463
- * rather than:
464
- *
465
- * if ( !a.isBefore( b ) || && !c.isAfter( d ) ) {
466
- * // do B.
467
- * } else {
468
- * // do A.
469
- * }
470
- *
471
- * This method is safe to use it on non-existing positions (for example during operational transformation).
472
- *
473
- * @param {module:engine/model/position~Position} otherPosition Position to compare with.
474
- * @returns {Boolean} True if this position is before given position.
475
- */
476
- isBefore( otherPosition ) {
477
- return this.compareWith( otherPosition ) == 'before';
478
- }
479
-
480
- /**
481
- * Checks whether this position is equal to given position.
482
- *
483
- * This method is safe to use it on non-existing positions (for example during operational transformation).
484
- *
485
- * @param {module:engine/model/position~Position} otherPosition Position to compare with.
486
- * @returns {Boolean} True if positions are same.
487
- */
488
- isEqual( otherPosition ) {
489
- return this.compareWith( otherPosition ) == 'same';
490
- }
491
-
492
- /**
493
- * Checks whether this position is touching given position. Positions touch when there are no text nodes
494
- * or empty nodes in a range between them. Technically, those positions are not equal but in many cases
495
- * they are very similar or even indistinguishable.
496
- *
497
- * @param {module:engine/model/position~Position} otherPosition Position to compare with.
498
- * @returns {Boolean} True if positions touch.
499
- */
500
- isTouching( otherPosition ) {
501
- let left = null;
502
- let right = null;
503
- const compare = this.compareWith( otherPosition );
504
-
505
- switch ( compare ) {
506
- case 'same':
507
- return true;
508
-
509
- case 'before':
510
- left = Position._createAt( this );
511
- right = Position._createAt( otherPosition );
512
- break;
513
-
514
- case 'after':
515
- left = Position._createAt( otherPosition );
516
- right = Position._createAt( this );
517
- break;
518
-
519
- default:
520
- return false;
521
- }
522
-
523
- // Cached for optimization purposes.
524
- let leftParent = left.parent;
525
-
526
- while ( left.path.length + right.path.length ) {
527
- if ( left.isEqual( right ) ) {
528
- return true;
529
- }
530
-
531
- if ( left.path.length > right.path.length ) {
532
- if ( left.offset !== leftParent.maxOffset ) {
533
- return false;
534
- }
535
-
536
- left.path = left.path.slice( 0, -1 );
537
- leftParent = leftParent.parent;
538
- left.offset++;
539
- } else {
540
- if ( right.offset !== 0 ) {
541
- return false;
542
- }
543
-
544
- right.path = right.path.slice( 0, -1 );
545
- }
546
- }
547
- }
548
-
549
- /**
550
- * Checks whether this object is of the given.
551
- *
552
- * position.is( 'position' ); // -> true
553
- * position.is( 'model:position' ); // -> true
554
- *
555
- * position.is( 'view:position' ); // -> false
556
- * position.is( 'documentSelection' ); // -> false
557
- *
558
- * {@link module:engine/model/node~Node#is Check the entire list of model objects} which implement the `is()` method.
559
- *
560
- * @param {String} type
561
- * @returns {Boolean}
562
- */
563
- is( type ) {
564
- return type === 'position' || type === 'model:position';
565
- }
566
-
567
- /**
568
- * Checks if two positions are in the same parent.
569
- *
570
- * This method is safe to use it on non-existing positions (for example during operational transformation).
571
- *
572
- * @param {module:engine/model/position~Position} position Position to compare with.
573
- * @returns {Boolean} `true` if positions have the same parent, `false` otherwise.
574
- */
575
- hasSameParentAs( position ) {
576
- if ( this.root !== position.root ) {
577
- return false;
578
- }
579
-
580
- const thisParentPath = this.getParentPath();
581
- const posParentPath = position.getParentPath();
582
-
583
- return compareArrays( thisParentPath, posParentPath ) == 'same';
584
- }
585
-
586
- /**
587
- * Returns a copy of this position that is transformed by given `operation`.
588
- *
589
- * The new position's parameters are updated accordingly to the effect of the `operation`.
590
- *
591
- * For example, if `n` nodes are inserted before the position, the returned position {@link ~Position#offset} will be
592
- * increased by `n`. If the position was in a merged element, it will be accordingly moved to the new element, etc.
593
- *
594
- * This method is safe to use it on non-existing positions (for example during operational transformation).
595
- *
596
- * @param {module:engine/model/operation/operation~Operation} operation Operation to transform by.
597
- * @returns {module:engine/model/position~Position} Transformed position.
598
- */
599
- getTransformedByOperation( operation ) {
600
- let result;
601
-
602
- switch ( operation.type ) {
603
- case 'insert':
604
- result = this._getTransformedByInsertOperation( operation );
605
- break;
606
- case 'move':
607
- case 'remove':
608
- case 'reinsert':
609
- result = this._getTransformedByMoveOperation( operation );
610
- break;
611
- case 'split':
612
- result = this._getTransformedBySplitOperation( operation );
613
- break;
614
- case 'merge':
615
- result = this._getTransformedByMergeOperation( operation );
616
- break;
617
- default:
618
- result = Position._createAt( this );
619
- break;
620
- }
621
-
622
- return result;
623
- }
624
-
625
- /**
626
- * Returns a copy of this position transformed by an insert operation.
627
- *
628
- * @protected
629
- * @param {module:engine/model/operation/insertoperation~InsertOperation} operation
630
- * @returns {module:engine/model/position~Position}
631
- */
632
- _getTransformedByInsertOperation( operation ) {
633
- return this._getTransformedByInsertion( operation.position, operation.howMany );
634
- }
635
-
636
- /**
637
- * Returns a copy of this position transformed by a move operation.
638
- *
639
- * @protected
640
- * @param {module:engine/model/operation/moveoperation~MoveOperation} operation
641
- * @returns {module:engine/model/position~Position}
642
- */
643
- _getTransformedByMoveOperation( operation ) {
644
- return this._getTransformedByMove( operation.sourcePosition, operation.targetPosition, operation.howMany );
645
- }
646
-
647
- /**
648
- * Returns a copy of this position transformed by a split operation.
649
- *
650
- * @protected
651
- * @param {module:engine/model/operation/splitoperation~SplitOperation} operation
652
- * @returns {module:engine/model/position~Position}
653
- */
654
- _getTransformedBySplitOperation( operation ) {
655
- const movedRange = operation.movedRange;
656
-
657
- const isContained = movedRange.containsPosition( this ) ||
658
- ( movedRange.start.isEqual( this ) && this.stickiness == 'toNext' );
659
-
660
- if ( isContained ) {
661
- return this._getCombined( operation.splitPosition, operation.moveTargetPosition );
662
- } else {
663
- if ( operation.graveyardPosition ) {
664
- return this._getTransformedByMove( operation.graveyardPosition, operation.insertionPosition, 1 );
665
- } else {
666
- return this._getTransformedByInsertion( operation.insertionPosition, 1 );
667
- }
668
- }
669
- }
670
-
671
- /**
672
- * Returns a copy of this position transformed by merge operation.
673
- *
674
- * @protected
675
- * @param {module:engine/model/operation/mergeoperation~MergeOperation} operation
676
- * @returns {module:engine/model/position~Position}
677
- */
678
- _getTransformedByMergeOperation( operation ) {
679
- const movedRange = operation.movedRange;
680
- const isContained = movedRange.containsPosition( this ) || movedRange.start.isEqual( this );
681
-
682
- let pos;
683
-
684
- if ( isContained ) {
685
- pos = this._getCombined( operation.sourcePosition, operation.targetPosition );
686
-
687
- if ( operation.sourcePosition.isBefore( operation.targetPosition ) ) {
688
- // Above happens during OT when the merged element is moved before the merged-to element.
689
- pos = pos._getTransformedByDeletion( operation.deletionPosition, 1 );
690
- }
691
- } else if ( this.isEqual( operation.deletionPosition ) ) {
692
- pos = Position._createAt( operation.deletionPosition );
693
- } else {
694
- pos = this._getTransformedByMove( operation.deletionPosition, operation.graveyardPosition, 1 );
695
- }
696
-
697
- return pos;
698
- }
699
-
700
- /**
701
- * Returns a copy of this position that is updated by removing `howMany` nodes starting from `deletePosition`.
702
- * It may happen that this position is in a removed node. If that is the case, `null` is returned instead.
703
- *
704
- * @protected
705
- * @param {module:engine/model/position~Position} deletePosition Position before the first removed node.
706
- * @param {Number} howMany How many nodes are removed.
707
- * @returns {module:engine/model/position~Position|null} Transformed position or `null`.
708
- */
709
- _getTransformedByDeletion( deletePosition, howMany ) {
710
- const transformed = Position._createAt( this );
711
-
712
- // This position can't be affected if deletion was in a different root.
713
- if ( this.root != deletePosition.root ) {
714
- return transformed;
715
- }
716
-
717
- if ( compareArrays( deletePosition.getParentPath(), this.getParentPath() ) == 'same' ) {
718
- // If nodes are removed from the node that is pointed by this position...
719
- if ( deletePosition.offset < this.offset ) {
720
- // And are removed from before an offset of that position...
721
- if ( deletePosition.offset + howMany > this.offset ) {
722
- // Position is in removed range, it's no longer in the tree.
723
- return null;
724
- } else {
725
- // Decrement the offset accordingly.
726
- transformed.offset -= howMany;
727
- }
728
- }
729
- } else if ( compareArrays( deletePosition.getParentPath(), this.getParentPath() ) == 'prefix' ) {
730
- // If nodes are removed from a node that is on a path to this position...
731
- const i = deletePosition.path.length - 1;
732
-
733
- if ( deletePosition.offset <= this.path[ i ] ) {
734
- // And are removed from before next node of that path...
735
- if ( deletePosition.offset + howMany > this.path[ i ] ) {
736
- // If the next node of that path is removed return null
737
- // because the node containing this position got removed.
738
- return null;
739
- } else {
740
- // Otherwise, decrement index on that path.
741
- transformed.path[ i ] -= howMany;
742
- }
743
- }
744
- }
745
-
746
- return transformed;
747
- }
748
-
749
- /**
750
- * Returns a copy of this position that is updated by inserting `howMany` nodes at `insertPosition`.
751
- *
752
- * @protected
753
- * @param {module:engine/model/position~Position} insertPosition Position where nodes are inserted.
754
- * @param {Number} howMany How many nodes are inserted.
755
- * @returns {module:engine/model/position~Position} Transformed position.
756
- */
757
- _getTransformedByInsertion( insertPosition, howMany ) {
758
- const transformed = Position._createAt( this );
759
-
760
- // This position can't be affected if insertion was in a different root.
761
- if ( this.root != insertPosition.root ) {
762
- return transformed;
763
- }
764
-
765
- if ( compareArrays( insertPosition.getParentPath(), this.getParentPath() ) == 'same' ) {
766
- // If nodes are inserted in the node that is pointed by this position...
767
- if ( insertPosition.offset < this.offset || ( insertPosition.offset == this.offset && this.stickiness != 'toPrevious' ) ) {
768
- // And are inserted before an offset of that position...
769
- // "Push" this positions offset.
770
- transformed.offset += howMany;
771
- }
772
- } else if ( compareArrays( insertPosition.getParentPath(), this.getParentPath() ) == 'prefix' ) {
773
- // If nodes are inserted in a node that is on a path to this position...
774
- const i = insertPosition.path.length - 1;
775
-
776
- if ( insertPosition.offset <= this.path[ i ] ) {
777
- // And are inserted before next node of that path...
778
- // "Push" the index on that path.
779
- transformed.path[ i ] += howMany;
780
- }
781
- }
782
-
783
- return transformed;
784
- }
785
-
786
- /**
787
- * Returns a copy of this position that is updated by moving `howMany` nodes from `sourcePosition` to `targetPosition`.
788
- *
789
- * @protected
790
- * @param {module:engine/model/position~Position} sourcePosition Position before the first element to move.
791
- * @param {module:engine/model/position~Position} targetPosition Position where moved elements will be inserted.
792
- * @param {Number} howMany How many consecutive nodes to move, starting from `sourcePosition`.
793
- * @returns {module:engine/model/position~Position} Transformed position.
794
- */
795
- _getTransformedByMove( sourcePosition, targetPosition, howMany ) {
796
- // Update target position, as it could be affected by nodes removal.
797
- targetPosition = targetPosition._getTransformedByDeletion( sourcePosition, howMany );
798
-
799
- if ( sourcePosition.isEqual( targetPosition ) ) {
800
- // If `targetPosition` is equal to `sourcePosition` this isn't really any move. Just return position as it is.
801
- return Position._createAt( this );
802
- }
803
-
804
- // Moving a range removes nodes from their original position. We acknowledge this by proper transformation.
805
- const transformed = this._getTransformedByDeletion( sourcePosition, howMany );
806
-
807
- const isMoved = transformed === null ||
808
- ( sourcePosition.isEqual( this ) && this.stickiness == 'toNext' ) ||
809
- ( sourcePosition.getShiftedBy( howMany ).isEqual( this ) && this.stickiness == 'toPrevious' );
810
-
811
- if ( isMoved ) {
812
- // This position is inside moved range (or sticks to it).
813
- // In this case, we calculate a combination of this position, move source position and target position.
814
- return this._getCombined( sourcePosition, targetPosition );
815
- } else {
816
- // This position is not inside a removed range.
817
- //
818
- // In next step, we simply reflect inserting `howMany` nodes, which might further affect the position.
819
- return transformed._getTransformedByInsertion( targetPosition, howMany );
820
- }
821
- }
822
-
823
- /**
824
- * Returns a new position that is a combination of this position and given positions.
825
- *
826
- * The combined position is a copy of this position transformed by moving a range starting at `source` position
827
- * to the `target` position. It is expected that this position is inside the moved range.
828
- *
829
- * Example:
830
- *
831
- * let original = model.createPositionFromPath( root, [ 2, 3, 1 ] );
832
- * let source = model.createPositionFromPath( root, [ 2, 2 ] );
833
- * let target = model.createPositionFromPath( otherRoot, [ 1, 1, 3 ] );
834
- * original._getCombined( source, target ); // path is [ 1, 1, 4, 1 ], root is `otherRoot`
835
- *
836
- * Explanation:
837
- *
838
- * We have a position `[ 2, 3, 1 ]` and move some nodes from `[ 2, 2 ]` to `[ 1, 1, 3 ]`. The original position
839
- * was inside moved nodes and now should point to the new place. The moved nodes will be after
840
- * positions `[ 1, 1, 3 ]`, `[ 1, 1, 4 ]`, `[ 1, 1, 5 ]`. Since our position was in the second moved node,
841
- * the transformed position will be in a sub-tree of a node at `[ 1, 1, 4 ]`. Looking at original path, we
842
- * took care of `[ 2, 3 ]` part of it. Now we have to add the rest of the original path to the transformed path.
843
- * Finally, the transformed position will point to `[ 1, 1, 4, 1 ]`.
844
- *
845
- * @protected
846
- * @param {module:engine/model/position~Position} source Beginning of the moved range.
847
- * @param {module:engine/model/position~Position} target Position where the range is moved.
848
- * @returns {module:engine/model/position~Position} Combined position.
849
- */
850
- _getCombined( source, target ) {
851
- const i = source.path.length - 1;
852
-
853
- // The first part of a path to combined position is a path to the place where nodes were moved.
854
- const combined = Position._createAt( target );
855
- combined.stickiness = this.stickiness;
856
-
857
- // Then we have to update the rest of the path.
858
-
859
- // Fix the offset because this position might be after `from` position and we have to reflect that.
860
- combined.offset = combined.offset + this.path[ i ] - source.offset;
861
-
862
- // Then, add the rest of the path.
863
- // If this position is at the same level as `from` position nothing will get added.
864
- combined.path = [ ...combined.path, ...this.path.slice( i + 1 ) ];
865
-
866
- return combined;
867
- }
868
-
869
- /**
870
- * @inheritDoc
871
- */
872
- toJSON() {
873
- return {
874
- root: this.root.toJSON(),
875
- path: Array.from( this.path ),
876
- stickiness: this.stickiness
877
- };
878
- }
879
-
880
- /**
881
- * Returns a new position that is equal to current position.
882
- *
883
- * @returns {module:engine/model/position~Position}
884
- */
885
- clone() {
886
- return new this.constructor( this.root, this.path, this.stickiness );
887
- }
888
-
889
- /**
890
- * Creates position at the given location. The location can be specified as:
891
- *
892
- * * a {@link module:engine/model/position~Position position},
893
- * * parent element and offset (offset defaults to `0`),
894
- * * parent element and `'end'` (sets position at the end of that element),
895
- * * {@link module:engine/model/item~Item model item} and `'before'` or `'after'` (sets position before or after given model item).
896
- *
897
- * This method is a shortcut to other factory methods such as:
898
- *
899
- * * {@link module:engine/model/position~Position._createBefore},
900
- * * {@link module:engine/model/position~Position._createAfter}.
901
- *
902
- * @param {module:engine/model/item~Item|module:engine/model/position~Position} itemOrPosition
903
- * @param {Number|'end'|'before'|'after'} [offset] Offset or one of the flags. Used only when the
904
- * first parameter is a {@link module:engine/model/item~Item model item}.
905
- * @param {module:engine/model/position~PositionStickiness} [stickiness='toNone'] Position stickiness. Used only when the
906
- * first parameter is a {@link module:engine/model/item~Item model item}.
907
- * @protected
908
- */
909
- static _createAt( itemOrPosition, offset, stickiness = 'toNone' ) {
910
- if ( itemOrPosition instanceof Position ) {
911
- return new Position( itemOrPosition.root, itemOrPosition.path, itemOrPosition.stickiness );
912
- } else {
913
- const node = itemOrPosition;
914
-
915
- if ( offset == 'end' ) {
916
- offset = node.maxOffset;
917
- } else if ( offset == 'before' ) {
918
- return this._createBefore( node, stickiness );
919
- } else if ( offset == 'after' ) {
920
- return this._createAfter( node, stickiness );
921
- } else if ( offset !== 0 && !offset ) {
922
- /**
923
- * {@link module:engine/model/model~Model#createPositionAt `Model#createPositionAt()`}
924
- * requires the offset to be specified when the first parameter is a model item.
925
- *
926
- * @error model-createpositionat-offset-required
927
- */
928
- throw new CKEditorError( 'model-createpositionat-offset-required', [ this, itemOrPosition ] );
929
- }
930
-
931
- if ( !node.is( 'element' ) && !node.is( 'documentFragment' ) ) {
932
- /**
933
- * Position parent have to be a model element or model document fragment.
934
- *
935
- * @error model-position-parent-incorrect
936
- */
937
- throw new CKEditorError(
938
- 'model-position-parent-incorrect',
939
- [ this, itemOrPosition ]
940
- );
941
- }
942
-
943
- const path = node.getPath();
944
-
945
- path.push( offset );
946
-
947
- return new this( node.root, path, stickiness );
948
- }
949
- }
950
-
951
- /**
952
- * Creates a new position, after given {@link module:engine/model/item~Item model item}.
953
- *
954
- * @param {module:engine/model/item~Item} item Item after which the position should be placed.
955
- * @param {module:engine/model/position~PositionStickiness} [stickiness='toNone'] Position stickiness.
956
- * @returns {module:engine/model/position~Position}
957
- * @protected
958
- */
959
- static _createAfter( item, stickiness ) {
960
- if ( !item.parent ) {
961
- /**
962
- * You can not make a position after a root element.
963
- *
964
- * @error model-position-after-root
965
- * @param {module:engine/model/item~Item} root
966
- */
967
- throw new CKEditorError(
968
- 'model-position-after-root',
969
- [ this, item ],
970
- { root: item }
971
- );
972
- }
973
-
974
- return this._createAt( item.parent, item.endOffset, stickiness );
975
- }
976
-
977
- /**
978
- * Creates a new position, before the given {@link module:engine/model/item~Item model item}.
979
- *
980
- * @param {module:engine/model/item~Item} item Item before which the position should be placed.
981
- * @param {module:engine/model/position~PositionStickiness} [stickiness='toNone'] Position stickiness.
982
- * @returns {module:engine/model/position~Position}
983
- * @protected
984
- */
985
- static _createBefore( item, stickiness ) {
986
- if ( !item.parent ) {
987
- /**
988
- * You can not make a position before a root element.
989
- *
990
- * @error model-position-before-root
991
- * @param {module:engine/model/item~Item} root
992
- */
993
- throw new CKEditorError(
994
- 'model-position-before-root',
995
- item,
996
- { root: item }
997
- );
998
- }
999
-
1000
- return this._createAt( item.parent, item.startOffset, stickiness );
1001
- }
1002
-
1003
- /**
1004
- * Creates a `Position` instance from given plain object (i.e. parsed JSON string).
1005
- *
1006
- * @param {Object} json Plain object to be converted to `Position`.
1007
- * @param {module:engine/model/document~Document} doc Document object that will be position owner.
1008
- * @returns {module:engine/model/position~Position} `Position` instance created using given plain object.
1009
- */
1010
- static fromJSON( json, doc ) {
1011
- if ( json.root === '$graveyard' ) {
1012
- const pos = new Position( doc.graveyard, json.path );
1013
- pos.stickiness = json.stickiness;
1014
-
1015
- return pos;
1016
- }
1017
-
1018
- if ( !doc.getRoot( json.root ) ) {
1019
- /**
1020
- * Cannot create position for document. Root with specified name does not exist.
1021
- *
1022
- * @error model-position-fromjson-no-root
1023
- * @param {String} rootName
1024
- */
1025
- throw new CKEditorError(
1026
- 'model-position-fromjson-no-root',
1027
- doc,
1028
- { rootName: json.root }
1029
- );
1030
- }
1031
-
1032
- return new Position( doc.getRoot( json.root ), json.path, json.stickiness );
1033
- }
1034
-
1035
- // @if CK_DEBUG_ENGINE // toString() {
1036
- // @if CK_DEBUG_ENGINE // return `${ this.root } [ ${ this.path.join( ', ' ) } ]`;
1037
- // @if CK_DEBUG_ENGINE // }
1038
-
1039
- // @if CK_DEBUG_ENGINE // log() {
1040
- // @if CK_DEBUG_ENGINE // console.log( 'ModelPosition: ' + this );
1041
- // @if CK_DEBUG_ENGINE // }
41
+ export default class Position extends TypeCheckable {
42
+ /**
43
+ * Creates a position.
44
+ *
45
+ * @param {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment} root Root of the position.
46
+ * @param {Array.<Number>} path Position path. See {@link module:engine/model/position~Position#path}.
47
+ * @param {module:engine/model/position~PositionStickiness} [stickiness='toNone'] Position stickiness.
48
+ * See {@link module:engine/model/position~PositionStickiness}.
49
+ */
50
+ constructor(root, path, stickiness = 'toNone') {
51
+ super();
52
+ if (!root.is('element') && !root.is('documentFragment')) {
53
+ /**
54
+ * Position root is invalid.
55
+ *
56
+ * Positions can only be anchored in elements or document fragments.
57
+ *
58
+ * @error model-position-root-invalid
59
+ */
60
+ throw new CKEditorError('model-position-root-invalid', root);
61
+ }
62
+ if (!(path instanceof Array) || path.length === 0) {
63
+ /**
64
+ * Position path must be an array with at least one item.
65
+ *
66
+ * @error model-position-path-incorrect-format
67
+ * @param path
68
+ */
69
+ throw new CKEditorError('model-position-path-incorrect-format', root, { path });
70
+ }
71
+ // Normalize the root and path when element (not root) is passed.
72
+ if (root.is('rootElement')) {
73
+ path = path.slice();
74
+ }
75
+ else {
76
+ path = [...root.getPath(), ...path];
77
+ root = root.root;
78
+ }
79
+ /**
80
+ * Root of the position path.
81
+ *
82
+ * @readonly
83
+ * @member {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment}
84
+ * module:engine/model/position~Position#root
85
+ */
86
+ this.root = root;
87
+ /**
88
+ * Position of the node in the tree. **Path contains offsets, not indexes.**
89
+ *
90
+ * Position can be placed before, after or in a {@link module:engine/model/node~Node node} if that node has
91
+ * {@link module:engine/model/node~Node#offsetSize} greater than `1`. Items in position path are
92
+ * {@link module:engine/model/node~Node#startOffset starting offsets} of position ancestors, starting from direct root children,
93
+ * down to the position offset in it's parent.
94
+ *
95
+ * ROOT
96
+ * |- P before: [ 0 ] after: [ 1 ]
97
+ * |- UL before: [ 1 ] after: [ 2 ]
98
+ * |- LI before: [ 1, 0 ] after: [ 1, 1 ]
99
+ * | |- foo before: [ 1, 0, 0 ] after: [ 1, 0, 3 ]
100
+ * |- LI before: [ 1, 1 ] after: [ 1, 2 ]
101
+ * |- bar before: [ 1, 1, 0 ] after: [ 1, 1, 3 ]
102
+ *
103
+ * `foo` and `bar` are representing {@link module:engine/model/text~Text text nodes}. Since text nodes has offset size
104
+ * greater than `1` you can place position offset between their start and end:
105
+ *
106
+ * ROOT
107
+ * |- P
108
+ * |- UL
109
+ * |- LI
110
+ * | |- f^o|o ^ has path: [ 1, 0, 1 ] | has path: [ 1, 0, 2 ]
111
+ * |- LI
112
+ * |- b^a|r ^ has path: [ 1, 1, 1 ] | has path: [ 1, 1, 2 ]
113
+ *
114
+ * @readonly
115
+ * @member {Array.<Number>} module:engine/model/position~Position#path
116
+ */
117
+ this.path = path;
118
+ /**
119
+ * Position stickiness. See {@link module:engine/model/position~PositionStickiness}.
120
+ *
121
+ * @member {module:engine/model/position~PositionStickiness} module:engine/model/position~Position#stickiness
122
+ */
123
+ this.stickiness = stickiness;
124
+ }
125
+ /**
126
+ * Offset at which this position is located in its {@link module:engine/model/position~Position#parent parent}. It is equal
127
+ * to the last item in position {@link module:engine/model/position~Position#path path}.
128
+ *
129
+ * @type {Number}
130
+ */
131
+ get offset() {
132
+ return this.path[this.path.length - 1];
133
+ }
134
+ set offset(newOffset) {
135
+ this.path[this.path.length - 1] = newOffset;
136
+ }
137
+ /**
138
+ * Parent element of this position.
139
+ *
140
+ * Keep in mind that `parent` value is calculated when the property is accessed.
141
+ * If {@link module:engine/model/position~Position#path position path}
142
+ * leads to a non-existing element, `parent` property will throw error.
143
+ *
144
+ * Also it is a good idea to cache `parent` property if it is used frequently in an algorithm (i.e. in a long loop).
145
+ *
146
+ * @readonly
147
+ * @type {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment}
148
+ */
149
+ get parent() {
150
+ let parent = this.root;
151
+ for (let i = 0; i < this.path.length - 1; i++) {
152
+ parent = parent.getChild(parent.offsetToIndex(this.path[i]));
153
+ if (!parent) {
154
+ /**
155
+ * The position's path is incorrect. This means that a position does not point to
156
+ * a correct place in the tree and hence, some of its methods and getters cannot work correctly.
157
+ *
158
+ * **Note**: Unlike DOM and view positions, in the model, the
159
+ * {@link module:engine/model/position~Position#parent position's parent} is always an element or a document fragment.
160
+ * The last offset in the {@link module:engine/model/position~Position#path position's path} is the point in this element
161
+ * where this position points.
162
+ *
163
+ * Read more about model positions and offsets in
164
+ * the {@glink framework/guides/architecture/editing-engine#indexes-and-offsets Editing engine architecture guide}.
165
+ *
166
+ * @error model-position-path-incorrect
167
+ * @param {module:engine/model/position~Position} position The incorrect position.
168
+ */
169
+ throw new CKEditorError('model-position-path-incorrect', this, { position: this });
170
+ }
171
+ }
172
+ if (parent.is('$text')) {
173
+ throw new CKEditorError('model-position-path-incorrect', this, { position: this });
174
+ }
175
+ return parent;
176
+ }
177
+ /**
178
+ * Position {@link module:engine/model/position~Position#offset offset} converted to an index in position's parent node. It is
179
+ * equal to the {@link module:engine/model/node~Node#index index} of a node after this position. If position is placed
180
+ * in text node, position index is equal to the index of that text node.
181
+ *
182
+ * @readonly
183
+ * @type {Number}
184
+ */
185
+ get index() {
186
+ return this.parent.offsetToIndex(this.offset);
187
+ }
188
+ /**
189
+ * Returns {@link module:engine/model/text~Text text node} instance in which this position is placed or `null` if this
190
+ * position is not in a text node.
191
+ *
192
+ * @readonly
193
+ * @type {module:engine/model/text~Text|null}
194
+ */
195
+ get textNode() {
196
+ return getTextNodeAtPosition(this, this.parent);
197
+ }
198
+ /**
199
+ * Node directly after this position or `null` if this position is in text node.
200
+ *
201
+ * @readonly
202
+ * @type {module:engine/model/node~Node|null}
203
+ */
204
+ get nodeAfter() {
205
+ // Cache the parent and reuse for performance reasons. See #6579 and #6582.
206
+ const parent = this.parent;
207
+ return getNodeAfterPosition(this, parent, getTextNodeAtPosition(this, parent));
208
+ }
209
+ /**
210
+ * Node directly before this position or `null` if this position is in text node.
211
+ *
212
+ * @readonly
213
+ * @type {module:engine/model/node~Node|null}
214
+ */
215
+ get nodeBefore() {
216
+ // Cache the parent and reuse for performance reasons. See #6579 and #6582.
217
+ const parent = this.parent;
218
+ return getNodeBeforePosition(this, parent, getTextNodeAtPosition(this, parent));
219
+ }
220
+ /**
221
+ * Is `true` if position is at the beginning of its {@link module:engine/model/position~Position#parent parent}, `false` otherwise.
222
+ *
223
+ * @readonly
224
+ * @type {Boolean}
225
+ */
226
+ get isAtStart() {
227
+ return this.offset === 0;
228
+ }
229
+ /**
230
+ * Is `true` if position is at the end of its {@link module:engine/model/position~Position#parent parent}, `false` otherwise.
231
+ *
232
+ * @readonly
233
+ * @type {Boolean}
234
+ */
235
+ get isAtEnd() {
236
+ return this.offset == this.parent.maxOffset;
237
+ }
238
+ /**
239
+ * Checks whether this position is before or after given position.
240
+ *
241
+ * This method is safe to use it on non-existing positions (for example during operational transformation).
242
+ *
243
+ * @param {module:engine/model/position~Position} otherPosition Position to compare with.
244
+ * @returns {module:engine/model/position~PositionRelation}
245
+ */
246
+ compareWith(otherPosition) {
247
+ if (this.root != otherPosition.root) {
248
+ return 'different';
249
+ }
250
+ const result = compareArrays(this.path, otherPosition.path);
251
+ switch (result) {
252
+ case 'same':
253
+ return 'same';
254
+ case 'prefix':
255
+ return 'before';
256
+ case 'extension':
257
+ return 'after';
258
+ default:
259
+ return this.path[result] < otherPosition.path[result] ? 'before' : 'after';
260
+ }
261
+ }
262
+ /**
263
+ * Gets the farthest position which matches the callback using
264
+ * {@link module:engine/model/treewalker~TreeWalker TreeWalker}.
265
+ *
266
+ * For example:
267
+ *
268
+ * getLastMatchingPosition( value => value.type == 'text' );
269
+ * // <paragraph>[]foo</paragraph> -> <paragraph>foo[]</paragraph>
270
+ *
271
+ * getLastMatchingPosition( value => value.type == 'text', { direction: 'backward' } );
272
+ * // <paragraph>foo[]</paragraph> -> <paragraph>[]foo</paragraph>
273
+ *
274
+ * getLastMatchingPosition( value => false );
275
+ * // Do not move the position.
276
+ *
277
+ * @param {Function} skip Callback function. Gets {@link module:engine/model/treewalker~TreeWalkerValue} and should
278
+ * return `true` if the value should be skipped or `false` if not.
279
+ * @param {Object} options Object with configuration options. See {@link module:engine/model/treewalker~TreeWalker}.
280
+ *
281
+ * @returns {module:engine/model/position~Position} The position after the last item which matches the `skip` callback test.
282
+ */
283
+ getLastMatchingPosition(skip, options = {}) {
284
+ options.startPosition = this;
285
+ const treeWalker = new TreeWalker(options);
286
+ treeWalker.skip(skip);
287
+ return treeWalker.position;
288
+ }
289
+ /**
290
+ * Returns a path to this position's parent. Parent path is equal to position {@link module:engine/model/position~Position#path path}
291
+ * but without the last item.
292
+ *
293
+ * This method is safe to use it on non-existing positions (for example during operational transformation).
294
+ *
295
+ * @returns {Array.<Number>} Path to the parent.
296
+ */
297
+ getParentPath() {
298
+ return this.path.slice(0, -1);
299
+ }
300
+ /**
301
+ * Returns ancestors array of this position, that is this position's parent and its ancestors.
302
+ *
303
+ * @returns {Array.<module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment>} Array with ancestors.
304
+ */
305
+ getAncestors() {
306
+ const parent = this.parent;
307
+ if (parent.is('documentFragment')) {
308
+ return [parent];
309
+ }
310
+ else {
311
+ return parent.getAncestors({ includeSelf: true });
312
+ }
313
+ }
314
+ /**
315
+ * Returns the parent element of the given name. Returns null if the position is not inside the desired parent.
316
+ *
317
+ * @param {String} parentName The name of the parent element to find.
318
+ * @returns {module:engine/model/element~Element|null}
319
+ */
320
+ findAncestor(parentName) {
321
+ const parent = this.parent;
322
+ if (parent.is('element')) {
323
+ return parent.findAncestor(parentName, { includeSelf: true });
324
+ }
325
+ return null;
326
+ }
327
+ /**
328
+ * Returns the slice of two position {@link #path paths} which is identical. The {@link #root roots}
329
+ * of these two paths must be identical.
330
+ *
331
+ * This method is safe to use it on non-existing positions (for example during operational transformation).
332
+ *
333
+ * @param {module:engine/model/position~Position} position The second position.
334
+ * @returns {Array.<Number>} The common path.
335
+ */
336
+ getCommonPath(position) {
337
+ if (this.root != position.root) {
338
+ return [];
339
+ }
340
+ // We find on which tree-level start and end have the lowest common ancestor
341
+ const cmp = compareArrays(this.path, position.path);
342
+ // If comparison returned string it means that arrays are same.
343
+ const diffAt = (typeof cmp == 'string') ? Math.min(this.path.length, position.path.length) : cmp;
344
+ return this.path.slice(0, diffAt);
345
+ }
346
+ /**
347
+ * Returns an {@link module:engine/model/element~Element} or {@link module:engine/model/documentfragment~DocumentFragment}
348
+ * which is a common ancestor of both positions. The {@link #root roots} of these two positions must be identical.
349
+ *
350
+ * @param {module:engine/model/position~Position} position The second position.
351
+ * @returns {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment|null}
352
+ */
353
+ getCommonAncestor(position) {
354
+ const ancestorsA = this.getAncestors();
355
+ const ancestorsB = position.getAncestors();
356
+ let i = 0;
357
+ while (ancestorsA[i] == ancestorsB[i] && ancestorsA[i]) {
358
+ i++;
359
+ }
360
+ return i === 0 ? null : ancestorsA[i - 1];
361
+ }
362
+ /**
363
+ * Returns a new instance of `Position`, that has same {@link #parent parent} but it's offset
364
+ * is shifted by `shift` value (can be a negative value).
365
+ *
366
+ * This method is safe to use it on non-existing positions (for example during operational transformation).
367
+ *
368
+ * @param {Number} shift Offset shift. Can be a negative value.
369
+ * @returns {module:engine/model/position~Position} Shifted position.
370
+ */
371
+ getShiftedBy(shift) {
372
+ const shifted = this.clone();
373
+ const offset = shifted.offset + shift;
374
+ shifted.offset = offset < 0 ? 0 : offset;
375
+ return shifted;
376
+ }
377
+ /**
378
+ * Checks whether this position is after given position.
379
+ *
380
+ * This method is safe to use it on non-existing positions (for example during operational transformation).
381
+ *
382
+ * @see module:engine/model/position~Position#isBefore
383
+ * @param {module:engine/model/position~Position} otherPosition Position to compare with.
384
+ * @returns {Boolean} True if this position is after given position.
385
+ */
386
+ isAfter(otherPosition) {
387
+ return this.compareWith(otherPosition) == 'after';
388
+ }
389
+ /**
390
+ * Checks whether this position is before given position.
391
+ *
392
+ * **Note:** watch out when using negation of the value returned by this method, because the negation will also
393
+ * be `true` if positions are in different roots and you might not expect this. You should probably use
394
+ * `a.isAfter( b ) || a.isEqual( b )` or `!a.isBefore( p ) && a.root == b.root` in most scenarios. If your
395
+ * condition uses multiple `isAfter` and `isBefore` checks, build them so they do not use negated values, i.e.:
396
+ *
397
+ * if ( a.isBefore( b ) && c.isAfter( d ) ) {
398
+ * // do A.
399
+ * } else {
400
+ * // do B.
401
+ * }
402
+ *
403
+ * or, if you have only one if-branch:
404
+ *
405
+ * if ( !( a.isBefore( b ) && c.isAfter( d ) ) {
406
+ * // do B.
407
+ * }
408
+ *
409
+ * rather than:
410
+ *
411
+ * if ( !a.isBefore( b ) || && !c.isAfter( d ) ) {
412
+ * // do B.
413
+ * } else {
414
+ * // do A.
415
+ * }
416
+ *
417
+ * This method is safe to use it on non-existing positions (for example during operational transformation).
418
+ *
419
+ * @param {module:engine/model/position~Position} otherPosition Position to compare with.
420
+ * @returns {Boolean} True if this position is before given position.
421
+ */
422
+ isBefore(otherPosition) {
423
+ return this.compareWith(otherPosition) == 'before';
424
+ }
425
+ /**
426
+ * Checks whether this position is equal to given position.
427
+ *
428
+ * This method is safe to use it on non-existing positions (for example during operational transformation).
429
+ *
430
+ * @param {module:engine/model/position~Position} otherPosition Position to compare with.
431
+ * @returns {Boolean} True if positions are same.
432
+ */
433
+ isEqual(otherPosition) {
434
+ return this.compareWith(otherPosition) == 'same';
435
+ }
436
+ /**
437
+ * Checks whether this position is touching given position. Positions touch when there are no text nodes
438
+ * or empty nodes in a range between them. Technically, those positions are not equal but in many cases
439
+ * they are very similar or even indistinguishable.
440
+ *
441
+ * @param {module:engine/model/position~Position} otherPosition Position to compare with.
442
+ * @returns {Boolean} True if positions touch.
443
+ */
444
+ isTouching(otherPosition) {
445
+ if (this.root !== otherPosition.root) {
446
+ return false;
447
+ }
448
+ const commonLevel = Math.min(this.path.length, otherPosition.path.length);
449
+ for (let level = 0; level < commonLevel; level++) {
450
+ const diff = this.path[level] - otherPosition.path[level];
451
+ // Positions are spread by a node, so they are not touching.
452
+ if (diff < -1 || diff > 1) {
453
+ return false;
454
+ }
455
+ else if (diff === 1) {
456
+ // `otherPosition` is on the left.
457
+ // `this` is on the right.
458
+ return checkTouchingBranch(otherPosition, this, level);
459
+ }
460
+ else if (diff === -1) {
461
+ // `this` is on the left.
462
+ // `otherPosition` is on the right.
463
+ return checkTouchingBranch(this, otherPosition, level);
464
+ }
465
+ // `diff === 0`.
466
+ // Positions are inside the same element on this level, compare deeper.
467
+ }
468
+ // If we ended up here, it means that positions paths have the same beginning.
469
+ // If the paths have the same length, then it means that they are identical, so the positions are same.
470
+ if (this.path.length === otherPosition.path.length) {
471
+ return true;
472
+ }
473
+ // If positions have different length of paths, then the common part is the same.
474
+ // In this case, the "shorter" position is on the left, the "longer" position is on the right.
475
+ //
476
+ // If the positions are touching, the "longer" position must have only zeroes. For example:
477
+ // [ 1, 2 ] vs [ 1, 2, 0 ]
478
+ // [ 1, 2 ] vs [ 1, 2, 0, 0, 0 ]
479
+ else if (this.path.length > otherPosition.path.length) {
480
+ return checkOnlyZeroes(this.path, commonLevel);
481
+ }
482
+ else {
483
+ return checkOnlyZeroes(otherPosition.path, commonLevel);
484
+ }
485
+ }
486
+ /**
487
+ * Checks if two positions are in the same parent.
488
+ *
489
+ * This method is safe to use it on non-existing positions (for example during operational transformation).
490
+ *
491
+ * @param {module:engine/model/position~Position} position Position to compare with.
492
+ * @returns {Boolean} `true` if positions have the same parent, `false` otherwise.
493
+ */
494
+ hasSameParentAs(position) {
495
+ if (this.root !== position.root) {
496
+ return false;
497
+ }
498
+ const thisParentPath = this.getParentPath();
499
+ const posParentPath = position.getParentPath();
500
+ return compareArrays(thisParentPath, posParentPath) == 'same';
501
+ }
502
+ /**
503
+ * Returns a copy of this position that is transformed by given `operation`.
504
+ *
505
+ * The new position's parameters are updated accordingly to the effect of the `operation`.
506
+ *
507
+ * For example, if `n` nodes are inserted before the position, the returned position {@link ~Position#offset} will be
508
+ * increased by `n`. If the position was in a merged element, it will be accordingly moved to the new element, etc.
509
+ *
510
+ * This method is safe to use it on non-existing positions (for example during operational transformation).
511
+ *
512
+ * @param {module:engine/model/operation/operation~Operation} operation Operation to transform by.
513
+ * @returns {module:engine/model/position~Position} Transformed position.
514
+ */
515
+ getTransformedByOperation(operation) {
516
+ let result;
517
+ switch (operation.type) {
518
+ case 'insert':
519
+ result = this._getTransformedByInsertOperation(operation);
520
+ break;
521
+ case 'move':
522
+ case 'remove':
523
+ case 'reinsert':
524
+ result = this._getTransformedByMoveOperation(operation);
525
+ break;
526
+ case 'split':
527
+ result = this._getTransformedBySplitOperation(operation);
528
+ break;
529
+ case 'merge':
530
+ result = this._getTransformedByMergeOperation(operation);
531
+ break;
532
+ default:
533
+ result = Position._createAt(this);
534
+ break;
535
+ }
536
+ return result;
537
+ }
538
+ /**
539
+ * Returns a copy of this position transformed by an insert operation.
540
+ *
541
+ * @internal
542
+ * @protected
543
+ * @param {module:engine/model/operation/insertoperation~InsertOperation} operation
544
+ * @returns {module:engine/model/position~Position}
545
+ */
546
+ _getTransformedByInsertOperation(operation) {
547
+ return this._getTransformedByInsertion(operation.position, operation.howMany);
548
+ }
549
+ /**
550
+ * Returns a copy of this position transformed by a move operation.
551
+ *
552
+ * @internal
553
+ * @protected
554
+ * @param {module:engine/model/operation/moveoperation~MoveOperation} operation
555
+ * @returns {module:engine/model/position~Position}
556
+ */
557
+ _getTransformedByMoveOperation(operation) {
558
+ return this._getTransformedByMove(operation.sourcePosition, operation.targetPosition, operation.howMany);
559
+ }
560
+ /**
561
+ * Returns a copy of this position transformed by a split operation.
562
+ *
563
+ * @internal
564
+ * @protected
565
+ * @param {module:engine/model/operation/splitoperation~SplitOperation} operation
566
+ * @returns {module:engine/model/position~Position}
567
+ */
568
+ _getTransformedBySplitOperation(operation) {
569
+ const movedRange = operation.movedRange;
570
+ const isContained = movedRange.containsPosition(this) ||
571
+ (movedRange.start.isEqual(this) && this.stickiness == 'toNext');
572
+ if (isContained) {
573
+ return this._getCombined(operation.splitPosition, operation.moveTargetPosition);
574
+ }
575
+ else {
576
+ if (operation.graveyardPosition) {
577
+ return this._getTransformedByMove(operation.graveyardPosition, operation.insertionPosition, 1);
578
+ }
579
+ else {
580
+ return this._getTransformedByInsertion(operation.insertionPosition, 1);
581
+ }
582
+ }
583
+ }
584
+ /**
585
+ * Returns a copy of this position transformed by merge operation.
586
+ *
587
+ * @internal
588
+ * @protected
589
+ * @param {module:engine/model/operation/mergeoperation~MergeOperation} operation
590
+ * @returns {module:engine/model/position~Position}
591
+ */
592
+ _getTransformedByMergeOperation(operation) {
593
+ const movedRange = operation.movedRange;
594
+ const isContained = movedRange.containsPosition(this) || movedRange.start.isEqual(this);
595
+ let pos;
596
+ if (isContained) {
597
+ pos = this._getCombined(operation.sourcePosition, operation.targetPosition);
598
+ if (operation.sourcePosition.isBefore(operation.targetPosition)) {
599
+ // Above happens during OT when the merged element is moved before the merged-to element.
600
+ pos = pos._getTransformedByDeletion(operation.deletionPosition, 1);
601
+ }
602
+ }
603
+ else if (this.isEqual(operation.deletionPosition)) {
604
+ pos = Position._createAt(operation.deletionPosition);
605
+ }
606
+ else {
607
+ pos = this._getTransformedByMove(operation.deletionPosition, operation.graveyardPosition, 1);
608
+ }
609
+ return pos;
610
+ }
611
+ /**
612
+ * Returns a copy of this position that is updated by removing `howMany` nodes starting from `deletePosition`.
613
+ * It may happen that this position is in a removed node. If that is the case, `null` is returned instead.
614
+ *
615
+ * @internal
616
+ * @protected
617
+ * @param {module:engine/model/position~Position} deletePosition Position before the first removed node.
618
+ * @param {Number} howMany How many nodes are removed.
619
+ * @returns {module:engine/model/position~Position|null} Transformed position or `null`.
620
+ */
621
+ _getTransformedByDeletion(deletePosition, howMany) {
622
+ const transformed = Position._createAt(this);
623
+ // This position can't be affected if deletion was in a different root.
624
+ if (this.root != deletePosition.root) {
625
+ return transformed;
626
+ }
627
+ if (compareArrays(deletePosition.getParentPath(), this.getParentPath()) == 'same') {
628
+ // If nodes are removed from the node that is pointed by this position...
629
+ if (deletePosition.offset < this.offset) {
630
+ // And are removed from before an offset of that position...
631
+ if (deletePosition.offset + howMany > this.offset) {
632
+ // Position is in removed range, it's no longer in the tree.
633
+ return null;
634
+ }
635
+ else {
636
+ // Decrement the offset accordingly.
637
+ transformed.offset -= howMany;
638
+ }
639
+ }
640
+ }
641
+ else if (compareArrays(deletePosition.getParentPath(), this.getParentPath()) == 'prefix') {
642
+ // If nodes are removed from a node that is on a path to this position...
643
+ const i = deletePosition.path.length - 1;
644
+ if (deletePosition.offset <= this.path[i]) {
645
+ // And are removed from before next node of that path...
646
+ if (deletePosition.offset + howMany > this.path[i]) {
647
+ // If the next node of that path is removed return null
648
+ // because the node containing this position got removed.
649
+ return null;
650
+ }
651
+ else {
652
+ // Otherwise, decrement index on that path.
653
+ transformed.path[i] -= howMany;
654
+ }
655
+ }
656
+ }
657
+ return transformed;
658
+ }
659
+ /**
660
+ * Returns a copy of this position that is updated by inserting `howMany` nodes at `insertPosition`.
661
+ *
662
+ * @internal
663
+ * @protected
664
+ * @param {module:engine/model/position~Position} insertPosition Position where nodes are inserted.
665
+ * @param {Number} howMany How many nodes are inserted.
666
+ * @returns {module:engine/model/position~Position} Transformed position.
667
+ */
668
+ _getTransformedByInsertion(insertPosition, howMany) {
669
+ const transformed = Position._createAt(this);
670
+ // This position can't be affected if insertion was in a different root.
671
+ if (this.root != insertPosition.root) {
672
+ return transformed;
673
+ }
674
+ if (compareArrays(insertPosition.getParentPath(), this.getParentPath()) == 'same') {
675
+ // If nodes are inserted in the node that is pointed by this position...
676
+ if (insertPosition.offset < this.offset || (insertPosition.offset == this.offset && this.stickiness != 'toPrevious')) {
677
+ // And are inserted before an offset of that position...
678
+ // "Push" this positions offset.
679
+ transformed.offset += howMany;
680
+ }
681
+ }
682
+ else if (compareArrays(insertPosition.getParentPath(), this.getParentPath()) == 'prefix') {
683
+ // If nodes are inserted in a node that is on a path to this position...
684
+ const i = insertPosition.path.length - 1;
685
+ if (insertPosition.offset <= this.path[i]) {
686
+ // And are inserted before next node of that path...
687
+ // "Push" the index on that path.
688
+ transformed.path[i] += howMany;
689
+ }
690
+ }
691
+ return transformed;
692
+ }
693
+ /**
694
+ * Returns a copy of this position that is updated by moving `howMany` nodes from `sourcePosition` to `targetPosition`.
695
+ *
696
+ * @internal
697
+ * @protected
698
+ * @param {module:engine/model/position~Position} sourcePosition Position before the first element to move.
699
+ * @param {module:engine/model/position~Position} targetPosition Position where moved elements will be inserted.
700
+ * @param {Number} howMany How many consecutive nodes to move, starting from `sourcePosition`.
701
+ * @returns {module:engine/model/position~Position} Transformed position.
702
+ */
703
+ _getTransformedByMove(sourcePosition, targetPosition, howMany) {
704
+ // Update target position, as it could be affected by nodes removal.
705
+ targetPosition = targetPosition._getTransformedByDeletion(sourcePosition, howMany);
706
+ if (sourcePosition.isEqual(targetPosition)) {
707
+ // If `targetPosition` is equal to `sourcePosition` this isn't really any move. Just return position as it is.
708
+ return Position._createAt(this);
709
+ }
710
+ // Moving a range removes nodes from their original position. We acknowledge this by proper transformation.
711
+ const transformed = this._getTransformedByDeletion(sourcePosition, howMany);
712
+ const isMoved = transformed === null ||
713
+ (sourcePosition.isEqual(this) && this.stickiness == 'toNext') ||
714
+ (sourcePosition.getShiftedBy(howMany).isEqual(this) && this.stickiness == 'toPrevious');
715
+ if (isMoved) {
716
+ // This position is inside moved range (or sticks to it).
717
+ // In this case, we calculate a combination of this position, move source position and target position.
718
+ return this._getCombined(sourcePosition, targetPosition);
719
+ }
720
+ else {
721
+ // This position is not inside a removed range.
722
+ //
723
+ // In next step, we simply reflect inserting `howMany` nodes, which might further affect the position.
724
+ return transformed._getTransformedByInsertion(targetPosition, howMany);
725
+ }
726
+ }
727
+ /**
728
+ * Returns a new position that is a combination of this position and given positions.
729
+ *
730
+ * The combined position is a copy of this position transformed by moving a range starting at `source` position
731
+ * to the `target` position. It is expected that this position is inside the moved range.
732
+ *
733
+ * Example:
734
+ *
735
+ * let original = model.createPositionFromPath( root, [ 2, 3, 1 ] );
736
+ * let source = model.createPositionFromPath( root, [ 2, 2 ] );
737
+ * let target = model.createPositionFromPath( otherRoot, [ 1, 1, 3 ] );
738
+ * original._getCombined( source, target ); // path is [ 1, 1, 4, 1 ], root is `otherRoot`
739
+ *
740
+ * Explanation:
741
+ *
742
+ * We have a position `[ 2, 3, 1 ]` and move some nodes from `[ 2, 2 ]` to `[ 1, 1, 3 ]`. The original position
743
+ * was inside moved nodes and now should point to the new place. The moved nodes will be after
744
+ * positions `[ 1, 1, 3 ]`, `[ 1, 1, 4 ]`, `[ 1, 1, 5 ]`. Since our position was in the second moved node,
745
+ * the transformed position will be in a sub-tree of a node at `[ 1, 1, 4 ]`. Looking at original path, we
746
+ * took care of `[ 2, 3 ]` part of it. Now we have to add the rest of the original path to the transformed path.
747
+ * Finally, the transformed position will point to `[ 1, 1, 4, 1 ]`.
748
+ *
749
+ * @internal
750
+ * @protected
751
+ * @param {module:engine/model/position~Position} source Beginning of the moved range.
752
+ * @param {module:engine/model/position~Position} target Position where the range is moved.
753
+ * @returns {module:engine/model/position~Position} Combined position.
754
+ */
755
+ _getCombined(source, target) {
756
+ const i = source.path.length - 1;
757
+ // The first part of a path to combined position is a path to the place where nodes were moved.
758
+ const combined = Position._createAt(target);
759
+ combined.stickiness = this.stickiness;
760
+ // Then we have to update the rest of the path.
761
+ // Fix the offset because this position might be after `from` position and we have to reflect that.
762
+ combined.offset = combined.offset + this.path[i] - source.offset;
763
+ // Then, add the rest of the path.
764
+ // If this position is at the same level as `from` position nothing will get added.
765
+ combined.path = [...combined.path, ...this.path.slice(i + 1)];
766
+ return combined;
767
+ }
768
+ /**
769
+ * @inheritDoc
770
+ */
771
+ toJSON() {
772
+ return {
773
+ root: this.root.toJSON(),
774
+ path: Array.from(this.path),
775
+ stickiness: this.stickiness
776
+ };
777
+ }
778
+ /**
779
+ * Returns a new position that is equal to current position.
780
+ *
781
+ * @returns {module:engine/model/position~Position}
782
+ */
783
+ clone() {
784
+ return new this.constructor(this.root, this.path, this.stickiness);
785
+ }
786
+ /**
787
+ * Creates position at the given location. The location can be specified as:
788
+ *
789
+ * * a {@link module:engine/model/position~Position position},
790
+ * * parent element and offset (offset defaults to `0`),
791
+ * * parent element and `'end'` (sets position at the end of that element),
792
+ * * {@link module:engine/model/item~Item model item} and `'before'` or `'after'` (sets position before or after given model item).
793
+ *
794
+ * This method is a shortcut to other factory methods such as:
795
+ *
796
+ * * {@link module:engine/model/position~Position._createBefore},
797
+ * * {@link module:engine/model/position~Position._createAfter}.
798
+ *
799
+ * @param {module:engine/model/item~Item|module:engine/model/position~Position} itemOrPosition
800
+ * @param {Number|'end'|'before'|'after'} [offset] Offset or one of the flags. Used only when the
801
+ * first parameter is a {@link module:engine/model/item~Item model item}.
802
+ * @param {module:engine/model/position~PositionStickiness} [stickiness='toNone'] Position stickiness. Used only when the
803
+ * first parameter is a {@link module:engine/model/item~Item model item}.
804
+ * @protected
805
+ * @internal
806
+ */
807
+ static _createAt(itemOrPosition, offset, stickiness = 'toNone') {
808
+ if (itemOrPosition instanceof Position) {
809
+ return new Position(itemOrPosition.root, itemOrPosition.path, itemOrPosition.stickiness);
810
+ }
811
+ else {
812
+ const node = itemOrPosition;
813
+ if (offset == 'end') {
814
+ offset = node.maxOffset;
815
+ }
816
+ else if (offset == 'before') {
817
+ return this._createBefore(node, stickiness);
818
+ }
819
+ else if (offset == 'after') {
820
+ return this._createAfter(node, stickiness);
821
+ }
822
+ else if (offset !== 0 && !offset) {
823
+ /**
824
+ * {@link module:engine/model/model~Model#createPositionAt `Model#createPositionAt()`}
825
+ * requires the offset to be specified when the first parameter is a model item.
826
+ *
827
+ * @error model-createpositionat-offset-required
828
+ */
829
+ throw new CKEditorError('model-createpositionat-offset-required', [this, itemOrPosition]);
830
+ }
831
+ if (!node.is('element') && !node.is('documentFragment')) {
832
+ /**
833
+ * Position parent have to be a model element or model document fragment.
834
+ *
835
+ * @error model-position-parent-incorrect
836
+ */
837
+ throw new CKEditorError('model-position-parent-incorrect', [this, itemOrPosition]);
838
+ }
839
+ const path = node.getPath();
840
+ path.push(offset);
841
+ return new this(node.root, path, stickiness);
842
+ }
843
+ }
844
+ /**
845
+ * Creates a new position, after given {@link module:engine/model/item~Item model item}.
846
+ *
847
+ * @param {module:engine/model/item~Item} item Item after which the position should be placed.
848
+ * @param {module:engine/model/position~PositionStickiness} [stickiness='toNone'] Position stickiness.
849
+ * @returns {module:engine/model/position~Position}
850
+ * @protected
851
+ * @internal
852
+ */
853
+ static _createAfter(item, stickiness) {
854
+ if (!item.parent) {
855
+ /**
856
+ * You can not make a position after a root element.
857
+ *
858
+ * @error model-position-after-root
859
+ * @param {module:engine/model/item~Item} root
860
+ */
861
+ throw new CKEditorError('model-position-after-root', [this, item], { root: item });
862
+ }
863
+ return this._createAt(item.parent, item.endOffset, stickiness);
864
+ }
865
+ /**
866
+ * Creates a new position, before the given {@link module:engine/model/item~Item model item}.
867
+ *
868
+ * @param {module:engine/model/item~Item} item Item before which the position should be placed.
869
+ * @param {module:engine/model/position~PositionStickiness} [stickiness='toNone'] Position stickiness.
870
+ * @returns {module:engine/model/position~Position}
871
+ * @protected
872
+ * @internal
873
+ */
874
+ static _createBefore(item, stickiness) {
875
+ if (!item.parent) {
876
+ /**
877
+ * You can not make a position before a root element.
878
+ *
879
+ * @error model-position-before-root
880
+ * @param {module:engine/model/item~Item} root
881
+ */
882
+ throw new CKEditorError('model-position-before-root', item, { root: item });
883
+ }
884
+ return this._createAt(item.parent, item.startOffset, stickiness);
885
+ }
886
+ /**
887
+ * Creates a `Position` instance from given plain object (i.e. parsed JSON string).
888
+ *
889
+ * @param {Object} json Plain object to be converted to `Position`.
890
+ * @param {module:engine/model/document~Document} doc Document object that will be position owner.
891
+ * @returns {module:engine/model/position~Position} `Position` instance created using given plain object.
892
+ */
893
+ static fromJSON(json, doc) {
894
+ if (json.root === '$graveyard') {
895
+ const pos = new Position(doc.graveyard, json.path);
896
+ pos.stickiness = json.stickiness;
897
+ return pos;
898
+ }
899
+ if (!doc.getRoot(json.root)) {
900
+ /**
901
+ * Cannot create position for document. Root with specified name does not exist.
902
+ *
903
+ * @error model-position-fromjson-no-root
904
+ * @param {String} rootName
905
+ */
906
+ throw new CKEditorError('model-position-fromjson-no-root', doc, { rootName: json.root });
907
+ }
908
+ return new Position(doc.getRoot(json.root), json.path, json.stickiness);
909
+ }
1042
910
  }
1043
-
1044
911
  /**
1045
- * A flag indicating whether this position is `'before'` or `'after'` or `'same'` as given position.
1046
- * If positions are in different roots `'different'` flag is returned.
1047
- *
1048
- * @typedef {String} module:engine/model/position~PositionRelation
1049
- */
1050
-
1051
- /**
1052
- * Represents how position is "sticking" with neighbour nodes. Used to define how position should be transformed (moved)
1053
- * in edge cases. Possible values: `'toNone'`, `'toNext'`, `'toPrevious'`.
1054
- *
1055
- * Examples:
1056
- *
1057
- * Insert. Position is at | and nodes are inserted at the same position, marked as ^:
1058
- *
1059
- * - sticks to none: <p>f^|oo</p> -> <p>fbar|oo</p>
1060
- * - sticks to next node: <p>f^|oo</p> -> <p>fbar|oo</p>
1061
- * - sticks to previous node: <p>f|^oo</p> -> <p>f|baroo</p>
912
+ * Checks whether this object is of the given.
1062
913
  *
914
+ * position.is( 'position' ); // -> true
915
+ * position.is( 'model:position' ); // -> true
1063
916
  *
1064
- * Move. Position is at | and range [oo] is moved to position ^:
917
+ * position.is( 'view:position' ); // -> false
918
+ * position.is( 'documentSelection' ); // -> false
1065
919
  *
1066
- * - sticks to none: <p>f|[oo]</p><p>b^ar</p> -> <p>f|</p><p>booar</p>
1067
- * - sticks to none: <p>f[oo]|</p><p>b^ar</p> -> <p>f|</p><p>booar</p>
920
+ * {@link module:engine/model/node~Node#is Check the entire list of model objects} which implement the `is()` method.
1068
921
  *
1069
- * - sticks to next node: <p>f|[oo]</p><p>b^ar</p> -> <p>f</p><p>b|ooar</p>
1070
- * - sticks to next node: <p>f[oo]|</p><p>b^ar</p> -> <p>f|</p><p>booar</p>
1071
- *
1072
- * - sticks to previous node: <p>f|[oo]</p><p>b^ar</p> -> <p>f|</p><p>booar</p>
1073
- * - sticks to previous node: <p>f[oo]|</p><p>b^ar</p> -> <p>f</p><p>boo|ar</p>
1074
- *
1075
- * @typedef {String} module:engine/model/position~PositionStickiness
922
+ * @param {String} type
923
+ * @returns {Boolean}
1076
924
  */
1077
-
925
+ Position.prototype.is = function (type) {
926
+ return type === 'position' || type === 'model:position';
927
+ };
1078
928
  /**
1079
929
  * Returns a text node at the given position.
1080
930
  *
@@ -1096,16 +946,13 @@ export default class Position {
1096
946
  * given position.
1097
947
  * @returns {module:engine/model/text~Text|null}
1098
948
  */
1099
- export function getTextNodeAtPosition( position, positionParent ) {
1100
- const node = positionParent.getChild( positionParent.offsetToIndex( position.offset ) );
1101
-
1102
- if ( node && node.is( '$text' ) && node.startOffset < position.offset ) {
1103
- return node;
1104
- }
1105
-
1106
- return null;
949
+ export function getTextNodeAtPosition(position, positionParent) {
950
+ const node = positionParent.getChild(positionParent.offsetToIndex(position.offset));
951
+ if (node && node.is('$text') && node.startOffset < position.offset) {
952
+ return node;
953
+ }
954
+ return null;
1107
955
  }
1108
-
1109
956
  /**
1110
957
  * Returns the node after the given position.
1111
958
  *
@@ -1131,14 +978,12 @@ export function getTextNodeAtPosition( position, positionParent ) {
1131
978
  * @param {module:engine/model/text~Text|null} textNode Text node at the given position.
1132
979
  * @returns {module:engine/model/node~Node|null}
1133
980
  */
1134
- export function getNodeAfterPosition( position, positionParent, textNode ) {
1135
- if ( textNode !== null ) {
1136
- return null;
1137
- }
1138
-
1139
- return positionParent.getChild( positionParent.offsetToIndex( position.offset ) );
981
+ export function getNodeAfterPosition(position, positionParent, textNode) {
982
+ if (textNode !== null) {
983
+ return null;
984
+ }
985
+ return positionParent.getChild(positionParent.offsetToIndex(position.offset));
1140
986
  }
1141
-
1142
987
  /**
1143
988
  * Returns the node before the given position.
1144
989
  *
@@ -1155,10 +1000,92 @@ export function getNodeAfterPosition( position, positionParent, textNode ) {
1155
1000
  * @param {module:engine/model/text~Text|null} textNode Text node at the given position.
1156
1001
  * @returns {module:engine/model/node~Node|null}
1157
1002
  */
1158
- export function getNodeBeforePosition( position, positionParent, textNode ) {
1159
- if ( textNode !== null ) {
1160
- return null;
1161
- }
1162
-
1163
- return positionParent.getChild( positionParent.offsetToIndex( position.offset ) - 1 );
1003
+ export function getNodeBeforePosition(position, positionParent, textNode) {
1004
+ if (textNode !== null) {
1005
+ return null;
1006
+ }
1007
+ return positionParent.getChild(positionParent.offsetToIndex(position.offset) - 1);
1008
+ }
1009
+ // This is a helper function for `Position#isTouching()`.
1010
+ //
1011
+ // It checks whether to given positions are touching, considering that they have the same root and paths
1012
+ // until given level, and at given level they differ by 1 (so they are branching at `level` point).
1013
+ //
1014
+ // The exact requirements for touching positions are described in `Position#isTouching()` and also
1015
+ // in the body of this function.
1016
+ //
1017
+ // @param {module:engine/model/position~Position} left Position "on the left" (it is before `right`).
1018
+ // @param {module:engine/model/position~Position} right Position "on the right" (it is after `left`).
1019
+ // @param {Number} level Level on which the positions are different.
1020
+ // @returns {Boolean}
1021
+ function checkTouchingBranch(left, right, level) {
1022
+ if (level + 1 === left.path.length) {
1023
+ // Left position does not have any more entries after the point where the positions differ.
1024
+ // [ 2 ] vs [ 3 ]
1025
+ // [ 2 ] vs [ 3, 0, 0 ]
1026
+ // The positions are spread by node at [ 2 ].
1027
+ return false;
1028
+ }
1029
+ if (!checkOnlyZeroes(right.path, level + 1)) {
1030
+ // Right position does not have only zeroes, so we have situation like:
1031
+ // [ 2, maxOffset ] vs [ 3, 1 ]
1032
+ // [ 2, maxOffset ] vs [ 3, 1, 0, 0 ]
1033
+ // The positions are spread by node at [ 3, 0 ].
1034
+ return false;
1035
+ }
1036
+ if (!checkOnlyMaxOffset(left, level + 1)) {
1037
+ // Left position does not have only max offsets, so we have situation like:
1038
+ // [ 2, 4 ] vs [ 3 ]
1039
+ // [ 2, 4 ] vs [ 3, 0, 0 ]
1040
+ // The positions are spread by node at [ 2, 5 ].
1041
+ return false;
1042
+ }
1043
+ // Left position has only max offsets and right position has only zeroes or nothing.
1044
+ // [ 2, maxOffset ] vs [ 3 ]
1045
+ // [ 2, maxOffset, maxOffset ] vs [ 3, 0 ]
1046
+ // There are not elements between positions. The positions are touching.
1047
+ return true;
1048
+ }
1049
+ // Checks whether for given array, starting from given index until the end of the array, all items are `0`s.
1050
+ //
1051
+ // This is a helper function for `Position#isTouching()`.
1052
+ //
1053
+ // @private
1054
+ // @param {Array.<Number>} arr Array to check.
1055
+ // @param {Number} idx Index to start checking from.
1056
+ // @returns {Boolean}
1057
+ function checkOnlyZeroes(arr, idx) {
1058
+ while (idx < arr.length) {
1059
+ if (arr[idx] !== 0) {
1060
+ return false;
1061
+ }
1062
+ idx++;
1063
+ }
1064
+ return true;
1065
+ }
1066
+ // Checks whether for given position, starting from given path level, whether the position is at the end of
1067
+ // its parent and whether each element on the path to the position is also at at the end of its parent.
1068
+ //
1069
+ // This is a helper function for `Position#isTouching()`.
1070
+ //
1071
+ // @private
1072
+ // @param {module:engine/model/position~Position} pos Position to check.
1073
+ // @param {Number} level Level to start checking from.
1074
+ // @returns {Boolean}
1075
+ function checkOnlyMaxOffset(pos, level) {
1076
+ let parent = pos.parent;
1077
+ let idx = pos.path.length - 1;
1078
+ let add = 0;
1079
+ while (idx >= level) {
1080
+ if (pos.path[idx] + add !== parent.maxOffset) {
1081
+ return false;
1082
+ }
1083
+ // After the first check, we "go up", and check whether the position's parent-parent is the last element.
1084
+ // However, we need to add 1 to the value in the path to "simulate" moving the path after the parent.
1085
+ // It happens just once.
1086
+ add = 1;
1087
+ idx--;
1088
+ parent = parent.parent;
1089
+ }
1090
+ return true;
1164
1091
  }