@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,31 +2,23 @@
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
- /* globals Node */
7
-
8
5
  /**
9
6
  * @module engine/view/renderer
10
7
  */
11
-
12
8
  import ViewText from './text';
13
9
  import ViewPosition from './position';
14
10
  import { INLINE_FILLER, INLINE_FILLER_LENGTH, startsWithFiller, isInlineFiller } from './filler';
15
-
16
- import mix from '@ckeditor/ckeditor5-utils/src/mix';
17
- import diff from '@ckeditor/ckeditor5-utils/src/diff';
11
+ import { default as diff } from '@ckeditor/ckeditor5-utils/src/diff';
18
12
  import insertAt from '@ckeditor/ckeditor5-utils/src/dom/insertat';
19
13
  import remove from '@ckeditor/ckeditor5-utils/src/dom/remove';
20
- import ObservableMixin from '@ckeditor/ckeditor5-utils/src/observablemixin';
14
+ import { Observable } from '@ckeditor/ckeditor5-utils/src/observablemixin';
21
15
  import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
22
16
  import isText from '@ckeditor/ckeditor5-utils/src/dom/istext';
23
17
  import isComment from '@ckeditor/ckeditor5-utils/src/dom/iscomment';
24
18
  import isNode from '@ckeditor/ckeditor5-utils/src/dom/isnode';
25
19
  import fastDiff from '@ckeditor/ckeditor5-utils/src/fastdiff';
26
20
  import env from '@ckeditor/ckeditor5-utils/src/env';
27
-
28
21
  import '../../theme/renderer.css';
29
-
30
22
  /**
31
23
  * Renderer is responsible for updating the DOM structure and the DOM selection based on
32
24
  * the {@link module:engine/view/renderer~Renderer#markToSync information about updated view nodes}.
@@ -40,919 +32,806 @@ import '../../theme/renderer.css';
40
32
  * Renderer uses {@link module:engine/view/domconverter~DomConverter} to transform view nodes and positions
41
33
  * to and from the DOM.
42
34
  */
