@ckeditor/ckeditor5-engine 35.0.1 → 35.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/CHANGELOG.md +4 -4
  2. package/package.json +30 -24
  3. package/src/controller/datacontroller.js +467 -561
  4. package/src/controller/editingcontroller.js +168 -204
  5. package/src/conversion/conversion.js +541 -565
  6. package/src/conversion/conversionhelpers.js +24 -28
  7. package/src/conversion/downcastdispatcher.js +457 -686
  8. package/src/conversion/downcasthelpers.js +1583 -1965
  9. package/src/conversion/mapper.js +518 -707
  10. package/src/conversion/modelconsumable.js +240 -283
  11. package/src/conversion/upcastdispatcher.js +372 -718
  12. package/src/conversion/upcasthelpers.js +707 -818
  13. package/src/conversion/viewconsumable.js +524 -581
  14. package/src/dataprocessor/basichtmlwriter.js +12 -16
  15. package/src/dataprocessor/dataprocessor.js +5 -0
  16. package/src/dataprocessor/htmldataprocessor.js +100 -116
  17. package/src/dataprocessor/htmlwriter.js +1 -18
  18. package/src/dataprocessor/xmldataprocessor.js +116 -137
  19. package/src/dev-utils/model.js +260 -352
  20. package/src/dev-utils/operationreplayer.js +106 -126
  21. package/src/dev-utils/utils.js +34 -51
  22. package/src/dev-utils/view.js +632 -753
  23. package/src/index.js +0 -11
  24. package/src/model/batch.js +111 -127
  25. package/src/model/differ.js +988 -1233
  26. package/src/model/document.js +340 -449
  27. package/src/model/documentfragment.js +327 -364
  28. package/src/model/documentselection.js +996 -1189
  29. package/src/model/element.js +306 -410
  30. package/src/model/history.js +224 -262
  31. package/src/model/item.js +5 -0
  32. package/src/model/liveposition.js +84 -145
  33. package/src/model/liverange.js +108 -185
  34. package/src/model/markercollection.js +379 -480
  35. package/src/model/model.js +883 -1034
  36. package/src/model/node.js +419 -463
  37. package/src/model/nodelist.js +175 -201
  38. package/src/model/operation/attributeoperation.js +153 -182
  39. package/src/model/operation/detachoperation.js +64 -83
  40. package/src/model/operation/insertoperation.js +135 -166
  41. package/src/model/operation/markeroperation.js +114 -140
  42. package/src/model/operation/mergeoperation.js +163 -191
  43. package/src/model/operation/moveoperation.js +157 -187
  44. package/src/model/operation/nooperation.js +28 -38
  45. package/src/model/operation/operation.js +106 -125
  46. package/src/model/operation/operationfactory.js +30 -34
  47. package/src/model/operation/renameoperation.js +109 -135
  48. package/src/model/operation/rootattributeoperation.js +155 -188
  49. package/src/model/operation/splitoperation.js +196 -232
  50. package/src/model/operation/transform.js +1833 -2204
  51. package/src/model/operation/utils.js +140 -204
  52. package/src/model/position.js +899 -1053
  53. package/src/model/range.js +910 -1028
  54. package/src/model/rootelement.js +77 -97
  55. package/src/model/schema.js +1189 -1835
  56. package/src/model/selection.js +745 -862
  57. package/src/model/text.js +90 -114
  58. package/src/model/textproxy.js +204 -240
  59. package/src/model/treewalker.js +316 -397
  60. package/src/model/typecheckable.js +16 -0
  61. package/src/model/utils/autoparagraphing.js +32 -44
  62. package/src/model/utils/deletecontent.js +334 -418
  63. package/src/model/utils/findoptimalinsertionrange.js +25 -36
  64. package/src/model/utils/getselectedcontent.js +96 -118
  65. package/src/model/utils/insertcontent.js +654 -773
  66. package/src/model/utils/insertobject.js +96 -119
  67. package/src/model/utils/modifyselection.js +120 -158
  68. package/src/model/utils/selection-post-fixer.js +153 -201
  69. package/src/model/writer.js +1305 -1474
  70. package/src/view/attributeelement.js +189 -225
  71. package/src/view/containerelement.js +75 -85
  72. package/src/view/document.js +172 -215
  73. package/src/view/documentfragment.js +200 -249
  74. package/src/view/documentselection.js +338 -367
  75. package/src/view/domconverter.js +1370 -1617
  76. package/src/view/downcastwriter.js +1747 -2076
  77. package/src/view/editableelement.js +81 -97
  78. package/src/view/element.js +739 -890
  79. package/src/view/elementdefinition.js +5 -0
  80. package/src/view/emptyelement.js +82 -92
  81. package/src/view/filler.js +35 -50
  82. package/src/view/item.js +5 -0
  83. package/src/view/matcher.js +260 -559
  84. package/src/view/node.js +274 -360
  85. package/src/view/observer/arrowkeysobserver.js +19 -28
  86. package/src/view/observer/bubblingemittermixin.js +120 -263
  87. package/src/view/observer/bubblingeventinfo.js +47 -55
  88. package/src/view/observer/clickobserver.js +7 -13
  89. package/src/view/observer/compositionobserver.js +14 -24
  90. package/src/view/observer/domeventdata.js +57 -67
  91. package/src/view/observer/domeventobserver.js +40 -64
  92. package/src/view/observer/fakeselectionobserver.js +81 -96
  93. package/src/view/observer/focusobserver.js +45 -61
  94. package/src/view/observer/inputobserver.js +7 -13
  95. package/src/view/observer/keyobserver.js +17 -27
  96. package/src/view/observer/mouseobserver.js +7 -14
  97. package/src/view/observer/mutationobserver.js +220 -315
  98. package/src/view/observer/observer.js +81 -102
  99. package/src/view/observer/selectionobserver.js +191 -246
  100. package/src/view/observer/tabobserver.js +23 -36
  101. package/src/view/placeholder.js +128 -173
  102. package/src/view/position.js +350 -401
  103. package/src/view/range.js +453 -513
  104. package/src/view/rawelement.js +85 -112
  105. package/src/view/renderer.js +874 -1018
  106. package/src/view/rooteditableelement.js +80 -90
  107. package/src/view/selection.js +608 -689
  108. package/src/view/styles/background.js +43 -44
  109. package/src/view/styles/border.js +220 -276
  110. package/src/view/styles/margin.js +8 -17
  111. package/src/view/styles/padding.js +8 -16
  112. package/src/view/styles/utils.js +127 -160
  113. package/src/view/stylesmap.js +728 -905
  114. package/src/view/text.js +102 -126
  115. package/src/view/textproxy.js +144 -170
  116. package/src/view/treewalker.js +383 -479
  117. package/src/view/typecheckable.js +19 -0
  118. package/src/view/uielement.js +166 -187
  119. package/src/view/upcastwriter.js +395 -449
  120. package/src/view/view.js +569 -664
  121. package/src/dataprocessor/dataprocessor.jsdoc +0 -64
  122. package/src/model/item.jsdoc +0 -14
  123. package/src/view/elementdefinition.jsdoc +0 -59
  124. package/src/view/item.jsdoc +0 -14
@@ -2,22 +2,16 @@
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/conversion/mapper
8
7
  */
9
-
10
8
  import ModelPosition from '../model/position';
11
9
  import ModelRange from '../model/range';
12
-
13
10
  import ViewPosition from '../view/position';
14
11
  import ViewRange from '../view/range';
15
12
  import ViewText from '../view/text';
