@ckeditor/ckeditor5-engine 35.0.1 → 35.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/CHANGELOG.md +4 -4
  2. package/package.json +30 -24
  3. package/src/controller/datacontroller.js +467 -561
  4. package/src/controller/editingcontroller.js +168 -204
  5. package/src/conversion/conversion.js +541 -565
  6. package/src/conversion/conversionhelpers.js +24 -28
  7. package/src/conversion/downcastdispatcher.js +457 -686
  8. package/src/conversion/downcasthelpers.js +1583 -1965
  9. package/src/conversion/mapper.js +518 -707
  10. package/src/conversion/modelconsumable.js +240 -283
  11. package/src/conversion/upcastdispatcher.js +372 -718
  12. package/src/conversion/upcasthelpers.js +707 -818
  13. package/src/conversion/viewconsumable.js +524 -581
  14. package/src/dataprocessor/basichtmlwriter.js +12 -16
  15. package/src/dataprocessor/dataprocessor.js +5 -0
  16. package/src/dataprocessor/htmldataprocessor.js +100 -116
  17. package/src/dataprocessor/htmlwriter.js +1 -18
  18. package/src/dataprocessor/xmldataprocessor.js +116 -137
  19. package/src/dev-utils/model.js +260 -352
  20. package/src/dev-utils/operationreplayer.js +106 -126
  21. package/src/dev-utils/utils.js +34 -51
  22. package/src/dev-utils/view.js +632 -753
  23. package/src/index.js +0 -11
  24. package/src/model/batch.js +111 -127
  25. package/src/model/differ.js +988 -1233
  26. package/src/model/document.js +340 -449
  27. package/src/model/documentfragment.js +327 -364
  28. package/src/model/documentselection.js +996 -1189
  29. package/src/model/element.js +306 -410
  30. package/src/model/history.js +224 -262
  31. package/src/model/item.js +5 -0
  32. package/src/model/liveposition.js +84 -145
  33. package/src/model/liverange.js +108 -185
  34. package/src/model/markercollection.js +379 -480
  35. package/src/model/model.js +883 -1034
  36. package/src/model/node.js +419 -463
  37. package/src/model/nodelist.js +176 -201
  38. package/src/model/operation/attributeoperation.js +153 -182
  39. package/src/model/operation/detachoperation.js +64 -83
  40. package/src/model/operation/insertoperation.js +135 -166
  41. package/src/model/operation/markeroperation.js +114 -140
  42. package/src/model/operation/mergeoperation.js +163 -191
  43. package/src/model/operation/moveoperation.js +157 -187
  44. package/src/model/operation/nooperation.js +28 -38
  45. package/src/model/operation/operation.js +106 -125
  46. package/src/model/operation/operationfactory.js +30 -34
  47. package/src/model/operation/renameoperation.js +109 -135
  48. package/src/model/operation/rootattributeoperation.js +155 -188
  49. package/src/model/operation/splitoperation.js +196 -232
  50. package/src/model/operation/transform.js +1833 -2204
  51. package/src/model/operation/utils.js +140 -204
  52. package/src/model/position.js +980 -1053
  53. package/src/model/range.js +910 -1028
  54. package/src/model/rootelement.js +77 -97
  55. package/src/model/schema.js +1189 -1835
  56. package/src/model/selection.js +745 -862
  57. package/src/model/text.js +90 -114
  58. package/src/model/textproxy.js +204 -240
  59. package/src/model/treewalker.js +316 -397
  60. package/src/model/typecheckable.js +16 -0
  61. package/src/model/utils/autoparagraphing.js +32 -44
  62. package/src/model/utils/deletecontent.js +334 -418
  63. package/src/model/utils/findoptimalinsertionrange.js +25 -36
  64. package/src/model/utils/getselectedcontent.js +96 -118
  65. package/src/model/utils/insertcontent.js +757 -773
  66. package/src/model/utils/insertobject.js +96 -119
  67. package/src/model/utils/modifyselection.js +120 -158
  68. package/src/model/utils/selection-post-fixer.js +153 -201
  69. package/src/model/writer.js +1305 -1474
  70. package/src/view/attributeelement.js +189 -225
  71. package/src/view/containerelement.js +75 -85
  72. package/src/view/document.js +172 -215
  73. package/src/view/documentfragment.js +200 -249
  74. package/src/view/documentselection.js +338 -367
  75. package/src/view/domconverter.js +1370 -1617
  76. package/src/view/downcastwriter.js +1747 -2076
  77. package/src/view/editableelement.js +81 -97
  78. package/src/view/element.js +739 -890
  79. package/src/view/elementdefinition.js +5 -0
  80. package/src/view/emptyelement.js +82 -92
  81. package/src/view/filler.js +35 -50
  82. package/src/view/item.js +5 -0
  83. package/src/view/matcher.js +260 -559
  84. package/src/view/node.js +274 -360
  85. package/src/view/observer/arrowkeysobserver.js +19 -28
  86. package/src/view/observer/bubblingemittermixin.js +120 -263
  87. package/src/view/observer/bubblingeventinfo.js +47 -55
  88. package/src/view/observer/clickobserver.js +7 -13
  89. package/src/view/observer/compositionobserver.js +14 -24
  90. package/src/view/observer/domeventdata.js +57 -67
  91. package/src/view/observer/domeventobserver.js +40 -64
  92. package/src/view/observer/fakeselectionobserver.js +81 -96
  93. package/src/view/observer/focusobserver.js +45 -61
  94. package/src/view/observer/inputobserver.js +7 -13
  95. package/src/view/observer/keyobserver.js +17 -27
  96. package/src/view/observer/mouseobserver.js +7 -14
  97. package/src/view/observer/mutationobserver.js +220 -315
  98. package/src/view/observer/observer.js +81 -102
  99. package/src/view/observer/selectionobserver.js +199 -246
  100. package/src/view/observer/tabobserver.js +23 -36
  101. package/src/view/placeholder.js +128 -173
  102. package/src/view/position.js +350 -401
  103. package/src/view/range.js +453 -513
  104. package/src/view/rawelement.js +85 -112
  105. package/src/view/renderer.js +874 -1018
  106. package/src/view/rooteditableelement.js +80 -90
  107. package/src/view/selection.js +608 -689
  108. package/src/view/styles/background.js +43 -44
  109. package/src/view/styles/border.js +220 -276
  110. package/src/view/styles/margin.js +8 -17
  111. package/src/view/styles/padding.js +8 -16
  112. package/src/view/styles/utils.js +127 -160
  113. package/src/view/stylesmap.js +728 -905
  114. package/src/view/text.js +102 -126
  115. package/src/view/textproxy.js +144 -170
  116. package/src/view/treewalker.js +383 -479
  117. package/src/view/typecheckable.js +19 -0
  118. package/src/view/uielement.js +166 -187
  119. package/src/view/upcastwriter.js +395 -449
  120. package/src/view/view.js +569 -664
  121. package/src/dataprocessor/dataprocessor.jsdoc +0 -64
  122. package/src/model/item.jsdoc +0 -14
  123. package/src/view/elementdefinition.jsdoc +0 -59
  124. package/src/view/item.jsdoc +0 -14
package/src/view/view.js CHANGED
@@ -2,11 +2,9 @@
2
2
  * @license Copyright (c) 2003-2022, CKSource Holding sp. z o.o. All rights reserved.
3
3
  * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4
4
  */
5
-
6
5
  /**
7
6
  * @module engine/view/view
8
7
  */
9
-
10
8
  import Document from './document';
11
9
  import DowncastWriter from './downcastwriter';
