@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,345 @@
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
+ /**
7
+ * @module engine/view/observer/mutationobserver
8
+ */
9
+
10
+ /* globals window */
11
+
12
+ import Observer from './observer';
13
+ import ViewSelection from '../selection';
14
+ import { startsWithFiller, getDataWithoutFiller } from '../filler';
15
+ import { isEqualWith } from 'lodash-es';
16
+
17
+ /**
18
+ * Mutation observer class observes changes in the DOM, fires {@link module:engine/view/document~Document#event:mutations} event, mark view
19
+ * elements as changed and call {@link module:engine/view/renderer~Renderer#render}.
20
+ * Because all mutated nodes are marked as "to be rendered" and the
21
+ * {@link module:engine/view/renderer~Renderer#render} is called, all changes will be reverted, unless the mutation will be handled by the
22
+ * {@link module:engine/view/document~Document#event:mutations} event listener. It means user will see only handled changes, and the editor
23
+ * will block all changes which are not handled.
24
+ *
25
+ * Mutation Observer also take care of reducing number of mutations which are fired. It removes duplicates and
26
+ * mutations on elements which do not have corresponding view elements. Also
27
+ * {@link module:engine/view/observer/mutationobserver~MutatedText text mutation} is fired only if parent element do not change child list.
28
+ *
29
+ * Note that this observer is attached by the {@link module:engine/view/view~View} and is available by default.
30
+ *
31
+ * @extends module:engine/view/observer/observer~Observer
32
+ */
33
+ export default class MutationObserver extends Observer {
34
+ constructor( view ) {
35
+ super( view );
36
+
37
+ /**
38
+ * Native mutation observer config.
39
+ *
40
+ * @private
41
+ * @member {Object}
42
+ */
43
+ this._config = {
44
+ childList: true,
45
+ characterData: true,
46
+ characterDataOldValue: true,
47
+ subtree: true
48
+ };
49
+
50
+ /**
51
+ * Reference to the {@link module:engine/view/view~View#domConverter}.
52
+ *
53
+ * @member {module:engine/view/domconverter~DomConverter}
54
+ */
55
+ this.domConverter = view.domConverter;
56
+
57
+ /**
58
+ * Reference to the {@link module:engine/view/view~View#_renderer}.
59
+ *
60
+ * @member {module:engine/view/renderer~Renderer}
61
+ */
62
+ this.renderer = view._renderer;
63
+
64
+ /**
65
+ * Observed DOM elements.
66
+ *
67
+ * @private
68
+ * @member {Array.<HTMLElement>}
69
+ */
70
+ this._domElements = [];
71
+
72
+ /**
73
+ * Native mutation observer.
74
+ *
75
+ * @private
76
+ * @member {MutationObserver}
77
+ */
78
+ this._mutationObserver = new window.MutationObserver( this._onMutations.bind( this ) );
79
+ }
80
+
81
+ /**
82
+ * Synchronously fires {@link module:engine/view/document~Document#event:mutations} event with all mutations in record queue.
83
+ * At the same time empties the queue so mutations will not be fired twice.
84
+ */
85
+ flush() {
86
+ this._onMutations( this._mutationObserver.takeRecords() );
87
+ }
88
+
89
+ /**
90
+ * @inheritDoc
91
+ */
92
+ observe( domElement ) {
93
+ this._domElements.push( domElement );
94
+
95
+ if ( this.isEnabled ) {
96
+ this._mutationObserver.observe( domElement, this._config );
97
+ }
98
+ }
99
+
100
+ /**
101
+ * @inheritDoc
102
+ */
103
+ enable() {
104
+ super.enable();
105
+
106
+ for ( const domElement of this._domElements ) {
107
+ this._mutationObserver.observe( domElement, this._config );
108
+ }
109
+ }
110
+
111
+ /**
112
+ * @inheritDoc
113
+ */
114
+ disable() {
115
+ super.disable();
116
+
117
+ this._mutationObserver.disconnect();
118
+ }
119
+
120
+ /**
121
+ * @inheritDoc
122
+ */
123
+ destroy() {
124
+ super.destroy();
125
+
126
+ this._mutationObserver.disconnect();
127
+ }
128
+
129
+ /**
130
+ * Handles mutations. Deduplicates, mark view elements to sync, fire event and call render.
131
+ *
132
+ * @private
133
+ * @param {Array.<Object>} domMutations Array of native mutations.
134
+ */
135
+ _onMutations( domMutations ) {
136
+ // As a result of this.flush() we can have an empty collection.
137
+ if ( domMutations.length === 0 ) {
138
+ return;
139
+ }
140
+
141
+ const domConverter = this.domConverter;
142
+
143
+ // Use map and set for deduplication.
144
+ const mutatedTexts = new Map();
145
+ const mutatedElements = new Set();
146
+
147
+ // Handle `childList` mutations first, so we will be able to check if the `characterData` mutation is in the
148
+ // element with changed structure anyway.
149
+ for ( const mutation of domMutations ) {
150
+ if ( mutation.type === 'childList' ) {
151
+ const element = domConverter.mapDomToView( mutation.target );
152
+
153
+ // Do not collect mutations from UIElements and RawElements.
154
+ if ( element && ( element.is( 'uiElement' ) || element.is( 'rawElement' ) ) ) {
155
+ continue;
156
+ }
157
+
158
+ if ( element && !this._isBogusBrMutation( mutation ) ) {
159
+ mutatedElements.add( element );
160
+ }
161
+ }
162
+ }
163
+
164
+ // Handle `characterData` mutations later, when we have the full list of nodes which changed structure.
165
+ for ( const mutation of domMutations ) {
166
+ const element = domConverter.mapDomToView( mutation.target );
167
+
168
+ // Do not collect mutations from UIElements and RawElements.
169
+ if ( element && ( element.is( 'uiElement' ) || element.is( 'rawElement' ) ) ) {
170
+ continue;
171
+ }
172
+
173
+ if ( mutation.type === 'characterData' ) {
174
+ const text = domConverter.findCorrespondingViewText( mutation.target );
175
+
176
+ if ( text && !mutatedElements.has( text.parent ) ) {
177
+ // Use text as a key, for deduplication. If there will be another mutation on the same text element
178
+ // we will have only one in the map.
179
+ mutatedTexts.set( text, {
180
+ type: 'text',
181
+ oldText: text.data,
182
+ newText: getDataWithoutFiller( mutation.target ),
183
+ node: text
184
+ } );
185
+ }
186
+ // When we added first letter to the text node which had only inline filler, for the DOM it is mutation
187
+ // on text, but for the view, where filler text node did not existed, new text node was created, so we
188
+ // need to fire 'children' mutation instead of 'text'.
189
+ else if ( !text && startsWithFiller( mutation.target ) ) {
190
+ mutatedElements.add( domConverter.mapDomToView( mutation.target.parentNode ) );
191
+ }
192
+ }
193
+ }
194
+
195
+ // Now we build the list of mutations to fire and mark elements. We did not do it earlier to avoid marking the
196
+ // same node multiple times in case of duplication.
197
+
198
+ // List of mutations we will fire.
199
+ const viewMutations = [];
200
+
201
+ for ( const mutatedText of mutatedTexts.values() ) {
202
+ this.renderer.markToSync( 'text', mutatedText.node );
203
+ viewMutations.push( mutatedText );
204
+ }
205
+
206
+ for ( const viewElement of mutatedElements ) {
207
+ const domElement = domConverter.mapViewToDom( viewElement );
208
+ const viewChildren = Array.from( viewElement.getChildren() );
209
+ const newViewChildren = Array.from( domConverter.domChildrenToView( domElement, { withChildren: false } ) );
210
+
211
+ // It may happen that as a result of many changes (sth was inserted and then removed),
212
+ // both elements haven't really changed. #1031
213
+ if ( !isEqualWith( viewChildren, newViewChildren, sameNodes ) ) {
214
+ this.renderer.markToSync( 'children', viewElement );
215
+
216
+ viewMutations.push( {
217
+ type: 'children',
218
+ oldChildren: viewChildren,
219
+ newChildren: newViewChildren,
220
+ node: viewElement
221
+ } );
222
+ }
223
+ }
224
+
225
+ // Retrieve `domSelection` using `ownerDocument` of one of mutated nodes.
226
+ // There should not be simultaneous mutation in multiple documents, so it's fine.
227
+ const domSelection = domMutations[ 0 ].target.ownerDocument.getSelection();
228
+
229
+ let viewSelection = null;
230
+
231
+ if ( domSelection && domSelection.anchorNode ) {
232
+ // If `domSelection` is inside a dom node that is already bound to a view node from view tree, get
233
+ // corresponding selection in the view and pass it together with `viewMutations`. The `viewSelection` may
234
+ // be used by features handling mutations.
235
+ // Only one range is supported.
236
+
237
+ const viewSelectionAnchor = domConverter.domPositionToView( domSelection.anchorNode, domSelection.anchorOffset );
238
+ const viewSelectionFocus = domConverter.domPositionToView( domSelection.focusNode, domSelection.focusOffset );
239
+
240
+ // Anchor and focus has to be properly mapped to view.
241
+ if ( viewSelectionAnchor && viewSelectionFocus ) {
242
+ viewSelection = new ViewSelection( viewSelectionAnchor );
243
+ viewSelection.setFocus( viewSelectionFocus );
244
+ }
245
+ }
246
+
247
+ // In case only non-relevant mutations were recorded it skips the event and force render (#5600).
248
+ if ( viewMutations.length ) {
249
+ this.document.fire( 'mutations', viewMutations, viewSelection );
250
+
251
+ // If nothing changes on `mutations` event, at this point we have "dirty DOM" (changed) and de-synched
252
+ // view (which has not been changed). In order to "reset DOM" we render the view again.
253
+ this.view.forceRender();
254
+ }
255
+
256
+ function sameNodes( child1, child2 ) {
257
+ // First level of comparison (array of children vs array of children) – use the Lodash's default behavior.
258
+ if ( Array.isArray( child1 ) ) {
259
+ return;
260
+ }
261
+
262
+ // Elements.
263
+ if ( child1 === child2 ) {
264
+ return true;
265
+ }
266
+ // Texts.
267
+ else if ( child1.is( '$text' ) && child2.is( '$text' ) ) {
268
+ return child1.data === child2.data;
269
+ }
270
+
271
+ // Not matching types.
272
+ return false;
273
+ }
274
+ }
275
+
276
+ /**
277
+ * Checks if mutation was generated by the browser inserting bogus br on the end of the block element.
278
+ * Such mutations are generated while pressing space or performing native spellchecker correction
279
+ * on the end of the block element in Firefox browser.
280
+ *
281
+ * @private
282
+ * @param {Object} mutation Native mutation object.
283
+ * @returns {Boolean}
284
+ */
285
+ _isBogusBrMutation( mutation ) {
286
+ let addedNode = null;
287
+
288
+ // Check if mutation added only one node on the end of its parent.
289
+ if ( mutation.nextSibling === null && mutation.removedNodes.length === 0 && mutation.addedNodes.length == 1 ) {
290
+ addedNode = this.domConverter.domToView( mutation.addedNodes[ 0 ], {
291
+ withChildren: false
292
+ } );
293
+ }
294
+
295
+ return addedNode && addedNode.is( 'element', 'br' );
296
+ }
297
+ }
298
+
299
+ /**
300
+ * Fired when mutation occurred. If tree view is not changed on this event, DOM will be reverted to the state before
301
+ * mutation, so all changes which should be applied, should be handled on this event.
302
+ *
303
+ * Introduced by {@link module:engine/view/observer/mutationobserver~MutationObserver}.
304
+ *
305
+ * Note that because {@link module:engine/view/observer/mutationobserver~MutationObserver} is attached by the
306
+ * {@link module:engine/view/view~View} this event is available by default.
307
+ *
308
+ * @see module:engine/view/observer/mutationobserver~MutationObserver
309
+ * @event module:engine/view/document~Document#event:mutations
310
+ * @param {Array.<module:engine/view/observer/mutationobserver~MutatedText|module:engine/view/observer/mutationobserver~MutatedChildren>}
311
+ * viewMutations Array of mutations.
312
+ * For mutated texts it will be {@link module:engine/view/observer/mutationobserver~MutatedText} and for mutated elements it will be
313
+ * {@link module:engine/view/observer/mutationobserver~MutatedChildren}. You can recognize the type based on the `type` property.
314
+ * @param {module:engine/view/selection~Selection|null} viewSelection View selection that is a result of converting DOM selection to view.
315
+ * Keep in
316
+ * mind that the DOM selection is already "updated", meaning that it already acknowledges changes done in mutation.
317
+ */
318
+
319
+ /**
320
+ * Mutation item for text.
321
+ *
322
+ * @see module:engine/view/document~Document#event:mutations
323
+ * @see module:engine/view/observer/mutationobserver~MutatedChildren
324
+ *
325
+ * @typedef {Object} module:engine/view/observer/mutationobserver~MutatedText
326
+ *
327
+ * @property {String} type For text mutations it is always 'text'.
328
+ * @property {module:engine/view/text~Text} node Mutated text node.
329
+ * @property {String} oldText Old text.
330
+ * @property {String} newText New text.
331
+ */
332
+
333
+ /**
334
+ * Mutation item for child nodes.
335
+ *
336
+ * @see module:engine/view/document~Document#event:mutations
337
+ * @see module:engine/view/observer/mutationobserver~MutatedText
338
+ *
339
+ * @typedef {Object} module:engine/view/observer/mutationobserver~MutatedChildren
340
+ *
341
+ * @property {String} type For child nodes mutations it is always 'children'.
342
+ * @property {module:engine/view/element~Element} node Parent of the mutated children.
343
+ * @property {Array.<module:engine/view/node~Node>} oldChildren Old child nodes.
344
+ * @property {Array.<module:engine/view/node~Node>} newChildren New child nodes.
345
+ */
@@ -0,0 +1,118 @@
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
+ /**
7
+ * @module engine/view/observer/observer
8
+ */
9
+
10
+ import DomEmitterMixin from '@ckeditor/ckeditor5-utils/src/dom/emittermixin';
11
+ import mix from '@ckeditor/ckeditor5-utils/src/mix';
12
+
13
+ /**
14
+ * Abstract base observer class. Observers are classes which listen to DOM events, do the preliminary
15
+ * processing and fire events on the {@link module:engine/view/document~Document} objects.
16
+ * Observers can also add features to the view, for instance by updating its status or marking elements
17
+ * which need a refresh on DOM events.
18
+ *
19
+ * @abstract
20
+ */
21
+ export default class Observer {
22
+ /**
23
+ * Creates an instance of the observer.
24
+ *
25
+ * @param {module:engine/view/view~View} view
26
+ */
27
+ constructor( view ) {
28
+ /**
29
+ * An instance of the view controller.
30
+ *
31
+ * @readonly
32
+ * @member {module:engine/view/view~View}
33
+ */
34
+ this.view = view;
35
+
36
+ /**
37
+ * A reference to the {@link module:engine/view/document~Document} object.
38
+ *
39
+ * @readonly
40
+ * @member {module:engine/view/document~Document}
41
+ */
42
+ this.document = view.document;
43
+
44
+ /**
45
+ * The state of the observer. If it is disabled, no events will be fired.
46
+ *
47
+ * @readonly
48
+ * @member {Boolean}
49
+ */
50
+ this.isEnabled = false;
51
+ }
52
+
53
+ /**
54
+ * Enables the observer. This method is called when the observer is registered to the
55
+ * {@link module:engine/view/view~View} and after {@link module:engine/view/view~View#forceRender rendering}
56
+ * (all observers are {@link #disable disabled} before rendering).
57
+ *
58
+ * A typical use case for disabling observers is that mutation observers need to be disabled for the rendering.
59
+ * However, a child class may not need to be disabled, so it can implement an empty method.
60
+ *
61
+ * @see module:engine/view/observer/observer~Observer#disable
62
+ */
63
+ enable() {
64
+ this.isEnabled = true;
65
+ }
66
+
67
+ /**
68
+ * Disables the observer. This method is called before
69
+ * {@link module:engine/view/view~View#forceRender rendering} to prevent firing events during rendering.
70
+ *
71
+ * @see module:engine/view/observer/observer~Observer#enable
72
+ */
73
+ disable() {
74
+ this.isEnabled = false;
75
+ }
76
+
77
+ /**
78
+ * Disables and destroys the observer, among others removes event listeners created by the observer.
79
+ */
80
+ destroy() {
81
+ this.disable();
82
+ this.stopListening();
83
+ }
84
+
85
+ /**
86
+ * Checks whether a given DOM event should be ignored (should not be turned into a synthetic view document event).
87
+ *
88
+ * Currently, an event will be ignored only if its target or any of its ancestors has the `data-cke-ignore-events` attribute.
89
+ * This attribute can be used inside the structures generated by
90
+ * {@link module:engine/view/downcastwriter~DowncastWriter#createUIElement `DowncastWriter#createUIElement()`} to ignore events
91
+ * fired within a UI that should be excluded from CKEditor 5's realms.
92
+ *
93
+ * @param {Node} domTarget The DOM event target to check (usually an element, sometimes a text node and
94
+ * potentially sometimes a document, too).
95
+ * @returns {Boolean} Whether this event should be ignored by the observer.
96
+ */
97
+ checkShouldIgnoreEventFromTarget( domTarget ) {
98
+ if ( domTarget && domTarget.nodeType === 3 ) {
99
+ domTarget = domTarget.parentNode;
100
+ }
101
+
102
+ if ( !domTarget || domTarget.nodeType !== 1 ) {
103
+ return false;
104
+ }
105
+
106
+ return domTarget.matches( '[data-cke-ignore-events], [data-cke-ignore-events] *' );
107
+ }
108
+
109
+ /**
110
+ * Starts observing the given root element.
111
+ *
112
+ * @method #observe
113
+ * @param {HTMLElement} domElement
114
+ * @param {String} name The name of the root element.
115
+ */
116
+ }
117
+
118
+ mix( Observer, DomEmitterMixin );
@@ -0,0 +1,242 @@
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
+ /**
7
+ * @module engine/view/observer/selectionobserver
8
+ */
9
+
10
+ /* global setInterval, clearInterval */
11
+
12
+ import Observer from './observer';
13
+ import MutationObserver from './mutationobserver';
14
+ import { debounce } from 'lodash-es';
15
+
16
+ /**
17
+ * Selection observer class observes selection changes in the document. If a selection changes on the document this
18
+ * observer checks if there are any mutations and if the DOM selection is different from the
19
+ * {@link module:engine/view/document~Document#selection view selection}. The selection observer fires
20
+ * {@link module:engine/view/document~Document#event:selectionChange} event only if a selection change was the only change in the document
21
+ * and the DOM selection is different then the view selection.
22
+ *
23
+ * Note that this observer is attached by the {@link module:engine/view/view~View} and is available by default.
24
+ *
25
+ * @see module:engine/view/observer/mutationobserver~MutationObserver
26
+ * @extends module:engine/view/observer/observer~Observer
27
+ */
28
+ export default class SelectionObserver extends Observer {
29
+ constructor( view ) {
30
+ super( view );
31
+
32
+ /**
33
+ * Instance of the mutation observer. Selection observer calls
34
+ * {@link module:engine/view/observer/mutationobserver~MutationObserver#flush} to ensure that the mutations will be handled
35
+ * before the {@link module:engine/view/document~Document#event:selectionChange} event is fired.
36
+ *
37
+ * @readonly
38
+ * @member {module:engine/view/observer/mutationobserver~MutationObserver}
39
+ * module:engine/view/observer/selectionobserver~SelectionObserver#mutationObserver
40
+ */
41
+ this.mutationObserver = view.getObserver( MutationObserver );
42
+
43
+ /**
44
+ * Reference to the view {@link module:engine/view/documentselection~DocumentSelection} object used to compare
45
+ * new selection with it.
46
+ *
47
+ * @readonly
48
+ * @member {module:engine/view/documentselection~DocumentSelection}
49
+ * module:engine/view/observer/selectionobserver~SelectionObserver#selection
50
+ */
51
+ this.selection = this.document.selection;
52
+
53
+ /* eslint-disable max-len */
54
+ /**
55
+ * Reference to the {@link module:engine/view/view~View#domConverter}.
56
+ *
57
+ * @readonly
58
+ * @member {module:engine/view/domconverter~DomConverter} module:engine/view/observer/selectionobserver~SelectionObserver#domConverter
59
+ */
60
+ /* eslint-enable max-len */
61
+ this.domConverter = view.domConverter;
62
+
63
+ /**
64
+ * A set of documents which have added `selectionchange` listener to avoid adding a listener twice to the same
65
+ * document.
66
+ *
67
+ * @private
68
+ * @member {WeakSet.<Document>} module:engine/view/observer/selectionobserver~SelectionObserver#_documents
69
+ */
70
+ this._documents = new WeakSet();
71
+
72
+ /**
73
+ * Fires debounced event `selectionChangeDone`. It uses `lodash#debounce` method to delay function call.
74
+ *
75
+ * @private
76
+ * @param {Object} data Selection change data.
77
+ * @method #_fireSelectionChangeDoneDebounced
78
+ */
79
+ this._fireSelectionChangeDoneDebounced = debounce( data => this.document.fire( 'selectionChangeDone', data ), 200 );
80
+
81
+ this._clearInfiniteLoopInterval = setInterval( () => this._clearInfiniteLoop(), 1000 );
82
+
83
+ /**
84
+ * Private property to check if the code does not enter infinite loop.
85
+ *
86
+ * @private
87
+ * @member {Number} module:engine/view/observer/selectionobserver~SelectionObserver#_loopbackCounter
88
+ */
89
+ this._loopbackCounter = 0;
90
+ }
91
+
92
+ /**
93
+ * @inheritDoc
94
+ */
95
+ observe( domElement ) {
96
+ const domDocument = domElement.ownerDocument;
97
+
98
+ // Add listener once per each document.
99
+ if ( this._documents.has( domDocument ) ) {
100
+ return;
101
+ }
102
+
103
+ this.listenTo( domDocument, 'selectionchange', ( evt, domEvent ) => {
104
+ this._handleSelectionChange( domEvent, domDocument );
105
+ } );
106
+
107
+ this._documents.add( domDocument );
108
+ }
109
+
110
+ /**
111
+ * @inheritDoc
112
+ */
113
+ destroy() {
114
+ super.destroy();
115
+
116
+ clearInterval( this._clearInfiniteLoopInterval );
117
+ this._fireSelectionChangeDoneDebounced.cancel();
118
+ }
119
+
120
+ /**
121
+ * Selection change listener. {@link module:engine/view/observer/mutationobserver~MutationObserver#flush Flush} mutations, check if
122
+ * a selection changes and fires {@link module:engine/view/document~Document#event:selectionChange} event on every change
123
+ * and {@link module:engine/view/document~Document#event:selectionChangeDone} when a selection stop changing.
124
+ *
125
+ * @private
126
+ * @param {Event} domEvent DOM event.
127
+ * @param {Document} domDocument DOM document.
128
+ */
129
+ _handleSelectionChange( domEvent, domDocument ) {
130
+ if ( !this.isEnabled ) {
131
+ return;
132
+ }
133
+
134
+ const domSelection = domDocument.defaultView.getSelection();
135
+
136
+ if ( this.checkShouldIgnoreEventFromTarget( domSelection.anchorNode ) ) {
137
+ return;
138
+ }
139
+
140
+ // Ensure the mutation event will be before selection event on all browsers.
141
+ this.mutationObserver.flush();
142
+
143
+ // If there were mutations then the view will be re-rendered by the mutation observer and the selection
144
+ // will be updated, so the selections will equal and the event will not be fired, as expected.
145
+ const newViewSelection = this.domConverter.domSelectionToView( domSelection );
146
+
147
+ // Do not convert selection change if the new view selection has no ranges in it.
148
+ //
149
+ // It means that the DOM selection is in some way incorrect. Ranges that were in the DOM selection could not be
150
+ // converted to the view. This happens when the DOM selection was moved outside of the editable element.
151
+ if ( newViewSelection.rangeCount == 0 ) {
152
+ this.view.hasDomSelection = false;
153
+
154
+ return;
155
+ }
156
+
157
+ this.view.hasDomSelection = true;
158
+
159
+ if ( this.selection.isEqual( newViewSelection ) && this.domConverter.isDomSelectionCorrect( domSelection ) ) {
160
+ return;
161
+ }
162
+
163
+ // Ensure we are not in the infinite loop (#400).
164
+ // This counter is reset each second. 60 selection changes in 1 second is enough high number
165
+ // to be very difficult (impossible) to achieve using just keyboard keys (during normal editor use).
166
+ if ( ++this._loopbackCounter > 60 ) {
167
+ // Selection change observer detected an infinite rendering loop.
168
+ // Most probably you try to put the selection in the position which is not allowed
169
+ // by the browser and browser fixes it automatically what causes `selectionchange` event on
170
+ // which a loopback through a model tries to re-render the wrong selection and again.
171
+ //
172
+ // @if CK_DEBUG // console.warn( 'Selection change observer detected an infinite rendering loop.' );
173
+
174
+ return;
175
+ }
176
+
177
+ if ( this.selection.isSimilar( newViewSelection ) ) {
178
+ // If selection was equal and we are at this point of algorithm, it means that it was incorrect.
179
+ // Just re-render it, no need to fire any events, etc.
180
+ this.view.forceRender();
181
+ } else {
182
+ const data = {
183
+ oldSelection: this.selection,
184
+ newSelection: newViewSelection,
185
+ domSelection
186
+ };
187
+
188
+ // Prepare data for new selection and fire appropriate events.
189
+ this.document.fire( 'selectionChange', data );
190
+
191
+ // Call `#_fireSelectionChangeDoneDebounced` every time when `selectionChange` event is fired.
192
+ // This function is debounced what means that `selectionChangeDone` event will be fired only when
193
+ // defined int the function time will elapse since the last time the function was called.
194
+ // So `selectionChangeDone` will be fired when selection will stop changing.
195
+ this._fireSelectionChangeDoneDebounced( data );
196
+ }
197
+ }
198
+
199
+ /**
200
+ * Clears `SelectionObserver` internal properties connected with preventing infinite loop.
201
+ *
202
+ * @protected
203
+ */
204
+ _clearInfiniteLoop() {
205
+ this._loopbackCounter = 0;
206
+ }
207
+ }
208
+
209
+ /**
210
+ * Fired when a selection has changed. This event is fired only when the selection change was the only change that happened
211
+ * in the document, and the old selection is different then the new selection.
212
+ *
213
+ * Introduced by {@link module:engine/view/observer/selectionobserver~SelectionObserver}.
214
+ *
215
+ * Note that because {@link module:engine/view/observer/selectionobserver~SelectionObserver} is attached by the
216
+ * {@link module:engine/view/view~View} this event is available by default.
217
+ *
218
+ * @see module:engine/view/observer/selectionobserver~SelectionObserver
219
+ * @event module:engine/view/document~Document#event:selectionChange
220
+ * @param {Object} data
221
+ * @param {module:engine/view/documentselection~DocumentSelection} data.oldSelection Old View selection which is
222
+ * {@link module:engine/view/document~Document#selection}.
223
+ * @param {module:engine/view/selection~Selection} data.newSelection New View selection which is converted DOM selection.
224
+ * @param {Selection} data.domSelection Native DOM selection.
225
+ */
226
+
227
+ /**
228
+ * Fired when selection stops changing.
229
+ *
230
+ * Introduced by {@link module:engine/view/observer/selectionobserver~SelectionObserver}.
231
+ *
232
+ * Note that because {@link module:engine/view/observer/selectionobserver~SelectionObserver} is attached by the
233
+ * {@link module:engine/view/view~View} this event is available by default.
234
+ *
235
+ * @see module:engine/view/observer/selectionobserver~SelectionObserver
236
+ * @event module:engine/view/document~Document#event:selectionChangeDone
237
+ * @param {Object} data
238
+ * @param {module:engine/view/documentselection~DocumentSelection} data.oldSelection Old View selection which is
239
+ * {@link module:engine/view/document~Document#selection}.
240
+ * @param {module:engine/view/selection~Selection} data.newSelection New View selection which is converted DOM selection.
241
+ * @param {Selection} data.domSelection Native DOM selection.
242
+ */