@ckeditor/ckeditor5-engine 34.2.0 → 35.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/CHANGELOG.md +823 -0
  2. package/LICENSE.md +4 -0
  3. package/package.json +32 -25
  4. package/src/controller/datacontroller.js +467 -561
  5. package/src/controller/editingcontroller.js +168 -204
  6. package/src/conversion/conversion.js +541 -565
  7. package/src/conversion/conversionhelpers.js +24 -28
  8. package/src/conversion/downcastdispatcher.js +457 -686
  9. package/src/conversion/downcasthelpers.js +1583 -1965
  10. package/src/conversion/mapper.js +518 -707
  11. package/src/conversion/modelconsumable.js +240 -283
  12. package/src/conversion/upcastdispatcher.js +372 -718
  13. package/src/conversion/upcasthelpers.js +707 -818
  14. package/src/conversion/viewconsumable.js +524 -581
  15. package/src/dataprocessor/basichtmlwriter.js +12 -16
  16. package/src/dataprocessor/dataprocessor.js +5 -0
  17. package/src/dataprocessor/htmldataprocessor.js +101 -117
  18. package/src/dataprocessor/htmlwriter.js +1 -18
  19. package/src/dataprocessor/xmldataprocessor.js +117 -138
  20. package/src/dev-utils/model.js +260 -352
  21. package/src/dev-utils/operationreplayer.js +106 -126
  22. package/src/dev-utils/utils.js +34 -51
  23. package/src/dev-utils/view.js +632 -753
  24. package/src/index.js +0 -11
  25. package/src/model/batch.js +111 -127
  26. package/src/model/differ.js +988 -1233
  27. package/src/model/document.js +340 -449
  28. package/src/model/documentfragment.js +327 -364
  29. package/src/model/documentselection.js +996 -1189
  30. package/src/model/element.js +306 -410
  31. package/src/model/history.js +224 -262
  32. package/src/model/item.js +5 -0
  33. package/src/model/liveposition.js +84 -145
  34. package/src/model/liverange.js +108 -185
  35. package/src/model/markercollection.js +379 -480
  36. package/src/model/model.js +883 -1034
  37. package/src/model/node.js +419 -463
  38. package/src/model/nodelist.js +175 -201
  39. package/src/model/operation/attributeoperation.js +153 -182
  40. package/src/model/operation/detachoperation.js +64 -83
  41. package/src/model/operation/insertoperation.js +135 -166
  42. package/src/model/operation/markeroperation.js +114 -140
  43. package/src/model/operation/mergeoperation.js +163 -191
  44. package/src/model/operation/moveoperation.js +157 -187
  45. package/src/model/operation/nooperation.js +28 -38
  46. package/src/model/operation/operation.js +106 -125
  47. package/src/model/operation/operationfactory.js +30 -34
  48. package/src/model/operation/renameoperation.js +109 -135
  49. package/src/model/operation/rootattributeoperation.js +155 -188
  50. package/src/model/operation/splitoperation.js +196 -232
  51. package/src/model/operation/transform.js +1833 -2204
  52. package/src/model/operation/utils.js +140 -204
  53. package/src/model/position.js +899 -1053
  54. package/src/model/range.js +910 -1028
  55. package/src/model/rootelement.js +77 -97
  56. package/src/model/schema.js +1189 -1835
  57. package/src/model/selection.js +745 -862
  58. package/src/model/text.js +90 -114
  59. package/src/model/textproxy.js +204 -240
  60. package/src/model/treewalker.js +316 -397
  61. package/src/model/typecheckable.js +16 -0
  62. package/src/model/utils/autoparagraphing.js +32 -44
  63. package/src/model/utils/deletecontent.js +334 -418
  64. package/src/model/utils/findoptimalinsertionrange.js +25 -36
  65. package/src/model/utils/getselectedcontent.js +96 -118
  66. package/src/model/utils/insertcontent.js +654 -773
  67. package/src/model/utils/insertobject.js +96 -119
  68. package/src/model/utils/modifyselection.js +120 -158
  69. package/src/model/utils/selection-post-fixer.js +153 -201
  70. package/src/model/writer.js +1305 -1474
  71. package/src/view/attributeelement.js +189 -225
  72. package/src/view/containerelement.js +75 -85
  73. package/src/view/document.js +172 -215
  74. package/src/view/documentfragment.js +200 -249
  75. package/src/view/documentselection.js +338 -367
  76. package/src/view/domconverter.js +1371 -1613
  77. package/src/view/downcastwriter.js +1747 -2076
  78. package/src/view/editableelement.js +81 -97
  79. package/src/view/element.js +739 -890
  80. package/src/view/elementdefinition.js +5 -0
  81. package/src/view/emptyelement.js +82 -92
  82. package/src/view/filler.js +35 -50
  83. package/src/view/item.js +5 -0
  84. package/src/view/matcher.js +260 -559
  85. package/src/view/node.js +274 -360
  86. package/src/view/observer/arrowkeysobserver.js +19 -28
  87. package/src/view/observer/bubblingemittermixin.js +120 -263
  88. package/src/view/observer/bubblingeventinfo.js +47 -55
  89. package/src/view/observer/clickobserver.js +7 -13
  90. package/src/view/observer/compositionobserver.js +14 -24
  91. package/src/view/observer/domeventdata.js +57 -67
  92. package/src/view/observer/domeventobserver.js +40 -64
  93. package/src/view/observer/fakeselectionobserver.js +81 -96
  94. package/src/view/observer/focusobserver.js +45 -61
  95. package/src/view/observer/inputobserver.js +7 -13
  96. package/src/view/observer/keyobserver.js +17 -27
  97. package/src/view/observer/mouseobserver.js +7 -14
  98. package/src/view/observer/mutationobserver.js +220 -315
  99. package/src/view/observer/observer.js +81 -102
  100. package/src/view/observer/selectionobserver.js +191 -246
  101. package/src/view/observer/tabobserver.js +23 -36
  102. package/src/view/placeholder.js +128 -173
  103. package/src/view/position.js +350 -401
  104. package/src/view/range.js +453 -513
  105. package/src/view/rawelement.js +85 -112
  106. package/src/view/renderer.js +874 -1014
  107. package/src/view/rooteditableelement.js +80 -90
  108. package/src/view/selection.js +608 -689
  109. package/src/view/styles/background.js +43 -44
  110. package/src/view/styles/border.js +220 -276
  111. package/src/view/styles/margin.js +8 -17
  112. package/src/view/styles/padding.js +8 -16
  113. package/src/view/styles/utils.js +127 -160
  114. package/src/view/stylesmap.js +728 -905
  115. package/src/view/text.js +102 -126
  116. package/src/view/textproxy.js +144 -170
  117. package/src/view/treewalker.js +383 -479
  118. package/src/view/typecheckable.js +19 -0
  119. package/src/view/uielement.js +166 -187
  120. package/src/view/upcastwriter.js +395 -449
  121. package/src/view/view.js +569 -664
  122. package/src/dataprocessor/dataprocessor.jsdoc +0 -64
  123. package/src/model/item.jsdoc +0 -14
  124. package/src/view/elementdefinition.jsdoc +0 -59
  125. package/src/view/item.jsdoc +0 -14
@@ -2,19 +2,17 @@
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
-
5
+ /* eslint-disable new-cap */
6
6
  /**
7
7
  * @module engine/model/selection
8
8
  */
9
-
10
- import Position from './position';
9
+ import TypeCheckable from './typecheckable';
11
10
  import Node from './node';
11
+ import Position from './position';
12
12
  import Range from './range';
13
- import EmitterMixin from '@ckeditor/ckeditor5-utils/src/emittermixin';
14
13
  import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
15
- import mix from '@ckeditor/ckeditor5-utils/src/mix';
14
+ import EmitterMixin from '@ckeditor/ckeditor5-utils/src/emittermixin';
16
15
  import isIterable from '@ckeditor/ckeditor5-utils/src/isiterable';
17
-
18
16
  /**
19
17
  * Selection is a set of {@link module:engine/model/range~Range ranges}. It has a direction specified by its
20
18
  * {@link module:engine/model/selection~Selection#anchor anchor} and {@link module:engine/model/selection~Selection#focus focus}
@@ -24,879 +22,764 @@ import isIterable from '@ckeditor/ckeditor5-utils/src/isiterable';
24
22
  *
25
23
  * @mixes module:utils/emittermixin~EmitterMixin
26
24
  */