12
10
  import Renderer from './renderer';
@@ -14,7 +12,6 @@ import DomConverter from './domconverter';
14
12
  import Position from './position';
15
13
  import Range from './range';
16
14
  import Selection from './selection';
17
-
18
15
  import MutationObserver from './observer/mutationobserver';
19
16
  import KeyObserver from './observer/keyobserver';
20
17
  import FakeSelectionObserver from './observer/fakeselectionobserver';
@@ -24,15 +21,12 @@ import CompositionObserver from './observer/compositionobserver';
24
21
  import InputObserver from './observer/inputobserver';
25
22
  import ArrowKeysObserver from './observer/arrowkeysobserver';
26
23
  import TabObserver from './observer/tabobserver';
27
-
28
- import ObservableMixin from '@ckeditor/ckeditor5-utils/src/observablemixin';
29
- import mix from '@ckeditor/ckeditor5-utils/src/mix';
24
+ import { Observable } from '@ckeditor/ckeditor5-utils/src/observablemixin';
30
25
  import { scrollViewportToShowTarget } from '@ckeditor/ckeditor5-utils/src/dom/scroll';
31
26
  import { injectUiElementHandling } from './uielement';
32
27
  import { injectQuirksHandling } from './filler';
33
28
  import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
34
29
  import env from '@ckeditor/ckeditor5-utils/src/env';
35
-
36
30
  /**
37
31
  * Editor's view controller class. Its main responsibility is DOM - View management for editing purposes, to provide
38
32
  * abstraction over the DOM structure and events and hide all browsers quirks.
@@ -65,661 +59,572 @@ import env from '@ckeditor/ckeditor5-utils/src/env';
65
59
  *
66
60
  * @mixes module:utils/observablemixin~ObservableMixin
67
61
  */