16
-
17
- import EmitterMixin from '@ckeditor/ckeditor5-utils/src/emittermixin';
13
+ import { Emitter } from '@ckeditor/ckeditor5-utils/src/emittermixin';
18
14
  import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
19
- import mix from '@ckeditor/ckeditor5-utils/src/mix';
20
-
21
15
  /**
22
16
  * Maps elements, positions and markers between the {@link module:engine/view/document~Document view} and
23
17
  * the {@link module:engine/model/model model}.
@@ -38,704 +32,521 @@ import mix from '@ckeditor/ckeditor5-utils/src/mix';
38
32
  * stop the event.
39
33
  * @mixes module:utils/emittermixin~EmitterMixin
40
34
  */
41
- export default class Mapper {
42
- /**
43
- * Creates an instance of the mapper.
44
- */
45
- constructor() {
46
- /**
47
- * Model element to view element mapping.
48
- *
49
- * @private
50
- * @member {WeakMap}
51
- */
52
- this._modelToViewMapping = new WeakMap();
53
-
54
- /**
55
- * View element to model element mapping.
56
- *
57
- * @private
58
- * @member {WeakMap}
59
- */
60
- this._viewToModelMapping = new WeakMap();
61
-
62
- /**
63
- * A map containing callbacks between view element names and functions evaluating length of view elements
64
- * in model.
65
- *
66
- * @private
67
- * @member {Map}
68
- */
69
- this._viewToModelLengthCallbacks = new Map();
70
-
71
- /**
72
- * Model marker name to view elements mapping.
73
- *
74
- * Keys are `String`s while values are `Set`s with {@link module:engine/view/element~Element view elements}.
75
- * One marker (name) can be mapped to multiple elements.
76
- *
77
- * @private
78
- * @member {Map}
79
- */
80
- this._markerNameToElements = new Map();
81
-
82
- /**
83
- * View element to model marker names mapping.
84
- *
85
- * This is reverse to {@link ~Mapper#_markerNameToElements} map.
86
- *
87
- * @private
88
- * @member {Map}
89
- */
90
- this._elementToMarkerNames = new Map();
91
-
92
- /**
93
- * The map of removed view elements with their current root (used for deferred unbinding).
94
- *
95
- * @private
96
- * @member {Map.<module:engine/view/element~Element,module:engine/view/documentfragment~DocumentFragment>}
97
- */
98
- this._deferredBindingRemovals = new Map();
99
-
100
- /**
101
- * Stores marker names of markers which have changed due to unbinding a view element (so it is assumed that the view element
102
- * has been removed, moved or renamed).
103
- *
104
- * @private
105
- * @member {Set.<module:engine/model/markercollection~Marker>}
106
- */
107
- this._unboundMarkerNames = new Set();
108
-
109
- // Default mapper algorithm for mapping model position to view position.
110
- this.on( 'modelToViewPosition', ( evt, data ) => {
111
- if ( data.viewPosition ) {
112
- return;
113
- }
114
-
115
- const viewContainer = this._modelToViewMapping.get( data.modelPosition.parent );
116
-
117
- if ( !viewContainer ) {
118
- /**
119
- * A model position could not be mapped to the view because the parent of the model position
120
- * does not have a mapped view element (might have not been converted yet or it has no converter).
121
- *
122
- * Make sure that the model element is correctly converted to the view.
123
- *
124
- * @error mapping-model-position-view-parent-not-found
125
- */
126
- throw new CKEditorError( 'mapping-model-position-view-parent-not-found', this, { modelPosition: data.modelPosition } );
127
- }
128
-
129
- data.viewPosition = this.findPositionIn( viewContainer, data.modelPosition.offset );
130
- }, { priority: 'low' } );
131
-
132
- // Default mapper algorithm for mapping view position to model position.
133
- this.on( 'viewToModelPosition', ( evt, data ) => {
134
- if ( data.modelPosition ) {
135
- return;
136
- }
137
-
138
- const viewBlock = this.findMappedViewAncestor( data.viewPosition );
139
- const modelParent = this._viewToModelMapping.get( viewBlock );
140
- const modelOffset = this._toModelOffset( data.viewPosition.parent, data.viewPosition.offset, viewBlock );
141
-
142
- data.modelPosition = ModelPosition._createAt( modelParent, modelOffset );
143
- }, { priority: 'low' } );
144
- }
145
-
146
- /**
147
- * Marks model and view elements as corresponding. Corresponding elements can be retrieved by using
148
- * the {@link module:engine/conversion/mapper~Mapper#toModelElement toModelElement} and
149
- * {@link module:engine/conversion/mapper~Mapper#toViewElement toViewElement} methods.
150
- * The information that elements are bound is also used to translate positions.
151
- *
152
- * @param {module:engine/model/element~Element} modelElement Model element.
153
- * @param {module:engine/view/element~Element} viewElement View element.
154
- */
155
- bindElements( modelElement, viewElement ) {
156
- this._modelToViewMapping.set( modelElement, viewElement );
157
- this._viewToModelMapping.set( viewElement, modelElement );
158
- }
159
-
160
- /**
161
- * Unbinds the given {@link module:engine/view/element~Element view element} from the map.
162
- *
163
- * **Note:** view-to-model binding will be removed, if it existed. However, corresponding model-to-view binding
164
- * will be removed only if model element is still bound to the passed `viewElement`.
165
- *
166
- * This behavior allows for re-binding model element to another view element without fear of losing the new binding
167
- * when the previously bound view element is unbound.
168
- *
169
- * @param {module:engine/view/element~Element} viewElement View element to unbind.
170
- * @param {Object} [options={}] The options object.
171
- * @param {Boolean} [options.defer=false] Controls whether the binding should be removed immediately or deferred until a
172
- * {@link #flushDeferredBindings `flushDeferredBindings()`} call.
173
- */
174
- unbindViewElement( viewElement, options = {} ) {
175
- const modelElement = this.toModelElement( viewElement );
176
-
177
- if ( this._elementToMarkerNames.has( viewElement ) ) {
178
- for ( const markerName of this._elementToMarkerNames.get( viewElement ) ) {
179
- this._unboundMarkerNames.add( markerName );
180
- }
181
- }
182
-
183
- if ( options.defer ) {
184
- this._deferredBindingRemovals.set( viewElement, viewElement.root );
185
- } else {
186
- this._viewToModelMapping.delete( viewElement );
187
-
188
- if ( this._modelToViewMapping.get( modelElement ) == viewElement ) {
189
- this._modelToViewMapping.delete( modelElement );
190
- }
191
- }
192
- }
193
-
194
- /**
195
- * Unbinds the given {@link module:engine/model/element~Element model element} from the map.
196
- *
197
- * **Note:** the model-to-view binding will be removed, if it existed. However, the corresponding view-to-model binding
198
- * will be removed only if the view element is still bound to the passed `modelElement`.
199
- *
200
- * This behavior lets for re-binding view element to another model element without fear of losing the new binding
201
- * when the previously bound model element is unbound.
202
- *
203
- * @param {module:engine/model/element~Element} modelElement Model element to unbind.
204
- */
205
- unbindModelElement( modelElement ) {
206
- const viewElement = this.toViewElement( modelElement );
207
-
208
- this._modelToViewMapping.delete( modelElement );
209
-
210
- if ( this._viewToModelMapping.get( viewElement ) == modelElement ) {
211
- this._viewToModelMapping.delete( viewElement );
212
- }
213
- }
214
-
215
- /**
216
- * Binds the given marker name with the given {@link module:engine/view/element~Element view element}. The element
217
- * will be added to the current set of elements bound with the given marker name.
218
- *
219
- * @param {module:engine/view/element~Element} element Element to bind.
220
- * @param {String} name Marker name.
221
- */
222
- bindElementToMarker( element, name ) {
223
- const elements = this._markerNameToElements.get( name ) || new Set();
224
- elements.add( element );
225
-
226
- const names = this._elementToMarkerNames.get( element ) || new Set();
227
- names.add( name );
228
-
229
- this._markerNameToElements.set( name, elements );
230
- this._elementToMarkerNames.set( element, names );
231
- }
232
-
233
- /**
234
- * Unbinds an element from given marker name.
235
- *
236
- * @param {module:engine/view/element~Element} element Element to unbind.
237
- * @param {String} name Marker name.
238
- */
239
- unbindElementFromMarkerName( element, name ) {
240
- const nameToElements = this._markerNameToElements.get( name );
241
-
242
- if ( nameToElements ) {
243
- nameToElements.delete( element );
244
-
245
- if ( nameToElements.size == 0 ) {
246
- this._markerNameToElements.delete( name );
247
- }
248
- }
249
-
250
- const elementToNames = this._elementToMarkerNames.get( element );
251
-
252
- if ( elementToNames ) {
253
- elementToNames.delete( name );
254
-
255
- if ( elementToNames.size == 0 ) {
256
- this._elementToMarkerNames.delete( element );
257
- }
258
- }
259
- }
260
-
261
- /**
262
- * Returns all marker names of markers which have changed due to unbinding a view element (so it is assumed that the view element
263
- * has been removed, moved or renamed) since the last flush. After returning, the marker names list is cleared.
264
- *
265
- * @returns {Array.<String>}
266
- */
267
- flushUnboundMarkerNames() {
268
- const markerNames = Array.from( this._unboundMarkerNames );
269
-
270
- this._unboundMarkerNames.clear();
271
-
272
- return markerNames;
273
- }
274
-
275
- /**
276
- * Unbinds all deferred binding removals of view elements that in the meantime were not re-attached to some root or document fragment.
277
- *
278
- * See: {@link #unbindViewElement `unbindViewElement()`}.
279
- */
280
- flushDeferredBindings() {
281
- for ( const [ viewElement, root ] of this._deferredBindingRemovals ) {
282
- // Unbind it only if it wasn't re-attached to some root or document fragment.
283
- if ( viewElement.root == root ) {
284
- this.unbindViewElement( viewElement );
285
- }
286
- }
287
-
288
- this._deferredBindingRemovals = new Map();
289
- }
290
-
291
- /**
292
- * Removes all model to view and view to model bindings.
293
- */
294
- clearBindings() {
295
- this._modelToViewMapping = new WeakMap();
296
- this._viewToModelMapping = new WeakMap();
297
- this._markerNameToElements = new Map();
298
- this._elementToMarkerNames = new Map();
299
- this._unboundMarkerNames = new Set();
300
- this._deferredBindingRemovals = new Map();
301
- }
302
-
303
- /**
304
- * Gets the corresponding model element.
305
- *
306
- * **Note:** {@link module:engine/view/uielement~UIElement} does not have corresponding element in model.
307
- *
308
- * @param {module:engine/view/element~Element} viewElement View element.
309
- * @returns {module:engine/model/element~Element|undefined} Corresponding model element or `undefined` if not found.
310
- */
311
- toModelElement( viewElement ) {
312
- return this._viewToModelMapping.get( viewElement );
313
- }
314
-
315
- /**
316
- * Gets the corresponding view element.
317
- *
318
- * @param {module:engine/model/element~Element} modelElement Model element.
319
- * @returns {module:engine/view/element~Element|undefined} Corresponding view element or `undefined` if not found.
320
- */
321
- toViewElement( modelElement ) {
322
- return this._modelToViewMapping.get( modelElement );
323
- }
324
-
325
- /**
326
- * Gets the corresponding model range.
327
- *
328
- * @param {module:engine/view/range~Range} viewRange View range.
329
- * @returns {module:engine/model/range~Range} Corresponding model range.
330
- */
331
- toModelRange( viewRange ) {
332
- return new ModelRange( this.toModelPosition( viewRange.start ), this.toModelPosition( viewRange.end ) );
333
- }
334
-
335
- /**
336
- * Gets the corresponding view range.
337
- *
338
- * @param {module:engine/model/range~Range} modelRange Model range.
339
- * @returns {module:engine/view/range~Range} Corresponding view range.
340
- */
341
- toViewRange( modelRange ) {
342
- return new ViewRange( this.toViewPosition( modelRange.start ), this.toViewPosition( modelRange.end ) );
343
- }
344
-
345
- /**
346
- * Gets the corresponding model position.
347
- *
348
- * @fires viewToModelPosition
349
- * @param {module:engine/view/position~Position} viewPosition View position.
350
- * @returns {module:engine/model/position~Position} Corresponding model position.
351
- */
352
- toModelPosition( viewPosition ) {
353
- const data = {
354
- viewPosition,
355
- mapper: this
356
- };
357
-
358
- this.fire( 'viewToModelPosition', data );
359
-
360
- return data.modelPosition;
361
- }
362
-
363
- /**
364
- * Gets the corresponding view position.
365
- *
366
- * @fires modelToViewPosition
367
- * @param {module:engine/model/position~Position} modelPosition Model position.
368
- * @param {Object} [options] Additional options for position mapping process.
369
- * @param {Boolean} [options.isPhantom=false] Should be set to `true` if the model position to map is pointing to a place
370
- * in model tree which no longer exists. For example, it could be an end of a removed model range.
371
- * @returns {module:engine/view/position~Position} Corresponding view position.
372
- */
373
- toViewPosition( modelPosition, options = { isPhantom: false } ) {
374
- const data = {
375
- modelPosition,
376
- mapper: this,
377
- isPhantom: options.isPhantom
378
- };
379
-
380
- this.fire( 'modelToViewPosition', data );
381
-
382
- return data.viewPosition;
383
- }
384
-
385
- /**
386
- * Gets all view elements bound to the given marker name.
387
- *
388
- * @param {String} name Marker name.
389
- * @returns {Set.<module:engine/view/element~Element>|null} View elements bound with the given marker name or `null`
390
- * if no elements are bound to the given marker name.
391
- */
392
- markerNameToElements( name ) {
393
- const boundElements = this._markerNameToElements.get( name );
394
-
395
- if ( !boundElements ) {
396
- return null;
397
- }
398
-
399
- const elements = new Set();
400
-
401
- for ( const element of boundElements ) {
402
- if ( element.is( 'attributeElement' ) ) {
403
- for ( const clone of element.getElementsWithSameId() ) {
404
- elements.add( clone );
405
- }
406
- } else {
407
- elements.add( element );
408
- }
409
- }
410
-
411
- return elements;
412
- }
413
-
414
- /**
415
- * Registers a callback that evaluates the length in the model of a view element with the given name.
416
- *
417
- * The callback is fired with one argument, which is a view element instance. The callback is expected to return
418
- * a number representing the length of the view element in the model.
419
- *
420
- * // List item in view may contain nested list, which have other list items. In model though,
421
- * // the lists are represented by flat structure. Because of those differences, length of list view element
422
- * // may be greater than one. In the callback it's checked how many nested list items are in evaluated list item.
423
- *
424
- * function getViewListItemLength( element ) {
425
- * let length = 1;
426
- *
427
- * for ( let child of element.getChildren() ) {
428
- * if ( child.name == 'ul' || child.name == 'ol' ) {
429
- * for ( let item of child.getChildren() ) {
430
- * length += getViewListItemLength( item );
431
- * }
432
- * }
433
- * }
434
- *
435
- * return length;
436
- * }
437
- *
438
- * mapper.registerViewToModelLength( 'li', getViewListItemLength );
439
- *
440
- * @param {String} viewElementName Name of view element for which callback is registered.
441
- * @param {Function} lengthCallback Function return a length of view element instance in model.
442
- */
443
- registerViewToModelLength( viewElementName, lengthCallback ) {
444
- this._viewToModelLengthCallbacks.set( viewElementName, lengthCallback );
445
- }
446
-
447
- /**
448
- * For the given `viewPosition`, finds and returns the closest ancestor of this position that has a mapping to
449
- * the model.
450
- *
451
- * @param {module:engine/view/position~Position} viewPosition Position for which a mapped ancestor should be found.
452
- * @returns {module:engine/view/element~Element}
453
- */
454
- findMappedViewAncestor( viewPosition ) {
455
- let parent = viewPosition.parent;
456
-
457
- while ( !this._viewToModelMapping.has( parent ) ) {
458
- parent = parent.parent;
459
- }
460
-
461
- return parent;
462
- }
463
-
464
- /**
465
- * Calculates model offset based on the view position and the block element.
466
- *
467
- * Example:
468
- *
469
- * <p>foo<b>ba|r</b></p> // _toModelOffset( b, 2, p ) -> 5
470
- *
471
- * Is a sum of:
472
- *
473
- * <p>foo|<b>bar</b></p> // _toModelOffset( p, 3, p ) -> 3
474
- * <p>foo<b>ba|r</b></p> // _toModelOffset( b, 2, b ) -> 2
475
- *
476
- * @private
477
- * @param {module:engine/view/element~Element} viewParent Position parent.
478
- * @param {Number} viewOffset Position offset.
479
- * @param {module:engine/view/element~Element} viewBlock Block used as a base to calculate offset.
480
- * @returns {Number} Offset in the model.
481
- */
482
- _toModelOffset( viewParent, viewOffset, viewBlock ) {
483
- if ( viewBlock != viewParent ) {
484
- // See example.
485
- const offsetToParentStart = this._toModelOffset( viewParent.parent, viewParent.index, viewBlock );
486
- const offsetInParent = this._toModelOffset( viewParent, viewOffset, viewParent );
487
-
488
- return offsetToParentStart + offsetInParent;
489
- }
490
-
491
- // viewBlock == viewParent, so we need to calculate the offset in the parent element.
492
-
493
- // If the position is a text it is simple ("ba|r" -> 2).
494
- if ( viewParent.is( '$text' ) ) {
495
- return viewOffset;
496
- }
497
-
498
- // If the position is in an element we need to sum lengths of siblings ( <b> bar </b> foo | -> 3 + 3 = 6 ).
499
- let modelOffset = 0;
500
-
501
- for ( let i = 0; i < viewOffset; i++ ) {
502
- modelOffset += this.getModelLength( viewParent.getChild( i ) );
503
- }
504
-
505
- return modelOffset;
506
- }
507
-
508
- /**
509
- * Gets the length of the view element in the model.
510
- *
511
- * The length is calculated as follows:
512
- * * if a {@link #registerViewToModelLength length mapping callback} is provided for the given `viewNode`, it is used to
513
- * evaluate the model length (`viewNode` is used as first and only parameter passed to the callback),
514
- * * length of a {@link module:engine/view/text~Text text node} is equal to the length of its
515
- * {@link module:engine/view/text~Text#data data},
516
- * * length of a {@link module:engine/view/uielement~UIElement ui element} is equal to 0,
517
- * * length of a mapped {@link module:engine/view/element~Element element} is equal to 1,
518
- * * length of a non-mapped {@link module:engine/view/element~Element element} is equal to the length of its children.
519
- *
520
- * Examples:
521
- *
522
- * foo -> 3 // Text length is equal to its data length.
523
- * <p>foo</p> -> 1 // Length of an element which is mapped is by default equal to 1.
524
- * <b>foo</b> -> 3 // Length of an element which is not mapped is a length of its children.
525
- * <div><p>x</p><p>y</p></div> -> 2 // Assuming that <div> is not mapped and <p> are mapped.
526
- *
527
- * @param {module:engine/view/element~Element} viewNode View node.
528
- * @returns {Number} Length of the node in the tree model.
529
- */
530
- getModelLength( viewNode ) {
531
- if ( this._viewToModelLengthCallbacks.get( viewNode.name ) ) {
532
- const callback = this._viewToModelLengthCallbacks.get( viewNode.name );
533
-
534
- return callback( viewNode );
535
- } else if ( this._viewToModelMapping.has( viewNode ) ) {
536
- return 1;
537
- } else if ( viewNode.is( '$text' ) ) {
538
- return viewNode.data.length;
539
- } else if ( viewNode.is( 'uiElement' ) ) {
540
- return 0;
541
- } else {
542
- let len = 0;
543
-
544
- for ( const child of viewNode.getChildren() ) {
545
- len += this.getModelLength( child );
546
- }
547
-
548
- return len;
549
- }
550
- }
551
-
552
- /**
553
- * Finds the position in the view node (or in its children) with the expected model offset.
554
- *
555
- * Example:
556
- *
557
- * <p>fo<b>bar</b>bom</p> -> expected offset: 4
558
- *
559
- * findPositionIn( p, 4 ):
560
- * <p>|fo<b>bar</b>bom</p> -> expected offset: 4, actual offset: 0
561
- * <p>fo|<b>bar</b>bom</p> -> expected offset: 4, actual offset: 2
562
- * <p>fo<b>bar</b>|bom</p> -> expected offset: 4, actual offset: 5 -> we are too far
563
- *
564
- * findPositionIn( b, 4 - ( 5 - 3 ) ):
565
- * <p>fo<b>|bar</b>bom</p> -> expected offset: 2, actual offset: 0
566
- * <p>fo<b>bar|</b>bom</p> -> expected offset: 2, actual offset: 3 -> we are too far
567
- *
568
- * findPositionIn( bar, 2 - ( 3 - 3 ) ):
569
- * We are in the text node so we can simple find the offset.
570
- * <p>fo<b>ba|r</b>bom</p> -> expected offset: 2, actual offset: 2 -> position found
571
- *
572
- * @param {module:engine/view/element~Element} viewParent Tree view element in which we are looking for the position.
573
- * @param {Number} expectedOffset Expected offset.
574
- * @returns {module:engine/view/position~Position} Found position.
575
- */
576
- findPositionIn( viewParent, expectedOffset ) {
577
- // Last scanned view node.
578
- let viewNode;
579
- // Length of the last scanned view node.
580
- let lastLength = 0;
581
-
582
- let modelOffset = 0;
583
- let viewOffset = 0;
584
-
585
- // In the text node it is simple: the offset in the model equals the offset in the text.
586
- if ( viewParent.is( '$text' ) ) {
587
- return new ViewPosition( viewParent, expectedOffset );
588
- }
589
-
590
- // In other cases we add lengths of child nodes to find the proper offset.
591
-
592
- // If it is smaller we add the length.
593
- while ( modelOffset < expectedOffset ) {
594
- viewNode = viewParent.getChild( viewOffset );
595
- lastLength = this.getModelLength( viewNode );
596
- modelOffset += lastLength;
597
- viewOffset++;
598
- }
599
-
600
- // If it equals we found the position.
601
- if ( modelOffset == expectedOffset ) {
602
- return this._moveViewPositionToTextNode( new ViewPosition( viewParent, viewOffset ) );
603
- }
604
- // If it is higher we need to enter last child.
605
- else {
606
- // ( modelOffset - lastLength ) is the offset to the child we enter,
607
- // so we subtract it from the expected offset to fine the offset in the child.
608
- return this.findPositionIn( viewNode, expectedOffset - ( modelOffset - lastLength ) );
609
- }
610
- }
611
-
612
- /**
613
- * Because we prefer positions in the text nodes over positions next to text nodes, if the view position was next to a text node,
614
- * it moves it into the text node instead.
615
- *
616
- * <p>[]<b>foo</b></p> -> <p>[]<b>foo</b></p> // do not touch if position is not directly next to text
617
- * <p>foo[]<b>foo</b></p> -> <p>foo{}<b>foo</b></p> // move to text node
618
- * <p><b>[]foo</b></p> -> <p><b>{}foo</b></p> // move to text node
619
- *
620
- * @private
621
- * @param {module:engine/view/position~Position} viewPosition Position potentially next to the text node.
622
- * @returns {module:engine/view/position~Position} Position in the text node if possible.
623
- */
624
- _moveViewPositionToTextNode( viewPosition ) {
625
- // If the position is just after a text node, put it at the end of that text node.
626
- // If the position is just before a text node, put it at the beginning of that text node.
627
- const nodeBefore = viewPosition.nodeBefore;
628
- const nodeAfter = viewPosition.nodeAfter;
629
-
630
- if ( nodeBefore instanceof ViewText ) {
631
- return new ViewPosition( nodeBefore, nodeBefore.data.length );
632
- } else if ( nodeAfter instanceof ViewText ) {
633
- return new ViewPosition( nodeAfter, 0 );
634
- }
635
-
636
- // Otherwise, just return the given position.
637
- return viewPosition;
638
- }
639
-
640
- /**
641
- * Fired for each model-to-view position mapping request. The purpose of this event is to enable custom model-to-view position
642
- * mapping. Callbacks added to this event take {@link module:engine/model/position~Position model position} and are expected to
643
- * calculate the {@link module:engine/view/position~Position view position}. The calculated view position should be added as
644
- * a `viewPosition` value in the `data` object that is passed as one of parameters to the event callback.
645
- *
646
- * // Assume that "captionedImage" model element is converted to <img> and following <span> elements in view,
647
- * // and the model element is bound to <img> element. Force mapping model positions inside "captionedImage" to that
648
- * // <span> element.
649
- * mapper.on( 'modelToViewPosition', ( evt, data ) => {
650
- * const positionParent = modelPosition.parent;
651
- *
652
- * if ( positionParent.name == 'captionedImage' ) {
653
- * const viewImg = data.mapper.toViewElement( positionParent );
654
- * const viewCaption = viewImg.nextSibling; // The <span> element.
655
- *
656
- * data.viewPosition = new ViewPosition( viewCaption, modelPosition.offset );
657
- *
658
- * // Stop the event if other callbacks should not modify calculated value.
659
- * evt.stop();
660
- * }
661
- * } );
662
- *
663
- * **Note:** keep in mind that sometimes a "phantom" model position is being converted. A "phantom" model position is
664
- * a position that points to a nonexistent place in model. Such a position might still be valid for conversion, though
665
- * (it would point to a correct place in the view when converted). One example of such a situation is when a range is
666
- * removed from the model, there may be a need to map the range's end (which is no longer a valid model position). To
667
- * handle such situations, check the `data.isPhantom` flag:
668
- *
669
- * // Assume that there is a "customElement" model element and whenever the position is before it,
670
- * // we want to move it to the inside of the view element bound to "customElement".
671
- * mapper.on( 'modelToViewPosition', ( evt, data ) => {
672
- * if ( data.isPhantom ) {
673
- * return;
674
- * }
675
- *
676
- * // Below line might crash for phantom position that does not exist in model.
677
- * const sibling = data.modelPosition.nodeBefore;
678
- *
679
- * // Check if this is the element we are interested in.
680
- * if ( !sibling.is( 'element', 'customElement' ) ) {
681
- * return;
682
- * }
683
- *
684
- * const viewElement = data.mapper.toViewElement( sibling );
685
- *
686
- * data.viewPosition = new ViewPosition( sibling, 0 );
687
- *
688
- * evt.stop();
689
- * } );
690
- *
691
- * **Note:** the default mapping callback is provided with a `low` priority setting and does not cancel the event, so it is possible to
692
- * attach a custom callback after a default callback and also use `data.viewPosition` calculated by the default callback
693
- * (for example to fix it).
694
- *
695
- * **Note:** the default mapping callback will not fire if `data.viewPosition` is already set.
696
- *
697
- * **Note:** these callbacks are called **very often**. For efficiency reasons, it is advised to use them only when position
698
- * mapping between the given model and view elements is unsolvable by using just elements mapping and default algorithm.
699
- * Also, the condition that checks if a special case scenario happened should be as simple as possible.
700
- *
701
- * @event modelToViewPosition
702
- * @param {Object} data Data pipeline object that can store and pass data between callbacks. The callback should add
703
- * the `viewPosition` value to that object with calculated the {@link module:engine/view/position~Position view position}.
704
- * @param {module:engine/conversion/mapper~Mapper} data.mapper Mapper instance that fired the event.
705
- */
706
-
707
- /**
708
- * Fired for each view-to-model position mapping request. See {@link module:engine/conversion/mapper~Mapper#event:modelToViewPosition}.
709
- *
710
- * // See example in `modelToViewPosition` event description.
711
- * // This custom mapping will map positions from <span> element next to <img> to the "captionedImage" element.
712
- * mapper.on( 'viewToModelPosition', ( evt, data ) => {
713
- * const positionParent = viewPosition.parent;
714
- *
715
- * if ( positionParent.hasClass( 'image-caption' ) ) {
716
- * const viewImg = positionParent.previousSibling;
717
- * const modelImg = data.mapper.toModelElement( viewImg );
718
- *
719
- * data.modelPosition = new ModelPosition( modelImg, viewPosition.offset );
720
- * evt.stop();
721
- * }
722
- * } );
723
- *
724
- * **Note:** the default mapping callback is provided with a `low` priority setting and does not cancel the event, so it is possible to
725
- * attach a custom callback after the default callback and also use `data.modelPosition` calculated by the default callback
726
- * (for example to fix it).
727
- *
728
- * **Note:** the default mapping callback will not fire if `data.modelPosition` is already set.
729
- *
730
- * **Note:** these callbacks are called **very often**. For efficiency reasons, it is advised to use them only when position
731
- * mapping between the given model and view elements is unsolvable by using just elements mapping and default algorithm.
732
- * Also, the condition that checks if special case scenario happened should be as simple as possible.
733
- *
734
- * @event viewToModelPosition
735
- * @param {Object} data Data pipeline object that can store and pass data between callbacks. The callback should add
736
- * `modelPosition` value to that object with calculated {@link module:engine/model/position~Position model position}.
737
- * @param {module:engine/conversion/mapper~Mapper} data.mapper Mapper instance that fired the event.
738
- */
35
+ export default class Mapper extends Emitter {
36
+ /**
37
+ * Creates an instance of the mapper.
38
+ */
39
+ constructor() {
40
+ super();
41
+ /**
42
+ * Model element to view element mapping.
43
+ *
44
+ * @private
45
+ * @member {WeakMap}
46
+ */
47
+ this._modelToViewMapping = new WeakMap();
48
+ /**
49
+ * View element to model element mapping.
50
+ *
51
+ * @private
52
+ * @member {WeakMap}
53
+ */
54
+ this._viewToModelMapping = new WeakMap();
55
+ /**
56
+ * A map containing callbacks between view element names and functions evaluating length of view elements
57
+ * in model.
58
+ *
59
+ * @private
60
+ * @member {Map}
61
+ */
62
+ this._viewToModelLengthCallbacks = new Map();
63
+ /**
64
+ * Model marker name to view elements mapping.
65
+ *
66
+ * Keys are `String`s while values are `Set`s with {@link module:engine/view/element~Element view elements}.
67
+ * One marker (name) can be mapped to multiple elements.
68
+ *
69
+ * @private
70
+ * @member {Map}
71
+ */
72
+ this._markerNameToElements = new Map();
73
+ /**
74
+ * View element to model marker names mapping.
75
+ *
76
+ * This is reverse to {@link ~Mapper#_markerNameToElements} map.
77
+ *
78
+ * @private
79
+ * @member {Map}
80
+ */
81
+ this._elementToMarkerNames = new Map();
82
+ /**
83
+ * The map of removed view elements with their current root (used for deferred unbinding).
84
+ *
85
+ * @private
86
+ * @member {Map.<module:engine/view/element~Element,module:engine/view/documentfragment~DocumentFragment>}
87
+ */
88
+ this._deferredBindingRemovals = new Map();
89
+ /**
90
+ * Stores marker names of markers which have changed due to unbinding a view element (so it is assumed that the view element
91
+ * has been removed, moved or renamed).
92
+ *
93
+ * @private
94
+ * @member {Set.<module:engine/model/markercollection~Marker>}
95
+ */
96
+ this._unboundMarkerNames = new Set();
97
+ // Default mapper algorithm for mapping model position to view position.
98
+ this.on('modelToViewPosition', (evt, data) => {
99
+ if (data.viewPosition) {
100
+ return;
101
+ }
102
+ const viewContainer = this._modelToViewMapping.get(data.modelPosition.parent);
103
+ if (!viewContainer) {
104
+ /**
105
+ * A model position could not be mapped to the view because the parent of the model position
106
+ * does not have a mapped view element (might have not been converted yet or it has no converter).
107
+ *
108
+ * Make sure that the model element is correctly converted to the view.
109
+ *
110
+ * @error mapping-model-position-view-parent-not-found
111
+ */
112
+ throw new CKEditorError('mapping-model-position-view-parent-not-found', this, { modelPosition: data.modelPosition });
113
+ }
114
+ data.viewPosition = this.findPositionIn(viewContainer, data.modelPosition.offset);
115
+ }, { priority: 'low' });
116
+ // Default mapper algorithm for mapping view position to model position.
117
+ this.on('viewToModelPosition', (evt, data) => {
118
+ if (data.modelPosition) {
119
+ return;
120
+ }
121
+ const viewBlock = this.findMappedViewAncestor(data.viewPosition);
122
+ const modelParent = this._viewToModelMapping.get(viewBlock);
123
+ const modelOffset = this._toModelOffset(data.viewPosition.parent, data.viewPosition.offset, viewBlock);
124
+ data.modelPosition = ModelPosition._createAt(modelParent, modelOffset);
125
+ }, { priority: 'low' });
126
+ }
127
+ /**
128
+ * Marks model and view elements as corresponding. Corresponding elements can be retrieved by using
129
+ * the {@link module:engine/conversion/mapper~Mapper#toModelElement toModelElement} and
130
+ * {@link module:engine/conversion/mapper~Mapper#toViewElement toViewElement} methods.
131
+ * The information that elements are bound is also used to translate positions.
132
+ *
133
+ * @param {module:engine/model/element~Element} modelElement Model element.
134
+ * @param {module:engine/view/element~Element} viewElement View element.
135
+ */
136
+ bindElements(modelElement, viewElement) {
137
+ this._modelToViewMapping.set(modelElement, viewElement);
138
+ this._viewToModelMapping.set(viewElement, modelElement);
139
+ }
140
+ /**
141
+ * Unbinds the given {@link module:engine/view/element~Element view element} from the map.
142
+ *
143
+ * **Note:** view-to-model binding will be removed, if it existed. However, corresponding model-to-view binding
144
+ * will be removed only if model element is still bound to the passed `viewElement`.
145
+ *
146
+ * This behavior allows for re-binding model element to another view element without fear of losing the new binding
147
+ * when the previously bound view element is unbound.
148
+ *
149
+ * @param {module:engine/view/element~Element} viewElement View element to unbind.
150
+ * @param {Object} [options={}] The options object.
151
+ * @param {Boolean} [options.defer=false] Controls whether the binding should be removed immediately or deferred until a
152
+ * {@link #flushDeferredBindings `flushDeferredBindings()`} call.
153
+ */
154
+ unbindViewElement(viewElement, options = {}) {
155
+ const modelElement = this.toModelElement(viewElement);
156
+ if (this._elementToMarkerNames.has(viewElement)) {
157
+ for (const markerName of this._elementToMarkerNames.get(viewElement)) {
158
+ this._unboundMarkerNames.add(markerName);
159
+ }
160
+ }
161
+ if (options.defer) {
162
+ this._deferredBindingRemovals.set(viewElement, viewElement.root);
163
+ }
164
+ else {
165
+ this._viewToModelMapping.delete(viewElement);
166
+ if (this._modelToViewMapping.get(modelElement) == viewElement) {
167
+ this._modelToViewMapping.delete(modelElement);
168
+ }
169
+ }
170
+ }
171
+ /**
172
+ * Unbinds the given {@link module:engine/model/element~Element model element} from the map.
173
+ *
174
+ * **Note:** the model-to-view binding will be removed, if it existed. However, the corresponding view-to-model binding
175
+ * will be removed only if the view element is still bound to the passed `modelElement`.
176
+ *
177
+ * This behavior lets for re-binding view element to another model element without fear of losing the new binding
178
+ * when the previously bound model element is unbound.
179
+ *
180
+ * @param {module:engine/model/element~Element} modelElement Model element to unbind.
181
+ */
182
+ unbindModelElement(modelElement) {
183
+ const viewElement = this.toViewElement(modelElement);
184
+ this._modelToViewMapping.delete(modelElement);
185
+ if (this._viewToModelMapping.get(viewElement) == modelElement) {
186
+ this._viewToModelMapping.delete(viewElement);
187
+ }
188
+ }
189
+ /**
190
+ * Binds the given marker name with the given {@link module:engine/view/element~Element view element}. The element
191
+ * will be added to the current set of elements bound with the given marker name.
192
+ *
193
+ * @param {module:engine/view/element~Element} element Element to bind.
194
+ * @param {String} name Marker name.
195
+ */
196
+ bindElementToMarker(element, name) {
197
+ const elements = this._markerNameToElements.get(name) || new Set();
198
+ elements.add(element);
199
+ const names = this._elementToMarkerNames.get(element) || new Set();
200
+ names.add(name);
201
+ this._markerNameToElements.set(name, elements);
202
+ this._elementToMarkerNames.set(element, names);
203
+ }
204
+ /**
205
+ * Unbinds an element from given marker name.
206
+ *
207
+ * @param {module:engine/view/element~Element} element Element to unbind.
208
+ * @param {String} name Marker name.
209
+ */
210
+ unbindElementFromMarkerName(element, name) {
211
+ const nameToElements = this._markerNameToElements.get(name);
212
+ if (nameToElements) {
213
+ nameToElements.delete(element);
214
+ if (nameToElements.size == 0) {
215
+ this._markerNameToElements.delete(name);
216
+ }
217
+ }
218
+ const elementToNames = this._elementToMarkerNames.get(element);
219
+ if (elementToNames) {
220
+ elementToNames.delete(name);
221
+ if (elementToNames.size == 0) {
222
+ this._elementToMarkerNames.delete(element);
223
+ }
224
+ }
225
+ }
226
+ /**
227
+ * Returns all marker names of markers which have changed due to unbinding a view element (so it is assumed that the view element
228
+ * has been removed, moved or renamed) since the last flush. After returning, the marker names list is cleared.
229
+ *
230
+ * @returns {Array.<String>}
231
+ */
232
+ flushUnboundMarkerNames() {
233
+ const markerNames = Array.from(this._unboundMarkerNames);
234
+ this._unboundMarkerNames.clear();
235
+ return markerNames;
236
+ }
237
+ /**
238
+ * Unbinds all deferred binding removals of view elements that in the meantime were not re-attached to some root or document fragment.
239
+ *
240
+ * See: {@link #unbindViewElement `unbindViewElement()`}.
241
+ */
242
+ flushDeferredBindings() {
243
+ for (const [viewElement, root] of this._deferredBindingRemovals) {
244
+ // Unbind it only if it wasn't re-attached to some root or document fragment.
245
+ if (viewElement.root == root) {
246
+ this.unbindViewElement(viewElement);
247
+ }
248
+ }
249
+ this._deferredBindingRemovals = new Map();
250
+ }
251
+ /**
252
+ * Removes all model to view and view to model bindings.
253
+ */
254
+ clearBindings() {
255
+ this._modelToViewMapping = new WeakMap();
256
+ this._viewToModelMapping = new WeakMap();
257
+ this._markerNameToElements = new Map();
258
+ this._elementToMarkerNames = new Map();
259
+ this._unboundMarkerNames = new Set();
260
+ this._deferredBindingRemovals = new Map();
261
+ }
262
+ toModelElement(viewElement) {
263
+ return this._viewToModelMapping.get(viewElement);
264
+ }
265
+ toViewElement(modelElement) {
266
+ return this._modelToViewMapping.get(modelElement);
267
+ }
268
+ /**
269
+ * Gets the corresponding model range.
270
+ *
271
+ * @param {module:engine/view/range~Range} viewRange View range.
272
+ * @returns {module:engine/model/range~Range} Corresponding model range.
273
+ */
274
+ toModelRange(viewRange) {
275
+ return new ModelRange(this.toModelPosition(viewRange.start), this.toModelPosition(viewRange.end));
276
+ }
277
+ /**
278
+ * Gets the corresponding view range.
279
+ *
280
+ * @param {module:engine/model/range~Range} modelRange Model range.
281
+ * @returns {module:engine/view/range~Range} Corresponding view range.
282
+ */
283
+ toViewRange(modelRange) {
284
+ return new ViewRange(this.toViewPosition(modelRange.start), this.toViewPosition(modelRange.end));
285
+ }
286
+ /**
287
+ * Gets the corresponding model position.
288
+ *
289
+ * @fires viewToModelPosition
290
+ * @param {module:engine/view/position~Position} viewPosition View position.
291
+ * @returns {module:engine/model/position~Position} Corresponding model position.
292
+ */
293
+ toModelPosition(viewPosition) {
294
+ const data = {
295
+ viewPosition,
296
+ mapper: this
297
+ };
298
+ this.fire('viewToModelPosition', data);
299
+ return data.modelPosition;
300
+ }
301
+ /**
302
+ * Gets the corresponding view position.
303
+ *
304
+ * @fires modelToViewPosition
305
+ * @param {module:engine/model/position~Position} modelPosition Model position.
306
+ * @param {Object} [options] Additional options for position mapping process.
307
+ * @param {Boolean} [options.isPhantom=false] Should be set to `true` if the model position to map is pointing to a place
308
+ * in model tree which no longer exists. For example, it could be an end of a removed model range.
309
+ * @returns {module:engine/view/position~Position} Corresponding view position.
310
+ */
311
+ toViewPosition(modelPosition, options = {}) {
312
+ const data = {
313
+ modelPosition,
314
+ mapper: this,
315
+ isPhantom: options.isPhantom
316
+ };
317
+ this.fire('modelToViewPosition', data);
318
+ return data.viewPosition;
319
+ }
320
+ /**
321
+ * Gets all view elements bound to the given marker name.
322
+ *
323
+ * @param {String} name Marker name.
324
+ * @returns {Set.<module:engine/view/element~Element>|null} View elements bound with the given marker name or `null`
325
+ * if no elements are bound to the given marker name.
326
+ */
327
+ markerNameToElements(name) {
328
+ const boundElements = this._markerNameToElements.get(name);
329
+ if (!boundElements) {
330
+ return null;
331
+ }
332
+ const elements = new Set();
333
+ for (const element of boundElements) {
334
+ if (element.is('attributeElement')) {
335
+ for (const clone of element.getElementsWithSameId()) {
336
+ elements.add(clone);
337
+ }
338
+ }
339
+ else {
340
+ elements.add(element);
341
+ }
342
+ }
343
+ return elements;
344
+ }
345
+ /**
346
+ * Registers a callback that evaluates the length in the model of a view element with the given name.
347
+ *
348
+ * The callback is fired with one argument, which is a view element instance. The callback is expected to return
349
+ * a number representing the length of the view element in the model.
350
+ *
351
+ * // List item in view may contain nested list, which have other list items. In model though,
352
+ * // the lists are represented by flat structure. Because of those differences, length of list view element
353
+ * // may be greater than one. In the callback it's checked how many nested list items are in evaluated list item.
354
+ *
355
+ * function getViewListItemLength( element ) {
356
+ * let length = 1;
357
+ *
358
+ * for ( let child of element.getChildren() ) {
359
+ * if ( child.name == 'ul' || child.name == 'ol' ) {
360
+ * for ( let item of child.getChildren() ) {
361
+ * length += getViewListItemLength( item );
362
+ * }
363
+ * }
364
+ * }
365
+ *
366
+ * return length;
367
+ * }
368
+ *
369
+ * mapper.registerViewToModelLength( 'li', getViewListItemLength );
370
+ *
371
+ * @param {String} viewElementName Name of view element for which callback is registered.
372
+ * @param {Function} lengthCallback Function return a length of view element instance in model.
373
+ */
374
+ registerViewToModelLength(viewElementName, lengthCallback) {
375
+ this._viewToModelLengthCallbacks.set(viewElementName, lengthCallback);
376
+ }
377
+ /**
378
+ * For the given `viewPosition`, finds and returns the closest ancestor of this position that has a mapping to
379
+ * the model.
380
+ *
381
+ * @param {module:engine/view/position~Position} viewPosition Position for which a mapped ancestor should be found.
382
+ * @returns {module:engine/view/element~Element}
383
+ */
384
+ findMappedViewAncestor(viewPosition) {
385
+ let parent = viewPosition.parent;
386
+ while (!this._viewToModelMapping.has(parent)) {
387
+ parent = parent.parent;
388
+ }
389
+ return parent;
390
+ }
391
+ /**
392
+ * Calculates model offset based on the view position and the block element.
393
+ *
394
+ * Example:
395
+ *
396
+ * <p>foo<b>ba|r</b></p> // _toModelOffset( b, 2, p ) -> 5
397
+ *
398
+ * Is a sum of:
399
+ *
400
+ * <p>foo|<b>bar</b></p> // _toModelOffset( p, 3, p ) -> 3
401
+ * <p>foo<b>ba|r</b></p> // _toModelOffset( b, 2, b ) -> 2
402
+ *
403
+ * @private
404
+ * @param {module:engine/view/element~Element} viewParent Position parent.
405
+ * @param {Number} viewOffset Position offset.
406
+ * @param {module:engine/view/element~Element} viewBlock Block used as a base to calculate offset.
407
+ * @returns {Number} Offset in the model.
408
+ */
409
+ _toModelOffset(viewParent, viewOffset, viewBlock) {
410
+ if (viewBlock != viewParent) {
411
+ // See example.
412
+ const offsetToParentStart = this._toModelOffset(viewParent.parent, viewParent.index, viewBlock);
413
+ const offsetInParent = this._toModelOffset(viewParent, viewOffset, viewParent);
414
+ return offsetToParentStart + offsetInParent;
415
+ }
416
+ // viewBlock == viewParent, so we need to calculate the offset in the parent element.
417
+ // If the position is a text it is simple ("ba|r" -> 2).
418
+ if (viewParent.is('$text')) {
419
+ return viewOffset;
420
+ }
421
+ // If the position is in an element we need to sum lengths of siblings ( <b> bar </b> foo | -> 3 + 3 = 6 ).
422
+ let modelOffset = 0;
423
+ for (let i = 0; i < viewOffset; i++) {
424
+ modelOffset += this.getModelLength(viewParent.getChild(i));
425
+ }
426
+ return modelOffset;
427
+ }
428
+ /**
429
+ * Gets the length of the view element in the model.
430
+ *
431
+ * The length is calculated as follows:
432
+ * * if a {@link #registerViewToModelLength length mapping callback} is provided for the given `viewNode`, it is used to
433
+ * evaluate the model length (`viewNode` is used as first and only parameter passed to the callback),
434
+ * * length of a {@link module:engine/view/text~Text text node} is equal to the length of its
435
+ * {@link module:engine/view/text~Text#data data},
436
+ * * length of a {@link module:engine/view/uielement~UIElement ui element} is equal to 0,
437
+ * * length of a mapped {@link module:engine/view/element~Element element} is equal to 1,
438
+ * * length of a non-mapped {@link module:engine/view/element~Element element} is equal to the length of its children.
439
+ *
440
+ * Examples:
441
+ *
442
+ * foo -> 3 // Text length is equal to its data length.
443
+ * <p>foo</p> -> 1 // Length of an element which is mapped is by default equal to 1.
444
+ * <b>foo</b> -> 3 // Length of an element which is not mapped is a length of its children.
445
+ * <div><p>x</p><p>y</p></div> -> 2 // Assuming that <div> is not mapped and <p> are mapped.
446
+ *
447
+ * @param {module:engine/view/element~Element} viewNode View node.
448
+ * @returns {Number} Length of the node in the tree model.
449
+ */
450
+ getModelLength(viewNode) {
451
+ if (this._viewToModelLengthCallbacks.get(viewNode.name)) {
452
+ const callback = this._viewToModelLengthCallbacks.get(viewNode.name);
453
+ return callback(viewNode);
454
+ }
455
+ else if (this._viewToModelMapping.has(viewNode)) {
456
+ return 1;
457
+ }
458
+ else if (viewNode.is('$text')) {
459
+ return viewNode.data.length;
460
+ }
461
+ else if (viewNode.is('uiElement')) {
462
+ return 0;
463
+ }
464
+ else {
465
+ let len = 0;
466
+ for (const child of viewNode.getChildren()) {
467
+ len += this.getModelLength(child);
468
+ }
469
+ return len;
470
+ }
471
+ }
472
+ /**
473
+ * Finds the position in the view node (or in its children) with the expected model offset.
474
+ *
475
+ * Example:
476
+ *
477
+ * <p>fo<b>bar</b>bom</p> -> expected offset: 4
478
+ *
479
+ * findPositionIn( p, 4 ):
480
+ * <p>|fo<b>bar</b>bom</p> -> expected offset: 4, actual offset: 0
481
+ * <p>fo|<b>bar</b>bom</p> -> expected offset: 4, actual offset: 2
482
+ * <p>fo<b>bar</b>|bom</p> -> expected offset: 4, actual offset: 5 -> we are too far
483
+ *
484
+ * findPositionIn( b, 4 - ( 5 - 3 ) ):
485
+ * <p>fo<b>|bar</b>bom</p> -> expected offset: 2, actual offset: 0
486
+ * <p>fo<b>bar|</b>bom</p> -> expected offset: 2, actual offset: 3 -> we are too far
487
+ *
488
+ * findPositionIn( bar, 2 - ( 3 - 3 ) ):
489
+ * We are in the text node so we can simple find the offset.
490
+ * <p>fo<b>ba|r</b>bom</p> -> expected offset: 2, actual offset: 2 -> position found
491
+ *
492
+ * @param {module:engine/view/element~Element} viewParent Tree view element in which we are looking for the position.
493
+ * @param {Number} expectedOffset Expected offset.
494
+ * @returns {module:engine/view/position~Position} Found position.
495
+ */
496
+ findPositionIn(viewParent, expectedOffset) {
497
+ // Last scanned view node.
498
+ let viewNode;
499
+ // Length of the last scanned view node.
500
+ let lastLength = 0;
501
+ let modelOffset = 0;
502
+ let viewOffset = 0;
503
+ // In the text node it is simple: the offset in the model equals the offset in the text.
504
+ if (viewParent.is('$text')) {
505
+ return new ViewPosition(viewParent, expectedOffset);
506
+ }
507
+ // In other cases we add lengths of child nodes to find the proper offset.
508
+ // If it is smaller we add the length.
509
+ while (modelOffset < expectedOffset) {
510
+ viewNode = viewParent.getChild(viewOffset);
511
+ lastLength = this.getModelLength(viewNode);
512
+ modelOffset += lastLength;
513
+ viewOffset++;
514
+ }
515
+ // If it equals we found the position.
516
+ if (modelOffset == expectedOffset) {
517
+ return this._moveViewPositionToTextNode(new ViewPosition(viewParent, viewOffset));
518
+ }
519
+ // If it is higher we need to enter last child.
520
+ else {
521
+ // ( modelOffset - lastLength ) is the offset to the child we enter,
522
+ // so we subtract it from the expected offset to fine the offset in the child.
523
+ return this.findPositionIn(viewNode, expectedOffset - (modelOffset - lastLength));
524
+ }
525
+ }
526
+ /**
527
+ * Because we prefer positions in the text nodes over positions next to text nodes, if the view position was next to a text node,
528
+ * it moves it into the text node instead.
529
+ *
530
+ * <p>[]<b>foo</b></p> -> <p>[]<b>foo</b></p> // do not touch if position is not directly next to text
531
+ * <p>foo[]<b>foo</b></p> -> <p>foo{}<b>foo</b></p> // move to text node
532
+ * <p><b>[]foo</b></p> -> <p><b>{}foo</b></p> // move to text node
533
+ *
534
+ * @private
535
+ * @param {module:engine/view/position~Position} viewPosition Position potentially next to the text node.
536
+ * @returns {module:engine/view/position~Position} Position in the text node if possible.
537
+ */
538
+ _moveViewPositionToTextNode(viewPosition) {
539
+ // If the position is just after a text node, put it at the end of that text node.
540
+ // If the position is just before a text node, put it at the beginning of that text node.
541
+ const nodeBefore = viewPosition.nodeBefore;
542
+ const nodeAfter = viewPosition.nodeAfter;
543
+ if (nodeBefore instanceof ViewText) {
544
+ return new ViewPosition(nodeBefore, nodeBefore.data.length);
545
+ }
546
+ else if (nodeAfter instanceof ViewText) {
547
+ return new ViewPosition(nodeAfter, 0);
548
+ }
549
+ // Otherwise, just return the given position.
550
+ return viewPosition;
551
+ }
739
552
  }
740
-
741
- mix( Mapper, EmitterMixin );