43
- export default class Renderer {
44
- /**
45
- * Creates a renderer instance.
46
- *
47
- * @param {module:engine/view/domconverter~DomConverter} domConverter Converter instance.
48
- * @param {module:engine/view/documentselection~DocumentSelection} selection View selection.
49
- */
50
- constructor( domConverter, selection ) {
51
- /**
52
- * Set of DOM Documents instances.
53
- *
54
- * @readonly
55
- * @member {Set.<Document>}
56
- */
57
- this.domDocuments = new Set();
58
-
59
- /**
60
- * Converter instance.
61
- *
62
- * @readonly
63
- * @member {module:engine/view/domconverter~DomConverter}
64
- */
65
- this.domConverter = domConverter;
66
-
67
- /**
68
- * Set of nodes which attributes changed and may need to be rendered.
69
- *
70
- * @readonly
71
- * @member {Set.<module:engine/view/node~Node>}
72
- */
73
- this.markedAttributes = new Set();
74
-
75
- /**
76
- * Set of elements which child lists changed and may need to be rendered.
77
- *
78
- * @readonly
79
- * @member {Set.<module:engine/view/node~Node>}
80
- */
81
- this.markedChildren = new Set();
82
-
83
- /**
84
- * Set of text nodes which text data changed and may need to be rendered.
85
- *
86
- * @readonly
87
- * @member {Set.<module:engine/view/node~Node>}
88
- */
89
- this.markedTexts = new Set();
90
-
91
- /**
92
- * View selection. Renderer updates DOM selection based on the view selection.
93
- *
94
- * @readonly
95
- * @member {module:engine/view/documentselection~DocumentSelection}
96
- */
97
- this.selection = selection;
98
-
99
- /**
100
- * Indicates if the view document is focused and selection can be rendered. Selection will not be rendered if
101
- * this is set to `false`.
102
- *
103
- * @member {Boolean}
104
- * @observable
105
- */
106
- this.set( 'isFocused', false );
107
-
108
- /**
109
- * Indicates whether the user is making a selection in the document (e.g. holding the mouse button and moving the cursor).
110
- * When they stop selecting, the property goes back to `false`.
111
- *
112
- * Note: In some browsers, the renderer will stop rendering the selection and inline fillers while the user is making
113
- * a selection to avoid glitches in DOM selection
114
- * (https://github.com/ckeditor/ckeditor5/issues/10562, https://github.com/ckeditor/ckeditor5/issues/10723).
115
- *
116
- * @member {Boolean}
117
- * @observable
118
- */
119
- this.set( 'isSelecting', false );
120
-
121
- // Rendering the selection and inline filler manipulation should be postponed in (non-Android) Blink until the user finishes
122
- // creating the selection in DOM to avoid accidental selection collapsing
123
- // (https://github.com/ckeditor/ckeditor5/issues/10562, https://github.com/ckeditor/ckeditor5/issues/10723).
124
- // When the user stops selecting, all pending changes should be rendered ASAP, though.
125
- if ( env.isBlink && !env.isAndroid ) {
126
- this.on( 'change:isSelecting', () => {
127
- if ( !this.isSelecting ) {
128
- this.render();
129
- }
130
- } );
131
- }
132
-
133
- /**
134
- * The text node in which the inline filler was rendered.
135
- *
136
- * @private
137
- * @member {Text}
138
- */
139
- this._inlineFiller = null;
140
-
141
- /**
142
- * DOM element containing fake selection.
143
- *
144
- * @private
145
- * @type {null|HTMLElement}
146
- */
147
- this._fakeSelectionContainer = null;
148
- }
149
-
150
- /**
151
- * Marks a view node to be updated in the DOM by {@link #render `render()`}.
152
- *
153
- * Note that only view nodes whose parents have corresponding DOM elements need to be marked to be synchronized.
154
- *
155
- * @see #markedAttributes
156
- * @see #markedChildren
157
- * @see #markedTexts
158
- *
159
- * @param {module:engine/view/document~ChangeType} type Type of the change.
160
- * @param {module:engine/view/node~Node} node Node to be marked.
161
- */
162
- markToSync( type, node ) {
163
- if ( type === 'text' ) {
164
- if ( this.domConverter.mapViewToDom( node.parent ) ) {
165
- this.markedTexts.add( node );
166
- }
167
- } else {
168
- // If the node has no DOM element it is not rendered yet,
169
- // its children/attributes do not need to be marked to be sync.
170
- if ( !this.domConverter.mapViewToDom( node ) ) {
171
- return;
172
- }
173
-
174
- if ( type === 'attributes' ) {
175
- this.markedAttributes.add( node );
176
- } else if ( type === 'children' ) {
177
- this.markedChildren.add( node );
178
- } else {
179
- /**
180
- * Unknown type passed to Renderer.markToSync.
181
- *
182
- * @error view-renderer-unknown-type
183
- */
184
- throw new CKEditorError( 'view-renderer-unknown-type', this );
185
- }
186
- }
187
- }
188
-
189
- /**
190
- * Renders all buffered changes ({@link #markedAttributes}, {@link #markedChildren} and {@link #markedTexts}) and
191
- * the current view selection (if needed) to the DOM by applying a minimal set of changes to it.
192
- *
193
- * Renderer tries not to break the text composition (e.g. IME) and x-index of the selection,
194
- * so it does as little as it is needed to update the DOM.
195
- *
196
- * Renderer also handles {@link module:engine/view/filler fillers}. Especially, it checks if the inline filler is needed
197
- * at the selection position and adds or removes it. To prevent breaking text composition inline filler will not be
198
- * removed as long as the selection is in the text node which needed it at first.
199
- */
200
- render() {
201
- let inlineFillerPosition;
202
- const isInlineFillerRenderingPossible = env.isBlink && !env.isAndroid ? !this.isSelecting : true;
203
-
204
- // Refresh mappings.
205
- for ( const element of this.markedChildren ) {
206
- this._updateChildrenMappings( element );
207
- }
208
-
209
- // Don't manipulate inline fillers while the selection is being made in (non-Android) Blink to prevent accidental
210
- // DOM selection collapsing
211
- // (https://github.com/ckeditor/ckeditor5/issues/10562, https://github.com/ckeditor/ckeditor5/issues/10723).
212
- if ( isInlineFillerRenderingPossible ) {
213
- // There was inline filler rendered in the DOM but it's not
214
- // at the selection position any more, so we can remove it
215
- // (cause even if it's needed, it must be placed in another location).
216
- if ( this._inlineFiller && !this._isSelectionInInlineFiller() ) {
217
- this._removeInlineFiller();
218
- }
219
-
220
- // If we've got the filler, let's try to guess its position in the view.
221
- if ( this._inlineFiller ) {
222
- inlineFillerPosition = this._getInlineFillerPosition();
223
- }
224
- // Otherwise, if it's needed, create it at the selection position.
225
- else if ( this._needsInlineFillerAtSelection() ) {
226
- inlineFillerPosition = this.selection.getFirstPosition();
227
-
228
- // Do not use `markToSync` so it will be added even if the parent is already added.
229
- this.markedChildren.add( inlineFillerPosition.parent );
230
- }
231
- }
232
- // Paranoid check: we make sure the inline filler has any parent so it can be mapped to view position
233
- // by DomConverter.
234
- else if ( this._inlineFiller && this._inlineFiller.parentNode ) {
235
- // While the user is making selection, preserve the inline filler at its original position.
236
- inlineFillerPosition = this.domConverter.domPositionToView( this._inlineFiller );
237
-
238
- if ( inlineFillerPosition.parent.is( '$text' ) ) {
239
- inlineFillerPosition = ViewPosition._createBefore( inlineFillerPosition.parent );
240
- }
241
- }
242
-
243
- for ( const element of this.markedAttributes ) {
244
- this._updateAttrs( element );
245
- }
246
-
247
- for ( const element of this.markedChildren ) {
248
- this._updateChildren( element, { inlineFillerPosition } );
249
- }
250
-
251
- for ( const node of this.markedTexts ) {
252
- if ( !this.markedChildren.has( node.parent ) && this.domConverter.mapViewToDom( node.parent ) ) {
253
- this._updateText( node, { inlineFillerPosition } );
254
- }
255
- }
256
-
257
- // * Check whether the inline filler is required and where it really is in the DOM.
258
- // At this point in most cases it will be in the DOM, but there are exceptions.
259
- // For example, if the inline filler was deep in the created DOM structure, it will not be created.
260
- // Similarly, if it was removed at the beginning of this function and then neither text nor children were updated,
261
- // it will not be present. Fix those and similar scenarios.
262
- // * Don't manipulate inline fillers while the selection is being made in (non-Android) Blink to prevent accidental
263
- // DOM selection collapsing
264
- // (https://github.com/ckeditor/ckeditor5/issues/10562, https://github.com/ckeditor/ckeditor5/issues/10723).
265
- if ( isInlineFillerRenderingPossible ) {
266
- if ( inlineFillerPosition ) {
267
- const fillerDomPosition = this.domConverter.viewPositionToDom( inlineFillerPosition );
268
- const domDocument = fillerDomPosition.parent.ownerDocument;
269
-
270
- if ( !startsWithFiller( fillerDomPosition.parent ) ) {
271
- // Filler has not been created at filler position. Create it now.
272
- this._inlineFiller = addInlineFiller( domDocument, fillerDomPosition.parent, fillerDomPosition.offset );
273
- } else {
274
- // Filler has been found, save it.
275
- this._inlineFiller = fillerDomPosition.parent;
276
- }
277
- } else {
278
- // There is no filler needed.
279
- this._inlineFiller = null;
280
- }
281
- }
282
-
283
- // First focus the new editing host, then update the selection.
284
- // Otherwise, FF may throw an error (https://github.com/ckeditor/ckeditor5/issues/721).
285
- this._updateFocus();
286
- this._updateSelection();
287
-
288
- this.markedTexts.clear();
289
- this.markedAttributes.clear();
290
- this.markedChildren.clear();
291
- }
292
-
293
- /**
294
- * Updates mappings of view element's children.
295
- *
296
- * Children that were replaced in the view structure by similar elements (same tag name) are treated as 'replaced'.
297
- * This means that their mappings can be updated so the new view elements are mapped to the existing DOM elements.
298
- * Thanks to that these elements do not need to be re-rendered completely.
299
- *
300
- * @private
301
- * @param {module:engine/view/node~Node} viewElement The view element whose children mappings will be updated.
302
- */
303
- _updateChildrenMappings( viewElement ) {
304
- const domElement = this.domConverter.mapViewToDom( viewElement );
305
-
306
- if ( !domElement ) {
307
- // If there is no `domElement` it means that it was already removed from DOM and there is no need to process it.
308
- return;
309
- }
310
-
311
- // Removing nodes from the DOM as we iterate can cause `actualDomChildren`
312
- // (which is a live-updating `NodeList`) to get out of sync with the
313
- // indices that we compute as we iterate over `actions`.
314
- // This would produce incorrect element mappings.
315
- //
316
- // Converting live list to an array to make the list static.
317
- const actualDomChildren = Array.from(
318
- this.domConverter.mapViewToDom( viewElement ).childNodes
319
- );
320
- const expectedDomChildren = Array.from(
321
- this.domConverter.viewChildrenToDom( viewElement, domElement.ownerDocument, { withChildren: false } )
322
- );
323
- const diff = this._diffNodeLists( actualDomChildren, expectedDomChildren );
324
- const actions = this._findReplaceActions( diff, actualDomChildren, expectedDomChildren );
325
-
326
- if ( actions.indexOf( 'replace' ) !== -1 ) {
327
- const counter = { equal: 0, insert: 0, delete: 0 };
328
-
329
- for ( const action of actions ) {
330
- if ( action === 'replace' ) {
331
- const insertIndex = counter.equal + counter.insert;
332
- const deleteIndex = counter.equal + counter.delete;
333
- const viewChild = viewElement.getChild( insertIndex );
334
-
335
- // UIElement and RawElement are special cases. Their children are not stored in a view (#799)
336
- // so we cannot use them with replacing flow (since they use view children during rendering
337
- // which will always result in rendering empty elements).
338
- if ( viewChild && !( viewChild.is( 'uiElement' ) || viewChild.is( 'rawElement' ) ) ) {
339
- this._updateElementMappings( viewChild, actualDomChildren[ deleteIndex ] );
340
- }
341
-
342
- remove( expectedDomChildren[ insertIndex ] );
343
- counter.equal++;
344
- } else {
345
- counter[ action ]++;
346
- }
347
- }
348
- }
349
- }
350
-
351
- /**
352
- * Updates mappings of a given view element.
353
- *
354
- * @private
355
- * @param {module:engine/view/node~Node} viewElement The view element whose mappings will be updated.
356
- * @param {Node} domElement The DOM element representing the given view element.
357
- */
358
- _updateElementMappings( viewElement, domElement ) {
359
- // Remap 'DomConverter' bindings.
360
- this.domConverter.unbindDomElement( domElement );
361
- this.domConverter.bindElements( domElement, viewElement );
362
-
363
- // View element may have children which needs to be updated, but are not marked, mark them to update.
364
- this.markedChildren.add( viewElement );
365
-
366
- // Because we replace new view element mapping with the existing one, the corresponding DOM element
367
- // will not be rerendered. The new view element may have different attributes than the previous one.
368
- // Since its corresponding DOM element will not be rerendered, new attributes will not be added
369
- // to the DOM, so we need to mark it here to make sure its attributes gets updated. See #1427 for more
370
- // detailed case study.
371
- // Also there are cases where replaced element is removed from the view structure and then has
372
- // its attributes changed or removed. In such cases the element will not be present in `markedAttributes`
373
- // and also may be the same (`element.isSimilar()`) as the reused element not having its attributes updated.
374
- // To prevent such situations we always mark reused element to have its attributes rerenderd (#1560).
375
- this.markedAttributes.add( viewElement );
376
- }
377
-
378
- /**
379
- * Gets the position of the inline filler based on the current selection.
380
- * Here, we assume that we know that the filler is needed and
381
- * {@link #_isSelectionInInlineFiller is at the selection position}, and, since it is needed,
382
- * it is somewhere at the selection position.
383
- *
384
- * Note: The filler position cannot be restored based on the filler's DOM text node, because
385
- * when this method is called (before rendering), the bindings will often be broken. View-to-DOM
386
- * bindings are only dependable after rendering.
387
- *
388
- * @private
389
- * @returns {module:engine/view/position~Position}
390
- */
391
- _getInlineFillerPosition() {
392
- const firstPos = this.selection.getFirstPosition();
393
-
394
- if ( firstPos.parent.is( '$text' ) ) {
395
- return ViewPosition._createBefore( this.selection.getFirstPosition().parent );
396
- } else {
397
- return firstPos;
398
- }
399
- }
400
-
401
- /**
402
- * Returns `true` if the selection has not left the inline filler's text node.
403
- * If it is `true`, it means that the filler had been added for a reason and the selection did not
404
- * leave the filler's text node. For example, the user can be in the middle of a composition so it should not be touched.
405
- *
406
- * @private
407
- * @returns {Boolean} `true` if the inline filler and selection are in the same place.
408
- */
409
- _isSelectionInInlineFiller() {
410
- if ( this.selection.rangeCount != 1 || !this.selection.isCollapsed ) {
411
- return false;
412
- }
413
-
414
- // Note, we can't check if selection's position equals position of the
415
- // this._inlineFiller node, because of #663. We may not be able to calculate
416
- // the filler's position in the view at this stage.
417
- // Instead, we check it the other way – whether selection is anchored in
418
- // that text node or next to it.
419
-
420
- // Possible options are:
421
- // "FILLER{}"
422
- // "FILLERadded-text{}"
423
- const selectionPosition = this.selection.getFirstPosition();
424
- const position = this.domConverter.viewPositionToDom( selectionPosition );
425
-
426
- if ( position && isText( position.parent ) && startsWithFiller( position.parent ) ) {
427
- return true;
428
- }
429
-
430
- return false;
431
- }
432
-
433
- /**
434
- * Removes the inline filler.
435
- *
436
- * @private
437
- */
438
- _removeInlineFiller() {
439
- const domFillerNode = this._inlineFiller;
440
-
441
- // Something weird happened and the stored node doesn't contain the filler's text.
442
- if ( !startsWithFiller( domFillerNode ) ) {
443
- /**
444
- * The inline filler node was lost. Most likely, something overwrote the filler text node
445
- * in the DOM.
446
- *
447
- * @error view-renderer-filler-was-lost
448
- */
449
- throw new CKEditorError( 'view-renderer-filler-was-lost', this );
450
- }
451
-
452
- if ( isInlineFiller( domFillerNode ) ) {
453
- domFillerNode.remove();
454
- } else {
455
- domFillerNode.data = domFillerNode.data.substr( INLINE_FILLER_LENGTH );
456
- }
457
-
458
- this._inlineFiller = null;
459
- }
460
-
461
- /**
462
- * Checks if the inline {@link module:engine/view/filler filler} should be added.
463
- *
464
- * @private
465
- * @returns {Boolean} `true` if the inline filler should be added.
466
- */
467
- _needsInlineFillerAtSelection() {
468
- if ( this.selection.rangeCount != 1 || !this.selection.isCollapsed ) {
469
- return false;
470
- }
471
-
472
- const selectionPosition = this.selection.getFirstPosition();
473
- const selectionParent = selectionPosition.parent;
474
- const selectionOffset = selectionPosition.offset;
475
-
476
- // If there is no DOM root we do not care about fillers.
477
- if ( !this.domConverter.mapViewToDom( selectionParent.root ) ) {
478
- return false;
479
- }
480
-
481
- if ( !( selectionParent.is( 'element' ) ) ) {
482
- return false;
483
- }
484
-
485
- // Prevent adding inline filler inside elements with contenteditable=false.
486
- // https://github.com/ckeditor/ckeditor5-engine/issues/1170
487
- if ( !isEditable( selectionParent ) ) {
488
- return false;
489
- }
490
-
491
- // We have block filler, we do not need inline one.
492
- if ( selectionOffset === selectionParent.getFillerOffset() ) {
493
- return false;
494
- }
495
-
496
- const nodeBefore = selectionPosition.nodeBefore;
497
- const nodeAfter = selectionPosition.nodeAfter;
498
-
499
- if ( nodeBefore instanceof ViewText || nodeAfter instanceof ViewText ) {
500
- return false;
501
- }
502
-
503
- return true;
504
- }
505
-
506
- /**
507
- * Checks if text needs to be updated and possibly updates it.
508
- *
509
- * @private
510
- * @param {module:engine/view/text~Text} viewText View text to update.
511
- * @param {Object} options
512
- * @param {module:engine/view/position~Position} options.inlineFillerPosition The position where the inline
513
- * filler should be rendered.
514
- */
515
- _updateText( viewText, options ) {
516
- const domText = this.domConverter.findCorrespondingDomText( viewText );
517
- const newDomText = this.domConverter.viewToDom( viewText, domText.ownerDocument );
518
-
519
- const actualText = domText.data;
520
- let expectedText = newDomText.data;
521
-
522
- const filler = options.inlineFillerPosition;
523
-
524
- if ( filler && filler.parent == viewText.parent && filler.offset == viewText.index ) {
525
- expectedText = INLINE_FILLER + expectedText;
526
- }
527
-
528
- if ( actualText != expectedText ) {
529
- const actions = fastDiff( actualText, expectedText );
530
-
531
- for ( const action of actions ) {
532
- if ( action.type === 'insert' ) {
533
- domText.insertData( action.index, action.values.join( '' ) );
534
- } else { // 'delete'
535
- domText.deleteData( action.index, action.howMany );
536
- }
537
- }
538
- }
539
- }
540
-
541
- /**
542
- * Checks if attribute list needs to be updated and possibly updates it.
543
- *
544
- * @private
545
- * @param {module:engine/view/element~Element} viewElement The view element to update.
546
- */
547
- _updateAttrs( viewElement ) {
548
- const domElement = this.domConverter.mapViewToDom( viewElement );
549
-
550
- if ( !domElement ) {
551
- // If there is no `domElement` it means that 'viewElement' is outdated as its mapping was updated
552
- // in 'this._updateChildrenMappings()'. There is no need to process it as new view element which
553
- // replaced old 'viewElement' mapping was also added to 'this.markedAttributes'
554
- // in 'this._updateChildrenMappings()' so it will be processed separately.
555
- return;
556
- }
557
-
558
- const domAttrKeys = Array.from( domElement.attributes ).map( attr => attr.name );
559
- const viewAttrKeys = viewElement.getAttributeKeys();
560
-
561
- // Add or overwrite attributes.
562
- for ( const key of viewAttrKeys ) {
563
- this.domConverter.setDomElementAttribute( domElement, key, viewElement.getAttribute( key ), viewElement );
564
- }
565
-
566
- // Remove from DOM attributes which do not exists in the view.
567
- for ( const key of domAttrKeys ) {
568
- // All other attributes not present in the DOM should be removed.
569
- if ( !viewElement.hasAttribute( key ) ) {
570
- this.domConverter.removeDomElementAttribute( domElement, key );
571
- }
572
- }
573
- }
574
-
575
- /**
576
- * Checks if elements child list needs to be updated and possibly updates it.
577
- *
578
- * @private
579
- * @param {module:engine/view/element~Element} viewElement View element to update.
580
- * @param {Object} options
581
- * @param {module:engine/view/position~Position} options.inlineFillerPosition The position where the inline
582
- * filler should be rendered.
583
- */
584
- _updateChildren( viewElement, options ) {
585
- const domElement = this.domConverter.mapViewToDom( viewElement );
586
-
587
- if ( !domElement ) {
588
- // If there is no `domElement` it means that it was already removed from DOM.
589
- // There is no need to process it. It will be processed when re-inserted.
590
- return;
591
- }
592
-
593
- const inlineFillerPosition = options.inlineFillerPosition;
594
- const actualDomChildren = this.domConverter.mapViewToDom( viewElement ).childNodes;
595
- const expectedDomChildren = Array.from(
596
- this.domConverter.viewChildrenToDom( viewElement, domElement.ownerDocument, { bind: true } )
597
- );
598
-
599
- // Inline filler element has to be created as it is present in the DOM, but not in the view. It is required
600
- // during diffing so text nodes could be compared correctly and also during rendering to maintain
601
- // proper order and indexes while updating the DOM.
602
- if ( inlineFillerPosition && inlineFillerPosition.parent === viewElement ) {
603
- addInlineFiller( domElement.ownerDocument, expectedDomChildren, inlineFillerPosition.offset );
604
- }
605
-
606
- const diff = this._diffNodeLists( actualDomChildren, expectedDomChildren );
607
-
608
- let i = 0;
609
- const nodesToUnbind = new Set();
610
-
611
- // Handle deletions first.
612
- // This is to prevent a situation where an element that already exists in `actualDomChildren` is inserted at a different
613
- // index in `actualDomChildren`. Since `actualDomChildren` is a `NodeList`, this works like move, not like an insert,
614
- // and it disrupts the whole algorithm. See https://github.com/ckeditor/ckeditor5/issues/6367.
615
- //
616
- // It doesn't matter in what order we remove or add nodes, as long as we remove and add correct nodes at correct indexes.
617
- for ( const action of diff ) {
618
- if ( action === 'delete' ) {
619
- nodesToUnbind.add( actualDomChildren[ i ] );
620
- remove( actualDomChildren[ i ] );
621
- } else if ( action === 'equal' ) {
622
- i++;
623
- }
624
- }
625
-
626
- i = 0;
627
-
628
- for ( const action of diff ) {
629
- if ( action === 'insert' ) {
630
- insertAt( domElement, i, expectedDomChildren[ i ] );
631
- i++;
632
- } else if ( action === 'equal' ) {
633
- // Force updating text nodes inside elements which did not change and do not need to be re-rendered (#1125).
634
- // Do it here (not in the loop above) because only after insertions the `i` index is correct.
635
- this._markDescendantTextToSync( this.domConverter.domToView( expectedDomChildren[ i ] ) );
636
- i++;
637
- }
638
- }
639
-
640
- // Unbind removed nodes. When node does not have a parent it means that it was removed from DOM tree during
641
- // comparison with the expected DOM. We don't need to check child nodes, because if child node was reinserted,
642
- // it was moved to DOM tree out of the removed node.
643
- for ( const node of nodesToUnbind ) {
644
- if ( !node.parentNode ) {
645
- this.domConverter.unbindDomElement( node );
646
- }
647
- }
648
- }
649
-
650
- /**
651
- * Shorthand for diffing two arrays or node lists of DOM nodes.
652
- *
653
- * @private
654
- * @param {Array.<Node>|NodeList} actualDomChildren Actual DOM children
655
- * @param {Array.<Node>|NodeList} expectedDomChildren Expected DOM children.
656
- * @returns {Array.<String>} The list of actions based on the {@link module:utils/diff~diff} function.
657
- */
658
- _diffNodeLists( actualDomChildren, expectedDomChildren ) {
659
- actualDomChildren = filterOutFakeSelectionContainer( actualDomChildren, this._fakeSelectionContainer );
660
-
661
- return diff( actualDomChildren, expectedDomChildren, sameNodes.bind( null, this.domConverter ) );
662
- }
663
-
664
- /**
665
- * Finds DOM nodes that were replaced with the similar nodes (same tag name) in the view. All nodes are compared
666
- * within one `insert`/`delete` action group, for example:
667
- *
668
- * Actual DOM: <p><b>Foo</b>Bar<i>Baz</i><b>Bax</b></p>
669
- * Expected DOM: <p>Bar<b>123</b><i>Baz</i><b>456</b></p>
670
- * Input actions: [ insert, insert, delete, delete, equal, insert, delete ]
671
- * Output actions: [ insert, replace, delete, equal, replace ]
672
- *
673
- * @private
674
- * @param {Array.<String>} actions Actions array which is a result of the {@link module:utils/diff~diff} function.
675
- * @param {Array.<Node>|NodeList} actualDom Actual DOM children
676
- * @param {Array.<Node>} expectedDom Expected DOM children.
677
- * @returns {Array.<String>} Actions array modified with the `replace` actions.
678
- */
679
- _findReplaceActions( actions, actualDom, expectedDom ) {
680
- // If there is no both 'insert' and 'delete' actions, no need to check for replaced elements.
681
- if ( actions.indexOf( 'insert' ) === -1 || actions.indexOf( 'delete' ) === -1 ) {
682
- return actions;
683
- }
684
-
685
- let newActions = [];
686
- let actualSlice = [];
687
- let expectedSlice = [];
688
-
689
- const counter = { equal: 0, insert: 0, delete: 0 };
690
-
691
- for ( const action of actions ) {
692
- if ( action === 'insert' ) {
693
- expectedSlice.push( expectedDom[ counter.equal + counter.insert ] );
694
- } else if ( action === 'delete' ) {
695
- actualSlice.push( actualDom[ counter.equal + counter.delete ] );
696
- } else { // equal
697
- newActions = newActions.concat( diff( actualSlice, expectedSlice, areSimilar ).map( x => x === 'equal' ? 'replace' : x ) );
698
- newActions.push( 'equal' );
699
- // Reset stored elements on 'equal'.
700
- actualSlice = [];
701
- expectedSlice = [];
702
- }
703
- counter[ action ]++;
704
- }
705
-
706
- return newActions.concat( diff( actualSlice, expectedSlice, areSimilar ).map( x => x === 'equal' ? 'replace' : x ) );
707
- }
708
-
709
- /**
710
- * Marks text nodes to be synchronized.
711
- *
712
- * If a text node is passed, it will be marked. If an element is passed, all descendant text nodes inside it will be marked.
713
- *
714
- * @private
715
- * @param {module:engine/view/node~Node} viewNode View node to sync.
716
- */
717
- _markDescendantTextToSync( viewNode ) {
718
- if ( !viewNode ) {
719
- return;
720
- }
721
-
722
- if ( viewNode.is( '$text' ) ) {
723
- this.markedTexts.add( viewNode );
724
- } else if ( viewNode.is( 'element' ) ) {
725
- for ( const child of viewNode.getChildren() ) {
726
- this._markDescendantTextToSync( child );
727
- }
728
- }
729
- }
730
-
731
- /**
732
- * Checks if the selection needs to be updated and possibly updates it.
733
- *
734
- * @private
735
- */
736
- _updateSelection() {
737
- // Block updating DOM selection in (non-Android) Blink while the user is selecting to prevent accidental selection collapsing.
738
- // Note: Structural changes in DOM must trigger selection rendering, though. Nodes the selection was anchored
739
- // to, may disappear in DOM which would break the selection (e.g. in real-time collaboration scenarios).
740
- // https://github.com/ckeditor/ckeditor5/issues/10562, https://github.com/ckeditor/ckeditor5/issues/10723
741
- if ( env.isBlink && !env.isAndroid && this.isSelecting && !this.markedChildren.size ) {
742
- return;
743
- }
744
-
745
- // If there is no selection - remove DOM and fake selections.
746
- if ( this.selection.rangeCount === 0 ) {
747
- this._removeDomSelection();
748
- this._removeFakeSelection();
749
-
750
- return;
751
- }
752
-
753
- const domRoot = this.domConverter.mapViewToDom( this.selection.editableElement );
754
-
755
- // Do nothing if there is no focus, or there is no DOM element corresponding to selection's editable element.
756
- if ( !this.isFocused || !domRoot ) {
757
- return;
758
- }
759
-
760
- // Render selection.
761
- if ( this.selection.isFake ) {
762
- this._updateFakeSelection( domRoot );
763
- } else {
764
- this._removeFakeSelection();
765
- this._updateDomSelection( domRoot );
766
- }
767
- }
768
-
769
- /**
770
- * Updates the fake selection.
771
- *
772
- * @private
773
- * @param {HTMLElement} domRoot A valid DOM root where the fake selection container should be added.
774
- */
775
- _updateFakeSelection( domRoot ) {
776
- const domDocument = domRoot.ownerDocument;
777
-
778
- if ( !this._fakeSelectionContainer ) {
779
- this._fakeSelectionContainer = createFakeSelectionContainer( domDocument );
780
- }
781
-
782
- const container = this._fakeSelectionContainer;
783
-
784
- // Bind fake selection container with the current selection *position*.
785
- this.domConverter.bindFakeSelection( container, this.selection );
786
-
787
- if ( !this._fakeSelectionNeedsUpdate( domRoot ) ) {
788
- return;
789
- }
790
-
791
- if ( !container.parentElement || container.parentElement != domRoot ) {
792
- domRoot.appendChild( container );
793
- }
794
-
795
- container.textContent = this.selection.fakeSelectionLabel || '\u00A0';
796
-
797
- const domSelection = domDocument.getSelection();
798
- const domRange = domDocument.createRange();
799
-
800
- domSelection.removeAllRanges();
801
- domRange.selectNodeContents( container );
802
- domSelection.addRange( domRange );
803
- }
804
-
805
- /**
806
- * Updates the DOM selection.
807
- *
808
- * @private
809
- * @param {HTMLElement} domRoot A valid DOM root where the DOM selection should be rendered.
810
- */
811
- _updateDomSelection( domRoot ) {
812
- const domSelection = domRoot.ownerDocument.defaultView.getSelection();
813
-
814
- // Let's check whether DOM selection needs updating at all.
815
- if ( !this._domSelectionNeedsUpdate( domSelection ) ) {
816
- return;
817
- }
818
-
819
- // Multi-range selection is not available in most browsers, and, at least in Chrome, trying to
820
- // set such selection, that is not continuous, throws an error. Because of that, we will just use anchor
821
- // and focus of view selection.
822
- // Since we are not supporting multi-range selection, we also do not need to check if proper editable is
823
- // selected. If there is any editable selected, it is okay (editable is taken from selection anchor).
824
- const anchor = this.domConverter.viewPositionToDom( this.selection.anchor );
825
- const focus = this.domConverter.viewPositionToDom( this.selection.focus );
826
-
827
- domSelection.collapse( anchor.parent, anchor.offset );
828
- domSelection.extend( focus.parent, focus.offset );
829
-
830
- // Firefox–specific hack (https://github.com/ckeditor/ckeditor5-engine/issues/1439).
831
- if ( env.isGecko ) {
832
- fixGeckoSelectionAfterBr( focus, domSelection );
833
- }
834
- }
835
-
836
- /**
837
- * Checks whether a given DOM selection needs to be updated.
838
- *
839
- * @private
840
- * @param {Selection} domSelection The DOM selection to check.
841
- * @returns {Boolean}
842
- */
843
- _domSelectionNeedsUpdate( domSelection ) {
844
- if ( !this.domConverter.isDomSelectionCorrect( domSelection ) ) {
845
- // Current DOM selection is in incorrect position. We need to update it.
846
- return true;
847
- }
848
-
849
- const oldViewSelection = domSelection && this.domConverter.domSelectionToView( domSelection );
850
-
851
- if ( oldViewSelection && this.selection.isEqual( oldViewSelection ) ) {
852
- return false;
853
- }
854
-
855
- // If selection is not collapsed, it does not need to be updated if it is similar.
856
- if ( !this.selection.isCollapsed && this.selection.isSimilar( oldViewSelection ) ) {
857
- // Selection did not changed and is correct, do not update.
858
- return false;
859
- }
860
-
861
- // Selections are not similar.
862
- return true;
863
- }
864
-
865
- /**
866
- * Checks whether the fake selection needs to be updated.
867
- *
868
- * @private
869
- * @param {HTMLElement} domRoot A valid DOM root where a new fake selection container should be added.
870
- * @returns {Boolean}
871
- */
872
- _fakeSelectionNeedsUpdate( domRoot ) {
873
- const container = this._fakeSelectionContainer;
874
- const domSelection = domRoot.ownerDocument.getSelection();
875
-
876
- // Fake selection needs to be updated if there's no fake selection container, or the container currently sits
877
- // in a different root.
878
- if ( !container || container.parentElement !== domRoot ) {
879
- return true;
880
- }
881
-
882
- // Make sure that the selection actually is within the fake selection.
883
- if ( domSelection.anchorNode !== container && !container.contains( domSelection.anchorNode ) ) {
884
- return true;
885
- }
886
-
887
- return container.textContent !== this.selection.fakeSelectionLabel;
888
- }
889
-
890
- /**
891
- * Removes the DOM selection.
892
- *
893
- * @private
894
- */
895
- _removeDomSelection() {
896
- for ( const doc of this.domDocuments ) {
897
- const domSelection = doc.getSelection();
898
-
899
- if ( domSelection.rangeCount ) {
900
- const activeDomElement = doc.activeElement;
901
- const viewElement = this.domConverter.mapDomToView( activeDomElement );
902
-
903
- if ( activeDomElement && viewElement ) {
904
- doc.getSelection().removeAllRanges();
905
- }
906
- }
907
- }
908
- }
909
-
910
- /**
911
- * Removes the fake selection.
912
- *
913
- * @private
914
- */
915
- _removeFakeSelection() {
916
- const container = this._fakeSelectionContainer;
917
-
918
- if ( container ) {
919
- container.remove();
920
- }
921
- }
922
-
923
- /**
924
- * Checks if focus needs to be updated and possibly updates it.
925
- *
926
- * @private
927
- */
928
- _updateFocus() {
929
- if ( this.isFocused ) {
930
- const editable = this.selection.editableElement;
931
-
932
- if ( editable ) {
933
- this.domConverter.focus( editable );
934
- }
935
- }
936
- }
35
+ export default class Renderer extends Observable {
36
+ /**
37
+ * Creates a renderer instance.
38
+ *
39
+ * @param {module:engine/view/domconverter~DomConverter} domConverter Converter instance.
40
+ * @param {module:engine/view/documentselection~DocumentSelection} selection View selection.
41
+ */
42
+ constructor(domConverter, selection) {
43
+ super();
44
+ /**
45
+ * Set of DOM Documents instances.
46
+ *
47
+ * @readonly
48
+ * @member {Set.<Document>}
49
+ */
50
+ this.domDocuments = new Set();
51
+ /**
52
+ * Converter instance.
53
+ *
54
+ * @readonly
55
+ * @member {module:engine/view/domconverter~DomConverter}
56
+ */
57
+ this.domConverter = domConverter;
58
+ /**
59
+ * Set of nodes which attributes changed and may need to be rendered.
60
+ *
61
+ * @readonly
62
+ * @member {Set.<module:engine/view/node~ViewNode>}
63
+ */
64
+ this.markedAttributes = new Set();
65
+ /**
66
+ * Set of elements which child lists changed and may need to be rendered.
67
+ *
68
+ * @readonly
69
+ * @member {Set.<module:engine/view/node~ViewNode>}
70
+ */
71
+ this.markedChildren = new Set();
72
+ /**
73
+ * Set of text nodes which text data changed and may need to be rendered.
74
+ *
75
+ * @readonly
76
+ * @member {Set.<module:engine/view/node~ViewNode>}
77
+ */
78
+ this.markedTexts = new Set();
79
+ /**
80
+ * View selection. Renderer updates DOM selection based on the view selection.
81
+ *
82
+ * @readonly
83
+ * @member {module:engine/view/documentselection~DocumentSelection}
84
+ */
85
+ this.selection = selection;
86
+ /**
87
+ * Indicates if the view document is focused and selection can be rendered. Selection will not be rendered if
88
+ * this is set to `false`.
89
+ *
90
+ * @member {Boolean}
91
+ * @observable
92
+ */
93
+ this.set('isFocused', false);
94
+ /**
95
+ * Indicates whether the user is making a selection in the document (e.g. holding the mouse button and moving the cursor).
96
+ * When they stop selecting, the property goes back to `false`.
97
+ *
98
+ * Note: In some browsers, the renderer will stop rendering the selection and inline fillers while the user is making
99
+ * a selection to avoid glitches in DOM selection
100
+ * (https://github.com/ckeditor/ckeditor5/issues/10562, https://github.com/ckeditor/ckeditor5/issues/10723).
101
+ *
102
+ * @member {Boolean}
103
+ * @observable
104
+ */
105
+ this.set('isSelecting', false);
106
+ // Rendering the selection and inline filler manipulation should be postponed in (non-Android) Blink until the user finishes
107
+ // creating the selection in DOM to avoid accidental selection collapsing
108
+ // (https://github.com/ckeditor/ckeditor5/issues/10562, https://github.com/ckeditor/ckeditor5/issues/10723).
109
+ // When the user stops selecting, all pending changes should be rendered ASAP, though.
110
+ if (env.isBlink && !env.isAndroid) {
111
+ this.on('change:isSelecting', () => {
112
+ if (!this.isSelecting) {
113
+ this.render();
114
+ }
115
+ });
116
+ }
117
+ /**
118
+ * The text node in which the inline filler was rendered.
119
+ *
120
+ * @private
121
+ * @member {Text}
122
+ */
123
+ this._inlineFiller = null;
124
+ /**
125
+ * DOM element containing fake selection.
126
+ *
127
+ * @private
128
+ * @type {null|HTMLElement}
129
+ */
130
+ this._fakeSelectionContainer = null;
131
+ }
132
+ /**
133
+ * Marks a view node to be updated in the DOM by {@link #render `render()`}.
134
+ *
135
+ * Note that only view nodes whose parents have corresponding DOM elements need to be marked to be synchronized.
136
+ *
137
+ * @see #markedAttributes
138
+ * @see #markedChildren
139
+ * @see #markedTexts
140
+ *
141
+ * @param {module:engine/view/document~ChangeType} type Type of the change.
142
+ * @param {module:engine/view/node~ViewNode} node ViewNode to be marked.
143
+ */
144
+ markToSync(type, node) {
145
+ if (type === 'text') {
146
+ if (this.domConverter.mapViewToDom(node.parent)) {
147
+ this.markedTexts.add(node);
148
+ }
149
+ }
150
+ else {
151
+ // If the node has no DOM element it is not rendered yet,
152
+ // its children/attributes do not need to be marked to be sync.
153
+ if (!this.domConverter.mapViewToDom(node)) {
154
+ return;
155
+ }
156
+ if (type === 'attributes') {
157
+ this.markedAttributes.add(node);
158
+ }
159
+ else if (type === 'children') {
160
+ this.markedChildren.add(node);
161
+ }
162
+ else {
163
+ /**
164
+ * Unknown type passed to Renderer.markToSync.
165
+ *
166
+ * @error view-renderer-unknown-type
167
+ */
168
+ throw new CKEditorError('view-renderer-unknown-type', this);
169
+ }
170
+ }
171
+ }
172
+ /**
173
+ * Renders all buffered changes ({@link #markedAttributes}, {@link #markedChildren} and {@link #markedTexts}) and
174
+ * the current view selection (if needed) to the DOM by applying a minimal set of changes to it.
175
+ *
176
+ * Renderer tries not to break the text composition (e.g. IME) and x-index of the selection,
177
+ * so it does as little as it is needed to update the DOM.
178
+ *
179
+ * Renderer also handles {@link module:engine/view/filler fillers}. Especially, it checks if the inline filler is needed
180
+ * at the selection position and adds or removes it. To prevent breaking text composition inline filler will not be
181
+ * removed as long as the selection is in the text node which needed it at first.
182
+ */
183
+ render() {
184
+ let inlineFillerPosition = null;
185
+ const isInlineFillerRenderingPossible = env.isBlink && !env.isAndroid ? !this.isSelecting : true;
186
+ // Refresh mappings.
187
+ for (const element of this.markedChildren) {
188
+ this._updateChildrenMappings(element);
189
+ }
190
+ // Don't manipulate inline fillers while the selection is being made in (non-Android) Blink to prevent accidental
191
+ // DOM selection collapsing
192
+ // (https://github.com/ckeditor/ckeditor5/issues/10562, https://github.com/ckeditor/ckeditor5/issues/10723).
193
+ if (isInlineFillerRenderingPossible) {
194
+ // There was inline filler rendered in the DOM but it's not
195
+ // at the selection position any more, so we can remove it
196
+ // (cause even if it's needed, it must be placed in another location).
197
+ if (this._inlineFiller && !this._isSelectionInInlineFiller()) {
198
+ this._removeInlineFiller();
199
+ }
200
+ // If we've got the filler, let's try to guess its position in the view.
201
+ if (this._inlineFiller) {
202
+ inlineFillerPosition = this._getInlineFillerPosition();
203
+ }
204
+ // Otherwise, if it's needed, create it at the selection position.
205
+ else if (this._needsInlineFillerAtSelection()) {
206
+ inlineFillerPosition = this.selection.getFirstPosition();
207
+ // Do not use `markToSync` so it will be added even if the parent is already added.
208
+ this.markedChildren.add(inlineFillerPosition.parent);
209
+ }
210
+ }
211
+ // Make sure the inline filler has any parent, so it can be mapped to view position by DomConverter.
212
+ else if (this._inlineFiller && this._inlineFiller.parentNode) {
213
+ // While the user is making selection, preserve the inline filler at its original position.
214
+ inlineFillerPosition = this.domConverter.domPositionToView(this._inlineFiller);
215
+ // While down-casting the document selection attributes, all existing empty
216
+ // attribute elements (for selection position) are removed from the view and DOM,
217
+ // so make sure that we were able to map filler position.
218
+ // https://github.com/ckeditor/ckeditor5/issues/12026
219
+ if (inlineFillerPosition && inlineFillerPosition.parent.is('$text')) {
220
+ // The inline filler position is expected to be before the text node.
221
+ inlineFillerPosition = ViewPosition._createBefore(inlineFillerPosition.parent);
222
+ }
223
+ }
224
+ for (const element of this.markedAttributes) {
225
+ this._updateAttrs(element);
226
+ }
227
+ for (const element of this.markedChildren) {
228
+ this._updateChildren(element, { inlineFillerPosition });
229
+ }
230
+ for (const node of this.markedTexts) {
231
+ if (!this.markedChildren.has(node.parent) && this.domConverter.mapViewToDom(node.parent)) {
232
+ this._updateText(node, { inlineFillerPosition });
233
+ }
234
+ }
235
+ // * Check whether the inline filler is required and where it really is in the DOM.
236
+ // At this point in most cases it will be in the DOM, but there are exceptions.
237
+ // For example, if the inline filler was deep in the created DOM structure, it will not be created.
238
+ // Similarly, if it was removed at the beginning of this function and then neither text nor children were updated,
239
+ // it will not be present. Fix those and similar scenarios.
240
+ // * Don't manipulate inline fillers while the selection is being made in (non-Android) Blink to prevent accidental
241
+ // DOM selection collapsing
242
+ // (https://github.com/ckeditor/ckeditor5/issues/10562, https://github.com/ckeditor/ckeditor5/issues/10723).
243
+ if (isInlineFillerRenderingPossible) {
244
+ if (inlineFillerPosition) {
245
+ const fillerDomPosition = this.domConverter.viewPositionToDom(inlineFillerPosition);
246
+ const domDocument = fillerDomPosition.parent.ownerDocument;
247
+ if (!startsWithFiller(fillerDomPosition.parent)) {
248
+ // Filler has not been created at filler position. Create it now.
249
+ this._inlineFiller = addInlineFiller(domDocument, fillerDomPosition.parent, fillerDomPosition.offset);
250
+ }
251
+ else {
252
+ // Filler has been found, save it.
253
+ this._inlineFiller = fillerDomPosition.parent;
254
+ }
255
+ }
256
+ else {
257
+ // There is no filler needed.
258
+ this._inlineFiller = null;
259
+ }
260
+ }
261
+ // First focus the new editing host, then update the selection.
262
+ // Otherwise, FF may throw an error (https://github.com/ckeditor/ckeditor5/issues/721).
263
+ this._updateFocus();
264
+ this._updateSelection();
265
+ this.markedTexts.clear();
266
+ this.markedAttributes.clear();
267
+ this.markedChildren.clear();
268
+ }
269
+ /**
270
+ * Updates mappings of view element's children.
271
+ *
272
+ * Children that were replaced in the view structure by similar elements (same tag name) are treated as 'replaced'.
273
+ * This means that their mappings can be updated so the new view elements are mapped to the existing DOM elements.
274
+ * Thanks to that these elements do not need to be re-rendered completely.
275
+ *
276
+ * @private
277
+ * @param {module:engine/view/node~ViewNode} viewElement The view element whose children mappings will be updated.
278
+ */
279
+ _updateChildrenMappings(viewElement) {
280
+ const domElement = this.domConverter.mapViewToDom(viewElement);
281
+ if (!domElement) {
282
+ // If there is no `domElement` it means that it was already removed from DOM and there is no need to process it.
283
+ return;
284
+ }
285
+ // Removing nodes from the DOM as we iterate can cause `actualDomChildren`
286
+ // (which is a live-updating `NodeList`) to get out of sync with the
287
+ // indices that we compute as we iterate over `actions`.
288
+ // This would produce incorrect element mappings.
289
+ //
290
+ // Converting live list to an array to make the list static.
291
+ const actualDomChildren = Array.from(this.domConverter.mapViewToDom(viewElement).childNodes);
292
+ const expectedDomChildren = Array.from(this.domConverter.viewChildrenToDom(viewElement, { withChildren: false }));
293
+ const diff = this._diffNodeLists(actualDomChildren, expectedDomChildren);
294
+ const actions = this._findReplaceActions(diff, actualDomChildren, expectedDomChildren);
295
+ if (actions.indexOf('replace') !== -1) {
296
+ const counter = { equal: 0, insert: 0, delete: 0 };
297
+ for (const action of actions) {
298
+ if (action === 'replace') {
299
+ const insertIndex = counter.equal + counter.insert;
300
+ const deleteIndex = counter.equal + counter.delete;
301
+ const viewChild = viewElement.getChild(insertIndex);
302
+ // UIElement and RawElement are special cases. Their children are not stored in a view (#799)
303
+ // so we cannot use them with replacing flow (since they use view children during rendering
304
+ // which will always result in rendering empty elements).
305
+ if (viewChild && !(viewChild.is('uiElement') || viewChild.is('rawElement'))) {
306
+ this._updateElementMappings(viewChild, actualDomChildren[deleteIndex]);
307
+ }
308
+ remove(expectedDomChildren[insertIndex]);
309
+ counter.equal++;
310
+ }
311
+ else {
312
+ counter[action]++;
313
+ }
314
+ }
315
+ }
316
+ }
317
+ /**
318
+ * Updates mappings of a given view element.
319
+ *
320
+ * @private
321
+ * @param {module:engine/view/node~ViewNode} viewElement The view element whose mappings will be updated.
322
+ * @param {ViewNode} domElement The DOM element representing the given view element.
323
+ */
324
+ _updateElementMappings(viewElement, domElement) {
325
+ // Remap 'DomConverter' bindings.
326
+ this.domConverter.unbindDomElement(domElement);
327
+ this.domConverter.bindElements(domElement, viewElement);
328
+ // View element may have children which needs to be updated, but are not marked, mark them to update.
329
+ this.markedChildren.add(viewElement);
330
+ // Because we replace new view element mapping with the existing one, the corresponding DOM element
331
+ // will not be rerendered. The new view element may have different attributes than the previous one.
332
+ // Since its corresponding DOM element will not be rerendered, new attributes will not be added
333
+ // to the DOM, so we need to mark it here to make sure its attributes gets updated. See #1427 for more
334
+ // detailed case study.
335
+ // Also there are cases where replaced element is removed from the view structure and then has
336
+ // its attributes changed or removed. In such cases the element will not be present in `markedAttributes`
337
+ // and also may be the same (`element.isSimilar()`) as the reused element not having its attributes updated.
338
+ // To prevent such situations we always mark reused element to have its attributes rerenderd (#1560).
339
+ this.markedAttributes.add(viewElement);
340
+ }
341
+ /**
342
+ * Gets the position of the inline filler based on the current selection.
343
+ * Here, we assume that we know that the filler is needed and
344
+ * {@link #_isSelectionInInlineFiller is at the selection position}, and, since it is needed,
345
+ * it is somewhere at the selection position.
346
+ *
347
+ * Note: The filler position cannot be restored based on the filler's DOM text node, because
348
+ * when this method is called (before rendering), the bindings will often be broken. View-to-DOM
349
+ * bindings are only dependable after rendering.
350
+ *
351
+ * @private
352
+ * @returns {module:engine/view/position~Position}
353
+ */
354
+ _getInlineFillerPosition() {
355
+ const firstPos = this.selection.getFirstPosition();
356
+ if (firstPos.parent.is('$text')) {
357
+ return ViewPosition._createBefore(firstPos.parent);
358
+ }
359
+ else {
360
+ return firstPos;
361
+ }
362
+ }
363
+ /**
364
+ * Returns `true` if the selection has not left the inline filler's text node.
365
+ * If it is `true`, it means that the filler had been added for a reason and the selection did not
366
+ * leave the filler's text node. For example, the user can be in the middle of a composition so it should not be touched.
367
+ *
368
+ * @private
369
+ * @returns {Boolean} `true` if the inline filler and selection are in the same place.
370
+ */
371
+ _isSelectionInInlineFiller() {
372
+ if (this.selection.rangeCount != 1 || !this.selection.isCollapsed) {
373
+ return false;
374
+ }
375
+ // Note, we can't check if selection's position equals position of the
376
+ // this._inlineFiller node, because of #663. We may not be able to calculate
377
+ // the filler's position in the view at this stage.
378
+ // Instead, we check it the other way – whether selection is anchored in
379
+ // that text node or next to it.
380
+ // Possible options are:
381
+ // "FILLER{}"
382
+ // "FILLERadded-text{}"
383
+ const selectionPosition = this.selection.getFirstPosition();
384
+ const position = this.domConverter.viewPositionToDom(selectionPosition);
385
+ if (position && isText(position.parent) && startsWithFiller(position.parent)) {
386
+ return true;
387
+ }
388
+ return false;
389
+ }
390
+ /**
391
+ * Removes the inline filler.
392
+ *
393
+ * @private
394
+ */
395
+ _removeInlineFiller() {
396
+ const domFillerNode = this._inlineFiller;
397
+ // Something weird happened and the stored node doesn't contain the filler's text.
398
+ if (!startsWithFiller(domFillerNode)) {
399
+ /**
400
+ * The inline filler node was lost. Most likely, something overwrote the filler text node
401
+ * in the DOM.
402
+ *
403
+ * @error view-renderer-filler-was-lost
404
+ */
405
+ throw new CKEditorError('view-renderer-filler-was-lost', this);
406
+ }
407
+ if (isInlineFiller(domFillerNode)) {
408
+ domFillerNode.remove();
409
+ }
410
+ else {
411
+ domFillerNode.data = domFillerNode.data.substr(INLINE_FILLER_LENGTH);
412
+ }
413
+ this._inlineFiller = null;
414
+ }
415
+ /**
416
+ * Checks if the inline {@link module:engine/view/filler filler} should be added.
417
+ *
418
+ * @private
419
+ * @returns {Boolean} `true` if the inline filler should be added.
420
+ */
421
+ _needsInlineFillerAtSelection() {
422
+ if (this.selection.rangeCount != 1 || !this.selection.isCollapsed) {
423
+ return false;
424
+ }
425
+ const selectionPosition = this.selection.getFirstPosition();
426
+ const selectionParent = selectionPosition.parent;
427
+ const selectionOffset = selectionPosition.offset;
428
+ // If there is no DOM root we do not care about fillers.
429
+ if (!this.domConverter.mapViewToDom(selectionParent.root)) {
430
+ return false;
431
+ }
432
+ if (!(selectionParent.is('element'))) {
433
+ return false;
434
+ }
435
+ // Prevent adding inline filler inside elements with contenteditable=false.
436
+ // https://github.com/ckeditor/ckeditor5-engine/issues/1170
437
+ if (!isEditable(selectionParent)) {
438
+ return false;
439
+ }
440
+ // We have block filler, we do not need inline one.
441
+ if (selectionOffset === selectionParent.getFillerOffset()) {
442
+ return false;
443
+ }
444
+ const nodeBefore = selectionPosition.nodeBefore;
445
+ const nodeAfter = selectionPosition.nodeAfter;
446
+ if (nodeBefore instanceof ViewText || nodeAfter instanceof ViewText) {
447
+ return false;
448
+ }
449
+ return true;
450
+ }
451
+ /**
452
+ * Checks if text needs to be updated and possibly updates it.
453
+ *
454
+ * @private
455
+ * @param {module:engine/view/text~Text} viewText View text to update.
456
+ * @param {Object} options
457
+ * @param {module:engine/view/position~Position} options.inlineFillerPosition The position where the inline
458
+ * filler should be rendered.
459
+ */
460
+ _updateText(viewText, options) {
461
+ const domText = this.domConverter.findCorrespondingDomText(viewText);
462
+ const newDomText = this.domConverter.viewToDom(viewText);
463
+ const actualText = domText.data;
464
+ let expectedText = newDomText.data;
465
+ const filler = options.inlineFillerPosition;
466
+ if (filler && filler.parent == viewText.parent && filler.offset == viewText.index) {
467
+ expectedText = INLINE_FILLER + expectedText;
468
+ }
469
+ if (actualText != expectedText) {
470
+ const actions = fastDiff(actualText, expectedText);
471
+ for (const action of actions) {
472
+ if (action.type === 'insert') {
473
+ domText.insertData(action.index, action.values.join(''));
474
+ }
475
+ else { // 'delete'
476
+ domText.deleteData(action.index, action.howMany);
477
+ }
478
+ }
479
+ }
480
+ }
481
+ /**
482
+ * Checks if attribute list needs to be updated and possibly updates it.
483
+ *
484
+ * @private
485
+ * @param {module:engine/view/element~Element} viewElement The view element to update.
486
+ */
487
+ _updateAttrs(viewElement) {
488
+ const domElement = this.domConverter.mapViewToDom(viewElement);
489
+ if (!domElement) {
490
+ // If there is no `domElement` it means that 'viewElement' is outdated as its mapping was updated
491
+ // in 'this._updateChildrenMappings()'. There is no need to process it as new view element which
492
+ // replaced old 'viewElement' mapping was also added to 'this.markedAttributes'
493
+ // in 'this._updateChildrenMappings()' so it will be processed separately.
494
+ return;
495
+ }
496
+ const domAttrKeys = Array.from(domElement.attributes).map(attr => attr.name);
497
+ const viewAttrKeys = viewElement.getAttributeKeys();
498
+ // Add or overwrite attributes.
499
+ for (const key of viewAttrKeys) {
500
+ this.domConverter.setDomElementAttribute(domElement, key, viewElement.getAttribute(key), viewElement);
501
+ }
502
+ // Remove from DOM attributes which do not exists in the view.
503
+ for (const key of domAttrKeys) {
504
+ // All other attributes not present in the DOM should be removed.
505
+ if (!viewElement.hasAttribute(key)) {
506
+ this.domConverter.removeDomElementAttribute(domElement, key);
507
+ }
508
+ }
509
+ }
510
+ /**
511
+ * Checks if elements child list needs to be updated and possibly updates it.
512
+ *
513
+ * @private
514
+ * @param {module:engine/view/element~Element} viewElement View element to update.
515
+ * @param {Object} options
516
+ * @param {module:engine/view/position~Position} options.inlineFillerPosition The position where the inline
517
+ * filler should be rendered.
518
+ */
519
+ _updateChildren(viewElement, options) {
520
+ const domElement = this.domConverter.mapViewToDom(viewElement);
521
+ if (!domElement) {
522
+ // If there is no `domElement` it means that it was already removed from DOM.
523
+ // There is no need to process it. It will be processed when re-inserted.
524
+ return;
525
+ }
526
+ const inlineFillerPosition = options.inlineFillerPosition;
527
+ const actualDomChildren = this.domConverter.mapViewToDom(viewElement).childNodes;
528
+ const expectedDomChildren = Array.from(this.domConverter.viewChildrenToDom(viewElement, { bind: true }));
529
+ // Inline filler element has to be created as it is present in the DOM, but not in the view. It is required
530
+ // during diffing so text nodes could be compared correctly and also during rendering to maintain
531
+ // proper order and indexes while updating the DOM.
532
+ if (inlineFillerPosition && inlineFillerPosition.parent === viewElement) {
533
+ addInlineFiller(domElement.ownerDocument, expectedDomChildren, inlineFillerPosition.offset);
534
+ }
535
+ const diff = this._diffNodeLists(actualDomChildren, expectedDomChildren);
536
+ let i = 0;
537
+ const nodesToUnbind = new Set();
538
+ // Handle deletions first.
539
+ // This is to prevent a situation where an element that already exists in `actualDomChildren` is inserted at a different
540
+ // index in `actualDomChildren`. Since `actualDomChildren` is a `NodeList`, this works like move, not like an insert,
541
+ // and it disrupts the whole algorithm. See https://github.com/ckeditor/ckeditor5/issues/6367.
542
+ //
543
+ // It doesn't matter in what order we remove or add nodes, as long as we remove and add correct nodes at correct indexes.
544
+ for (const action of diff) {
545
+ if (action === 'delete') {
546
+ nodesToUnbind.add(actualDomChildren[i]);
547
+ remove(actualDomChildren[i]);
548
+ }
549
+ else if (action === 'equal') {
550
+ i++;
551
+ }
552
+ }
553
+ i = 0;
554
+ for (const action of diff) {
555
+ if (action === 'insert') {
556
+ insertAt(domElement, i, expectedDomChildren[i]);
557
+ i++;
558
+ }
559
+ else if (action === 'equal') {
560
+ // Force updating text nodes inside elements which did not change and do not need to be re-rendered (#1125).
561
+ // Do it here (not in the loop above) because only after insertions the `i` index is correct.
562
+ this._markDescendantTextToSync(this.domConverter.domToView(expectedDomChildren[i]));
563
+ i++;
564
+ }
565
+ }
566
+ // Unbind removed nodes. When node does not have a parent it means that it was removed from DOM tree during
567
+ // comparison with the expected DOM. We don't need to check child nodes, because if child node was reinserted,
568
+ // it was moved to DOM tree out of the removed node.
569
+ for (const node of nodesToUnbind) {
570
+ if (!node.parentNode) {
571
+ this.domConverter.unbindDomElement(node);
572
+ }
573
+ }
574
+ }
575
+ /**
576
+ * Shorthand for diffing two arrays or node lists of DOM nodes.
577
+ *
578
+ * @private
579
+ * @param {Array.<ViewNode>|NodeList} actualDomChildren Actual DOM children
580
+ * @param {Array.<ViewNode>|NodeList} expectedDomChildren Expected DOM children.
581
+ * @returns {Array.<String>} The list of actions based on the {@link module:utils/diff~diff} function.
582
+ */
583
+ _diffNodeLists(actualDomChildren, expectedDomChildren) {
584
+ actualDomChildren = filterOutFakeSelectionContainer(actualDomChildren, this._fakeSelectionContainer);
585
+ return diff(actualDomChildren, expectedDomChildren, sameNodes.bind(null, this.domConverter));
586
+ }
587
+ /**
588
+ * Finds DOM nodes that were replaced with the similar nodes (same tag name) in the view. All nodes are compared
589
+ * within one `insert`/`delete` action group, for example:
590
+ *
591
+ * Actual DOM: <p><b>Foo</b>Bar<i>Baz</i><b>Bax</b></p>
592
+ * Expected DOM: <p>Bar<b>123</b><i>Baz</i><b>456</b></p>
593
+ * Input actions: [ insert, insert, delete, delete, equal, insert, delete ]
594
+ * Output actions: [ insert, replace, delete, equal, replace ]
595
+ *
596
+ * @private
597
+ * @param {Array.<String>} actions Actions array which is a result of the {@link module:utils/diff~diff} function.
598
+ * @param {Array.<ViewNode>|NodeList} actualDom Actual DOM children
599
+ * @param {Array.<ViewNode>} expectedDom Expected DOM children.
600
+ * @returns {Array.<String>} Actions array modified with the `replace` actions.
601
+ */
602
+ _findReplaceActions(actions, actualDom, expectedDom) {
603
+ // If there is no both 'insert' and 'delete' actions, no need to check for replaced elements.
604
+ if (actions.indexOf('insert') === -1 || actions.indexOf('delete') === -1) {
605
+ return actions;
606
+ }
607
+ let newActions = [];
608
+ let actualSlice = [];
609
+ let expectedSlice = [];
610
+ const counter = { equal: 0, insert: 0, delete: 0 };
611
+ for (const action of actions) {
612
+ if (action === 'insert') {
613
+ expectedSlice.push(expectedDom[counter.equal + counter.insert]);
614
+ }
615
+ else if (action === 'delete') {
616
+ actualSlice.push(actualDom[counter.equal + counter.delete]);
617
+ }
618
+ else { // equal
619
+ newActions = newActions.concat(diff(actualSlice, expectedSlice, areSimilar).map(x => x === 'equal' ? 'replace' : x));
620
+ newActions.push('equal');
621
+ // Reset stored elements on 'equal'.
622
+ actualSlice = [];
623
+ expectedSlice = [];
624
+ }
625
+ counter[action]++;
626
+ }
627
+ return newActions.concat(diff(actualSlice, expectedSlice, areSimilar).map(x => x === 'equal' ? 'replace' : x));
628
+ }
629
+ /**
630
+ * Marks text nodes to be synchronized.
631
+ *
632
+ * If a text node is passed, it will be marked. If an element is passed, all descendant text nodes inside it will be marked.
633
+ *
634
+ * @private
635
+ * @param {module:engine/view/node~ViewNode} viewNode View node to sync.
636
+ */
637
+ _markDescendantTextToSync(viewNode) {
638
+ if (!viewNode) {
639
+ return;
640
+ }
641
+ if (viewNode.is('$text')) {
642
+ this.markedTexts.add(viewNode);
643
+ }
644
+ else if (viewNode.is('element')) {
645
+ for (const child of viewNode.getChildren()) {
646
+ this._markDescendantTextToSync(child);
647
+ }
648
+ }
649
+ }
650
+ /**
651
+ * Checks if the selection needs to be updated and possibly updates it.
652
+ *
653
+ * @private
654
+ */
655
+ _updateSelection() {
656
+ // Block updating DOM selection in (non-Android) Blink while the user is selecting to prevent accidental selection collapsing.
657
+ // Note: Structural changes in DOM must trigger selection rendering, though. Nodes the selection was anchored
658
+ // to, may disappear in DOM which would break the selection (e.g. in real-time collaboration scenarios).
659
+ // https://github.com/ckeditor/ckeditor5/issues/10562, https://github.com/ckeditor/ckeditor5/issues/10723
660
+ if (env.isBlink && !env.isAndroid && this.isSelecting && !this.markedChildren.size) {
661
+ return;
662
+ }
663
+ // If there is no selection - remove DOM and fake selections.
664
+ if (this.selection.rangeCount === 0) {
665
+ this._removeDomSelection();
666
+ this._removeFakeSelection();
667
+ return;
668
+ }
669
+ const domRoot = this.domConverter.mapViewToDom(this.selection.editableElement);
670
+ // Do nothing if there is no focus, or there is no DOM element corresponding to selection's editable element.
671
+ if (!this.isFocused || !domRoot) {
672
+ return;
673
+ }
674
+ // Render selection.
675
+ if (this.selection.isFake) {
676
+ this._updateFakeSelection(domRoot);
677
+ }
678
+ else {
679
+ this._removeFakeSelection();
680
+ this._updateDomSelection(domRoot);
681
+ }
682
+ }
683
+ /**
684
+ * Updates the fake selection.
685
+ *
686
+ * @private
687
+ * @param {HTMLElement} domRoot A valid DOM root where the fake selection container should be added.
688
+ */
689
+ _updateFakeSelection(domRoot) {
690
+ const domDocument = domRoot.ownerDocument;
691
+ if (!this._fakeSelectionContainer) {
692
+ this._fakeSelectionContainer = createFakeSelectionContainer(domDocument);
693
+ }
694
+ const container = this._fakeSelectionContainer;
695
+ // Bind fake selection container with the current selection *position*.
696
+ this.domConverter.bindFakeSelection(container, this.selection);
697
+ if (!this._fakeSelectionNeedsUpdate(domRoot)) {
698
+ return;
699
+ }
700
+ if (!container.parentElement || container.parentElement != domRoot) {
701
+ domRoot.appendChild(container);
702
+ }
703
+ container.textContent = this.selection.fakeSelectionLabel || '\u00A0';
704
+ const domSelection = domDocument.getSelection();
705
+ const domRange = domDocument.createRange();
706
+ domSelection.removeAllRanges();
707
+ domRange.selectNodeContents(container);
708
+ domSelection.addRange(domRange);
709
+ }
710
+ /**
711
+ * Updates the DOM selection.
712
+ *
713
+ * @private
714
+ * @param {HTMLElement} domRoot A valid DOM root where the DOM selection should be rendered.
715
+ */
716
+ _updateDomSelection(domRoot) {
717
+ const domSelection = domRoot.ownerDocument.defaultView.getSelection();
718
+ // Let's check whether DOM selection needs updating at all.
719
+ if (!this._domSelectionNeedsUpdate(domSelection)) {
720
+ return;
721
+ }
722
+ // Multi-range selection is not available in most browsers, and, at least in Chrome, trying to
723
+ // set such selection, that is not continuous, throws an error. Because of that, we will just use anchor
724
+ // and focus of view selection.
725
+ // Since we are not supporting multi-range selection, we also do not need to check if proper editable is
726
+ // selected. If there is any editable selected, it is okay (editable is taken from selection anchor).
727
+ const anchor = this.domConverter.viewPositionToDom(this.selection.anchor);
728
+ const focus = this.domConverter.viewPositionToDom(this.selection.focus);
729
+ domSelection.collapse(anchor.parent, anchor.offset);
730
+ domSelection.extend(focus.parent, focus.offset);
731
+ // Firefox–specific hack (https://github.com/ckeditor/ckeditor5-engine/issues/1439).
732
+ if (env.isGecko) {
733
+ fixGeckoSelectionAfterBr(focus, domSelection);
734
+ }
735
+ }
736
+ /**
737
+ * Checks whether a given DOM selection needs to be updated.
738
+ *
739
+ * @private
740
+ * @param {Selection} domSelection The DOM selection to check.
741
+ * @returns {Boolean}
742
+ */
743
+ _domSelectionNeedsUpdate(domSelection) {
744
+ if (!this.domConverter.isDomSelectionCorrect(domSelection)) {
745
+ // Current DOM selection is in incorrect position. We need to update it.
746
+ return true;
747
+ }
748
+ const oldViewSelection = domSelection && this.domConverter.domSelectionToView(domSelection);
749
+ if (oldViewSelection && this.selection.isEqual(oldViewSelection)) {
750
+ return false;
751
+ }
752
+ // If selection is not collapsed, it does not need to be updated if it is similar.
753
+ if (!this.selection.isCollapsed && this.selection.isSimilar(oldViewSelection)) {
754
+ // Selection did not changed and is correct, do not update.
755
+ return false;
756
+ }
757
+ // Selections are not similar.
758
+ return true;
759
+ }
760
+ /**
761
+ * Checks whether the fake selection needs to be updated.
762
+ *
763
+ * @private
764
+ * @param {HTMLElement} domRoot A valid DOM root where a new fake selection container should be added.
765
+ * @returns {Boolean}
766
+ */
767
+ _fakeSelectionNeedsUpdate(domRoot) {
768
+ const container = this._fakeSelectionContainer;
769
+ const domSelection = domRoot.ownerDocument.getSelection();
770
+ // Fake selection needs to be updated if there's no fake selection container, or the container currently sits
771
+ // in a different root.
772
+ if (!container || container.parentElement !== domRoot) {
773
+ return true;
774
+ }
775
+ // Make sure that the selection actually is within the fake selection.
776
+ if (domSelection.anchorNode !== container && !container.contains(domSelection.anchorNode)) {
777
+ return true;
778
+ }
779
+ return container.textContent !== this.selection.fakeSelectionLabel;
780
+ }
781
+ /**
782
+ * Removes the DOM selection.
783
+ *
784
+ * @private
785
+ */
786
+ _removeDomSelection() {
787
+ for (const doc of this.domDocuments) {
788
+ const domSelection = doc.getSelection();
789
+ if (domSelection.rangeCount) {
790
+ const activeDomElement = doc.activeElement;
791
+ const viewElement = this.domConverter.mapDomToView(activeDomElement);
792
+ if (activeDomElement && viewElement) {
793
+ domSelection.removeAllRanges();
794
+ }
795
+ }
796
+ }
797
+ }
798
+ /**
799
+ * Removes the fake selection.
800
+ *
801
+ * @private
802
+ */
803
+ _removeFakeSelection() {
804
+ const container = this._fakeSelectionContainer;
805
+ if (container) {
806
+ container.remove();
807
+ }
808
+ }
809
+ /**
810
+ * Checks if focus needs to be updated and possibly updates it.
811
+ *
812
+ * @private
813
+ */
814
+ _updateFocus() {
815
+ if (this.isFocused) {
816
+ const editable = this.selection.editableElement;
817
+ if (editable) {
818
+ this.domConverter.focus(editable);
819
+ }
820
+ }
821
+ }
937
822
  }
938
-
939
- mix( Renderer, ObservableMixin );
940
-
941
823
  // Checks if provided element is editable.
942
824
  //
943
825
  // @private
944
826
  // @param {module:engine/view/element~Element} element
945
827
  // @returns {Boolean}
946
- function isEditable( element ) {
947
- if ( element.getAttribute( 'contenteditable' ) == 'false' ) {
948
- return false;
949
- }
950
-
951
- const parent = element.findAncestor( element => element.hasAttribute( 'contenteditable' ) );
952
-
953
- return !parent || parent.getAttribute( 'contenteditable' ) == 'true';
828
+ function isEditable(element) {
829
+ if (element.getAttribute('contenteditable') == 'false') {
830
+ return false;
831
+ }
832
+ const parent = element.findAncestor(element => element.hasAttribute('contenteditable'));
833
+ return !parent || parent.getAttribute('contenteditable') == 'true';
954
834
  }
955
-
956
835
  // Adds inline filler at a given position.
957
836
  //
958
837
  // The position can be given as an array of DOM nodes and an offset in that array,
@@ -960,44 +839,40 @@ function isEditable( element ) {
960
839
  //
961
840
  // @private
962
841
  // @param {Document} domDocument
963
- // @param {Element|Array.<Node>} domParentOrArray
842
+ // @param {Element|Array.<ViewNode>} domParentOrArray
964
843
  // @param {Number} offset
965
844
  // @returns {Text} The DOM text node that contains an inline filler.
966
- function addInlineFiller( domDocument, domParentOrArray, offset ) {
967
- const childNodes = domParentOrArray instanceof Array ? domParentOrArray : domParentOrArray.childNodes;
968
- const nodeAfterFiller = childNodes[ offset ];
969
-
970
- if ( isText( nodeAfterFiller ) ) {
971
- nodeAfterFiller.data = INLINE_FILLER + nodeAfterFiller.data;
972
-
973
- return nodeAfterFiller;
974
- } else {
975
- const fillerNode = domDocument.createTextNode( INLINE_FILLER );
976
-
977
- if ( Array.isArray( domParentOrArray ) ) {
978
- childNodes.splice( offset, 0, fillerNode );
979
- } else {
980
- insertAt( domParentOrArray, offset, fillerNode );
981
- }
982
-
983
- return fillerNode;
984
- }
845
+ function addInlineFiller(domDocument, domParentOrArray, offset) {
846
+ const childNodes = domParentOrArray instanceof Array ? domParentOrArray : domParentOrArray.childNodes;
847
+ const nodeAfterFiller = childNodes[offset];
848
+ if (isText(nodeAfterFiller)) {
849
+ nodeAfterFiller.data = INLINE_FILLER + nodeAfterFiller.data;
850
+ return nodeAfterFiller;
851
+ }
852
+ else {
853
+ const fillerNode = domDocument.createTextNode(INLINE_FILLER);
854
+ if (Array.isArray(domParentOrArray)) {
855
+ childNodes.splice(offset, 0, fillerNode);
856
+ }
857
+ else {
858
+ insertAt(domParentOrArray, offset, fillerNode);
859
+ }
860
+ return fillerNode;
861
+ }
985
862
  }
986
-
987
863
  // Whether two DOM nodes should be considered as similar.
988
864
  // Nodes are considered similar if they have the same tag name.
989
865
  //
990
866
  // @private
991
- // @param {Node} node1
992
- // @param {Node} node2
867
+ // @param {ViewNode} node1
868
+ // @param {ViewNode} node2
993
869
  // @returns {Boolean}
994
- function areSimilar( node1, node2 ) {
995
- return isNode( node1 ) && isNode( node2 ) &&
996
- !isText( node1 ) && !isText( node2 ) &&
997
- !isComment( node1 ) && !isComment( node2 ) &&
998
- node1.tagName.toLowerCase() === node2.tagName.toLowerCase();
870
+ function areSimilar(node1, node2) {
871
+ return isNode(node1) && isNode(node2) &&
872
+ !isText(node1) && !isText(node2) &&
873
+ !isComment(node1) && !isComment(node2) &&
874
+ node1.tagName.toLowerCase() === node2.tagName.toLowerCase();
999
875
  }
1000
-
1001
876
  // Whether two dom nodes should be considered as the same.
1002
877
  // Two nodes which are considered the same are:
1003
878
  //
@@ -1007,28 +882,26 @@ function areSimilar( node1, node2 ) {
1007
882
  //
1008
883
  // @private
1009
884
  // @param {String} blockFillerMode Block filler mode, see {@link module:engine/view/domconverter~DomConverter#blockFillerMode}.
1010
- // @param {Node} node1
1011
- // @param {Node} node2
885
+ // @param {ViewNode} node1
886
+ // @param {ViewNode} node2
1012
887
  // @returns {Boolean}
1013
- function sameNodes( domConverter, actualDomChild, expectedDomChild ) {
1014
- // Elements.
1015
- if ( actualDomChild === expectedDomChild ) {
1016
- return true;
1017
- }
1018
- // Texts.
1019
- else if ( isText( actualDomChild ) && isText( expectedDomChild ) ) {
1020
- return actualDomChild.data === expectedDomChild.data;
1021
- }
1022
- // Block fillers.
1023
- else if ( domConverter.isBlockFiller( actualDomChild ) &&
1024
- domConverter.isBlockFiller( expectedDomChild ) ) {
1025
- return true;
1026
- }
1027
-
1028
- // Not matching types.
1029
- return false;
888
+ function sameNodes(domConverter, actualDomChild, expectedDomChild) {
889
+ // Elements.
890
+ if (actualDomChild === expectedDomChild) {
891
+ return true;
892
+ }
893
+ // Texts.
894
+ else if (isText(actualDomChild) && isText(expectedDomChild)) {
895
+ return actualDomChild.data === expectedDomChild.data;
896
+ }
897
+ // Block fillers.
898
+ else if (domConverter.isBlockFiller(actualDomChild) &&
899
+ domConverter.isBlockFiller(expectedDomChild)) {
900
+ return true;
901
+ }
902
+ // Not matching types.
903
+ return false;
1030
904
  }
1031
-
1032
905
  // The following is a Firefox–specific hack (https://github.com/ckeditor/ckeditor5-engine/issues/1439).
1033
906
  // When the native DOM selection is at the end of the block and preceded by <br /> e.g.
1034
907
  //
@@ -1036,60 +909,47 @@ function sameNodes( domConverter, actualDomChild, expectedDomChild ) {
1036
909
  //
1037
910
  // which happens a lot when using the soft line break, the browser fails to (visually) move the
1038
911
  // caret to the new line. A quick fix is as simple as force–refreshing the selection with the same range.
1039
- function fixGeckoSelectionAfterBr( focus, domSelection ) {
1040
- const parent = focus.parent;
1041
-
1042
- // This fix works only when the focus point is at the very end of an element.
1043
- // There is no point in running it in cases unrelated to the browser bug.
1044
- if ( parent.nodeType != Node.ELEMENT_NODE || focus.offset != parent.childNodes.length - 1 ) {
1045
- return;
1046
- }
1047
-
1048
- const childAtOffset = parent.childNodes[ focus.offset ];
1049
-
1050
- // To stay on the safe side, the fix being as specific as possible, it targets only the
1051
- // selection which is at the very end of the element and preceded by <br />.
1052
- if ( childAtOffset && childAtOffset.tagName == 'BR' ) {
1053
- domSelection.addRange( domSelection.getRangeAt( 0 ) );
1054
- }
912
+ function fixGeckoSelectionAfterBr(focus, domSelection) {
913
+ const parent = focus.parent;
914
+ // This fix works only when the focus point is at the very end of an element.
915
+ // There is no point in running it in cases unrelated to the browser bug.
916
+ if (parent.nodeType != Node.ELEMENT_NODE || focus.offset != parent.childNodes.length - 1) {
917
+ return;
918
+ }
919
+ const childAtOffset = parent.childNodes[focus.offset];
920
+ // To stay on the safe side, the fix being as specific as possible, it targets only the
921
+ // selection which is at the very end of the element and preceded by <br />.
922
+ if (childAtOffset && childAtOffset.tagName == 'BR') {
923
+ domSelection.addRange(domSelection.getRangeAt(0));
924
+ }
1055
925
  }
1056
-
1057
- function filterOutFakeSelectionContainer( domChildList, fakeSelectionContainer ) {
1058
- const childList = Array.from( domChildList );
1059
-
1060
- if ( childList.length == 0 || !fakeSelectionContainer ) {
1061
- return childList;
1062
- }
1063
-
1064
- const last = childList[ childList.length - 1 ];
1065
-
1066
- if ( last == fakeSelectionContainer ) {
1067
- childList.pop();
1068
- }
1069
-
1070
- return childList;
926
+ function filterOutFakeSelectionContainer(domChildList, fakeSelectionContainer) {
927
+ const childList = Array.from(domChildList);
928
+ if (childList.length == 0 || !fakeSelectionContainer) {
929
+ return childList;
930
+ }
931
+ const last = childList[childList.length - 1];
932
+ if (last == fakeSelectionContainer) {
933
+ childList.pop();
934
+ }
935
+ return childList;
1071
936
  }
1072
-
1073
937
  // Creates a fake selection container for a given document.
1074
938
  //
1075
939
  // @private
1076
940
  // @param {Document} domDocument
1077
941
  // @returns {HTMLElement}
1078
- function createFakeSelectionContainer( domDocument ) {
1079
- const container = domDocument.createElement( 'div' );
1080
-
1081
- container.className = 'ck-fake-selection-container';
1082
-
1083
- Object.assign( container.style, {
1084
- position: 'fixed',
1085
- top: 0,
1086
- left: '-9999px',
1087
- // See https://github.com/ckeditor/ckeditor5/issues/752.
1088
- width: '42px'
1089
- } );
1090
-
1091
- // Fill it with a text node so we can update it later.
1092
- container.textContent = '\u00A0';
1093
-
1094
- return container;
942
+ function createFakeSelectionContainer(domDocument) {
943
+ const container = domDocument.createElement('div');
944
+ container.className = 'ck-fake-selection-container';
945
+ Object.assign(container.style, {
946
+ position: 'fixed',
947
+ top: 0,
948
+ left: '-9999px',
949
+ // See https://github.com/ckeditor/ckeditor5/issues/752.
950
+ width: '42px'
951
+ });
952
+ // Fill it with a text node so we can update it later.
953
+ container.textContent = '\u00A0';
954
+ return container;
1095
955
  }