@ckeditor/ckeditor5-engine 40.0.0 → 40.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (242) hide show
  1. package/LICENSE.md +3 -3
  2. package/package.json +2 -2
  3. package/src/controller/datacontroller.d.ts +334 -334
  4. package/src/controller/datacontroller.js +481 -481
  5. package/src/controller/editingcontroller.d.ts +98 -98
  6. package/src/controller/editingcontroller.js +191 -191
  7. package/src/conversion/conversion.d.ts +478 -478
  8. package/src/conversion/conversion.js +601 -601
  9. package/src/conversion/conversionhelpers.d.ts +26 -26
  10. package/src/conversion/conversionhelpers.js +32 -32
  11. package/src/conversion/downcastdispatcher.d.ts +562 -562
  12. package/src/conversion/downcastdispatcher.js +547 -547
  13. package/src/conversion/downcasthelpers.d.ts +1226 -1226
  14. package/src/conversion/downcasthelpers.js +2178 -2183
  15. package/src/conversion/mapper.d.ts +503 -503
  16. package/src/conversion/mapper.js +536 -536
  17. package/src/conversion/modelconsumable.d.ts +201 -201
  18. package/src/conversion/modelconsumable.js +333 -333
  19. package/src/conversion/upcastdispatcher.d.ts +492 -492
  20. package/src/conversion/upcastdispatcher.js +460 -460
  21. package/src/conversion/upcasthelpers.d.ts +499 -499
  22. package/src/conversion/upcasthelpers.js +950 -950
  23. package/src/conversion/viewconsumable.d.ts +369 -369
  24. package/src/conversion/viewconsumable.js +536 -532
  25. package/src/dataprocessor/basichtmlwriter.d.ts +18 -18
  26. package/src/dataprocessor/basichtmlwriter.js +20 -19
  27. package/src/dataprocessor/dataprocessor.d.ts +61 -61
  28. package/src/dataprocessor/dataprocessor.js +5 -5
  29. package/src/dataprocessor/htmldataprocessor.d.ts +76 -76
  30. package/src/dataprocessor/htmldataprocessor.js +96 -96
  31. package/src/dataprocessor/htmlwriter.d.ts +16 -16
  32. package/src/dataprocessor/htmlwriter.js +5 -5
  33. package/src/dataprocessor/xmldataprocessor.d.ts +90 -90
  34. package/src/dataprocessor/xmldataprocessor.js +108 -108
  35. package/src/dev-utils/model.d.ts +124 -124
  36. package/src/dev-utils/model.js +395 -395
  37. package/src/dev-utils/operationreplayer.d.ts +51 -51
  38. package/src/dev-utils/operationreplayer.js +112 -112
  39. package/src/dev-utils/utils.d.ts +37 -37
  40. package/src/dev-utils/utils.js +73 -73
  41. package/src/dev-utils/view.d.ts +319 -319
  42. package/src/dev-utils/view.js +967 -967
  43. package/src/index.d.ts +114 -114
  44. package/src/index.js +78 -78
  45. package/src/model/batch.d.ts +106 -106
  46. package/src/model/batch.js +96 -96
  47. package/src/model/differ.d.ts +387 -387
  48. package/src/model/differ.js +1149 -1149
  49. package/src/model/document.d.ts +272 -272
  50. package/src/model/document.js +360 -361
  51. package/src/model/documentfragment.d.ts +200 -200
  52. package/src/model/documentfragment.js +306 -306
  53. package/src/model/documentselection.d.ts +420 -420
  54. package/src/model/documentselection.js +993 -993
  55. package/src/model/element.d.ts +165 -165
  56. package/src/model/element.js +281 -281
  57. package/src/model/history.d.ts +114 -114
  58. package/src/model/history.js +207 -207
  59. package/src/model/item.d.ts +14 -14
  60. package/src/model/item.js +5 -5
  61. package/src/model/liveposition.d.ts +77 -77
  62. package/src/model/liveposition.js +93 -93
  63. package/src/model/liverange.d.ts +102 -102
  64. package/src/model/liverange.js +120 -120
  65. package/src/model/markercollection.d.ts +335 -335
  66. package/src/model/markercollection.js +403 -403
  67. package/src/model/model.d.ts +919 -919
  68. package/src/model/model.js +842 -842
  69. package/src/model/node.d.ts +256 -256
  70. package/src/model/node.js +375 -375
  71. package/src/model/nodelist.d.ts +91 -91
  72. package/src/model/nodelist.js +163 -163
  73. package/src/model/operation/attributeoperation.d.ts +103 -103
  74. package/src/model/operation/attributeoperation.js +148 -148
  75. package/src/model/operation/detachoperation.d.ts +60 -60
  76. package/src/model/operation/detachoperation.js +77 -77
  77. package/src/model/operation/insertoperation.d.ts +90 -90
  78. package/src/model/operation/insertoperation.js +135 -135
  79. package/src/model/operation/markeroperation.d.ts +91 -91
  80. package/src/model/operation/markeroperation.js +107 -107
  81. package/src/model/operation/mergeoperation.d.ts +100 -100
  82. package/src/model/operation/mergeoperation.js +167 -167
  83. package/src/model/operation/moveoperation.d.ts +96 -96
  84. package/src/model/operation/moveoperation.js +164 -164
  85. package/src/model/operation/nooperation.d.ts +38 -38
  86. package/src/model/operation/nooperation.js +48 -48
  87. package/src/model/operation/operation.d.ts +96 -96
  88. package/src/model/operation/operation.js +59 -62
  89. package/src/model/operation/operationfactory.d.ts +18 -18
  90. package/src/model/operation/operationfactory.js +44 -44
  91. package/src/model/operation/renameoperation.d.ts +83 -83
  92. package/src/model/operation/renameoperation.js +115 -115
  93. package/src/model/operation/rootattributeoperation.d.ts +98 -98
  94. package/src/model/operation/rootattributeoperation.js +155 -155
  95. package/src/model/operation/rootoperation.d.ts +76 -76
  96. package/src/model/operation/rootoperation.js +90 -90
  97. package/src/model/operation/splitoperation.d.ts +109 -109
  98. package/src/model/operation/splitoperation.js +194 -194
  99. package/src/model/operation/transform.d.ts +100 -100
  100. package/src/model/operation/transform.js +1985 -1985
  101. package/src/model/operation/utils.d.ts +71 -71
  102. package/src/model/operation/utils.js +217 -213
  103. package/src/model/position.d.ts +539 -539
  104. package/src/model/position.js +979 -979
  105. package/src/model/range.d.ts +458 -458
  106. package/src/model/range.js +875 -875
  107. package/src/model/rootelement.d.ts +60 -60
  108. package/src/model/rootelement.js +74 -74
  109. package/src/model/schema.d.ts +1186 -1186
  110. package/src/model/schema.js +1242 -1242
  111. package/src/model/selection.d.ts +482 -482
  112. package/src/model/selection.js +789 -789
  113. package/src/model/text.d.ts +66 -66
  114. package/src/model/text.js +85 -85
  115. package/src/model/textproxy.d.ts +144 -144
  116. package/src/model/textproxy.js +189 -189
  117. package/src/model/treewalker.d.ts +186 -186
  118. package/src/model/treewalker.js +244 -244
  119. package/src/model/typecheckable.d.ts +285 -285
  120. package/src/model/typecheckable.js +16 -16
  121. package/src/model/utils/autoparagraphing.d.ts +37 -37
  122. package/src/model/utils/autoparagraphing.js +63 -63
  123. package/src/model/utils/deletecontent.d.ts +58 -58
  124. package/src/model/utils/deletecontent.js +488 -488
  125. package/src/model/utils/findoptimalinsertionrange.d.ts +32 -32
  126. package/src/model/utils/findoptimalinsertionrange.js +57 -57
  127. package/src/model/utils/getselectedcontent.d.ts +30 -30
  128. package/src/model/utils/getselectedcontent.js +125 -125
  129. package/src/model/utils/insertcontent.d.ts +46 -46
  130. package/src/model/utils/insertcontent.js +705 -705
  131. package/src/model/utils/insertobject.d.ts +44 -44
  132. package/src/model/utils/insertobject.js +139 -139
  133. package/src/model/utils/modifyselection.d.ts +48 -48
  134. package/src/model/utils/modifyselection.js +186 -186
  135. package/src/model/utils/selection-post-fixer.d.ts +74 -74
  136. package/src/model/utils/selection-post-fixer.js +260 -260
  137. package/src/model/writer.d.ts +851 -851
  138. package/src/model/writer.js +1306 -1306
  139. package/src/view/attributeelement.d.ts +108 -108
  140. package/src/view/attributeelement.js +184 -184
  141. package/src/view/containerelement.d.ts +49 -49
  142. package/src/view/containerelement.js +80 -80
  143. package/src/view/datatransfer.d.ts +79 -79
  144. package/src/view/datatransfer.js +98 -98
  145. package/src/view/document.d.ts +184 -184
  146. package/src/view/document.js +122 -120
  147. package/src/view/documentfragment.d.ts +153 -149
  148. package/src/view/documentfragment.js +234 -228
  149. package/src/view/documentselection.d.ts +306 -306
  150. package/src/view/documentselection.js +256 -256
  151. package/src/view/domconverter.d.ts +652 -640
  152. package/src/view/domconverter.js +1473 -1450
  153. package/src/view/downcastwriter.d.ts +996 -996
  154. package/src/view/downcastwriter.js +1696 -1696
  155. package/src/view/editableelement.d.ts +62 -62
  156. package/src/view/editableelement.js +62 -62
  157. package/src/view/element.d.ts +468 -468
  158. package/src/view/element.js +724 -724
  159. package/src/view/elementdefinition.d.ts +87 -87
  160. package/src/view/elementdefinition.js +5 -5
  161. package/src/view/emptyelement.d.ts +41 -41
  162. package/src/view/emptyelement.js +73 -73
  163. package/src/view/filler.d.ts +111 -111
  164. package/src/view/filler.js +150 -150
  165. package/src/view/item.d.ts +14 -14
  166. package/src/view/item.js +5 -5
  167. package/src/view/matcher.d.ts +486 -486
  168. package/src/view/matcher.js +507 -507
  169. package/src/view/node.d.ts +163 -163
  170. package/src/view/node.js +228 -228
  171. package/src/view/observer/arrowkeysobserver.d.ts +45 -45
  172. package/src/view/observer/arrowkeysobserver.js +40 -40
  173. package/src/view/observer/bubblingemittermixin.d.ts +166 -166
  174. package/src/view/observer/bubblingemittermixin.js +172 -172
  175. package/src/view/observer/bubblingeventinfo.d.ts +47 -47
  176. package/src/view/observer/bubblingeventinfo.js +37 -37
  177. package/src/view/observer/clickobserver.d.ts +43 -43
  178. package/src/view/observer/clickobserver.js +29 -29
  179. package/src/view/observer/compositionobserver.d.ts +82 -82
  180. package/src/view/observer/compositionobserver.js +60 -60
  181. package/src/view/observer/domeventdata.d.ts +50 -50
  182. package/src/view/observer/domeventdata.js +47 -47
  183. package/src/view/observer/domeventobserver.d.ts +73 -73
  184. package/src/view/observer/domeventobserver.js +79 -79
  185. package/src/view/observer/fakeselectionobserver.d.ts +47 -47
  186. package/src/view/observer/fakeselectionobserver.js +91 -91
  187. package/src/view/observer/focusobserver.d.ts +82 -82
  188. package/src/view/observer/focusobserver.js +86 -86
  189. package/src/view/observer/inputobserver.d.ts +86 -86
  190. package/src/view/observer/inputobserver.js +164 -164
  191. package/src/view/observer/keyobserver.d.ts +66 -66
  192. package/src/view/observer/keyobserver.js +39 -39
  193. package/src/view/observer/mouseobserver.d.ts +89 -89
  194. package/src/view/observer/mouseobserver.js +29 -29
  195. package/src/view/observer/mutationobserver.d.ts +86 -86
  196. package/src/view/observer/mutationobserver.js +206 -206
  197. package/src/view/observer/observer.d.ts +89 -89
  198. package/src/view/observer/observer.js +84 -84
  199. package/src/view/observer/selectionobserver.d.ts +148 -148
  200. package/src/view/observer/selectionobserver.js +202 -202
  201. package/src/view/observer/tabobserver.d.ts +46 -46
  202. package/src/view/observer/tabobserver.js +42 -42
  203. package/src/view/placeholder.d.ts +96 -96
  204. package/src/view/placeholder.js +267 -267
  205. package/src/view/position.d.ts +189 -189
  206. package/src/view/position.js +324 -324
  207. package/src/view/range.d.ts +279 -279
  208. package/src/view/range.js +430 -430
  209. package/src/view/rawelement.d.ts +73 -73
  210. package/src/view/rawelement.js +105 -105
  211. package/src/view/renderer.d.ts +265 -265
  212. package/src/view/renderer.js +1000 -999
  213. package/src/view/rooteditableelement.d.ts +41 -41
  214. package/src/view/rooteditableelement.js +69 -69
  215. package/src/view/selection.d.ts +375 -375
  216. package/src/view/selection.js +559 -559
  217. package/src/view/styles/background.d.ts +33 -33
  218. package/src/view/styles/background.js +74 -74
  219. package/src/view/styles/border.d.ts +43 -43
  220. package/src/view/styles/border.js +316 -316
  221. package/src/view/styles/margin.d.ts +29 -29
  222. package/src/view/styles/margin.js +34 -34
  223. package/src/view/styles/padding.d.ts +29 -29
  224. package/src/view/styles/padding.js +34 -34
  225. package/src/view/styles/utils.d.ts +93 -93
  226. package/src/view/styles/utils.js +219 -219
  227. package/src/view/stylesmap.d.ts +675 -675
  228. package/src/view/stylesmap.js +765 -766
  229. package/src/view/text.d.ts +74 -74
  230. package/src/view/text.js +93 -93
  231. package/src/view/textproxy.d.ts +97 -97
  232. package/src/view/textproxy.js +124 -124
  233. package/src/view/treewalker.d.ts +195 -195
  234. package/src/view/treewalker.js +327 -327
  235. package/src/view/typecheckable.d.ts +448 -448
  236. package/src/view/typecheckable.js +19 -19
  237. package/src/view/uielement.d.ts +96 -96
  238. package/src/view/uielement.js +183 -182
  239. package/src/view/upcastwriter.d.ts +417 -417
  240. package/src/view/upcastwriter.js +359 -359
  241. package/src/view/view.d.ts +487 -487
  242. package/src/view/view.js +546 -546
