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