68
- export default class View {
69
- /**
70
- * @param {module:engine/view/stylesmap~StylesProcessor} stylesProcessor The styles processor instance.
71
- */
72
- constructor( stylesProcessor ) {
73
- /**
74
- * Instance of the {@link module:engine/view/document~Document} associated with this view controller.
75
- *
76
- * @readonly
77
- * @type {module:engine/view/document~Document}
78
- */
79
- this.document = new Document( stylesProcessor );
80
-
81
- /**
82
- * Instance of the {@link module:engine/view/domconverter~DomConverter domConverter} used by
83
- * {@link module:engine/view/view~View#_renderer renderer}
84
- * and {@link module:engine/view/observer/observer~Observer observers}.
85
- *
86
- * @readonly
87
- * @type {module:engine/view/domconverter~DomConverter}
88
- */
89
- this.domConverter = new DomConverter( this.document );
90
-
91
- /**
92
- * Roots of the DOM tree. Map on the `HTMLElement`s with roots names as keys.
93
- *
94
- * @readonly
95
- * @type {Map.<String, HTMLElement>}
96
- */
97
- this.domRoots = new Map();
98
-
99
- /**
100
- * Used to prevent calling {@link #forceRender} and {@link #change} during rendering view to the DOM.
101
- *
102
- * @readonly
103
- * @member {Boolean} #isRenderingInProgress
104
- */
105
- this.set( 'isRenderingInProgress', false );
106
-
107
- /**
108
- * Informs whether the DOM selection is inside any of the DOM roots managed by the view.
109
- *
110
- * @readonly
111
- * @member {Boolean} #hasDomSelection
112
- */
113
- this.set( 'hasDomSelection', false );
114
-
115
- /**
116
- * Instance of the {@link module:engine/view/renderer~Renderer renderer}.
117
- *
118
- * @protected
119
- * @type {module:engine/view/renderer~Renderer}
120
- */
121
- this._renderer = new Renderer( this.domConverter, this.document.selection );
122
- this._renderer.bind( 'isFocused', 'isSelecting' ).to( this.document );
123
-
124
- /**
125
- * A DOM root attributes cache. It saves the initial values of DOM root attributes before the DOM element
126
- * is {@link module:engine/view/view~View#attachDomRoot attached} to the view so later on, when
127
- * the view is destroyed ({@link module:engine/view/view~View#detachDomRoot}), they can be easily restored.
128
- * This way, the DOM element can go back to the (clean) state as if the editing view never used it.
129
- *
130
- * @private
131
- * @member {WeakMap.<HTMLElement,Object>}
132
- */
133
- this._initialDomRootAttributes = new WeakMap();
134
-
135
- /**
136
- * Map of registered {@link module:engine/view/observer/observer~Observer observers}.
137
- *
138
- * @private
139
- * @type {Map.<Function, module:engine/view/observer/observer~Observer>}
140
- */
141
- this._observers = new Map();
142
-
143
- /**
144
- * Is set to `true` when {@link #change view changes} are currently in progress.
145
- *
146
- * @private
147
- * @type {Boolean}
148
- */
149
- this._ongoingChange = false;
150
-
151
- /**
152
- * Used to prevent calling {@link #forceRender} and {@link #change} during rendering view to the DOM.
153
- *
154
- * @private
155
- * @type {Boolean}
156
- */
157
- this._postFixersInProgress = false;
158
-
159
- /**
160
- * Internal flag to temporary disable rendering. See the usage in the {@link #_disableRendering}.
161
- *
162
- * @private
163
- * @type {Boolean}
164
- */
165
- this._renderingDisabled = false;
166
-
167
- /**
168
- * Internal flag that disables rendering when there are no changes since the last rendering.
169
- * It stores information about changed selection and changed elements from attached document roots.
170
- *
171
- * @private
172
- * @type {Boolean}
173
- */
174
- this._hasChangedSinceTheLastRendering = false;
175
-
176
- /**
177
- * DowncastWriter instance used in {@link #change change method} callbacks.
178
- *
179
- * @private
180
- * @type {module:engine/view/downcastwriter~DowncastWriter}
181
- */
182
- this._writer = new DowncastWriter( this.document );
183
-
184
- // Add default observers.
185
- this.addObserver( MutationObserver );
186
- this.addObserver( SelectionObserver );
187
- this.addObserver( FocusObserver );
188
- this.addObserver( KeyObserver );
189
- this.addObserver( FakeSelectionObserver );
190
- this.addObserver( CompositionObserver );
191
- this.addObserver( ArrowKeysObserver );
192
- this.addObserver( TabObserver );
193
-
194
- if ( env.isAndroid ) {
195
- this.addObserver( InputObserver );
196
- }
197
-
198
- // Inject quirks handlers.
199
- injectQuirksHandling( this );
200
- injectUiElementHandling( this );
201
-
202
- // Use 'normal' priority so that rendering is performed as first when using that priority.
203
- this.on( 'render', () => {
204
- this._render();
205
-
206
- // Informs that layout has changed after render.
207
- this.document.fire( 'layoutChanged' );
208
-
209
- // Reset the `_hasChangedSinceTheLastRendering` flag after rendering.
210
- this._hasChangedSinceTheLastRendering = false;
211
- } );
212
-
213
- // Listen to the document selection changes directly.
214
- this.listenTo( this.document.selection, 'change', () => {
215
- this._hasChangedSinceTheLastRendering = true;
216
- } );
217
-
218
- // Trigger re-render if only the focus changed.
219
- this.listenTo( this.document, 'change:isFocused', () => {
220
- this._hasChangedSinceTheLastRendering = true;
221
- } );
222
- }
223
-
224
- /**
225
- * Attaches a DOM root element to the view element and enable all observers on that element.
226
- * Also {@link module:engine/view/renderer~Renderer#markToSync mark element} to be synchronized
227
- * with the view what means that all child nodes will be removed and replaced with content of the view root.
228
- *
229
- * This method also will change view element name as the same as tag name of given dom root.
230
- * Name is always transformed to lower case.
231
- *
232
- * **Note:** Use {@link #detachDomRoot `detachDomRoot()`} to revert this action.
233
- *
234
- * @param {Element} domRoot DOM root element.
235
- * @param {String} [name='main'] Name of the root.
236
- */
237
- attachDomRoot( domRoot, name = 'main' ) {
238
- const viewRoot = this.document.getRoot( name );
239
-
240
- // Set view root name the same as DOM root tag name.
241
- viewRoot._name = domRoot.tagName.toLowerCase();
242
-
243
- const initialDomRootAttributes = {};
244
-
245
- // 1. Copy and cache the attributes to remember the state of the element before attaching.
246
- // The cached attributes will be restored in detachDomRoot() so the element goes to the
247
- // clean state as if the editing view never used it.
248
- // 2. Apply the attributes using the view writer, so they all go under the control of the engine.
249
- // The editing view takes over the attribute management completely because various
250
- // features (e.g. addPlaceholder()) require dynamic changes of those attributes and they
251
- // cannot be managed by the engine and the UI library at the same time.
252
- for ( const { name, value } of Array.from( domRoot.attributes ) ) {
253
- initialDomRootAttributes[ name ] = value;
254
-
255
- // Do not use writer.setAttribute() for the class attribute. The EditableUIView class
256
- // and its descendants could have already set some using the writer.addClass() on the view
257
- // document root. They haven't been rendered yet so they are not present in the DOM root.
258
- // Using writer.setAttribute( 'class', ... ) would override them completely.
259
- if ( name === 'class' ) {
260
- this._writer.addClass( value.split( ' ' ), viewRoot );
261
- } else {
262
- this._writer.setAttribute( name, value, viewRoot );
263
- }
264
- }
265
-
266
- this._initialDomRootAttributes.set( domRoot, initialDomRootAttributes );
267
-
268
- const updateContenteditableAttribute = () => {
269
- this._writer.setAttribute( 'contenteditable', !viewRoot.isReadOnly, viewRoot );
270
-
271
- if ( viewRoot.isReadOnly ) {
272
- this._writer.addClass( 'ck-read-only', viewRoot );
273
- } else {
274
- this._writer.removeClass( 'ck-read-only', viewRoot );
275
- }
276
- };
277
-
278
- // Set initial value.
279
- updateContenteditableAttribute();
280
-
281
- this.domRoots.set( name, domRoot );
282
- this.domConverter.bindElements( domRoot, viewRoot );
283
- this._renderer.markToSync( 'children', viewRoot );
284
- this._renderer.markToSync( 'attributes', viewRoot );
285
- this._renderer.domDocuments.add( domRoot.ownerDocument );
286
-
287
- viewRoot.on( 'change:children', ( evt, node ) => this._renderer.markToSync( 'children', node ) );
288
- viewRoot.on( 'change:attributes', ( evt, node ) => this._renderer.markToSync( 'attributes', node ) );
289
- viewRoot.on( 'change:text', ( evt, node ) => this._renderer.markToSync( 'text', node ) );
290
- viewRoot.on( 'change:isReadOnly', () => this.change( updateContenteditableAttribute ) );
291
-
292
- viewRoot.on( 'change', () => {
293
- this._hasChangedSinceTheLastRendering = true;
294
- } );
295
-
296
- for ( const observer of this._observers.values() ) {
297
- observer.observe( domRoot, name );
298
- }
299
- }
300
-
301
- /**
302
- * Detaches a DOM root element from the view element and restores its attributes to the state before
303
- * {@link #attachDomRoot `attachDomRoot()`}.
304
- *
305
- * @param {String} name Name of the root to detach.
306
- */
307
- detachDomRoot( name ) {
308
- const domRoot = this.domRoots.get( name );
309
-
310
- // Remove all root attributes so the DOM element is "bare".
311
- Array.from( domRoot.attributes ).forEach( ( { name } ) => domRoot.removeAttribute( name ) );
312
-
313
- const initialDomRootAttributes = this._initialDomRootAttributes.get( domRoot );
314
-
315
- // Revert all view root attributes back to the state before attachDomRoot was called.
316
- for ( const attribute in initialDomRootAttributes ) {
317
- domRoot.setAttribute( attribute, initialDomRootAttributes[ attribute ] );
318
- }
319
-
320
- this.domRoots.delete( name );
321
- this.domConverter.unbindDomElement( domRoot );
322
- }
323
-
324
- /**
325
- * Gets DOM root element.
326
- *
327
- * @param {String} [name='main'] Name of the root.
328
- * @returns {Element} DOM root element instance.
329
- */
330
- getDomRoot( name = 'main' ) {
331
- return this.domRoots.get( name );
332
- }
333
-
334
- /**
335
- * Creates observer of the given type if not yet created, {@link module:engine/view/observer/observer~Observer#enable enables} it
336
- * and {@link module:engine/view/observer/observer~Observer#observe attaches} to all existing and future
337
- * {@link #domRoots DOM roots}.
338
- *
339
- * Note: Observers are recognized by their constructor (classes). A single observer will be instantiated and used only
340
- * when registered for the first time. This means that features and other components can register a single observer
341
- * multiple times without caring whether it has been already added or not.
342
- *
343
- * @param {Function} Observer The constructor of an observer to add.
344
- * Should create an instance inheriting from {@link module:engine/view/observer/observer~Observer}.
345
- * @returns {module:engine/view/observer/observer~Observer} Added observer instance.
346
- */
347
- addObserver( Observer ) {
348
- let observer = this._observers.get( Observer );
349
-
350
- if ( observer ) {
351
- return observer;
352
- }
353
-
354
- observer = new Observer( this );
355
-
356
- this._observers.set( Observer, observer );
357
-
358
- for ( const [ name, domElement ] of this.domRoots ) {
359
- observer.observe( domElement, name );
360
- }
361
-
362
- observer.enable();
363
-
364
- return observer;
365
- }
366
-
367
- /**
368
- * Returns observer of the given type or `undefined` if such observer has not been added yet.
369
- *
370
- * @param {Function} Observer The constructor of an observer to get.
371
- * @returns {module:engine/view/observer/observer~Observer|undefined} Observer instance or undefined.
372
- */
373
- getObserver( Observer ) {
374
- return this._observers.get( Observer );
375
- }
376
-
377
- /**
378
- * Disables all added observers.
379
- */
380
- disableObservers() {
381
- for ( const observer of this._observers.values() ) {
382
- observer.disable();
383
- }
384
- }
385
-
386
- /**
387
- * Enables all added observers.
388
- */
389
- enableObservers() {
390
- for ( const observer of this._observers.values() ) {
391
- observer.enable();
392
- }
393
- }
394
-
395
- /**
396
- * Scrolls the page viewport and {@link #domRoots} with their ancestors to reveal the
397
- * caret, if not already visible to the user.
398
- */
399
- scrollToTheSelection() {
400
- const range = this.document.selection.getFirstRange();
401
-
402
- if ( range ) {
403
- scrollViewportToShowTarget( {
404
- target: this.domConverter.viewRangeToDom( range ),
405
- viewportOffset: 20
406
- } );
407
- }
408
- }
409
-
410
- /**
411
- * It will focus DOM element representing {@link module:engine/view/editableelement~EditableElement EditableElement}
412
- * that is currently having selection inside.
413
- */
414
- focus() {
415
- if ( !this.document.isFocused ) {
416
- const editable = this.document.selection.editableElement;
417
-
418
- if ( editable ) {
419
- this.domConverter.focus( editable );
420
- this.forceRender();
421
- } else {
422
- // Before focusing view document, selection should be placed inside one of the view's editables.
423
- // Normally its selection will be converted from model document (which have default selection), but
424
- // when using view document on its own, we need to manually place selection before focusing it.
425
- //
426
- // @if CK_DEBUG // console.warn( 'There is no selection in any editable to focus.' );
427
- }
428
- }
429
- }
430
-
431
- /**
432
- * The `change()` method is the primary way of changing the view. You should use it to modify any node in the view tree.
433
- * It makes sure that after all changes are made the view is rendered to the DOM (assuming that the view will be changed
434
- * inside the callback). It prevents situations when the DOM is updated when the view state is not yet correct. It allows
435
- * to nest calls one inside another and still performs a single rendering after all those changes are made.
436
- * It also returns the return value of its callback.
437
- *
438
- * const text = view.change( writer => {
439
- * const newText = writer.createText( 'foo' );
440
- * writer.insert( position1, newText );
441
- *
442
- * view.change( writer => {
443
- * writer.insert( position2, writer.createText( 'bar' ) );
444
- * } );
445
- *
446
- * writer.remove( range );
447
- *
448
- * return newText;
449
- * } );
450
- *
451
- * When the outermost change block is done and rendering to the DOM is over the
452
- * {@link module:engine/view/view~View#event:render `View#render`} event is fired.
453
- *
454
- * This method throws a `applying-view-changes-on-rendering` error when
455
- * the change block is used after rendering to the DOM has started.
456
- *
457
- * @param {Function} callback Callback function which may modify the view.
458
- * @returns {*} Value returned by the callback.
459
- */
460
- change( callback ) {
461
- if ( this.isRenderingInProgress || this._postFixersInProgress ) {
462
- /**
463
- * Thrown when there is an attempt to make changes to the view tree when it is in incorrect state. This may
464
- * cause some unexpected behaviour and inconsistency between the DOM and the view.
465
- * This may be caused by:
466
- *
467
- * * calling {@link #change} or {@link #forceRender} during rendering process,
468
- * * calling {@link #change} or {@link #forceRender} inside of
469
- * {@link module:engine/view/document~Document#registerPostFixer post-fixer function}.
470
- *
471
- * @error cannot-change-view-tree
472
- */
473
- throw new CKEditorError(
474
- 'cannot-change-view-tree',
475
- this
476
- );
477
- }
478
-
479
- try {
480
- // Recursive call to view.change() method - execute listener immediately.
481
- if ( this._ongoingChange ) {
482
- return callback( this._writer );
483
- }
484
-
485
- // This lock will assure that all recursive calls to view.change() will end up in same block - one "render"
486
- // event for all nested calls.
487
- this._ongoingChange = true;
488
- const callbackResult = callback( this._writer );
489
- this._ongoingChange = false;
490
-
491
- // This lock is used by editing controller to render changes from outer most model.change() once. As plugins might call
492
- // view.change() inside model.change() block - this will ensures that postfixers and rendering are called once after all
493
- // changes. Also, we don't need to render anything if there're no changes since last rendering.
494
- if ( !this._renderingDisabled && this._hasChangedSinceTheLastRendering ) {
495
- this._postFixersInProgress = true;
496
- this.document._callPostFixers( this._writer );
497
- this._postFixersInProgress = false;
498
-
499
- this.fire( 'render' );
500
- }
501
-
502
- return callbackResult;
503
- } catch ( err ) {
504
- // @if CK_DEBUG // throw err;
505
- /* istanbul ignore next */
506
- CKEditorError.rethrowUnexpectedError( err, this );
507
- }
508
- }
509
-
510
- /**
511
- * Forces rendering {@link module:engine/view/document~Document view document} to DOM. If any view changes are
512
- * currently in progress, rendering will start after all {@link #change change blocks} are processed.
513
- *
514
- * Note that this method is dedicated for special cases. All view changes should be wrapped in the {@link #change}
515
- * block and the view will automatically check whether it needs to render DOM or not.
516
- *
517
- * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `applying-view-changes-on-rendering` when
518
- * trying to re-render when rendering to DOM has already started.
519
- */
520
- forceRender() {
521
- this._hasChangedSinceTheLastRendering = true;
522
- this.change( () => {} );
523
- }
524
-
525
- /**
526
- * Destroys this instance. Makes sure that all observers are destroyed and listeners removed.
527
- */
528
- destroy() {
529
- for ( const observer of this._observers.values() ) {
530
- observer.destroy();
531
- }
532
-
533
- this.document.destroy();
534
-
535
- this.stopListening();
536
- }
537
-
538
- /**
539
- * Creates position at the given location. The location can be specified as:
540
- *
541
- * * a {@link module:engine/view/position~Position position},
542
- * * parent element and offset (offset defaults to `0`),
543
- * * parent element and `'end'` (sets position at the end of that element),
544
- * * {@link module:engine/view/item~Item view item} and `'before'` or `'after'` (sets position before or after given view item).
545
- *
546
- * This method is a shortcut to other constructors such as:
547
- *
548
- * * {@link #createPositionBefore},
549
- * * {@link #createPositionAfter},
550
- *
551
- * @param {module:engine/view/item~Item|module:engine/model/position~Position} itemOrPosition
552
- * @param {Number|'end'|'before'|'after'} [offset] Offset or one of the flags. Used only when
553
- * first parameter is a {@link module:engine/view/item~Item view item}.
554
- */
555
- createPositionAt( itemOrPosition, offset ) {
556
- return Position._createAt( itemOrPosition, offset );
557
- }
558
-
559
- /**
560
- * Creates a new position after given view item.
561
- *
562
- * @param {module:engine/view/item~Item} item View item after which the position should be located.
563
- * @returns {module:engine/view/position~Position}
564
- */
565
- createPositionAfter( item ) {
566
- return Position._createAfter( item );
567
- }
568
-
569
- /**
570
- * Creates a new position before given view item.
571
- *
572
- * @param {module:engine/view/item~Item} item View item before which the position should be located.
573
- * @returns {module:engine/view/position~Position}
574
- */
575
- createPositionBefore( item ) {
576
- return Position._createBefore( item );
577
- }
578
-
579
- /**
580
- * Creates a range spanning from `start` position to `end` position.
581
- *
582
- * **Note:** This factory method creates it's own {@link module:engine/view/position~Position} instances basing on passed values.
583
- *
584
- * @param {module:engine/view/position~Position} start Start position.
585
- * @param {module:engine/view/position~Position} [end] End position. If not set, range will be collapsed at `start` position.
586
- * @returns {module:engine/view/range~Range}
587
- */
588
- createRange( start, end ) {
589
- return new Range( start, end );
590
- }
591
-
592
- /**
593
- * Creates a range that starts before given {@link module:engine/view/item~Item view item} and ends after it.
594
- *
595
- * @param {module:engine/view/item~Item} item
596
- * @returns {module:engine/view/range~Range}
597
- */
598
- createRangeOn( item ) {
599
- return Range._createOn( item );
600
- }
601
-
602
- /**
603
- * Creates a range inside an {@link module:engine/view/element~Element element} which starts before the first child of
604
- * that element and ends after the last child of that element.
605
- *
606
- * @param {module:engine/view/element~Element} element Element which is a parent for the range.
607
- * @returns {module:engine/view/range~Range}
608
- */
609
- createRangeIn( element ) {
610
- return Range._createIn( element );
611
- }
612
-
613
- /**
614
- Creates new {@link module:engine/view/selection~Selection} instance.
615
- *
616
- * // Creates empty selection without ranges.
617
- * const selection = view.createSelection();
618
- *
619
- * // Creates selection at the given range.
620
- * const range = view.createRange( start, end );
621
- * const selection = view.createSelection( range );
622
- *
623
- * // Creates selection at the given ranges
624
- * const ranges = [ view.createRange( start1, end2 ), view.createRange( star2, end2 ) ];
625
- * const selection = view.createSelection( ranges );
626
- *
627
- * // Creates selection from the other selection.
628
- * const otherSelection = view.createSelection();
629
- * const selection = view.createSelection( otherSelection );
630
- *
631
- * // Creates selection from the document selection.
632
- * const selection = view.createSelection( editor.editing.view.document.selection );
633
- *
634
- * // Creates selection at the given position.
635
- * const position = view.createPositionFromPath( root, path );
636
- * const selection = view.createSelection( position );
637
- *
638
- * // Creates collapsed selection at the position of given item and offset.
639
- * const paragraph = view.createContainerElement( 'paragraph' );
640
- * const selection = view.createSelection( paragraph, offset );
641
- *
642
- * // Creates a range inside an {@link module:engine/view/element~Element element} which starts before the
643
- * // first child of that element and ends after the last child of that element.
644
- * const selection = view.createSelection( paragraph, 'in' );
645
- *
646
- * // Creates a range on an {@link module:engine/view/item~Item item} which starts before the item and ends
647
- * // just after the item.
648
- * const selection = view.createSelection( paragraph, 'on' );
649
- *
650
- * `Selection`'s factory method allow passing additional options (`backward`, `fake` and `label`) as the last argument.
651
- *
652
- * // Creates backward selection.
653
- * const selection = view.createSelection( range, { backward: true } );
654
- *
655
- * Fake selection does not render as browser native selection over selected elements and is hidden to the user.
656
- * This way, no native selection UI artifacts are displayed to the user and selection over elements can be
657
- * represented in other way, for example by applying proper CSS class.
658
- *
659
- * Additionally fake's selection label can be provided. It will be used to describe fake selection in DOM
660
- * (and be properly handled by screen readers).
661
- *
662
- * // Creates fake selection with label.
663
- * const selection = view.createSelection( range, { fake: true, label: 'foo' } );
664
- *
665
- * @param {module:engine/view/selection~Selectable} [selectable=null]
666
- * @param {Number|'before'|'end'|'after'|'on'|'in'} [placeOrOffset] Offset or place when selectable is an `Item`.
667
- * @param {Object} [options]
668
- * @param {Boolean} [options.backward] Sets this selection instance to be backward.
669
- * @param {Boolean} [options.fake] Sets this selection instance to be marked as `fake`.
670
- * @param {String} [options.label] Label for the fake selection.
671
- * @returns {module:engine/view/selection~Selection}
672
- */
673
- createSelection( selectable, placeOrOffset, options ) {
674
- return new Selection( selectable, placeOrOffset, options );
675
- }
676
-
677
- /**
678
- * Disables or enables rendering. If the flag is set to `true` then the rendering will be disabled.
679
- * If the flag is set to `false` and if there was some change in the meantime, then the rendering action will be performed.
680
- *
681
- * @protected
682
- * @param {Boolean} flag A flag indicates whether the rendering should be disabled.
683
- */
684
- _disableRendering( flag ) {
685
- this._renderingDisabled = flag;
686
-
687
- if ( flag == false ) {
688
- // Render when you stop blocking rendering.
689
- this.change( () => {} );
690
- }
691
- }
692
-
693
- /**
694
- * Renders all changes. In order to avoid triggering the observers (e.g. mutations) all observers are disabled
695
- * before rendering and re-enabled after that.
696
- *
697
- * @private
698
- */
699
- _render() {
700
- this.isRenderingInProgress = true;
701
- this.disableObservers();
702
- this._renderer.render();
703
- this.enableObservers();
704
- this.isRenderingInProgress = false;
705
- }
706
-
707
- /**
708
- * Fired after a topmost {@link module:engine/view/view~View#change change block} and all
709
- * {@link module:engine/view/document~Document#registerPostFixer post-fixers} are executed.
710
- *
711
- * Actual rendering is performed as a first listener on 'normal' priority.
712
- *
713
- * view.on( 'render', () => {
714
- * // Rendering to the DOM is complete.
715
- * } );
716
- *
717
- * This event is useful when you want to update interface elements after the rendering, e.g. position of the
718
- * balloon panel. If you wants to change view structure use
719
- * {@link module:engine/view/document~Document#registerPostFixer post-fixers}.
720
- *
721
- * @event module:engine/view/view~View#event:render
722
- */
62
+ export default class View extends Observable {
63
+ /**
64
+ * @param {module:engine/view/stylesmap~StylesProcessor} stylesProcessor The styles processor instance.
65
+ */
66
+ constructor(stylesProcessor) {
67
+ super();
68
+ /**
69
+ * Instance of the {@link module:engine/view/document~Document} associated with this view controller.
70
+ *
71
+ * @readonly
72
+ * @type {module:engine/view/document~Document}
73
+ */
74
+ this.document = new Document(stylesProcessor);
75
+ /**
76
+ * Instance of the {@link module:engine/view/domconverter~DomConverter domConverter} used by
77
+ * {@link module:engine/view/view~View#_renderer renderer}
78
+ * and {@link module:engine/view/observer/observer~Observer observers}.
79
+ *
80
+ * @readonly
81
+ * @type {module:engine/view/domconverter~DomConverter}
82
+ */
83
+ this.domConverter = new DomConverter(this.document);
84
+ /**
85
+ * Roots of the DOM tree. Map on the `HTMLElement`s with roots names as keys.
86
+ *
87
+ * @readonly
88
+ * @type {Map.<String, HTMLElement>}
89
+ */
90
+ this.domRoots = new Map();
91
+ /**
92
+ * Used to prevent calling {@link #forceRender} and {@link #change} during rendering view to the DOM.
93
+ *
94
+ * @readonly
95
+ * @member {Boolean} #isRenderingInProgress
96
+ */
97
+ this.set('isRenderingInProgress', false);
98
+ /**
99
+ * Informs whether the DOM selection is inside any of the DOM roots managed by the view.
100
+ *
101
+ * @readonly
102
+ * @member {Boolean} #hasDomSelection
103
+ */
104
+ this.set('hasDomSelection', false);
105
+ /**
106
+ * Instance of the {@link module:engine/view/renderer~Renderer renderer}.
107
+ *
108
+ * @protected
109
+ * @type {module:engine/view/renderer~Renderer}
110
+ */
111
+ this._renderer = new Renderer(this.domConverter, this.document.selection);
112
+ this._renderer.bind('isFocused', 'isSelecting').to(this.document, 'isFocused', 'isSelecting');
113
+ /**
114
+ * A DOM root attributes cache. It saves the initial values of DOM root attributes before the DOM element
115
+ * is {@link module:engine/view/view~View#attachDomRoot attached} to the view so later on, when
116
+ * the view is destroyed ({@link module:engine/view/view~View#detachDomRoot}), they can be easily restored.
117
+ * This way, the DOM element can go back to the (clean) state as if the editing view never used it.
118
+ *
119
+ * @private
120
+ * @member {WeakMap.<HTMLElement,Object>}
121
+ */
122
+ this._initialDomRootAttributes = new WeakMap();
123
+ /**
124
+ * Map of registered {@link module:engine/view/observer/observer~Observer observers}.
125
+ *
126
+ * @private
127
+ * @type {Map.<Function, module:engine/view/observer/observer~Observer>}
128
+ */
129
+ this._observers = new Map();
130
+ /**
131
+ * Is set to `true` when {@link #change view changes} are currently in progress.
132
+ *
133
+ * @private
134
+ * @type {Boolean}
135
+ */
136
+ this._ongoingChange = false;
137
+ /**
138
+ * Used to prevent calling {@link #forceRender} and {@link #change} during rendering view to the DOM.
139
+ *
140
+ * @private
141
+ * @type {Boolean}
142
+ */
143
+ this._postFixersInProgress = false;
144
+ /**
145
+ * Internal flag to temporary disable rendering. See the usage in the {@link #_disableRendering}.
146
+ *
147
+ * @private
148
+ * @type {Boolean}
149
+ */
150
+ this._renderingDisabled = false;
151
+ /**
152
+ * Internal flag that disables rendering when there are no changes since the last rendering.
153
+ * It stores information about changed selection and changed elements from attached document roots.
154
+ *
155
+ * @private
156
+ * @type {Boolean}
157
+ */
158
+ this._hasChangedSinceTheLastRendering = false;
159
+ /**
160
+ * DowncastWriter instance used in {@link #change change method} callbacks.
161
+ *
162
+ * @private
163
+ * @type {module:engine/view/downcastwriter~DowncastWriter}
164
+ */
165
+ this._writer = new DowncastWriter(this.document);
166
+ // Add default observers.
167
+ this.addObserver(MutationObserver);
168
+ this.addObserver(SelectionObserver);
169
+ this.addObserver(FocusObserver);
170
+ this.addObserver(KeyObserver);
171
+ this.addObserver(FakeSelectionObserver);
172
+ this.addObserver(CompositionObserver);
173
+ this.addObserver(ArrowKeysObserver);
174
+ this.addObserver(TabObserver);
175
+ if (env.isAndroid) {
176
+ this.addObserver(InputObserver);
177
+ }
178
+ // Inject quirks handlers.
179
+ injectQuirksHandling(this);
180
+ injectUiElementHandling(this);
181
+ // Use 'normal' priority so that rendering is performed as first when using that priority.
182
+ this.on('render', () => {
183
+ this._render();
184
+ // Informs that layout has changed after render.
185
+ this.document.fire('layoutChanged');
186
+ // Reset the `_hasChangedSinceTheLastRendering` flag after rendering.
187
+ this._hasChangedSinceTheLastRendering = false;
188
+ });
189
+ // Listen to the document selection changes directly.
190
+ this.listenTo(this.document.selection, 'change', () => {
191
+ this._hasChangedSinceTheLastRendering = true;
192
+ });
193
+ // Trigger re-render if only the focus changed.
194
+ this.listenTo(this.document, 'change:isFocused', () => {
195
+ this._hasChangedSinceTheLastRendering = true;
196
+ });
197
+ }
198
+ /**
199
+ * Attaches a DOM root element to the view element and enable all observers on that element.
200
+ * Also {@link module:engine/view/renderer~Renderer#markToSync mark element} to be synchronized
201
+ * with the view what means that all child nodes will be removed and replaced with content of the view root.
202
+ *
203
+ * This method also will change view element name as the same as tag name of given dom root.
204
+ * Name is always transformed to lower case.
205
+ *
206
+ * **Note:** Use {@link #detachDomRoot `detachDomRoot()`} to revert this action.
207
+ *
208
+ * @param {Element} domRoot DOM root element.
209
+ * @param {String} [name='main'] Name of the root.
210
+ */
211
+ attachDomRoot(domRoot, name = 'main') {
212
+ const viewRoot = this.document.getRoot(name);
213
+ // Set view root name the same as DOM root tag name.
214
+ viewRoot._name = domRoot.tagName.toLowerCase();
215
+ const initialDomRootAttributes = {};
216
+ // 1. Copy and cache the attributes to remember the state of the element before attaching.
217
+ // The cached attributes will be restored in detachDomRoot() so the element goes to the
218
+ // clean state as if the editing view never used it.
219
+ // 2. Apply the attributes using the view writer, so they all go under the control of the engine.
220
+ // The editing view takes over the attribute management completely because various
221
+ // features (e.g. addPlaceholder()) require dynamic changes of those attributes and they
222
+ // cannot be managed by the engine and the UI library at the same time.
223
+ for (const { name, value } of Array.from(domRoot.attributes)) {
224
+ initialDomRootAttributes[name] = value;
225
+ // Do not use writer.setAttribute() for the class attribute. The EditableUIView class
226
+ // and its descendants could have already set some using the writer.addClass() on the view
227
+ // document root. They haven't been rendered yet so they are not present in the DOM root.
228
+ // Using writer.setAttribute( 'class', ... ) would override them completely.
229
+ if (name === 'class') {
230
+ this._writer.addClass(value.split(' '), viewRoot);
231
+ }
232
+ else {
233
+ this._writer.setAttribute(name, value, viewRoot);
234
+ }
235
+ }
236
+ this._initialDomRootAttributes.set(domRoot, initialDomRootAttributes);
237
+ const updateContenteditableAttribute = () => {
238
+ this._writer.setAttribute('contenteditable', (!viewRoot.isReadOnly).toString(), viewRoot);
239
+ if (viewRoot.isReadOnly) {
240
+ this._writer.addClass('ck-read-only', viewRoot);
241
+ }
242
+ else {
243
+ this._writer.removeClass('ck-read-only', viewRoot);
244
+ }
245
+ };
246
+ // Set initial value.
247
+ updateContenteditableAttribute();
248
+ this.domRoots.set(name, domRoot);
249
+ this.domConverter.bindElements(domRoot, viewRoot);
250
+ this._renderer.markToSync('children', viewRoot);
251
+ this._renderer.markToSync('attributes', viewRoot);
252
+ this._renderer.domDocuments.add(domRoot.ownerDocument);
253
+ viewRoot.on('change:children', (evt, node) => this._renderer.markToSync('children', node));
254
+ viewRoot.on('change:attributes', (evt, node) => this._renderer.markToSync('attributes', node));
255
+ viewRoot.on('change:text', (evt, node) => this._renderer.markToSync('text', node));
256
+ viewRoot.on('change:isReadOnly', () => this.change(updateContenteditableAttribute));
257
+ viewRoot.on('change', () => {
258
+ this._hasChangedSinceTheLastRendering = true;
259
+ });
260
+ for (const observer of this._observers.values()) {
261
+ observer.observe(domRoot, name);
262
+ }
263
+ }
264
+ /**
265
+ * Detaches a DOM root element from the view element and restores its attributes to the state before
266
+ * {@link #attachDomRoot `attachDomRoot()`}.
267
+ *
268
+ * @param {String} name Name of the root to detach.
269
+ */
270
+ detachDomRoot(name) {
271
+ const domRoot = this.domRoots.get(name);
272
+ // Remove all root attributes so the DOM element is "bare".
273
+ Array.from(domRoot.attributes).forEach(({ name }) => domRoot.removeAttribute(name));
274
+ const initialDomRootAttributes = this._initialDomRootAttributes.get(domRoot);
275
+ // Revert all view root attributes back to the state before attachDomRoot was called.
276
+ for (const attribute in initialDomRootAttributes) {
277
+ domRoot.setAttribute(attribute, initialDomRootAttributes[attribute]);
278
+ }
279
+ this.domRoots.delete(name);
280
+ this.domConverter.unbindDomElement(domRoot);
281
+ }
282
+ /**
283
+ * Gets DOM root element.
284
+ *
285
+ * @param {String} [name='main'] Name of the root.
286
+ * @returns {Element} DOM root element instance.
287
+ */
288
+ getDomRoot(name = 'main') {
289
+ return this.domRoots.get(name);
290
+ }
291
+ /**
292
+ * Creates observer of the given type if not yet created, {@link module:engine/view/observer/observer~Observer#enable enables} it
293
+ * and {@link module:engine/view/observer/observer~Observer#observe attaches} to all existing and future
294
+ * {@link #domRoots DOM roots}.
295
+ *
296
+ * Note: Observers are recognized by their constructor (classes). A single observer will be instantiated and used only
297
+ * when registered for the first time. This means that features and other components can register a single observer
298
+ * multiple times without caring whether it has been already added or not.
299
+ *
300
+ * @param {Function} Observer The constructor of an observer to add.
301
+ * Should create an instance inheriting from {@link module:engine/view/observer/observer~Observer}.
302
+ * @returns {module:engine/view/observer/observer~Observer} Added observer instance.
303
+ */
304
+ addObserver(ObserverConstructor) {
305
+ let observer = this._observers.get(ObserverConstructor);
306
+ if (observer) {
307
+ return observer;
308
+ }
309
+ observer = new ObserverConstructor(this);
310
+ this._observers.set(ObserverConstructor, observer);
311
+ for (const [name, domElement] of this.domRoots) {
312
+ observer.observe(domElement, name);
313
+ }
314
+ observer.enable();
315
+ return observer;
316
+ }
317
+ /**
318
+ * Returns observer of the given type or `undefined` if such observer has not been added yet.
319
+ *
320
+ * @param {Function} Observer The constructor of an observer to get.
321
+ * @returns {module:engine/view/observer/observer~Observer|undefined} Observer instance or undefined.
322
+ */
323
+ getObserver(ObserverConstructor) {
324
+ return this._observers.get(ObserverConstructor);
325
+ }
326
+ /**
327
+ * Disables all added observers.
328
+ */
329
+ disableObservers() {
330
+ for (const observer of this._observers.values()) {
331
+ observer.disable();
332
+ }
333
+ }
334
+ /**
335
+ * Enables all added observers.
336
+ */
337
+ enableObservers() {
338
+ for (const observer of this._observers.values()) {
339
+ observer.enable();
340
+ }
341
+ }
342
+ /**
343
+ * Scrolls the page viewport and {@link #domRoots} with their ancestors to reveal the
344
+ * caret, if not already visible to the user.
345
+ */
346
+ scrollToTheSelection() {
347
+ const range = this.document.selection.getFirstRange();
348
+ if (range) {
349
+ scrollViewportToShowTarget({
350
+ target: this.domConverter.viewRangeToDom(range),
351
+ viewportOffset: 20
352
+ });
353
+ }
354
+ }
355
+ /**
356
+ * It will focus DOM element representing {@link module:engine/view/editableelement~EditableElement EditableElement}
357
+ * that is currently having selection inside.
358
+ */
359
+ focus() {
360
+ if (!this.document.isFocused) {
361
+ const editable = this.document.selection.editableElement;
362
+ if (editable) {
363
+ this.domConverter.focus(editable);
364
+ this.forceRender();
365
+ }
366
+ else {
367
+ // Before focusing view document, selection should be placed inside one of the view's editables.
368
+ // Normally its selection will be converted from model document (which have default selection), but
369
+ // when using view document on its own, we need to manually place selection before focusing it.
370
+ //
371
+ // @if CK_DEBUG // console.warn( 'There is no selection in any editable to focus.' );
372
+ }
373
+ }
374
+ }
375
+ /**
376
+ * The `change()` method is the primary way of changing the view. You should use it to modify any node in the view tree.
377
+ * It makes sure that after all changes are made the view is rendered to the DOM (assuming that the view will be changed
378
+ * inside the callback). It prevents situations when the DOM is updated when the view state is not yet correct. It allows
379
+ * to nest calls one inside another and still performs a single rendering after all those changes are made.
380
+ * It also returns the return value of its callback.
381
+ *
382
+ * const text = view.change( writer => {
383
+ * const newText = writer.createText( 'foo' );
384
+ * writer.insert( position1, newText );
385
+ *
386
+ * view.change( writer => {
387
+ * writer.insert( position2, writer.createText( 'bar' ) );
388
+ * } );
389
+ *
390
+ * writer.remove( range );
391
+ *
392
+ * return newText;
393
+ * } );
394
+ *
395
+ * When the outermost change block is done and rendering to the DOM is over the
396
+ * {@link module:engine/view/view~View#event:render `View#render`} event is fired.
397
+ *
398
+ * This method throws a `applying-view-changes-on-rendering` error when
399
+ * the change block is used after rendering to the DOM has started.
400
+ *
401
+ * @param {Function} callback Callback function which may modify the view.
402
+ * @returns {*} Value returned by the callback.
403
+ */
404
+ change(callback) {
405
+ if (this.isRenderingInProgress || this._postFixersInProgress) {
406
+ /**
407
+ * Thrown when there is an attempt to make changes to the view tree when it is in incorrect state. This may
408
+ * cause some unexpected behaviour and inconsistency between the DOM and the view.
409
+ * This may be caused by:
410
+ *
411
+ * * calling {@link #change} or {@link #forceRender} during rendering process,
412
+ * * calling {@link #change} or {@link #forceRender} inside of
413
+ * {@link module:engine/view/document~Document#registerPostFixer post-fixer function}.
414
+ *
415
+ * @error cannot-change-view-tree
416
+ */
417
+ throw new CKEditorError('cannot-change-view-tree', this);
418
+ }
419
+ try {
420
+ // Recursive call to view.change() method - execute listener immediately.
421
+ if (this._ongoingChange) {
422
+ return callback(this._writer);
423
+ }
424
+ // This lock will assure that all recursive calls to view.change() will end up in same block - one "render"
425
+ // event for all nested calls.
426
+ this._ongoingChange = true;
427
+ const callbackResult = callback(this._writer);
428
+ this._ongoingChange = false;
429
+ // This lock is used by editing controller to render changes from outer most model.change() once. As plugins might call
430
+ // view.change() inside model.change() block - this will ensures that postfixers and rendering are called once after all
431
+ // changes. Also, we don't need to render anything if there're no changes since last rendering.
432
+ if (!this._renderingDisabled && this._hasChangedSinceTheLastRendering) {
433
+ this._postFixersInProgress = true;
434
+ this.document._callPostFixers(this._writer);
435
+ this._postFixersInProgress = false;
436
+ this.fire('render');
437
+ }
438
+ return callbackResult;
439
+ }
440
+ catch (err) {
441
+ // @if CK_DEBUG // throw err;
442
+ /* istanbul ignore next */
443
+ CKEditorError.rethrowUnexpectedError(err, this);
444
+ }
445
+ }
446
+ /**
447
+ * Forces rendering {@link module:engine/view/document~Document view document} to DOM. If any view changes are
448
+ * currently in progress, rendering will start after all {@link #change change blocks} are processed.
449
+ *
450
+ * Note that this method is dedicated for special cases. All view changes should be wrapped in the {@link #change}
451
+ * block and the view will automatically check whether it needs to render DOM or not.
452
+ *
453
+ * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `applying-view-changes-on-rendering` when
454
+ * trying to re-render when rendering to DOM has already started.
455
+ */
456
+ forceRender() {
457
+ this._hasChangedSinceTheLastRendering = true;
458
+ this.change(() => { });
459
+ }
460
+ /**
461
+ * Destroys this instance. Makes sure that all observers are destroyed and listeners removed.
462
+ */
463
+ destroy() {
464
+ for (const observer of this._observers.values()) {
465
+ observer.destroy();
466
+ }
467
+ this.document.destroy();
468
+ this.stopListening();
469
+ }
470
+ /**
471
+ * Creates position at the given location. The location can be specified as:
472
+ *
473
+ * * a {@link module:engine/view/position~Position position},
474
+ * * parent element and offset (offset defaults to `0`),
475
+ * * parent element and `'end'` (sets position at the end of that element),
476
+ * * {@link module:engine/view/item~Item view item} and `'before'` or `'after'` (sets position before or after given view item).
477
+ *
478
+ * This method is a shortcut to other constructors such as:
479
+ *
480
+ * * {@link #createPositionBefore},
481
+ * * {@link #createPositionAfter},
482
+ *
483
+ * @param {module:engine/view/item~Item|module:engine/model/position~Position} itemOrPosition
484
+ * @param {Number|'end'|'before'|'after'} [offset] Offset or one of the flags. Used only when
485
+ * first parameter is a {@link module:engine/view/item~Item view item}.
486
+ */
487
+ createPositionAt(itemOrPosition, offset) {
488
+ return Position._createAt(itemOrPosition, offset);
489
+ }
490
+ /**
491
+ * Creates a new position after given view item.
492
+ *
493
+ * @param {module:engine/view/item~Item} item View item after which the position should be located.
494
+ * @returns {module:engine/view/position~Position}
495
+ */
496
+ createPositionAfter(item) {
497
+ return Position._createAfter(item);
498
+ }
499
+ /**
500
+ * Creates a new position before given view item.
501
+ *
502
+ * @param {module:engine/view/item~Item} item View item before which the position should be located.
503
+ * @returns {module:engine/view/position~Position}
504
+ */
505
+ createPositionBefore(item) {
506
+ return Position._createBefore(item);
507
+ }
508
+ /**
509
+ * Creates a range spanning from `start` position to `end` position.
510
+ *
511
+ * **Note:** This factory method creates it's own {@link module:engine/view/position~Position} instances basing on passed values.
512
+ *
513
+ * @param {module:engine/view/position~Position} start Start position.
514
+ * @param {module:engine/view/position~Position} [end] End position. If not set, range will be collapsed at `start` position.
515
+ * @returns {module:engine/view/range~Range}
516
+ */
517
+ createRange(...args) {
518
+ return new Range(...args);
519
+ }
520
+ /**
521
+ * Creates a range that starts before given {@link module:engine/view/item~Item view item} and ends after it.
522
+ *
523
+ * @param {module:engine/view/item~Item} item
524
+ * @returns {module:engine/view/range~Range}
525
+ */
526
+ createRangeOn(item) {
527
+ return Range._createOn(item);
528
+ }
529
+ /**
530
+ * Creates a range inside an {@link module:engine/view/element~Element element} which starts before the first child of
531
+ * that element and ends after the last child of that element.
532
+ *
533
+ * @param {module:engine/view/element~Element} element Element which is a parent for the range.
534
+ * @returns {module:engine/view/range~Range}
535
+ */
536
+ createRangeIn(element) {
537
+ return Range._createIn(element);
538
+ }
539
+ /**
540
+ Creates new {@link module:engine/view/selection~Selection} instance.
541
+ *
542
+ * // Creates empty selection without ranges.
543
+ * const selection = view.createSelection();
544
+ *
545
+ * // Creates selection at the given range.
546
+ * const range = view.createRange( start, end );
547
+ * const selection = view.createSelection( range );
548
+ *
549
+ * // Creates selection at the given ranges
550
+ * const ranges = [ view.createRange( start1, end2 ), view.createRange( star2, end2 ) ];
551
+ * const selection = view.createSelection( ranges );
552
+ *
553
+ * // Creates selection from the other selection.
554
+ * const otherSelection = view.createSelection();
555
+ * const selection = view.createSelection( otherSelection );
556
+ *
557
+ * // Creates selection from the document selection.
558
+ * const selection = view.createSelection( editor.editing.view.document.selection );
559
+ *
560
+ * // Creates selection at the given position.
561
+ * const position = view.createPositionFromPath( root, path );
562
+ * const selection = view.createSelection( position );
563
+ *
564
+ * // Creates collapsed selection at the position of given item and offset.
565
+ * const paragraph = view.createContainerElement( 'paragraph' );
566
+ * const selection = view.createSelection( paragraph, offset );
567
+ *
568
+ * // Creates a range inside an {@link module:engine/view/element~Element element} which starts before the
569
+ * // first child of that element and ends after the last child of that element.
570
+ * const selection = view.createSelection( paragraph, 'in' );
571
+ *
572
+ * // Creates a range on an {@link module:engine/view/item~Item item} which starts before the item and ends
573
+ * // just after the item.
574
+ * const selection = view.createSelection( paragraph, 'on' );
575
+ *
576
+ * `Selection`'s factory method allow passing additional options (`backward`, `fake` and `label`) as the last argument.
577
+ *
578
+ * // Creates backward selection.
579
+ * const selection = view.createSelection( range, { backward: true } );
580
+ *
581
+ * Fake selection does not render as browser native selection over selected elements and is hidden to the user.
582
+ * This way, no native selection UI artifacts are displayed to the user and selection over elements can be
583
+ * represented in other way, for example by applying proper CSS class.
584
+ *
585
+ * Additionally fake's selection label can be provided. It will be used to describe fake selection in DOM
586
+ * (and be properly handled by screen readers).
587
+ *
588
+ * // Creates fake selection with label.
589
+ * const selection = view.createSelection( range, { fake: true, label: 'foo' } );
590
+ *
591
+ * @param {module:engine/view/selection~Selectable} [selectable=null]
592
+ * @param {Number|'before'|'end'|'after'|'on'|'in'} [placeOrOffset] Offset or place when selectable is an `Item`.
593
+ * @param {Object} [options]
594
+ * @param {Boolean} [options.backward] Sets this selection instance to be backward.
595
+ * @param {Boolean} [options.fake] Sets this selection instance to be marked as `fake`.
596
+ * @param {String} [options.label] Label for the fake selection.
597
+ * @returns {module:engine/view/selection~Selection}
598
+ */
599
+ createSelection(...args) {
600
+ return new Selection(...args);
601
+ }
602
+ /**
603
+ * Disables or enables rendering. If the flag is set to `true` then the rendering will be disabled.
604
+ * If the flag is set to `false` and if there was some change in the meantime, then the rendering action will be performed.
605
+ *
606
+ * @protected
607
+ * @internal
608
+ * @param {Boolean} flag A flag indicates whether the rendering should be disabled.
609
+ */
610
+ _disableRendering(flag) {
611
+ this._renderingDisabled = flag;
612
+ if (flag == false) {
613
+ // Render when you stop blocking rendering.
614
+ this.change(() => { });
615
+ }
616
+ }
617
+ /**
618
+ * Renders all changes. In order to avoid triggering the observers (e.g. mutations) all observers are disabled
619
+ * before rendering and re-enabled after that.
620
+ *
621
+ * @private
622
+ */
623
+ _render() {
624
+ this.isRenderingInProgress = true;
625
+ this.disableObservers();
626
+ this._renderer.render();
627
+ this.enableObservers();
628
+ this.isRenderingInProgress = false;
629
+ }
723
630
  }
724
-
725
- mix( View, ObservableMixin );