package/src/view/view.js CHANGED
@@ -1,546 +1,546 @@
1
- /**
2
- * @license Copyright (c) 2003-2023, CKSource Holding sp. z o.o. All rights reserved.
3
- * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4
- */
5
- /**
6
- * @module engine/view/view
7
- */
8
- import Document from './document';
9
- import DowncastWriter from './downcastwriter';
10
- import Renderer from './renderer';
11
- import DomConverter from './domconverter';
12
- import Position from './position';
13
- import Range from './range';
14
- import Selection from './selection';
15
- import KeyObserver from './observer/keyobserver';
16
- import FakeSelectionObserver from './observer/fakeselectionobserver';
17
- import MutationObserver from './observer/mutationobserver';
18
- import SelectionObserver from './observer/selectionobserver';
19
- import FocusObserver from './observer/focusobserver';
20
- import CompositionObserver from './observer/compositionobserver';
21
- import InputObserver from './observer/inputobserver';
22
- import ArrowKeysObserver from './observer/arrowkeysobserver';
23
- import TabObserver from './observer/tabobserver';
24
- import { CKEditorError, env, ObservableMixin, scrollViewportToShowTarget } from '@ckeditor/ckeditor5-utils';
25
- import { injectUiElementHandling } from './uielement';
26
- import { injectQuirksHandling } from './filler';
27
- import { cloneDeep } from 'lodash-es';
28
- /**
29
- * Editor's view controller class. Its main responsibility is DOM - View management for editing purposes, to provide
30
- * abstraction over the DOM structure and events and hide all browsers quirks.
31
- *
32
- * View controller renders view document to DOM whenever view structure changes. To determine when view can be rendered,
33
- * all changes need to be done using the {@link module:engine/view/view~View#change} method, using
34
- * {@link module:engine/view/downcastwriter~DowncastWriter}:
35
- *
36
- * ```ts
37
- * view.change( writer => {
38
- * writer.insert( position, writer.createText( 'foo' ) );
39
- * } );
40
- * ```
41
- *
42
- * View controller also register {@link module:engine/view/observer/observer~Observer observers} which observes changes
43
- * on DOM and fire events on the {@link module:engine/view/document~Document Document}.
44
- * Note that the following observers are added by the class constructor and are always available:
45
- *
46
- * * {@link module:engine/view/observer/selectionobserver~SelectionObserver},
47
- * * {@link module:engine/view/observer/focusobserver~FocusObserver},
48
- * * {@link module:engine/view/observer/keyobserver~KeyObserver},
49
- * * {@link module:engine/view/observer/fakeselectionobserver~FakeSelectionObserver}.
50
- * * {@link module:engine/view/observer/compositionobserver~CompositionObserver}.
51
- * * {@link module:engine/view/observer/inputobserver~InputObserver}.
52
- * * {@link module:engine/view/observer/arrowkeysobserver~ArrowKeysObserver}.
53
- * * {@link module:engine/view/observer/tabobserver~TabObserver}.
54
- *
55
- * This class also {@link module:engine/view/view~View#attachDomRoot binds the DOM and the view elements}.
56
- *
57
- * If you do not need full a DOM - view management, and only want to transform a tree of view elements to a tree of DOM
58
- * elements you do not need this controller. You can use the {@link module:engine/view/domconverter~DomConverter DomConverter} instead.
59
- */
60
- export default class View extends ObservableMixin() {
61
- /**
62
- * @param stylesProcessor The styles processor instance.
63
- */
64
- constructor(stylesProcessor) {
65
- super();
66
- /**
67
- * Roots of the DOM tree. Map on the `HTMLElement`s with roots names as keys.
68
- */
69
- this.domRoots = new Map();
70
- /**
71
- * A DOM root attributes cache. It saves the initial values of DOM root attributes before the DOM element
72
- * is {@link module:engine/view/view~View#attachDomRoot attached} to the view so later on, when
73
- * the view is destroyed ({@link module:engine/view/view~View#detachDomRoot}), they can be easily restored.
74
- * This way, the DOM element can go back to the (clean) state as if the editing view never used it.
75
- */
76
- this._initialDomRootAttributes = new WeakMap();
77
- /**
78
- * Map of registered {@link module:engine/view/observer/observer~Observer observers}.
79
- */
80
- this._observers = new Map();
81
- /**
82
- * Is set to `true` when {@link #change view changes} are currently in progress.
83
- */
84
- this._ongoingChange = false;
85
- /**
86
- * Used to prevent calling {@link #forceRender} and {@link #change} during rendering view to the DOM.
87
- */
88
- this._postFixersInProgress = false;
89
- /**
90
- * Internal flag to temporary disable rendering. See the usage in the {@link #_disableRendering}.
91
- */
92
- this._renderingDisabled = false;
93
- /**
94
- * Internal flag that disables rendering when there are no changes since the last rendering.
95
- * It stores information about changed selection and changed elements from attached document roots.
96
- */
97
- this._hasChangedSinceTheLastRendering = false;
98
- this.document = new Document(stylesProcessor);
99
- this.domConverter = new DomConverter(this.document);
100
- this.set('isRenderingInProgress', false);
101
- this.set('hasDomSelection', false);
102
- this._renderer = new Renderer(this.domConverter, this.document.selection);
103
- this._renderer.bind('isFocused', 'isSelecting', 'isComposing')
104
- .to(this.document, 'isFocused', 'isSelecting', 'isComposing');
105
- this._writer = new DowncastWriter(this.document);
106
- // Add default observers.
107
- // Make sure that this list matches AlwaysRegisteredObservers type.
108
- this.addObserver(MutationObserver);
109
- this.addObserver(FocusObserver);
110
- this.addObserver(SelectionObserver);
111
- this.addObserver(KeyObserver);
112
- this.addObserver(FakeSelectionObserver);
113
- this.addObserver(CompositionObserver);
114
- this.addObserver(ArrowKeysObserver);
115
- this.addObserver(InputObserver);
116
- this.addObserver(TabObserver);
117
- // Inject quirks handlers.
118
- injectQuirksHandling(this);
119
- injectUiElementHandling(this);
120
- // Use 'normal' priority so that rendering is performed as first when using that priority.
121
- this.on('render', () => {
122
- this._render();
123
- // Informs that layout has changed after render.
124
- this.document.fire('layoutChanged');
125
- // Reset the `_hasChangedSinceTheLastRendering` flag after rendering.
126
- this._hasChangedSinceTheLastRendering = false;
127
- });
128
- // Listen to the document selection changes directly.
129
- this.listenTo(this.document.selection, 'change', () => {
130
- this._hasChangedSinceTheLastRendering = true;
131
- });
132
- // Trigger re-render if only the focus changed.
133
- this.listenTo(this.document, 'change:isFocused', () => {
134
- this._hasChangedSinceTheLastRendering = true;
135
- });
136
- // Remove ranges from DOM selection if editor is blurred.
137
- // See https://github.com/ckeditor/ckeditor5/issues/5753.
138
- if (env.isiOS) {
139
- this.listenTo(this.document, 'blur', (evt, data) => {
140
- const relatedViewElement = this.domConverter.mapDomToView(data.domEvent.relatedTarget);
141
- // Do not modify DOM selection if focus is moved to other editable of the same editor.
142
- if (!relatedViewElement) {
143
- this.domConverter._clearDomSelection();
144
- }
145
- });
146
- }
147
- }
148
- /**
149
- * Attaches a DOM root element to the view element and enable all observers on that element.
150
- * Also {@link module:engine/view/renderer~Renderer#markToSync mark element} to be synchronized
151
- * with the view what means that all child nodes will be removed and replaced with content of the view root.
152
- *
153
- * This method also will change view element name as the same as tag name of given dom root.
154
- * Name is always transformed to lower case.
155
- *
156
- * **Note:** Use {@link #detachDomRoot `detachDomRoot()`} to revert this action.
157
- *
158
- * @param domRoot DOM root element.
159
- * @param name Name of the root.
160
- */
161
- attachDomRoot(domRoot, name = 'main') {
162
- const viewRoot = this.document.getRoot(name);
163
- // Set view root name the same as DOM root tag name.
164
- viewRoot._name = domRoot.tagName.toLowerCase();
165
- const initialDomRootAttributes = {};
166
- // 1. Copy and cache the attributes to remember the state of the element before attaching.
167
- // The cached attributes will be restored in detachDomRoot() so the element goes to the
168
- // clean state as if the editing view never used it.
169
- // 2. Apply the attributes using the view writer, so they all go under the control of the engine.
170
- // The editing view takes over the attribute management completely because various
171
- // features (e.g. addPlaceholder()) require dynamic changes of those attributes and they
172
- // cannot be managed by the engine and the UI library at the same time.
173
- for (const { name, value } of Array.from(domRoot.attributes)) {
174
- initialDomRootAttributes[name] = value;
175
- // Do not use writer.setAttribute() for the class attribute. The EditableUIView class
176
- // and its descendants could have already set some using the writer.addClass() on the view
177
- // document root. They haven't been rendered yet so they are not present in the DOM root.
178
- // Using writer.setAttribute( 'class', ... ) would override them completely.
179
- if (name === 'class') {
180
- this._writer.addClass(value.split(' '), viewRoot);
181
- }
182
- else {
183
- this._writer.setAttribute(name, value, viewRoot);
184
- }
185
- }
186
- this._initialDomRootAttributes.set(domRoot, initialDomRootAttributes);
187
- const updateContenteditableAttribute = () => {
188
- this._writer.setAttribute('contenteditable', (!viewRoot.isReadOnly).toString(), viewRoot);
189
- if (viewRoot.isReadOnly) {
190
- this._writer.addClass('ck-read-only', viewRoot);
191
- }
192
- else {
193
- this._writer.removeClass('ck-read-only', viewRoot);
194
- }
195
- };
196
- // Set initial value.
197
- updateContenteditableAttribute();
198
- this.domRoots.set(name, domRoot);
199
- this.domConverter.bindElements(domRoot, viewRoot);
200
- this._renderer.markToSync('children', viewRoot);
201
- this._renderer.markToSync('attributes', viewRoot);
202
- this._renderer.domDocuments.add(domRoot.ownerDocument);
203
- viewRoot.on('change:children', (evt, node) => this._renderer.markToSync('children', node));
204
- viewRoot.on('change:attributes', (evt, node) => this._renderer.markToSync('attributes', node));
205
- viewRoot.on('change:text', (evt, node) => this._renderer.markToSync('text', node));
206
- viewRoot.on('change:isReadOnly', () => this.change(updateContenteditableAttribute));
207
- viewRoot.on('change', () => {
208
- this._hasChangedSinceTheLastRendering = true;
209
- });
210
- for (const observer of this._observers.values()) {
211
- observer.observe(domRoot, name);
212
- }
213
- }
214
- /**
215
- * Detaches a DOM root element from the view element and restores its attributes to the state before
216
- * {@link #attachDomRoot `attachDomRoot()`}.
217
- *
218
- * @param name Name of the root to detach.
219
- */
220
- detachDomRoot(name) {
221
- const domRoot = this.domRoots.get(name);
222
- // Remove all root attributes so the DOM element is "bare".
223
- Array.from(domRoot.attributes).forEach(({ name }) => domRoot.removeAttribute(name));
224
- const initialDomRootAttributes = this._initialDomRootAttributes.get(domRoot);
225
- // Revert all view root attributes back to the state before attachDomRoot was called.
226
- for (const attribute in initialDomRootAttributes) {
227
- domRoot.setAttribute(attribute, initialDomRootAttributes[attribute]);
228
- }
229
- this.domRoots.delete(name);
230
- this.domConverter.unbindDomElement(domRoot);
231
- for (const observer of this._observers.values()) {
232
- observer.stopObserving(domRoot);
233
- }
234
- }
235
- /**
236
- * Gets DOM root element.
237
- *
238
- * @param name Name of the root.
239
- * @returns DOM root element instance.
240
- */
241
- getDomRoot(name = 'main') {
242
- return this.domRoots.get(name);
243
- }
244
- /**
245
- * Creates observer of the given type if not yet created, {@link module:engine/view/observer/observer~Observer#enable enables} it
246
- * and {@link module:engine/view/observer/observer~Observer#observe attaches} to all existing and future
247
- * {@link #domRoots DOM roots}.
248
- *
249
- * Note: Observers are recognized by their constructor (classes). A single observer will be instantiated and used only
250
- * when registered for the first time. This means that features and other components can register a single observer
251
- * multiple times without caring whether it has been already added or not.
252
- *
253
- * @param ObserverConstructor The constructor of an observer to add.
254
- * Should create an instance inheriting from {@link module:engine/view/observer/observer~Observer}.
255
- * @returns Added observer instance.
256
- */
257
- addObserver(ObserverConstructor) {
258
- let observer = this._observers.get(ObserverConstructor);
259
- if (observer) {
260
- return observer;
261
- }
262
- observer = new ObserverConstructor(this);
263
- this._observers.set(ObserverConstructor, observer);
264
- for (const [name, domElement] of this.domRoots) {
265
- observer.observe(domElement, name);
266
- }
267
- observer.enable();
268
- return observer;
269
- }
270
- /**
271
- * Returns observer of the given type or `undefined` if such observer has not been added yet.
272
- *
273
- * @param ObserverConstructor The constructor of an observer to get.
274
- * @returns Observer instance or undefined.
275
- */
276
- getObserver(ObserverConstructor) {
277
- return this._observers.get(ObserverConstructor);
278
- }
279
- /**
280
- * Disables all added observers.
281
- */
282
- disableObservers() {
283
- for (const observer of this._observers.values()) {
284
- observer.disable();
285
- }
286
- }
287
- /**
288
- * Enables all added observers.
289
- */
290
- enableObservers() {
291
- for (const observer of this._observers.values()) {
292
- observer.enable();
293
- }
294
- }
295
- /**
296
- * Scrolls the page viewport and {@link #domRoots} with their ancestors to reveal the
297
- * caret, **if not already visible to the user**.
298
- *
299
- * **Note**: Calling this method fires the {@link module:engine/view/view~ViewScrollToTheSelectionEvent} event that
300
- * allows custom behaviors.
301
- *
302
- * @param options Additional configuration of the scrolling behavior.
303
- * @param options.viewportOffset A distance between the DOM selection and the viewport boundary to be maintained
304
- * while scrolling to the selection (default is 20px). Setting this value to `0` will reveal the selection precisely at
305
- * the viewport boundary.
306
- * @param options.ancestorOffset A distance between the DOM selection and scrollable DOM root ancestor(s) to be maintained
307
- * while scrolling to the selection (default is 20px). Setting this value to `0` will reveal the selection precisely at
308
- * the scrollable ancestor(s) boundary.
309
- * @param options.alignToTop When set `true`, the DOM selection will be aligned to the top of the viewport if not already visible
310
- * (see `forceScroll` to learn more).
311
- * @param options.forceScroll When set `true`, the DOM selection will be aligned to the top of the viewport and scrollable ancestors
312
- * whether it is already visible or not. This option will only work when `alignToTop` is `true`.
313
- */
314
- scrollToTheSelection({ alignToTop, forceScroll, viewportOffset = 20, ancestorOffset = 20 } = {}) {
315
- const range = this.document.selection.getFirstRange();
316
- if (!range) {
317
- return;
318
- }
319
- // Clone to make sure properties like `viewportOffset` are not mutated in the event listeners.
320
- const originalArgs = cloneDeep({ alignToTop, forceScroll, viewportOffset, ancestorOffset });
321
- if (typeof viewportOffset === 'number') {
322
- viewportOffset = {
323
- top: viewportOffset,
324
- bottom: viewportOffset,
325
- left: viewportOffset,
326
- right: viewportOffset
327
- };
328
- }
329
- const options = {
330
- target: this.domConverter.viewRangeToDom(range),
331
- viewportOffset,
332
- ancestorOffset,
333
- alignToTop,
334
- forceScroll
335
- };
336
- this.fire('scrollToTheSelection', options, originalArgs);
337
- scrollViewportToShowTarget(options);
338
- }
339
- /**
340
- * It will focus DOM element representing {@link module:engine/view/editableelement~EditableElement EditableElement}
341
- * that is currently having selection inside.
342
- */
343
- focus() {
344
- if (!this.document.isFocused) {
345
- const editable = this.document.selection.editableElement;
346
- if (editable) {
347
- this.domConverter.focus(editable);
348
- this.forceRender();
349
- }
350
- else {
351
- // Before focusing view document, selection should be placed inside one of the view's editables.
352
- // Normally its selection will be converted from model document (which have default selection), but
353
- // when using view document on its own, we need to manually place selection before focusing it.
354
- //
355
- // @if CK_DEBUG // console.warn( 'There is no selection in any editable to focus.' );
356
- }
357
- }
358
- }
359
- /**
360
- * The `change()` method is the primary way of changing the view. You should use it to modify any node in the view tree.
361
- * It makes sure that after all changes are made the view is rendered to the DOM (assuming that the view will be changed
362
- * inside the callback). It prevents situations when the DOM is updated when the view state is not yet correct. It allows
363
- * to nest calls one inside another and still performs a single rendering after all those changes are made.
364
- * It also returns the return value of its callback.
365
- *
366
- * ```ts
367
- * const text = view.change( writer => {
368
- * const newText = writer.createText( 'foo' );
369
- * writer.insert( position1, newText );
370
- *
371
- * view.change( writer => {
372
- * writer.insert( position2, writer.createText( 'bar' ) );
373
- * } );
374
- *
375
- * writer.remove( range );
376
- *
377
- * return newText;
378
- * } );
379
- * ```
380
- *
381
- * When the outermost change block is done and rendering to the DOM is over the
382
- * {@link module:engine/view/view~View#event:render `View#render`} event is fired.
383
- *
384
- * This method throws a `applying-view-changes-on-rendering` error when
385
- * the change block is used after rendering to the DOM has started.
386
- *
387
- * @param callback Callback function which may modify the view.
388
- * @returns Value returned by the callback.
389
- */
390
- change(callback) {
391
- if (this.isRenderingInProgress || this._postFixersInProgress) {
392
- /**
393
- * Thrown when there is an attempt to make changes to the view tree when it is in incorrect state. This may
394
- * cause some unexpected behaviour and inconsistency between the DOM and the view.
395
- * This may be caused by:
396
- *
397
- * * calling {@link module:engine/view/view~View#change} or {@link module:engine/view/view~View#forceRender} during rendering
398
- * process,
399
- * * calling {@link module:engine/view/view~View#change} or {@link module:engine/view/view~View#forceRender} inside of
400
- * {@link module:engine/view/document~Document#registerPostFixer post-fixer function}.
401
- *
402
- * @error cannot-change-view-tree
403
- */
404
- throw new CKEditorError('cannot-change-view-tree', this);
405
- }
406
- try {
407
- // Recursive call to view.change() method - execute listener immediately.
408
- if (this._ongoingChange) {
409
- return callback(this._writer);
410
- }
411
- // This lock will assure that all recursive calls to view.change() will end up in same block - one "render"
412
- // event for all nested calls.
413
- this._ongoingChange = true;
414
- const callbackResult = callback(this._writer);
415
- this._ongoingChange = false;
416
- // This lock is used by editing controller to render changes from outer most model.change() once. As plugins might call
417
- // view.change() inside model.change() block - this will ensures that postfixers and rendering are called once after all
418
- // changes. Also, we don't need to render anything if there're no changes since last rendering.
419
- if (!this._renderingDisabled && this._hasChangedSinceTheLastRendering) {
420
- this._postFixersInProgress = true;
421
- this.document._callPostFixers(this._writer);
422
- this._postFixersInProgress = false;
423
- this.fire('render');
424
- }
425
- return callbackResult;
426
- }
427
- catch (err) {
428
- // @if CK_DEBUG // throw err;
429
- /* istanbul ignore next -- @preserve */
430
- CKEditorError.rethrowUnexpectedError(err, this);
431
- }
432
- }
433
- /**
434
- * Forces rendering {@link module:engine/view/document~Document view document} to DOM. If any view changes are
435
- * currently in progress, rendering will start after all {@link #change change blocks} are processed.
436
- *
437
- * Note that this method is dedicated for special cases. All view changes should be wrapped in the {@link #change}
438
- * block and the view will automatically check whether it needs to render DOM or not.
439
- *
440
- * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `applying-view-changes-on-rendering` when
441
- * trying to re-render when rendering to DOM has already started.
442
- */
443
- forceRender() {
444
- this._hasChangedSinceTheLastRendering = true;
445
- this.getObserver(FocusObserver).flush();
446
- this.change(() => { });
447
- }
448
- /**
449
- * Destroys this instance. Makes sure that all observers are destroyed and listeners removed.
450
- */
451
- destroy() {
452
- for (const observer of this._observers.values()) {
453
- observer.destroy();
454
- }
455
- this.document.destroy();
456
- this.stopListening();
457
- }
458
- /**
459
- * Creates position at the given location. The location can be specified as:
460
- *
461
- * * a {@link module:engine/view/position~Position position},
462
- * * parent element and offset (offset defaults to `0`),
463
- * * parent element and `'end'` (sets position at the end of that element),
464
- * * {@link module:engine/view/item~Item view item} and `'before'` or `'after'` (sets position before or after given view item).
465
- *
466
- * This method is a shortcut to other constructors such as:
467
- *
468
- * * {@link #createPositionBefore},
469
- * * {@link #createPositionAfter},
470
- *
471
- * @param offset Offset or one of the flags. Used only when first parameter is a {@link module:engine/view/item~Item view item}.
472
- */
473
- createPositionAt(itemOrPosition, offset) {
474
- return Position._createAt(itemOrPosition, offset);
475
- }
476
- /**
477
- * Creates a new position after given view item.
478
- *
479
- * @param item View item after which the position should be located.
480
- */
481
- createPositionAfter(item) {
482
- return Position._createAfter(item);
483
- }
484
- /**
485
- * Creates a new position before given view item.
486
- *
487
- * @param item View item before which the position should be located.
488
- */
489
- createPositionBefore(item) {
490
- return Position._createBefore(item);
491
- }
492
- /**
493
- * Creates a range spanning from `start` position to `end` position.
494
- *
495
- * **Note:** This factory method creates it's own {@link module:engine/view/position~Position} instances basing on passed values.
496
- *
497
- * @param start Start position.
498
- * @param end End position. If not set, range will be collapsed at `start` position.
499
- */
500
- createRange(start, end) {
501
- return new Range(start, end);
502
- }
503
- /**
504
- * Creates a range that starts before given {@link module:engine/view/item~Item view item} and ends after it.
505
- */
506
- createRangeOn(item) {
507
- return Range._createOn(item);
508
- }
509
- /**
510
- * Creates a range inside an {@link module:engine/view/element~Element element} which starts before the first child of
511
- * that element and ends after the last child of that element.
512
- *
513
- * @param element Element which is a parent for the range.
514
- */
515
- createRangeIn(element) {
516
- return Range._createIn(element);
517
- }
518
- createSelection(...args) {
519
- return new Selection(...args);
520
- }
521
- /**
522
- * Disables or enables rendering. If the flag is set to `true` then the rendering will be disabled.
523
- * If the flag is set to `false` and if there was some change in the meantime, then the rendering action will be performed.
524
- *
525
- * @internal
526
- * @param flag A flag indicates whether the rendering should be disabled.
527
- */
528
- _disableRendering(flag) {
529
- this._renderingDisabled = flag;
530
- if (flag == false) {
531
- // Render when you stop blocking rendering.
532
- this.change(() => { });
533
- }
534
- }
535
- /**
536
- * Renders all changes. In order to avoid triggering the observers (e.g. selection) all observers are disabled
537
- * before rendering and re-enabled after that.
538
- */
539
- _render() {
540
- this.isRenderingInProgress = true;
541
- this.disableObservers();
542
- this._renderer.render();
543
- this.enableObservers();
544
- this.isRenderingInProgress = false;
545
- }
546
- }
1
+ /**
2
+ * @license Copyright (c) 2003-2023, CKSource Holding sp. z o.o. All rights reserved.
3
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4
+ */
5
+ /**
6
+ * @module engine/view/view
7
+ */
8
+ import Document from './document';
9
+ import DowncastWriter from './downcastwriter';
10
+ import Renderer from './renderer';
11
+ import DomConverter from './domconverter';
12
+ import Position from './position';
13
+ import Range from './range';
14
+ import Selection from './selection';
15
+ import KeyObserver from './observer/keyobserver';
16
+ import FakeSelectionObserver from './observer/fakeselectionobserver';
17
+ import MutationObserver from './observer/mutationobserver';
18
+ import SelectionObserver from './observer/selectionobserver';
19
+ import FocusObserver from './observer/focusobserver';
20
+ import CompositionObserver from './observer/compositionobserver';
21
+ import InputObserver from './observer/inputobserver';
22
+ import ArrowKeysObserver from './observer/arrowkeysobserver';
23
+ import TabObserver from './observer/tabobserver';
24
+ import { CKEditorError, env, ObservableMixin, scrollViewportToShowTarget } from '@ckeditor/ckeditor5-utils';
25
+ import { injectUiElementHandling } from './uielement';
26
+ import { injectQuirksHandling } from './filler';
27
+ import { cloneDeep } from 'lodash-es';
28
+ /**
29
+ * Editor's view controller class. Its main responsibility is DOM - View management for editing purposes, to provide
30
+ * abstraction over the DOM structure and events and hide all browsers quirks.
31
+ *
32
+ * View controller renders view document to DOM whenever view structure changes. To determine when view can be rendered,
33
+ * all changes need to be done using the {@link module:engine/view/view~View#change} method, using
34
+ * {@link module:engine/view/downcastwriter~DowncastWriter}:
35
+ *
36
+ * ```ts
37
+ * view.change( writer => {
38
+ * writer.insert( position, writer.createText( 'foo' ) );
39
+ * } );
40
+ * ```
41
+ *
42
+ * View controller also register {@link module:engine/view/observer/observer~Observer observers} which observes changes
43
+ * on DOM and fire events on the {@link module:engine/view/document~Document Document}.
44
+ * Note that the following observers are added by the class constructor and are always available:
45
+ *
46
+ * * {@link module:engine/view/observer/selectionobserver~SelectionObserver},
47
+ * * {@link module:engine/view/observer/focusobserver~FocusObserver},
48
+ * * {@link module:engine/view/observer/keyobserver~KeyObserver},
49
+ * * {@link module:engine/view/observer/fakeselectionobserver~FakeSelectionObserver}.
50
+ * * {@link module:engine/view/observer/compositionobserver~CompositionObserver}.
51
+ * * {@link module:engine/view/observer/inputobserver~InputObserver}.
52
+ * * {@link module:engine/view/observer/arrowkeysobserver~ArrowKeysObserver}.
53
+ * * {@link module:engine/view/observer/tabobserver~TabObserver}.
54
+ *
55
+ * This class also {@link module:engine/view/view~View#attachDomRoot binds the DOM and the view elements}.
56
+ *
57
+ * If you do not need full a DOM - view management, and only want to transform a tree of view elements to a tree of DOM
58
+ * elements you do not need this controller. You can use the {@link module:engine/view/domconverter~DomConverter DomConverter} instead.
59
+ */
60
+ export default class View extends ObservableMixin() {
61
+ /**
62
+ * @param stylesProcessor The styles processor instance.
63
+ */
64
+ constructor(stylesProcessor) {
65
+ super();
66
+ /**
67
+ * Roots of the DOM tree. Map on the `HTMLElement`s with roots names as keys.
68
+ */
69
+ this.domRoots = new Map();
70
+ /**
71
+ * A DOM root attributes cache. It saves the initial values of DOM root attributes before the DOM element
72
+ * is {@link module:engine/view/view~View#attachDomRoot attached} to the view so later on, when
73
+ * the view is destroyed ({@link module:engine/view/view~View#detachDomRoot}), they can be easily restored.
74
+ * This way, the DOM element can go back to the (clean) state as if the editing view never used it.
75
+ */
76
+ this._initialDomRootAttributes = new WeakMap();
77
+ /**
78
+ * Map of registered {@link module:engine/view/observer/observer~Observer observers}.
79
+ */
80
+ this._observers = new Map();
81
+ /**
82
+ * Is set to `true` when {@link #change view changes} are currently in progress.
83
+ */
84
+ this._ongoingChange = false;
85
+ /**
86
+ * Used to prevent calling {@link #forceRender} and {@link #change} during rendering view to the DOM.
87
+ */
88
+ this._postFixersInProgress = false;
89
+ /**
90
+ * Internal flag to temporary disable rendering. See the usage in the {@link #_disableRendering}.
91
+ */
92
+ this._renderingDisabled = false;
93
+ /**
94
+ * Internal flag that disables rendering when there are no changes since the last rendering.
95
+ * It stores information about changed selection and changed elements from attached document roots.
96
+ */
97
+ this._hasChangedSinceTheLastRendering = false;
98
+ this.document = new Document(stylesProcessor);
99
+ this.domConverter = new DomConverter(this.document);
100
+ this.set('isRenderingInProgress', false);
101
+ this.set('hasDomSelection', false);
102
+ this._renderer = new Renderer(this.domConverter, this.document.selection);
103
+ this._renderer.bind('isFocused', 'isSelecting', 'isComposing')
104
+ .to(this.document, 'isFocused', 'isSelecting', 'isComposing');
105
+ this._writer = new DowncastWriter(this.document);
106
+ // Add default observers.
107
+ // Make sure that this list matches AlwaysRegisteredObservers type.
108
+ this.addObserver(MutationObserver);
109
+ this.addObserver(FocusObserver);
110
+ this.addObserver(SelectionObserver);
111
+ this.addObserver(KeyObserver);
112
+ this.addObserver(FakeSelectionObserver);
113
+ this.addObserver(CompositionObserver);
114
+ this.addObserver(ArrowKeysObserver);
115
+ this.addObserver(InputObserver);
116
+ this.addObserver(TabObserver);
117
+ // Inject quirks handlers.
118
+ injectQuirksHandling(this);
119
+ injectUiElementHandling(this);
120
+ // Use 'normal' priority so that rendering is performed as first when using that priority.
121
+ this.on('render', () => {
122
+ this._render();
123
+ // Informs that layout has changed after render.
124
+ this.document.fire('layoutChanged');
125
+ // Reset the `_hasChangedSinceTheLastRendering` flag after rendering.
126
+ this._hasChangedSinceTheLastRendering = false;
127
+ });
128
+ // Listen to the document selection changes directly.
129
+ this.listenTo(this.document.selection, 'change', () => {
130
+ this._hasChangedSinceTheLastRendering = true;
131
+ });
132
+ // Trigger re-render if only the focus changed.
133
+ this.listenTo(this.document, 'change:isFocused', () => {
134
+ this._hasChangedSinceTheLastRendering = true;
135
+ });
136
+ // Remove ranges from DOM selection if editor is blurred.
137
+ // See https://github.com/ckeditor/ckeditor5/issues/5753.
138
+ if (env.isiOS) {
139
+ this.listenTo(this.document, 'blur', (evt, data) => {
140
+ const relatedViewElement = this.domConverter.mapDomToView(data.domEvent.relatedTarget);
141
+ // Do not modify DOM selection if focus is moved to other editable of the same editor.
142
+ if (!relatedViewElement) {
143
+ this.domConverter._clearDomSelection();
144
+ }
145
+ });
146
+ }
147
+ }
148
+ /**
149
+ * Attaches a DOM root element to the view element and enable all observers on that element.
150
+ * Also {@link module:engine/view/renderer~Renderer#markToSync mark element} to be synchronized
151
+ * with the view what means that all child nodes will be removed and replaced with content of the view root.
152
+ *
153
+ * This method also will change view element name as the same as tag name of given dom root.
154
+ * Name is always transformed to lower case.
155
+ *
156
+ * **Note:** Use {@link #detachDomRoot `detachDomRoot()`} to revert this action.
157
+ *
158
+ * @param domRoot DOM root element.
159
+ * @param name Name of the root.
160
+ */
161
+ attachDomRoot(domRoot, name = 'main') {
162
+ const viewRoot = this.document.getRoot(name);
163
+ // Set view root name the same as DOM root tag name.
164
+ viewRoot._name = domRoot.tagName.toLowerCase();
165
+ const initialDomRootAttributes = {};
166
+ // 1. Copy and cache the attributes to remember the state of the element before attaching.
167
+ // The cached attributes will be restored in detachDomRoot() so the element goes to the
168
+ // clean state as if the editing view never used it.
169
+ // 2. Apply the attributes using the view writer, so they all go under the control of the engine.
170
+ // The editing view takes over the attribute management completely because various
171
+ // features (e.g. addPlaceholder()) require dynamic changes of those attributes and they
172
+ // cannot be managed by the engine and the UI library at the same time.
173
+ for (const { name, value } of Array.from(domRoot.attributes)) {
174
+ initialDomRootAttributes[name] = value;
175
+ // Do not use writer.setAttribute() for the class attribute. The EditableUIView class
176
+ // and its descendants could have already set some using the writer.addClass() on the view
177
+ // document root. They haven't been rendered yet so they are not present in the DOM root.
178
+ // Using writer.setAttribute( 'class', ... ) would override them completely.
179
+ if (name === 'class') {
180
+ this._writer.addClass(value.split(' '), viewRoot);
181
+ }
182
+ else {
183
+ this._writer.setAttribute(name, value, viewRoot);
184
+ }
185
+ }
186
+ this._initialDomRootAttributes.set(domRoot, initialDomRootAttributes);
187
+ const updateContenteditableAttribute = () => {
188
+ this._writer.setAttribute('contenteditable', (!viewRoot.isReadOnly).toString(), viewRoot);
189
+ if (viewRoot.isReadOnly) {
190
+ this._writer.addClass('ck-read-only', viewRoot);
191
+ }
192
+ else {
193
+ this._writer.removeClass('ck-read-only', viewRoot);
194
+ }
195
+ };
196
+ // Set initial value.
197
+ updateContenteditableAttribute();
198
+ this.domRoots.set(name, domRoot);
199
+ this.domConverter.bindElements(domRoot, viewRoot);
200
+ this._renderer.markToSync('children', viewRoot);
201
+ this._renderer.markToSync('attributes', viewRoot);
202
+ this._renderer.domDocuments.add(domRoot.ownerDocument);
203
+ viewRoot.on('change:children', (evt, node) => this._renderer.markToSync('children', node));
204
+ viewRoot.on('change:attributes', (evt, node) => this._renderer.markToSync('attributes', node));
205
+ viewRoot.on('change:text', (evt, node) => this._renderer.markToSync('text', node));
206
+ viewRoot.on('change:isReadOnly', () => this.change(updateContenteditableAttribute));
207
+ viewRoot.on('change', () => {
208
+ this._hasChangedSinceTheLastRendering = true;
209
+ });
210
+ for (const observer of this._observers.values()) {
211
+ observer.observe(domRoot, name);
212
+ }
213
+ }
214
+ /**
215
+ * Detaches a DOM root element from the view element and restores its attributes to the state before
216
+ * {@link #attachDomRoot `attachDomRoot()`}.
217
+ *
218
+ * @param name Name of the root to detach.
219
+ */
220
+ detachDomRoot(name) {
221
+ const domRoot = this.domRoots.get(name);
222
+ // Remove all root attributes so the DOM element is "bare".
223
+ Array.from(domRoot.attributes).forEach(({ name }) => domRoot.removeAttribute(name));
224
+ const initialDomRootAttributes = this._initialDomRootAttributes.get(domRoot);
225
+ // Revert all view root attributes back to the state before attachDomRoot was called.
226
+ for (const attribute in initialDomRootAttributes) {
227
+ domRoot.setAttribute(attribute, initialDomRootAttributes[attribute]);
228
+ }
229
+ this.domRoots.delete(name);
230
+ this.domConverter.unbindDomElement(domRoot);
231
+ for (const observer of this._observers.values()) {
232
+ observer.stopObserving(domRoot);
233
+ }
234
+ }
235
+ /**
236
+ * Gets DOM root element.
237
+ *
238
+ * @param name Name of the root.
239
+ * @returns DOM root element instance.
240
+ */
241
+ getDomRoot(name = 'main') {
242
+ return this.domRoots.get(name);
243
+ }
244
+ /**
245
+ * Creates observer of the given type if not yet created, {@link module:engine/view/observer/observer~Observer#enable enables} it
246
+ * and {@link module:engine/view/observer/observer~Observer#observe attaches} to all existing and future
247
+ * {@link #domRoots DOM roots}.
248
+ *
249
+ * Note: Observers are recognized by their constructor (classes). A single observer will be instantiated and used only
250
+ * when registered for the first time. This means that features and other components can register a single observer
251
+ * multiple times without caring whether it has been already added or not.
252
+ *
253
+ * @param ObserverConstructor The constructor of an observer to add.
254
+ * Should create an instance inheriting from {@link module:engine/view/observer/observer~Observer}.
255
+ * @returns Added observer instance.
256
+ */
257
+ addObserver(ObserverConstructor) {
258
+ let observer = this._observers.get(ObserverConstructor);
259
+ if (observer) {
260
+ return observer;
261
+ }
262
+ observer = new ObserverConstructor(this);
263
+ this._observers.set(ObserverConstructor, observer);
264
+ for (const [name, domElement] of this.domRoots) {
265
+ observer.observe(domElement, name);
266
+ }
267
+ observer.enable();
268
+ return observer;
269
+ }
270
+ /**
271
+ * Returns observer of the given type or `undefined` if such observer has not been added yet.
272
+ *
273
+ * @param ObserverConstructor The constructor of an observer to get.
274
+ * @returns Observer instance or undefined.
275
+ */
276
+ getObserver(ObserverConstructor) {
277
+ return this._observers.get(ObserverConstructor);
278
+ }
279
+ /**
280
+ * Disables all added observers.
281
+ */
282
+ disableObservers() {
283
+ for (const observer of this._observers.values()) {
284
+ observer.disable();
285
+ }
286
+ }
287
+ /**
288
+ * Enables all added observers.
289
+ */
290
+ enableObservers() {
291
+ for (const observer of this._observers.values()) {
292
+ observer.enable();
293
+ }
294
+ }
295
+ /**
296
+ * Scrolls the page viewport and {@link #domRoots} with their ancestors to reveal the
297
+ * caret, **if not already visible to the user**.
298
+ *
299
+ * **Note**: Calling this method fires the {@link module:engine/view/view~ViewScrollToTheSelectionEvent} event that
300
+ * allows custom behaviors.
301
+ *
302
+ * @param options Additional configuration of the scrolling behavior.
303
+ * @param options.viewportOffset A distance between the DOM selection and the viewport boundary to be maintained
304
+ * while scrolling to the selection (default is 20px). Setting this value to `0` will reveal the selection precisely at
305
+ * the viewport boundary.
306
+ * @param options.ancestorOffset A distance between the DOM selection and scrollable DOM root ancestor(s) to be maintained
307
+ * while scrolling to the selection (default is 20px). Setting this value to `0` will reveal the selection precisely at
308
+ * the scrollable ancestor(s) boundary.
309
+ * @param options.alignToTop When set `true`, the DOM selection will be aligned to the top of the viewport if not already visible
310
+ * (see `forceScroll` to learn more).
311
+ * @param options.forceScroll When set `true`, the DOM selection will be aligned to the top of the viewport and scrollable ancestors
312
+ * whether it is already visible or not. This option will only work when `alignToTop` is `true`.
313
+ */
314
+ scrollToTheSelection({ alignToTop, forceScroll, viewportOffset = 20, ancestorOffset = 20 } = {}) {
315
+ const range = this.document.selection.getFirstRange();
316
+ if (!range) {
317
+ return;
318
+ }
319
+ // Clone to make sure properties like `viewportOffset` are not mutated in the event listeners.
320
+ const originalArgs = cloneDeep({ alignToTop, forceScroll, viewportOffset, ancestorOffset });
321
+ if (typeof viewportOffset === 'number') {
322
+ viewportOffset = {
323
+ top: viewportOffset,
324
+ bottom: viewportOffset,
325
+ left: viewportOffset,
326
+ right: viewportOffset
327
+ };
328
+ }
329
+ const options = {
330
+ target: this.domConverter.viewRangeToDom(range),
331
+ viewportOffset,
332
+ ancestorOffset,
333
+ alignToTop,
334
+ forceScroll
335
+ };
336
+ this.fire('scrollToTheSelection', options, originalArgs);
337
+ scrollViewportToShowTarget(options);
338
+ }
339
+ /**
340
+ * It will focus DOM element representing {@link module:engine/view/editableelement~EditableElement EditableElement}
341
+ * that is currently having selection inside.
342
+ */
343
+ focus() {
344
+ if (!this.document.isFocused) {
345
+ const editable = this.document.selection.editableElement;
346
+ if (editable) {
347
+ this.domConverter.focus(editable);
348
+ this.forceRender();
349
+ }
350
+ else {
351
+ // Before focusing view document, selection should be placed inside one of the view's editables.
352
+ // Normally its selection will be converted from model document (which have default selection), but
353
+ // when using view document on its own, we need to manually place selection before focusing it.
354
+ //
355
+ // @if CK_DEBUG // console.warn( 'There is no selection in any editable to focus.' );
356
+ }
357
+ }
358
+ }
359
+ /**
360
+ * The `change()` method is the primary way of changing the view. You should use it to modify any node in the view tree.
361
+ * It makes sure that after all changes are made the view is rendered to the DOM (assuming that the view will be changed
362
+ * inside the callback). It prevents situations when the DOM is updated when the view state is not yet correct. It allows
363
+ * to nest calls one inside another and still performs a single rendering after all those changes are made.
364
+ * It also returns the return value of its callback.
365
+ *
366
+ * ```ts
367
+ * const text = view.change( writer => {
368
+ * const newText = writer.createText( 'foo' );
369
+ * writer.insert( position1, newText );
370
+ *
371
+ * view.change( writer => {
372
+ * writer.insert( position2, writer.createText( 'bar' ) );
373
+ * } );
374
+ *
375
+ * writer.remove( range );
376
+ *
377
+ * return newText;
378
+ * } );
379
+ * ```
380
+ *
381
+ * When the outermost change block is done and rendering to the DOM is over the
382
+ * {@link module:engine/view/view~View#event:render `View#render`} event is fired.
383
+ *
384
+ * This method throws a `applying-view-changes-on-rendering` error when
385
+ * the change block is used after rendering to the DOM has started.
386
+ *
387
+ * @param callback Callback function which may modify the view.
388
+ * @returns Value returned by the callback.
389
+ */
390
+ change(callback) {
391
+ if (this.isRenderingInProgress || this._postFixersInProgress) {
392
+ /**
393
+ * Thrown when there is an attempt to make changes to the view tree when it is in incorrect state. This may
394
+ * cause some unexpected behaviour and inconsistency between the DOM and the view.
395
+ * This may be caused by:
396
+ *
397
+ * * calling {@link module:engine/view/view~View#change} or {@link module:engine/view/view~View#forceRender} during rendering
398
+ * process,
399
+ * * calling {@link module:engine/view/view~View#change} or {@link module:engine/view/view~View#forceRender} inside of
400
+ * {@link module:engine/view/document~Document#registerPostFixer post-fixer function}.
401
+ *
402
+ * @error cannot-change-view-tree
403
+ */
404
+ throw new CKEditorError('cannot-change-view-tree', this);
405
+ }
406
+ try {
407
+ // Recursive call to view.change() method - execute listener immediately.
408
+ if (this._ongoingChange) {
409
+ return callback(this._writer);
410
+ }
411
+ // This lock will assure that all recursive calls to view.change() will end up in same block - one "render"
412
+ // event for all nested calls.
413
+ this._ongoingChange = true;
414
+ const callbackResult = callback(this._writer);
415
+ this._ongoingChange = false;
416
+ // This lock is used by editing controller to render changes from outer most model.change() once. As plugins might call
417
+ // view.change() inside model.change() block - this will ensures that postfixers and rendering are called once after all
418
+ // changes. Also, we don't need to render anything if there're no changes since last rendering.
419
+ if (!this._renderingDisabled && this._hasChangedSinceTheLastRendering) {
420
+ this._postFixersInProgress = true;
421
+ this.document._callPostFixers(this._writer);
422
+ this._postFixersInProgress = false;
423
+ this.fire('render');
424
+ }
425
+ return callbackResult;
426
+ }
427
+ catch (err) {
428
+ // @if CK_DEBUG // throw err;
429
+ /* istanbul ignore next -- @preserve */
430
+ CKEditorError.rethrowUnexpectedError(err, this);
431
+ }
432
+ }
433
+ /**
434
+ * Forces rendering {@link module:engine/view/document~Document view document} to DOM. If any view changes are
435
+ * currently in progress, rendering will start after all {@link #change change blocks} are processed.
436
+ *
437
+ * Note that this method is dedicated for special cases. All view changes should be wrapped in the {@link #change}
438
+ * block and the view will automatically check whether it needs to render DOM or not.
439
+ *
440
+ * Throws {@link module:utils/ckeditorerror~CKEditorError CKEditorError} `applying-view-changes-on-rendering` when
441
+ * trying to re-render when rendering to DOM has already started.
442
+ */
443
+ forceRender() {
444
+ this._hasChangedSinceTheLastRendering = true;
445
+ this.getObserver(FocusObserver).flush();
446
+ this.change(() => { });
447
+ }
448
+ /**
449
+ * Destroys this instance. Makes sure that all observers are destroyed and listeners removed.
450
+ */
451
+ destroy() {
452
+ for (const observer of this._observers.values()) {
453
+ observer.destroy();
454
+ }
455
+ this.document.destroy();
456
+ this.stopListening();
457
+ }
458
+ /**
459
+ * Creates position at the given location. The location can be specified as:
460
+ *
461
+ * * a {@link module:engine/view/position~Position position},
462
+ * * parent element and offset (offset defaults to `0`),
463
+ * * parent element and `'end'` (sets position at the end of that element),
464
+ * * {@link module:engine/view/item~Item view item} and `'before'` or `'after'` (sets position before or after given view item).
465
+ *
466
+ * This method is a shortcut to other constructors such as:
467
+ *
468
+ * * {@link #createPositionBefore},
469
+ * * {@link #createPositionAfter},
470
+ *
471
+ * @param offset Offset or one of the flags. Used only when first parameter is a {@link module:engine/view/item~Item view item}.
472
+ */
473
+ createPositionAt(itemOrPosition, offset) {
474
+ return Position._createAt(itemOrPosition, offset);
475
+ }
476
+ /**
477
+ * Creates a new position after given view item.
478
+ *
479
+ * @param item View item after which the position should be located.
480
+ */
481
+ createPositionAfter(item) {
482
+ return Position._createAfter(item);
483
+ }
484
+ /**
485
+ * Creates a new position before given view item.
486
+ *
487
+ * @param item View item before which the position should be located.
488
+ */
489
+ createPositionBefore(item) {
490
+ return Position._createBefore(item);
491
+ }
492
+ /**
493
+ * Creates a range spanning from `start` position to `end` position.
494
+ *
495
+ * **Note:** This factory method creates it's own {@link module:engine/view/position~Position} instances basing on passed values.
496
+ *
497
+ * @param start Start position.
498
+ * @param end End position. If not set, range will be collapsed at `start` position.
499
+ */
500
+ createRange(start, end) {
501
+ return new Range(start, end);
502
+ }
503
+ /**
504
+ * Creates a range that starts before given {@link module:engine/view/item~Item view item} and ends after it.
505
+ */
506
+ createRangeOn(item) {
507
+ return Range._createOn(item);
508
+ }
509
+ /**
510
+ * Creates a range inside an {@link module:engine/view/element~Element element} which starts before the first child of
511
+ * that element and ends after the last child of that element.
512
+ *
513
+ * @param element Element which is a parent for the range.
514
+ */
515
+ createRangeIn(element) {
516
+ return Range._createIn(element);
517
+ }
518
+ createSelection(...args) {
519
+ return new Selection(...args);
520
+ }
521
+ /**
522
+ * Disables or enables rendering. If the flag is set to `true` then the rendering will be disabled.
523
+ * If the flag is set to `false` and if there was some change in the meantime, then the rendering action will be performed.
524
+ *
525
+ * @internal
526
+ * @param flag A flag indicates whether the rendering should be disabled.
527
+ */
528
+ _disableRendering(flag) {
529
+ this._renderingDisabled = flag;
530
+ if (flag == false) {
531
+ // Render when you stop blocking rendering.
532
+ this.change(() => { });
533
+ }
534
+ }
535
+ /**
536
+ * Renders all changes. In order to avoid triggering the observers (e.g. selection) all observers are disabled
537
+ * before rendering and re-enabled after that.
538
+ */
539
+ _render() {
540
+ this.isRenderingInProgress = true;
541
+ this.disableObservers();
542
+ this._renderer.render();
543
+ this.enableObservers();
544
+ this.isRenderingInProgress = false;
545
+ }
546
+ }