27
- export default class Selection {
28
- /**
29
- * Creates a new selection instance based on the given {@link module:engine/model/selection~Selectable selectable}
30
- * or creates an empty selection if no arguments were passed.
31
- *
32
- * // Creates empty selection without ranges.
33
- * const selection = writer.createSelection();
34
- *
35
- * // Creates selection at the given range.
36
- * const range = writer.createRange( start, end );
37
- * const selection = writer.createSelection( range );
38
- *
39
- * // Creates selection at the given ranges
40
- * const ranges = [ writer.createRange( start1, end2 ), writer.createRange( star2, end2 ) ];
41
- * const selection = writer.createSelection( ranges );
42
- *
43
- * // Creates selection from the other selection.
44
- * // Note: It doesn't copies selection attributes.
45
- * const otherSelection = writer.createSelection();
46
- * const selection = writer.createSelection( otherSelection );
47
- *
48
- * // Creates selection from the given document selection.
49
- * // Note: It doesn't copies selection attributes.
50
- * const documentSelection = model.document.selection;
51
- * const selection = writer.createSelection( documentSelection );
52
- *
53
- * // Creates selection at the given position.
54
- * const position = writer.createPositionFromPath( root, path );
55
- * const selection = writer.createSelection( position );
56
- *
57
- * // Creates selection at the given offset in the given element.
58
- * const paragraph = writer.createElement( 'paragraph' );
59
- * const selection = writer.createSelection( paragraph, offset );
60
- *
61
- * // Creates a range inside an {@link module:engine/model/element~Element element} which starts before the
62
- * // first child of that element and ends after the last child of that element.
63
- * const selection = writer.createSelection( paragraph, 'in' );
64
- *
65
- * // Creates a range on an {@link module:engine/model/item~Item item} which starts before the item and ends
66
- * // just after the item.
67
- * const selection = writer.createSelection( paragraph, 'on' );
68
- *
69
- * Selection's constructor allow passing additional options (`'backward'`) as the last argument.
70
- *
71
- * // Creates backward selection.
72
- * const selection = writer.createSelection( range, { backward: true } );
73
- *
74
- * @param {module:engine/model/selection~Selectable} [selectable]
75
- * @param {Number|'before'|'end'|'after'|'on'|'in'} [placeOrOffset] Sets place or offset of the selection.
76
- * @param {Object} [options]
77
- * @param {Boolean} [options.backward] Sets this selection instance to be backward.
78
- */
79
- constructor( selectable, placeOrOffset, options ) {
80
- /**
81
- * Specifies whether the last added range was added as a backward or forward range.
82
- *
83
- * @private
84
- * @type {Boolean}
85
- */
86
- this._lastRangeBackward = false;
87
-
88
- /**
89
- * Stores selection ranges.
90
- *
91
- * @protected
92
- * @type {Array.<module:engine/model/range~Range>}
93
- */
94
- this._ranges = [];
95
-
96
- /**
97
- * List of attributes set on current selection.
98
- *
99
- * @protected
100
- * @type {Map.<String,*>}
101
- */
102
- this._attrs = new Map();
103
-
104
- if ( selectable ) {
105
- this.setTo( selectable, placeOrOffset, options );
106
- }
107
- }
108
-
109
- /**
110
- * Selection anchor. Anchor is the position from which the selection was started. If a user is making a selection
111
- * by dragging the mouse, the anchor is where the user pressed the mouse button (the beginning of the selection).
112
- *
113
- * Anchor and {@link #focus} define the direction of the selection, which is important
114
- * when expanding/shrinking selection. The focus moves, while the anchor should remain in the same place.
115
- *
116
- * Anchor is always set to the {@link module:engine/model/range~Range#start start} or
117
- * {@link module:engine/model/range~Range#end end} position of the last of selection's ranges. Whether it is
118
- * the `start` or `end` depends on the specified `options.backward`. See the {@link #setTo `setTo()`} method.
119
- *
120
- * May be set to `null` if there are no ranges in the selection.
121
- *
122
- * @see #focus
123
- * @readonly
124
- * @type {module:engine/model/position~Position|null}
125
- */
126
- get anchor() {
127
- if ( this._ranges.length > 0 ) {
128
- const range = this._ranges[ this._ranges.length - 1 ];
129
-
130
- return this._lastRangeBackward ? range.end : range.start;
131
- }
132
-
133
- return null;
134
- }
135
-
136
- /**
137
- * Selection focus. Focus is the position where the selection ends. If a user is making a selection
138
- * by dragging the mouse, the focus is where the mouse cursor is.
139
- *
140
- * May be set to `null` if there are no ranges in the selection.
141
- *
142
- * @see #anchor
143
- * @readonly
144
- * @type {module:engine/model/position~Position|null}
145
- */
146
- get focus() {
147
- if ( this._ranges.length > 0 ) {
148
- const range = this._ranges[ this._ranges.length - 1 ];
149
-
150
- return this._lastRangeBackward ? range.start : range.end;
151
- }
152
-
153
- return null;
154
- }
155
-
156
- /**
157
- * Whether the selection is collapsed. Selection is collapsed when there is exactly one range in it
158
- * and it is collapsed.
159
- *
160
- * @readonly
161
- * @type {Boolean}
162
- */
163
- get isCollapsed() {
164
- const length = this._ranges.length;
165
-
166
- if ( length === 1 ) {
167
- return this._ranges[ 0 ].isCollapsed;
168
- } else {
169
- return false;
170
- }
171
- }
172
-
173
- /**
174
- * Returns the number of ranges in the selection.
175
- *
176
- * @readonly
177
- * @type {Number}
178
- */
179
- get rangeCount() {
180
- return this._ranges.length;
181
- }
182
-
183
- /**
184
- * Specifies whether the selection's {@link #focus} precedes the selection's {@link #anchor}.
185
- *
186
- * @readonly
187
- * @type {Boolean}
188
- */
189
- get isBackward() {
190
- return !this.isCollapsed && this._lastRangeBackward;
191
- }
192
-
193
- /**
194
- * Checks whether this selection is equal to the given selection. Selections are equal if they have the same directions,
195
- * the same number of ranges and all ranges from one selection equal to ranges from the another selection.
196
- *
197
- * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection} otherSelection
198
- * Selection to compare with.
199
- * @returns {Boolean} `true` if selections are equal, `false` otherwise.
200
- */
201
- isEqual( otherSelection ) {
202
- if ( this.rangeCount != otherSelection.rangeCount ) {
203
- return false;
204
- } else if ( this.rangeCount === 0 ) {
205
- return true;
206
- }
207
-
208
- if ( !this.anchor.isEqual( otherSelection.anchor ) || !this.focus.isEqual( otherSelection.focus ) ) {
209
- return false;
210
- }
211
-
212
- for ( const thisRange of this._ranges ) {
213
- let found = false;
214
-
215
- for ( const otherRange of otherSelection._ranges ) {
216
- if ( thisRange.isEqual( otherRange ) ) {
217
- found = true;
218
- break;
219
- }
220
- }
221
-
222
- if ( !found ) {
223
- return false;
224
- }
225
- }
226
-
227
- return true;
228
- }
229
-
230
- /**
231
- * Returns an iterable object that iterates over copies of selection ranges.
232
- *
233
- * @returns {Iterable.<module:engine/model/range~Range>}
234
- */
235
- * getRanges() {
236
- for ( const range of this._ranges ) {
237
- yield new Range( range.start, range.end );
238
- }
239
- }
240
-
241
- /**
242
- * Returns a copy of the first range in the selection.
243
- * First range is the one which {@link module:engine/model/range~Range#start start} position
244
- * {@link module:engine/model/position~Position#isBefore is before} start position of all other ranges
245
- * (not to confuse with the first range added to the selection).
246
- *
247
- * Returns `null` if there are no ranges in selection.
248
- *
249
- * @returns {module:engine/model/range~Range|null}
250
- */
251
- getFirstRange() {
252
- let first = null;
253
-
254
- for ( const range of this._ranges ) {
255
- if ( !first || range.start.isBefore( first.start ) ) {
256
- first = range;
257
- }
258
- }
259
-
260
- return first ? new Range( first.start, first.end ) : null;
261
- }
262
-
263
- /**
264
- * Returns a copy of the last range in the selection.
265
- * Last range is the one which {@link module:engine/model/range~Range#end end} position
266
- * {@link module:engine/model/position~Position#isAfter is after} end position of all other ranges (not to confuse with the range most
267
- * recently added to the selection).
268
- *
269
- * Returns `null` if there are no ranges in selection.
270
- *
271
- * @returns {module:engine/model/range~Range|null}
272
- */
273
- getLastRange() {
274
- let last = null;
275
-
276
- for ( const range of this._ranges ) {
277
- if ( !last || range.end.isAfter( last.end ) ) {
278
- last = range;
279
- }
280
- }
281
-
282
- return last ? new Range( last.start, last.end ) : null;
283
- }
284
-
285
- /**
286
- * Returns the first position in the selection.
287
- * First position is the position that {@link module:engine/model/position~Position#isBefore is before}
288
- * any other position in the selection.
289
- *
290
- * Returns `null` if there are no ranges in selection.
291
- *
292
- * @returns {module:engine/model/position~Position|null}
293
- */
294
- getFirstPosition() {
295
- const first = this.getFirstRange();
296
-
297
- return first ? first.start.clone() : null;
298
- }
299
-
300
- /**
301
- * Returns the last position in the selection.
302
- * Last position is the position that {@link module:engine/model/position~Position#isAfter is after}
303
- * any other position in the selection.
304
- *
305
- * Returns `null` if there are no ranges in selection.
306
- *
307
- * @returns {module:engine/model/position~Position|null}
308
- */
309
- getLastPosition() {
310
- const lastRange = this.getLastRange();
311
-
312
- return lastRange ? lastRange.end.clone() : null;
313
- }
314
-
315
- /**
316
- * Sets this selection's ranges and direction to the specified location based on the given
317
- * {@link module:engine/model/selection~Selectable selectable}.
318
- *
319
- * // Removes all selection's ranges.
320
- * selection.setTo( null );
321
- *
322
- * // Sets selection to the given range.
323
- * const range = writer.createRange( start, end );
324
- * selection.setTo( range );
325
- *
326
- * // Sets selection to given ranges.
327
- * const ranges = [ writer.createRange( start1, end2 ), writer.createRange( star2, end2 ) ];
328
- * selection.setTo( ranges );
329
- *
330
- * // Sets selection to other selection.
331
- * // Note: It doesn't copies selection attributes.
332
- * const otherSelection = writer.createSelection();
333
- * selection.setTo( otherSelection );
334
- *
335
- * // Sets selection to the given document selection.
336
- * // Note: It doesn't copies selection attributes.
337
- * const documentSelection = new DocumentSelection( doc );
338
- * selection.setTo( documentSelection );
339
- *
340
- * // Sets collapsed selection at the given position.
341
- * const position = writer.createPositionFromPath( root, path );
342
- * selection.setTo( position );
343
- *
344
- * // Sets collapsed selection at the position of the given node and an offset.
345
- * selection.setTo( paragraph, offset );
346
- *
347
- * Creates a range inside an {@link module:engine/model/element~Element element} which starts before the first child of
348
- * that element and ends after the last child of that element.
349
- *
350
- * selection.setTo( paragraph, 'in' );
351
- *
352
- * Creates a range on an {@link module:engine/model/item~Item item} which starts before the item and ends just after the item.
353
- *
354
- * selection.setTo( paragraph, 'on' );
355
- *
356
- * `Selection#setTo()`' method allow passing additional options (`backward`) as the last argument.
357
- *
358
- * // Sets backward selection.
359
- * const selection = writer.createSelection( range, { backward: true } );
360
- *
361
- * @param {module:engine/model/selection~Selectable} selectable
362
- * @param {Number|'before'|'end'|'after'|'on'|'in'} [placeOrOffset] Sets place or offset of the selection.
363
- * @param {Object} [options]
364
- * @param {Boolean} [options.backward] Sets this selection instance to be backward.
365
- */
366
- setTo( selectable, placeOrOffset, options ) {
367
- if ( selectable === null ) {
368
- this._setRanges( [] );
369
- } else if ( selectable instanceof Selection ) {
370
- this._setRanges( selectable.getRanges(), selectable.isBackward );
371
- } else if ( selectable && typeof selectable.getRanges == 'function' ) {
372
- // We assume that the selectable is a DocumentSelection.
373
- // It can't be imported here, because it would lead to circular imports.
374
- this._setRanges( selectable.getRanges(), selectable.isBackward );
375
- } else if ( selectable instanceof Range ) {
376
- this._setRanges( [ selectable ], !!placeOrOffset && !!placeOrOffset.backward );
377
- } else if ( selectable instanceof Position ) {
378
- this._setRanges( [ new Range( selectable ) ] );
379
- } else if ( selectable instanceof Node ) {
380
- const backward = !!options && !!options.backward;
381
- let range;
382
-
383
- if ( placeOrOffset == 'in' ) {
384
- range = Range._createIn( selectable );
385
- } else if ( placeOrOffset == 'on' ) {
386
- range = Range._createOn( selectable );
387
- } else if ( placeOrOffset !== undefined ) {
388
- range = new Range( Position._createAt( selectable, placeOrOffset ) );
389
- } else {
390
- /**
391
- * selection.setTo requires the second parameter when the first parameter is a node.
392
- *
393
- * @error model-selection-setto-required-second-parameter
394
- */
395
- throw new CKEditorError( 'model-selection-setto-required-second-parameter', [ this, selectable ] );
396
- }
397
-
398
- this._setRanges( [ range ], backward );
399
- } else if ( isIterable( selectable ) ) {
400
- // We assume that the selectable is an iterable of ranges.
401
- this._setRanges( selectable, placeOrOffset && !!placeOrOffset.backward );
402
- } else {
403
- /**
404
- * Cannot set the selection to the given place.
405
- *
406
- * Invalid parameters were specified when setting the selection. Common issues:
407
- *
408
- * * A {@link module:engine/model/textproxy~TextProxy} instance was passed instead of
409
- * a real {@link module:engine/model/text~Text}.
410
- * * View nodes were passed instead of model nodes.
411
- * * `null`/`undefined` was passed.
412
- *
413
- * @error model-selection-setto-not-selectable
414
- */
415
- throw new CKEditorError( 'model-selection-setto-not-selectable', [ this, selectable ] );
416
- }
417
- }
418
-
419
- /**
420
- * Replaces all ranges that were added to the selection with given array of ranges. Last range of the array
421
- * is treated like the last added range and is used to set {@link module:engine/model/selection~Selection#anchor} and
422
- * {@link module:engine/model/selection~Selection#focus}. Accepts a flag describing in which direction the selection is made.
423
- *
424
- * @protected
425
- * @fires change:range
426
- * @param {Iterable.<module:engine/model/range~Range>} newRanges Ranges to set.
427
- * @param {Boolean} [isLastBackward=false] Flag describing if last added range was selected forward - from start to end (`false`)
428
- * or backward - from end to start (`true`).
429
- */
430
- _setRanges( newRanges, isLastBackward = false ) {
431
- newRanges = Array.from( newRanges );
432
-
433
- // Check whether there is any range in new ranges set that is different than all already added ranges.
434
- const anyNewRange = newRanges.some( newRange => {
435
- if ( !( newRange instanceof Range ) ) {
436
- /**
437
- * Selection range set to an object that is not an instance of {@link module:engine/model/range~Range}.
438
- *
439
- * Only {@link module:engine/model/range~Range} instances can be used to set a selection.
440
- * Common mistakes leading to this error are:
441
- *
442
- * * using DOM `Range` object,
443
- * * incorrect CKEditor 5 installation with multiple `ckeditor5-engine` packages having different versions.
444
- *
445
- * @error model-selection-set-ranges-not-range
446
- */
447
- throw new CKEditorError(
448
- 'model-selection-set-ranges-not-range',
449
- [ this, newRanges ]
450
- );
451
- }
452
-
453
- return this._ranges.every( oldRange => {
454
- return !oldRange.isEqual( newRange );
455
- } );
456
- } );
457
-
458
- // Don't do anything if nothing changed.
459
- if ( newRanges.length === this._ranges.length && !anyNewRange ) {
460
- return;
461
- }
462
-
463
- this._removeAllRanges();
464
-
465
- for ( const range of newRanges ) {
466
- this._pushRange( range );
467
- }
468
-
469
- this._lastRangeBackward = !!isLastBackward;
470
-
471
- this.fire( 'change:range', { directChange: true } );
472
- }
473
-
474
- /**
475
- * Moves {@link module:engine/model/selection~Selection#focus} to the specified location.
476
- *
477
- * The location can be specified in the same form as
478
- * {@link module:engine/model/writer~Writer#createPositionAt writer.createPositionAt()} parameters.
479
- *
480
- * @fires change:range
481
- * @param {module:engine/model/item~Item|module:engine/model/position~Position} itemOrPosition
482
- * @param {Number|'end'|'before'|'after'} [offset] Offset or one of the flags. Used only when
483
- * first parameter is a {@link module:engine/model/item~Item model item}.
484
- */
485
- setFocus( itemOrPosition, offset ) {
486
- if ( this.anchor === null ) {
487
- /**
488
- * Cannot set selection focus if there are no ranges in selection.
489
- *
490
- * @error model-selection-setfocus-no-ranges
491
- */
492
- throw new CKEditorError( 'model-selection-setfocus-no-ranges', [ this, itemOrPosition ] );
493
- }
494
-
495
- const newFocus = Position._createAt( itemOrPosition, offset );
496
-
497
- if ( newFocus.compareWith( this.focus ) == 'same' ) {
498
- return;
499
- }
500
-
501
- const anchor = this.anchor;
502
-
503
- if ( this._ranges.length ) {
504
- this._popRange();
505
- }
506
-
507
- if ( newFocus.compareWith( anchor ) == 'before' ) {
508
- this._pushRange( new Range( newFocus, anchor ) );
509
- this._lastRangeBackward = true;
510
- } else {
511
- this._pushRange( new Range( anchor, newFocus ) );
512
- this._lastRangeBackward = false;
513
- }
514
-
515
- this.fire( 'change:range', { directChange: true } );
516
- }
517
-
518
- /**
519
- * Gets an attribute value for given key or `undefined` if that attribute is not set on the selection.
520
- *
521
- * @param {String} key Key of attribute to look for.
522
- * @returns {*} Attribute value or `undefined`.
523
- */
524
- getAttribute( key ) {
525
- return this._attrs.get( key );
526
- }
527
-
528
- /**
529
- * Returns iterable that iterates over this selection's attributes.
530
- *
531
- * Attributes are returned as arrays containing two items. First one is attribute key and second is attribute value.
532
- * This format is accepted by native `Map` object and also can be passed in `Node` constructor.
533
- *
534
- * @returns {Iterable.<*>}
535
- */
536
- getAttributes() {
537
- return this._attrs.entries();
538
- }
539
-
540
- /**
541
- * Returns iterable that iterates over this selection's attribute keys.
542
- *
543
- * @returns {Iterable.<String>}
544
- */
545
- getAttributeKeys() {
546
- return this._attrs.keys();
547
- }
548
-
549
- /**
550
- * Checks if the selection has an attribute for given key.
551
- *
552
- * @param {String} key Key of attribute to check.
553
- * @returns {Boolean} `true` if attribute with given key is set on selection, `false` otherwise.
554
- */
555
- hasAttribute( key ) {
556
- return this._attrs.has( key );
557
- }
558
-
559
- /**
560
- * Removes an attribute with given key from the selection.
561
- *
562
- * If given attribute was set on the selection, fires the {@link #event:change:range} event with
563
- * removed attribute key.
564
- *
565
- * @fires change:attribute
566
- * @param {String} key Key of attribute to remove.
567
- */
568
- removeAttribute( key ) {
569
- if ( this.hasAttribute( key ) ) {
570
- this._attrs.delete( key );
571
-
572
- this.fire( 'change:attribute', { attributeKeys: [ key ], directChange: true } );
573
- }
574
- }
575
-
576
- /**
577
- * Sets attribute on the selection. If attribute with the same key already is set, it's value is overwritten.
578
- *
579
- * If the attribute value has changed, fires the {@link #event:change:range} event with
580
- * the attribute key.
581
- *
582
- * @fires change:attribute
583
- * @param {String} key Key of attribute to set.
584
- * @param {*} value Attribute value.
585
- */
586
- setAttribute( key, value ) {
587
- if ( this.getAttribute( key ) !== value ) {
588
- this._attrs.set( key, value );
589
-
590
- this.fire( 'change:attribute', { attributeKeys: [ key ], directChange: true } );
591
- }
592
- }
593
-
594
- /**
595
- * Returns the selected element. {@link module:engine/model/element~Element Element} is considered as selected if there is only
596
- * one range in the selection, and that range contains exactly one element.
597
- * Returns `null` if there is no selected element.
598
- *
599
- * @returns {module:engine/model/element~Element|null}
600
- */
601
- getSelectedElement() {
602
- if ( this.rangeCount !== 1 ) {
603
- return null;
604
- }
605
-
606
- return this.getFirstRange().getContainedElement();
607
- }
608
-
609
- /**
610
- * Checks whether this object is of the given.
611
- *
612
- * selection.is( 'selection' ); // -> true
613
- * selection.is( 'model:selection' ); // -> true
614
- *
615
- * selection.is( 'view:selection' ); // -> false
616
- * selection.is( 'range' ); // -> false
617
- *
618
- * {@link module:engine/model/node~Node#is Check the entire list of model objects} which implement the `is()` method.
619
- *
620
- * @param {String} type
621
- * @returns {Boolean}
622
- */
623
- is( type ) {
624
- return type === 'selection' || type === 'model:selection';
625
- }
626
-
627
- /**
628
- * Gets elements of type {@link module:engine/model/schema~Schema#isBlock "block"} touched by the selection.
629
- *
630
- * This method's result can be used for example to apply block styling to all blocks covered by this selection.
631
- *
632
- * **Note:** `getSelectedBlocks()` returns blocks that are nested in other non-block elements
633
- * but will not return blocks nested in other blocks.
634
- *
635
- * In this case the function will return exactly all 3 paragraphs (note: `<blockQuote>` is not a block itself):
636
- *
637
- * <paragraph>[a</paragraph>
638
- * <blockQuote>
639
- * <paragraph>b</paragraph>
640
- * </blockQuote>
641
- * <paragraph>c]d</paragraph>
642
- *
643
- * In this case the paragraph will also be returned, despite the collapsed selection:
644
- *
645
- * <paragraph>[]a</paragraph>
646
- *
647
- * In such a scenario, however, only blocks A, B & E will be returned as blocks C & D are nested in block B:
648
- *
649
- * [<blockA></blockA>
650
- * <blockB>
651
- * <blockC></blockC>
652
- * <blockD></blockD>
653
- * </blockB>
654
- * <blockE></blockE>]
655
- *
656
- * If the selection is inside a block all the inner blocks (A & B) are returned:
657
- *
658
- * <block>
659
- * <blockA>[a</blockA>
660
- * <blockB>b]</blockB>
661
- * </block>
662
- *
663
- * **Special case**: If a selection ends at the beginning of a block, that block is not returned as from user perspective
664
- * this block wasn't selected. See [#984](https://github.com/ckeditor/ckeditor5-engine/issues/984) for more details.
665
- *
666
- * <paragraph>[a</paragraph>
667
- * <paragraph>b</paragraph>
668
- * <paragraph>]c</paragraph> // this block will not be returned
669
- *
670
- * @returns {Iterable.<module:engine/model/element~Element>}
671
- */
672
- * getSelectedBlocks() {
673
- const visited = new WeakSet();
674
-
675
- for ( const range of this.getRanges() ) {
676
- // Get start block of range in case of a collapsed range.
677
- const startBlock = getParentBlock( range.start, visited );
678
-
679
- if ( startBlock && isTopBlockInRange( startBlock, range ) ) {
680
- yield startBlock;
681
- }
682
-
683
- for ( const value of range.getWalker() ) {
684
- const block = value.item;
685
-
686
- if ( value.type == 'elementEnd' && isUnvisitedTopBlock( block, visited, range ) ) {
687
- yield block;
688
- }
689
- }
690
-
691
- const endBlock = getParentBlock( range.end, visited );
692
-
693
- // #984. Don't return the end block if the range ends right at its beginning.
694
- if ( endBlock && !range.end.isTouching( Position._createAt( endBlock, 0 ) ) && isTopBlockInRange( endBlock, range ) ) {
695
- yield endBlock;
696
- }
697
- }
698
- }
699
-
700
- /**
701
- * Checks whether the selection contains the entire content of the given element. This means that selection must start
702
- * at a position {@link module:engine/model/position~Position#isTouching touching} the element's start and ends at position
703
- * touching the element's end.
704
- *
705
- * By default, this method will check whether the entire content of the selection's current root is selected.
706
- * Useful to check if e.g. the user has just pressed <kbd>Ctrl</kbd> + <kbd>A</kbd>.
707
- *
708
- * @param {module:engine/model/element~Element} [element=this.anchor.root]
709
- * @returns {Boolean}
710
- */
711
- containsEntireContent( element = this.anchor.root ) {
712
- const limitStartPosition = Position._createAt( element, 0 );
713
- const limitEndPosition = Position._createAt( element, 'end' );
714
-
715
- return limitStartPosition.isTouching( this.getFirstPosition() ) &&
716
- limitEndPosition.isTouching( this.getLastPosition() );
717
- }
718
-
719
- /**
720
- * Adds given range to internal {@link #_ranges ranges array}. Throws an error
721
- * if given range is intersecting with any range that is already stored in this selection.
722
- *
723
- * @protected
724
- * @param {module:engine/model/range~Range} range Range to add.
725
- */
726
- _pushRange( range ) {
727
- this._checkRange( range );
728
- this._ranges.push( new Range( range.start, range.end ) );
729
- }
730
-
731
- /**
732
- * Checks if given range intersects with ranges that are already in the selection. Throws an error if it does.
733
- *
734
- * @protected
735
- * @param {module:engine/model/range~Range} range Range to check.
736
- */
737
- _checkRange( range ) {
738
- for ( let i = 0; i < this._ranges.length; i++ ) {
739
- if ( range.isIntersecting( this._ranges[ i ] ) ) {
740
- /**
741
- * Trying to add a range that intersects with another range in the selection.
742
- *
743
- * @error model-selection-range-intersects
744
- * @param {module:engine/model/range~Range} addedRange Range that was added to the selection.
745
- * @param {module:engine/model/range~Range} intersectingRange Range in the selection that intersects with `addedRange`.
746
- */
747
- throw new CKEditorError(
748
- 'model-selection-range-intersects',
749
- [ this, range ],
750
- { addedRange: range, intersectingRange: this._ranges[ i ] }
751
- );
752
- }
753
- }
754
- }
755
-
756
- /**
757
- * Deletes ranges from internal range array. Uses {@link #_popRange _popRange} to
758
- * ensure proper ranges removal.
759
- *
760
- * @protected
761
- */
762
- _removeAllRanges() {
763
- while ( this._ranges.length > 0 ) {
764
- this._popRange();
765
- }
766
- }
767
-
768
- /**
769
- * Removes most recently added range from the selection.
770
- *
771
- * @protected
772
- */
773
- _popRange() {
774
- this._ranges.pop();
775
- }
776
-
777
- /**
778
- * Fired when selection range(s) changed.
779
- *
780
- * @event change:range
781
- * @param {Boolean} directChange In case of {@link module:engine/model/selection~Selection} class it is always set
782
- * to `true` which indicates that the selection change was caused by a direct use of selection's API.
783
- * The {@link module:engine/model/documentselection~DocumentSelection}, however, may change because its position
784
- * was directly changed through the {@link module:engine/model/writer~Writer writer} or because its position was
785
- * changed because the structure of the model has been changed (which means an indirect change).
786
- * The indirect change does not occur in case of normal (detached) selections because they are "static" (as "not live")
787
- * which mean that they are not updated once the document changes.
788
- */
789
-
790
- /**
791
- * Fired when selection attribute changed.
792
- *
793
- * @event change:attribute
794
- * @param {Boolean} directChange In case of {@link module:engine/model/selection~Selection} class it is always set
795
- * to `true` which indicates that the selection change was caused by a direct use of selection's API.
796
- * The {@link module:engine/model/documentselection~DocumentSelection}, however, may change because its attributes
797
- * were directly changed through the {@link module:engine/model/writer~Writer writer} or because its position was
798
- * changed in the model and its attributes were refreshed (which means an indirect change).
799
- * The indirect change does not occur in case of normal (detached) selections because they are "static" (as "not live")
800
- * which mean that they are not updated once the document changes.
801
- * @param {Array.<String>} attributeKeys Array containing keys of attributes that changed.
802
- */
25
+ export default class Selection extends EmitterMixin(TypeCheckable) {
26
+ /**
27
+ * Creates a new selection instance based on the given {@link module:engine/model/selection~Selectable selectable}
28
+ * or creates an empty selection if no arguments were passed.
29
+ *
30
+ * // Creates empty selection without ranges.
31
+ * const selection = writer.createSelection();
32
+ *
33
+ * // Creates selection at the given range.
34
+ * const range = writer.createRange( start, end );
35
+ * const selection = writer.createSelection( range );
36
+ *
37
+ * // Creates selection at the given ranges
38
+ * const ranges = [ writer.createRange( start1, end2 ), writer.createRange( star2, end2 ) ];
39
+ * const selection = writer.createSelection( ranges );
40
+ *
41
+ * // Creates selection from the other selection.
42
+ * // Note: It doesn't copies selection attributes.
43
+ * const otherSelection = writer.createSelection();
44
+ * const selection = writer.createSelection( otherSelection );
45
+ *
46
+ * // Creates selection from the given document selection.
47
+ * // Note: It doesn't copies selection attributes.
48
+ * const documentSelection = model.document.selection;
49
+ * const selection = writer.createSelection( documentSelection );
50
+ *
51
+ * // Creates selection at the given position.
52
+ * const position = writer.createPositionFromPath( root, path );
53
+ * const selection = writer.createSelection( position );
54
+ *
55
+ * // Creates selection at the given offset in the given element.
56
+ * const paragraph = writer.createElement( 'paragraph' );
57
+ * const selection = writer.createSelection( paragraph, offset );
58
+ *
59
+ * // Creates a range inside an {@link module:engine/model/element~Element element} which starts before the
60
+ * // first child of that element and ends after the last child of that element.
61
+ * const selection = writer.createSelection( paragraph, 'in' );
62
+ *
63
+ * // Creates a range on an {@link module:engine/model/item~Item item} which starts before the item and ends
64
+ * // just after the item.
65
+ * const selection = writer.createSelection( paragraph, 'on' );
66
+ *
67
+ * Selection's constructor allow passing additional options (`'backward'`) as the last argument.
68
+ *
69
+ * // Creates backward selection.
70
+ * const selection = writer.createSelection( range, { backward: true } );
71
+ *
72
+ * @param {module:engine/model/selection~Selectable} [selectable]
73
+ * @param {Number|'before'|'end'|'after'|'on'|'in'} [placeOrOffset] Sets place or offset of the selection.
74
+ * @param {Object} [options]
75
+ * @param {Boolean} [options.backward] Sets this selection instance to be backward.
76
+ */
77
+ constructor(...args) {
78
+ super();
79
+ /**
80
+ * Specifies whether the last added range was added as a backward or forward range.
81
+ *
82
+ * @private
83
+ * @type {Boolean}
84
+ */
85
+ this._lastRangeBackward = false;
86
+ /**
87
+ * Stores selection ranges.
88
+ *
89
+ * @protected
90
+ * @type {Array.<module:engine/model/range~Range>}
91
+ */
92
+ this._ranges = [];
93
+ /**
94
+ * List of attributes set on current selection.
95
+ *
96
+ * @protected
97
+ * @type {Map.<String,*>}
98
+ */
99
+ this._attrs = new Map();
100
+ if (args.length) {
101
+ this.setTo(...args);
102
+ }
103
+ }
104
+ /**
105
+ * Selection anchor. Anchor is the position from which the selection was started. If a user is making a selection
106
+ * by dragging the mouse, the anchor is where the user pressed the mouse button (the beginning of the selection).
107
+ *
108
+ * Anchor and {@link #focus} define the direction of the selection, which is important
109
+ * when expanding/shrinking selection. The focus moves, while the anchor should remain in the same place.
110
+ *
111
+ * Anchor is always set to the {@link module:engine/model/range~Range#start start} or
112
+ * {@link module:engine/model/range~Range#end end} position of the last of selection's ranges. Whether it is
113
+ * the `start` or `end` depends on the specified `options.backward`. See the {@link #setTo `setTo()`} method.
114
+ *
115
+ * May be set to `null` if there are no ranges in the selection.
116
+ *
117
+ * @see #focus
118
+ * @readonly
119
+ * @type {module:engine/model/position~Position|null}
120
+ */
121
+ get anchor() {
122
+ if (this._ranges.length > 0) {
123
+ const range = this._ranges[this._ranges.length - 1];
124
+ return this._lastRangeBackward ? range.end : range.start;
125
+ }
126
+ return null;
127
+ }
128
+ /**
129
+ * Selection focus. Focus is the position where the selection ends. If a user is making a selection
130
+ * by dragging the mouse, the focus is where the mouse cursor is.
131
+ *
132
+ * May be set to `null` if there are no ranges in the selection.
133
+ *
134
+ * @see #anchor
135
+ * @readonly
136
+ * @type {module:engine/model/position~Position|null}
137
+ */
138
+ get focus() {
139
+ if (this._ranges.length > 0) {
140
+ const range = this._ranges[this._ranges.length - 1];
141
+ return this._lastRangeBackward ? range.start : range.end;
142
+ }
143
+ return null;
144
+ }
145
+ /**
146
+ * Whether the selection is collapsed. Selection is collapsed when there is exactly one range in it
147
+ * and it is collapsed.
148
+ *
149
+ * @readonly
150
+ * @type {Boolean}
151
+ */
152
+ get isCollapsed() {
153
+ const length = this._ranges.length;
154
+ if (length === 1) {
155
+ return this._ranges[0].isCollapsed;
156
+ }
157
+ else {
158
+ return false;
159
+ }
160
+ }
161
+ /**
162
+ * Returns the number of ranges in the selection.
163
+ *
164
+ * @readonly
165
+ * @type {Number}
166
+ */
167
+ get rangeCount() {
168
+ return this._ranges.length;
169
+ }
170
+ /**
171
+ * Specifies whether the selection's {@link #focus} precedes the selection's {@link #anchor}.
172
+ *
173
+ * @readonly
174
+ * @type {Boolean}
175
+ */
176
+ get isBackward() {
177
+ return !this.isCollapsed && this._lastRangeBackward;
178
+ }
179
+ /**
180
+ * Checks whether this selection is equal to the given selection. Selections are equal if they have the same directions,
181
+ * the same number of ranges and all ranges from one selection equal to ranges from the another selection.
182
+ *
183
+ * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection} otherSelection
184
+ * Selection to compare with.
185
+ * @returns {Boolean} `true` if selections are equal, `false` otherwise.
186
+ */
187
+ isEqual(otherSelection) {
188
+ if (this.rangeCount != otherSelection.rangeCount) {
189
+ return false;
190
+ }
191
+ else if (this.rangeCount === 0) {
192
+ return true;
193
+ }
194
+ if (!this.anchor.isEqual(otherSelection.anchor) || !this.focus.isEqual(otherSelection.focus)) {
195
+ return false;
196
+ }
197
+ for (const thisRange of this._ranges) {
198
+ let found = false;
199
+ for (const otherRange of otherSelection._ranges) {
200
+ if (thisRange.isEqual(otherRange)) {
201
+ found = true;
202
+ break;
203
+ }
204
+ }
205
+ if (!found) {
206
+ return false;
207
+ }
208
+ }
209
+ return true;
210
+ }
211
+ /**
212
+ * Returns an iterable object that iterates over copies of selection ranges.
213
+ *
214
+ * @returns {Iterable.<module:engine/model/range~Range>}
215
+ */
216
+ *getRanges() {
217
+ for (const range of this._ranges) {
218
+ yield new Range(range.start, range.end);
219
+ }
220
+ }
221
+ /**
222
+ * Returns a copy of the first range in the selection.
223
+ * First range is the one which {@link module:engine/model/range~Range#start start} position
224
+ * {@link module:engine/model/position~Position#isBefore is before} start position of all other ranges
225
+ * (not to confuse with the first range added to the selection).
226
+ *
227
+ * Returns `null` if there are no ranges in selection.
228
+ *
229
+ * @returns {module:engine/model/range~Range|null}
230
+ */
231
+ getFirstRange() {
232
+ let first = null;
233
+ for (const range of this._ranges) {
234
+ if (!first || range.start.isBefore(first.start)) {
235
+ first = range;
236
+ }
237
+ }
238
+ return first ? new Range(first.start, first.end) : null;
239
+ }
240
+ /**
241
+ * Returns a copy of the last range in the selection.
242
+ * Last range is the one which {@link module:engine/model/range~Range#end end} position
243
+ * {@link module:engine/model/position~Position#isAfter is after} end position of all other ranges (not to confuse with the range most
244
+ * recently added to the selection).
245
+ *
246
+ * Returns `null` if there are no ranges in selection.
247
+ *
248
+ * @returns {module:engine/model/range~Range|null}
249
+ */
250
+ getLastRange() {
251
+ let last = null;
252
+ for (const range of this._ranges) {
253
+ if (!last || range.end.isAfter(last.end)) {
254
+ last = range;
255
+ }
256
+ }
257
+ return last ? new Range(last.start, last.end) : null;
258
+ }
259
+ /**
260
+ * Returns the first position in the selection.
261
+ * First position is the position that {@link module:engine/model/position~Position#isBefore is before}
262
+ * any other position in the selection.
263
+ *
264
+ * Returns `null` if there are no ranges in selection.
265
+ *
266
+ * @returns {module:engine/model/position~Position|null}
267
+ */
268
+ getFirstPosition() {
269
+ const first = this.getFirstRange();
270
+ return first ? first.start.clone() : null;
271
+ }
272
+ /**
273
+ * Returns the last position in the selection.
274
+ * Last position is the position that {@link module:engine/model/position~Position#isAfter is after}
275
+ * any other position in the selection.
276
+ *
277
+ * Returns `null` if there are no ranges in selection.
278
+ *
279
+ * @returns {module:engine/model/position~Position|null}
280
+ */
281
+ getLastPosition() {
282
+ const lastRange = this.getLastRange();
283
+ return lastRange ? lastRange.end.clone() : null;
284
+ }
285
+ /**
286
+ * Sets this selection's ranges and direction to the specified location based on the given
287
+ * {@link module:engine/model/selection~Selectable selectable}.
288
+ *
289
+ * // Removes all selection's ranges.
290
+ * selection.setTo( null );
291
+ *
292
+ * // Sets selection to the given range.
293
+ * const range = writer.createRange( start, end );
294
+ * selection.setTo( range );
295
+ *
296
+ * // Sets selection to given ranges.
297
+ * const ranges = [ writer.createRange( start1, end2 ), writer.createRange( star2, end2 ) ];
298
+ * selection.setTo( ranges );
299
+ *
300
+ * // Sets selection to other selection.
301
+ * // Note: It doesn't copies selection attributes.
302
+ * const otherSelection = writer.createSelection();
303
+ * selection.setTo( otherSelection );
304
+ *
305
+ * // Sets selection to the given document selection.
306
+ * // Note: It doesn't copies selection attributes.
307
+ * const documentSelection = new DocumentSelection( doc );
308
+ * selection.setTo( documentSelection );
309
+ *
310
+ * // Sets collapsed selection at the given position.
311
+ * const position = writer.createPositionFromPath( root, path );
312
+ * selection.setTo( position );
313
+ *
314
+ * // Sets collapsed selection at the position of the given node and an offset.
315
+ * selection.setTo( paragraph, offset );
316
+ *
317
+ * Creates a range inside an {@link module:engine/model/element~Element element} which starts before the first child of
318
+ * that element and ends after the last child of that element.
319
+ *
320
+ * selection.setTo( paragraph, 'in' );
321
+ *
322
+ * Creates a range on an {@link module:engine/model/item~Item item} which starts before the item and ends just after the item.
323
+ *
324
+ * selection.setTo( paragraph, 'on' );
325
+ *
326
+ * `Selection#setTo()`' method allow passing additional options (`backward`) as the last argument.
327
+ *
328
+ * // Sets backward selection.
329
+ * const selection = writer.createSelection( range, { backward: true } );
330
+ *
331
+ * @param {module:engine/model/selection~Selectable} selectable
332
+ * @param {Number|'before'|'end'|'after'|'on'|'in'} [placeOrOffset] Sets place or offset of the selection.
333
+ * @param {Object} [options]
334
+ * @param {Boolean} [options.backward] Sets this selection instance to be backward.
335
+ */
336
+ setTo(...args) {
337
+ let [selectable, placeOrOffset, options] = args;
338
+ if (typeof placeOrOffset == 'object') {
339
+ options = placeOrOffset;
340
+ placeOrOffset = undefined;
341
+ }
342
+ if (selectable === null) {
343
+ this._setRanges([]);
344
+ }
345
+ else if (selectable instanceof Selection) {
346
+ this._setRanges(selectable.getRanges(), selectable.isBackward);
347
+ }
348
+ else if (selectable && typeof selectable.getRanges == 'function') {
349
+ // We assume that the selectable is a DocumentSelection.
350
+ // It can't be imported here, because it would lead to circular imports.
351
+ this._setRanges(selectable.getRanges(), selectable.isBackward);
352
+ }
353
+ else if (selectable instanceof Range) {
354
+ this._setRanges([selectable], !!options && !!options.backward);
355
+ }
356
+ else if (selectable instanceof Position) {
357
+ this._setRanges([new Range(selectable)]);
358
+ }
359
+ else if (selectable instanceof Node) {
360
+ const backward = !!options && !!options.backward;
361
+ let range;
362
+ if (placeOrOffset == 'in') {
363
+ range = Range._createIn(selectable);
364
+ }
365
+ else if (placeOrOffset == 'on') {
366
+ range = Range._createOn(selectable);
367
+ }
368
+ else if (placeOrOffset !== undefined) {
369
+ range = new Range(Position._createAt(selectable, placeOrOffset));
370
+ }
371
+ else {
372
+ /**
373
+ * selection.setTo requires the second parameter when the first parameter is a node.
374
+ *
375
+ * @error model-selection-setto-required-second-parameter
376
+ */
377
+ throw new CKEditorError('model-selection-setto-required-second-parameter', [this, selectable]);
378
+ }
379
+ this._setRanges([range], backward);
380
+ }
381
+ else if (isIterable(selectable)) {
382
+ // We assume that the selectable is an iterable of ranges.
383
+ this._setRanges(selectable, options && !!options.backward);
384
+ }
385
+ else {
386
+ /**
387
+ * Cannot set the selection to the given place.
388
+ *
389
+ * Invalid parameters were specified when setting the selection. Common issues:
390
+ *
391
+ * * A {@link module:engine/model/textproxy~TextProxy} instance was passed instead of
392
+ * a real {@link module:engine/model/text~Text}.
393
+ * * View nodes were passed instead of model nodes.
394
+ * * `null`/`undefined` was passed.
395
+ *
396
+ * @error model-selection-setto-not-selectable
397
+ */
398
+ throw new CKEditorError('model-selection-setto-not-selectable', [this, selectable]);
399
+ }
400
+ }
401
+ /**
402
+ * Replaces all ranges that were added to the selection with given array of ranges. Last range of the array
403
+ * is treated like the last added range and is used to set {@link module:engine/model/selection~Selection#anchor} and
404
+ * {@link module:engine/model/selection~Selection#focus}. Accepts a flag describing in which direction the selection is made.
405
+ *
406
+ * @protected
407
+ * @fires change:range
408
+ * @param {Iterable.<module:engine/model/range~Range>} newRanges Ranges to set.
409
+ * @param {Boolean} [isLastBackward=false] Flag describing if last added range was selected forward - from start to end (`false`)
410
+ * or backward - from end to start (`true`).
411
+ */
412
+ _setRanges(newRanges, isLastBackward = false) {
413
+ const ranges = Array.from(newRanges);
414
+ // Check whether there is any range in new ranges set that is different than all already added ranges.
415
+ const anyNewRange = ranges.some(newRange => {
416
+ if (!(newRange instanceof Range)) {
417
+ /**
418
+ * Selection range set to an object that is not an instance of {@link module:engine/model/range~Range}.
419
+ *
420
+ * Only {@link module:engine/model/range~Range} instances can be used to set a selection.
421
+ * Common mistakes leading to this error are:
422
+ *
423
+ * * using DOM `Range` object,
424
+ * * incorrect CKEditor 5 installation with multiple `ckeditor5-engine` packages having different versions.
425
+ *
426
+ * @error model-selection-set-ranges-not-range
427
+ */
428
+ throw new CKEditorError('model-selection-set-ranges-not-range', [this, newRanges]);
429
+ }
430
+ return this._ranges.every(oldRange => {
431
+ return !oldRange.isEqual(newRange);
432
+ });
433
+ });
434
+ // Don't do anything if nothing changed.
435
+ if (ranges.length === this._ranges.length && !anyNewRange) {
436
+ return;
437
+ }
438
+ this._replaceAllRanges(ranges);
439
+ this._lastRangeBackward = !!isLastBackward;
440
+ this.fire('change:range', { directChange: true });
441
+ }
442
+ /**
443
+ * Moves {@link module:engine/model/selection~Selection#focus} to the specified location.
444
+ *
445
+ * The location can be specified in the same form as
446
+ * {@link module:engine/model/writer~Writer#createPositionAt writer.createPositionAt()} parameters.
447
+ *
448
+ * @fires change:range
449
+ * @param {module:engine/model/item~Item|module:engine/model/position~Position} itemOrPosition
450
+ * @param {Number|'end'|'before'|'after'} [offset] Offset or one of the flags. Used only when
451
+ * first parameter is a {@link module:engine/model/item~Item model item}.
452
+ */
453
+ setFocus(itemOrPosition, offset) {
454
+ if (this.anchor === null) {
455
+ /**
456
+ * Cannot set selection focus if there are no ranges in selection.
457
+ *
458
+ * @error model-selection-setfocus-no-ranges
459
+ */
460
+ throw new CKEditorError('model-selection-setfocus-no-ranges', [this, itemOrPosition]);
461
+ }
462
+ const newFocus = Position._createAt(itemOrPosition, offset);
463
+ if (newFocus.compareWith(this.focus) == 'same') {
464
+ return;
465
+ }
466
+ const anchor = this.anchor;
467
+ if (this._ranges.length) {
468
+ this._popRange();
469
+ }
470
+ if (newFocus.compareWith(anchor) == 'before') {
471
+ this._pushRange(new Range(newFocus, anchor));
472
+ this._lastRangeBackward = true;
473
+ }
474
+ else {
475
+ this._pushRange(new Range(anchor, newFocus));
476
+ this._lastRangeBackward = false;
477
+ }
478
+ this.fire('change:range', { directChange: true });
479
+ }
480
+ /**
481
+ * Gets an attribute value for given key or `undefined` if that attribute is not set on the selection.
482
+ *
483
+ * @param {String} key Key of attribute to look for.
484
+ * @returns {*} Attribute value or `undefined`.
485
+ */
486
+ getAttribute(key) {
487
+ return this._attrs.get(key);
488
+ }
489
+ /**
490
+ * Returns iterable that iterates over this selection's attributes.
491
+ *
492
+ * Attributes are returned as arrays containing two items. First one is attribute key and second is attribute value.
493
+ * This format is accepted by native `Map` object and also can be passed in `Node` constructor.
494
+ *
495
+ * @returns {Iterable.<*>}
496
+ */
497
+ getAttributes() {
498
+ return this._attrs.entries();
499
+ }
500
+ /**
501
+ * Returns iterable that iterates over this selection's attribute keys.
502
+ *
503
+ * @returns {Iterable.<String>}
504
+ */
505
+ getAttributeKeys() {
506
+ return this._attrs.keys();
507
+ }
508
+ /**
509
+ * Checks if the selection has an attribute for given key.
510
+ *
511
+ * @param {String} key Key of attribute to check.
512
+ * @returns {Boolean} `true` if attribute with given key is set on selection, `false` otherwise.
513
+ */
514
+ hasAttribute(key) {
515
+ return this._attrs.has(key);
516
+ }
517
+ /**
518
+ * Removes an attribute with given key from the selection.
519
+ *
520
+ * If given attribute was set on the selection, fires the {@link #event:change:range} event with
521
+ * removed attribute key.
522
+ *
523
+ * @fires change:attribute
524
+ * @param {String} key Key of attribute to remove.
525
+ */
526
+ removeAttribute(key) {
527
+ if (this.hasAttribute(key)) {
528
+ this._attrs.delete(key);
529
+ this.fire('change:attribute', { attributeKeys: [key], directChange: true });
530
+ }
531
+ }
532
+ /**
533
+ * Sets attribute on the selection. If attribute with the same key already is set, it's value is overwritten.
534
+ *
535
+ * If the attribute value has changed, fires the {@link #event:change:range} event with
536
+ * the attribute key.
537
+ *
538
+ * @fires change:attribute
539
+ * @param {String} key Key of attribute to set.
540
+ * @param {*} value Attribute value.
541
+ */
542
+ setAttribute(key, value) {
543
+ if (this.getAttribute(key) !== value) {
544
+ this._attrs.set(key, value);
545
+ this.fire('change:attribute', { attributeKeys: [key], directChange: true });
546
+ }
547
+ }
548
+ /**
549
+ * Returns the selected element. {@link module:engine/model/element~Element Element} is considered as selected if there is only
550
+ * one range in the selection, and that range contains exactly one element.
551
+ * Returns `null` if there is no selected element.
552
+ *
553
+ * @returns {module:engine/model/element~Element|null}
554
+ */
555
+ getSelectedElement() {
556
+ if (this.rangeCount !== 1) {
557
+ return null;
558
+ }
559
+ return this.getFirstRange().getContainedElement();
560
+ }
561
+ /**
562
+ * Gets elements of type {@link module:engine/model/schema~Schema#isBlock "block"} touched by the selection.
563
+ *
564
+ * This method's result can be used for example to apply block styling to all blocks covered by this selection.
565
+ *
566
+ * **Note:** `getSelectedBlocks()` returns blocks that are nested in other non-block elements
567
+ * but will not return blocks nested in other blocks.
568
+ *
569
+ * In this case the function will return exactly all 3 paragraphs (note: `<blockQuote>` is not a block itself):
570
+ *
571
+ * <paragraph>[a</paragraph>
572
+ * <blockQuote>
573
+ * <paragraph>b</paragraph>
574
+ * </blockQuote>
575
+ * <paragraph>c]d</paragraph>
576
+ *
577
+ * In this case the paragraph will also be returned, despite the collapsed selection:
578
+ *
579
+ * <paragraph>[]a</paragraph>
580
+ *
581
+ * In such a scenario, however, only blocks A, B & E will be returned as blocks C & D are nested in block B:
582
+ *
583
+ * [<blockA></blockA>
584
+ * <blockB>
585
+ * <blockC></blockC>
586
+ * <blockD></blockD>
587
+ * </blockB>
588
+ * <blockE></blockE>]
589
+ *
590
+ * If the selection is inside a block all the inner blocks (A & B) are returned:
591
+ *
592
+ * <block>
593
+ * <blockA>[a</blockA>
594
+ * <blockB>b]</blockB>
595
+ * </block>
596
+ *
597
+ * **Special case**: If a selection ends at the beginning of a block, that block is not returned as from user perspective
598
+ * this block wasn't selected. See [#984](https://github.com/ckeditor/ckeditor5-engine/issues/984) for more details.
599
+ *
600
+ * <paragraph>[a</paragraph>
601
+ * <paragraph>b</paragraph>
602
+ * <paragraph>]c</paragraph> // this block will not be returned
603
+ *
604
+ * @returns {Iterable.<module:engine/model/element~Element>}
605
+ */
606
+ *getSelectedBlocks() {
607
+ const visited = new WeakSet();
608
+ for (const range of this.getRanges()) {
609
+ // Get start block of range in case of a collapsed range.
610
+ const startBlock = getParentBlock(range.start, visited);
611
+ if (startBlock && isTopBlockInRange(startBlock, range)) {
612
+ yield startBlock;
613
+ }
614
+ for (const value of range.getWalker()) {
615
+ const block = value.item;
616
+ if (value.type == 'elementEnd' && isUnvisitedTopBlock(block, visited, range)) {
617
+ yield block;
618
+ }
619
+ }
620
+ const endBlock = getParentBlock(range.end, visited);
621
+ // #984. Don't return the end block if the range ends right at its beginning.
622
+ if (endBlock && !range.end.isTouching(Position._createAt(endBlock, 0)) && isTopBlockInRange(endBlock, range)) {
623
+ yield endBlock;
624
+ }
625
+ }
626
+ }
627
+ /**
628
+ * Checks whether the selection contains the entire content of the given element. This means that selection must start
629
+ * at a position {@link module:engine/model/position~Position#isTouching touching} the element's start and ends at position
630
+ * touching the element's end.
631
+ *
632
+ * By default, this method will check whether the entire content of the selection's current root is selected.
633
+ * Useful to check if e.g. the user has just pressed <kbd>Ctrl</kbd> + <kbd>A</kbd>.
634
+ *
635
+ * @param {module:engine/model/element~Element} [element=this.anchor.root]
636
+ * @returns {Boolean}
637
+ */
638
+ containsEntireContent(element = this.anchor.root) {
639
+ const limitStartPosition = Position._createAt(element, 0);
640
+ const limitEndPosition = Position._createAt(element, 'end');
641
+ return limitStartPosition.isTouching(this.getFirstPosition()) &&
642
+ limitEndPosition.isTouching(this.getLastPosition());
643
+ }
644
+ /**
645
+ * Adds given range to internal {@link #_ranges ranges array}. Throws an error
646
+ * if given range is intersecting with any range that is already stored in this selection.
647
+ *
648
+ * @protected
649
+ * @param {module:engine/model/range~Range} range Range to add.
650
+ */
651
+ _pushRange(range) {
652
+ this._checkRange(range);
653
+ this._ranges.push(new Range(range.start, range.end));
654
+ }
655
+ /**
656
+ * Checks if given range intersects with ranges that are already in the selection. Throws an error if it does.
657
+ *
658
+ * @protected
659
+ * @param {module:engine/model/range~Range} range Range to check.
660
+ */
661
+ _checkRange(range) {
662
+ for (let i = 0; i < this._ranges.length; i++) {
663
+ if (range.isIntersecting(this._ranges[i])) {
664
+ /**
665
+ * Trying to add a range that intersects with another range in the selection.
666
+ *
667
+ * @error model-selection-range-intersects
668
+ * @param {module:engine/model/range~Range} addedRange Range that was added to the selection.
669
+ * @param {module:engine/model/range~Range} intersectingRange Range in the selection that intersects with `addedRange`.
670
+ */
671
+ throw new CKEditorError('model-selection-range-intersects', [this, range], { addedRange: range, intersectingRange: this._ranges[i] });
672
+ }
673
+ }
674
+ }
675
+ /**
676
+ * Replaces all the ranges by the given ones.
677
+ * Uses {@link #_popRange _popRange} and {@link #_pushRange _pushRange} to ensure proper ranges removal and addition.
678
+ *
679
+ * @param {Array.<module:engine/model/range~Range>} ranges
680
+ * @protected
681
+ */
682
+ _replaceAllRanges(ranges) {
683
+ this._removeAllRanges();
684
+ for (const range of ranges) {
685
+ this._pushRange(range);
686
+ }
687
+ }
688
+ /**
689
+ * Deletes ranges from internal range array. Uses {@link #_popRange _popRange} to
690
+ * ensure proper ranges removal.
691
+ *
692
+ * @protected
693
+ */
694
+ _removeAllRanges() {
695
+ while (this._ranges.length > 0) {
696
+ this._popRange();
697
+ }
698
+ }
699
+ /**
700
+ * Removes most recently added range from the selection.
701
+ *
702
+ * @protected
703
+ */
704
+ _popRange() {
705
+ this._ranges.pop();
706
+ }
803
707
  }
804
-
805
- mix( Selection, EmitterMixin );
806
-
708
+ /**
709
+ * Checks whether this object is of the given.
710
+ *
711
+ * selection.is( 'selection' ); // -> true
712
+ * selection.is( 'model:selection' ); // -> true
713
+ *
714
+ * selection.is( 'view:selection' ); // -> false
715
+ * selection.is( 'range' ); // -> false
716
+ *
717
+ * {@link module:engine/model/node~Node#is Check the entire list of model objects} which implement the `is()` method.
718
+ *
719
+ * @param {String} type
720
+ * @returns {Boolean}
721
+ */
722
+ Selection.prototype.is = function (type) {
723
+ return type === 'selection' || type === 'model:selection';
724
+ };
807
725
  // Checks whether the given element extends $block in the schema and has a parent (is not a root).
808
726
  // Marks it as already visited.
809
- function isUnvisitedBlock( element, visited ) {
810
- if ( visited.has( element ) ) {
811
- return false;
812
- }
813
-
814
- visited.add( element );
815
-
816
- return element.root.document.model.schema.isBlock( element ) && element.parent;
727
+ function isUnvisitedBlock(element, visited) {
728
+ if (visited.has(element)) {
729
+ return false;
730
+ }
731
+ visited.add(element);
732
+ return element.root.document.model.schema.isBlock(element) && element.parent;
817
733
  }
818
-
819
734
  // Checks if the given element is a $block was not previously visited and is a top block in a range.
820
- function isUnvisitedTopBlock( element, visited, range ) {
821
- return isUnvisitedBlock( element, visited ) && isTopBlockInRange( element, range );
735
+ function isUnvisitedTopBlock(element, visited, range) {
736
+ return isUnvisitedBlock(element, visited) && isTopBlockInRange(element, range);
822
737
  }
823
-
824
738
  // Finds the lowest element in position's ancestors which is a block.
825
739
  // It will search until first ancestor that is a limit element.
826
740
  // Marks all ancestors as already visited to not include any of them later on.
827
- function getParentBlock( position, visited ) {
828
- const element = position.parent;
829
- const schema = element.root.document.model.schema;
830
-
831
- const ancestors = position.parent.getAncestors( { parentFirst: true, includeSelf: true } );
832
-
833
- let hasParentLimit = false;
834
-
835
- const block = ancestors.find( element => {
836
- // Stop searching after first parent node that is limit element.
837
- if ( hasParentLimit ) {
838
- return false;
839
- }
840
-
841
- hasParentLimit = schema.isLimit( element );
842
-
843
- return !hasParentLimit && isUnvisitedBlock( element, visited );
844
- } );
845
-
846
- // Mark all ancestors of this position's parent, because find() might've stopped early and
847
- // the found block may be a child of another block.
848
- ancestors.forEach( element => visited.add( element ) );
849
-
850
- return block;
741
+ function getParentBlock(position, visited) {
742
+ const element = position.parent;
743
+ const schema = element.root.document.model.schema;
744
+ const ancestors = position.parent.getAncestors({ parentFirst: true, includeSelf: true });
745
+ let hasParentLimit = false;
746
+ const block = ancestors.find(element => {
747
+ // Stop searching after first parent node that is limit element.
748
+ if (hasParentLimit) {
749
+ return false;
750
+ }
751
+ hasParentLimit = schema.isLimit(element);
752
+ return !hasParentLimit && isUnvisitedBlock(element, visited);
753
+ });
754
+ // Mark all ancestors of this position's parent, because find() might've stopped early and
755
+ // the found block may be a child of another block.
756
+ ancestors.forEach(element => visited.add(element));
757
+ return block;
851
758
  }
852
-
853
759
  // Checks if the blocks is not nested in other block inside a range.
854
760
  //
855
761
  // @param {module:engine/model/element~Element} block Block to check.
856
762
  // @param {module:engine/model/range~Range} range Range to check.
857
- function isTopBlockInRange( block, range ) {
858
- const parentBlock = findAncestorBlock( block );
859
-
860
- if ( !parentBlock ) {
861
- return true;
862
- }
863
-
864
- // Add loose flag to check as parentRange can be equal to range.
865
- const isParentInRange = range.containsRange( Range._createOn( parentBlock ), true );
866
-
867
- return !isParentInRange;
763
+ function isTopBlockInRange(block, range) {
764
+ const parentBlock = findAncestorBlock(block);
765
+ if (!parentBlock) {
766
+ return true;
767
+ }
768
+ // Add loose flag to check as parentRange can be equal to range.
769
+ const isParentInRange = range.containsRange(Range._createOn(parentBlock), true);
770
+ return !isParentInRange;
868
771
  }
869
-
870
772
  // Returns first ancestor block of a node.
871
773
  //
872
774
  // @param {module:engine/model/node~Node} node
873
775
  // @returns {module:engine/model/node~Node|undefined}
874
- function findAncestorBlock( node ) {
875
- const schema = node.root.document.model.schema;
876
-
877
- let parent = node.parent;
878
-
879
- while ( parent ) {
880
- if ( schema.isBlock( parent ) ) {
881
- return parent;
882
- }
883
-
884
- parent = parent.parent;
885
- }
776
+ function findAncestorBlock(node) {
777
+ const schema = node.root.document.model.schema;
778
+ let parent = node.parent;
779
+ while (parent) {
780
+ if (schema.isBlock(parent)) {
781
+ return parent;
782
+ }
783
+ parent = parent.parent;
784
+ }
886
785
  }
887
-
888
- /**
889
- * An entity that is used to set selection.
890
- *
891
- * See also {@link module:engine/model/selection~Selection#setTo}
892
- *
893
- * @typedef {
894
- * module:engine/model/selection~Selection|
895
- * module:engine/model/documentselection~DocumentSelection|
896
- * module:engine/model/position~Position|
897
- * module:engine/model/range~Range|
898
- * module:engine/model/node~Node|
899
- * Iterable.<module:engine/model/range~Range>|
900
- * null
901
- * } module:engine/model/selection~Selectable
902
- */