@ckeditor/ckeditor5-engine 39.0.1 → 40.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (244) hide show
  1. package/CHANGELOG.md +2 -2
  2. package/LICENSE.md +1 -1
  3. package/README.md +8 -8
  4. package/package.json +2 -6
  5. package/src/controller/datacontroller.d.ts +334 -334
  6. package/src/controller/datacontroller.js +481 -481
  7. package/src/controller/editingcontroller.d.ts +98 -98
  8. package/src/controller/editingcontroller.js +191 -191
  9. package/src/conversion/conversion.d.ts +478 -478
  10. package/src/conversion/conversion.js +601 -601
  11. package/src/conversion/conversionhelpers.d.ts +26 -26
  12. package/src/conversion/conversionhelpers.js +32 -32
  13. package/src/conversion/downcastdispatcher.d.ts +562 -562
  14. package/src/conversion/downcastdispatcher.js +547 -547
  15. package/src/conversion/downcasthelpers.d.ts +1226 -1226
  16. package/src/conversion/downcasthelpers.js +2183 -2183
  17. package/src/conversion/mapper.d.ts +503 -503
  18. package/src/conversion/mapper.js +536 -536
  19. package/src/conversion/modelconsumable.d.ts +201 -201
  20. package/src/conversion/modelconsumable.js +333 -333
  21. package/src/conversion/upcastdispatcher.d.ts +492 -492
  22. package/src/conversion/upcastdispatcher.js +460 -460
  23. package/src/conversion/upcasthelpers.d.ts +499 -499
  24. package/src/conversion/upcasthelpers.js +950 -950
  25. package/src/conversion/viewconsumable.d.ts +369 -369
  26. package/src/conversion/viewconsumable.js +532 -532
  27. package/src/dataprocessor/basichtmlwriter.d.ts +18 -18
  28. package/src/dataprocessor/basichtmlwriter.js +19 -19
  29. package/src/dataprocessor/dataprocessor.d.ts +61 -61
  30. package/src/dataprocessor/dataprocessor.js +5 -5
  31. package/src/dataprocessor/htmldataprocessor.d.ts +76 -76
  32. package/src/dataprocessor/htmldataprocessor.js +96 -96
  33. package/src/dataprocessor/htmlwriter.d.ts +16 -16
  34. package/src/dataprocessor/htmlwriter.js +5 -5
  35. package/src/dataprocessor/xmldataprocessor.d.ts +90 -90
  36. package/src/dataprocessor/xmldataprocessor.js +108 -108
  37. package/src/dev-utils/model.d.ts +124 -124
  38. package/src/dev-utils/model.js +395 -395
  39. package/src/dev-utils/operationreplayer.d.ts +51 -51
  40. package/src/dev-utils/operationreplayer.js +112 -112
  41. package/src/dev-utils/utils.d.ts +37 -37
  42. package/src/dev-utils/utils.js +73 -73
  43. package/src/dev-utils/view.d.ts +319 -319
  44. package/src/dev-utils/view.js +967 -967
  45. package/src/index.d.ts +114 -114
  46. package/src/index.js +78 -78
  47. package/src/model/batch.d.ts +106 -106
  48. package/src/model/batch.js +96 -96
  49. package/src/model/differ.d.ts +387 -387
  50. package/src/model/differ.js +1149 -1149
  51. package/src/model/document.d.ts +272 -272
  52. package/src/model/document.js +361 -361
  53. package/src/model/documentfragment.d.ts +200 -200
  54. package/src/model/documentfragment.js +306 -306
  55. package/src/model/documentselection.d.ts +420 -420
  56. package/src/model/documentselection.js +993 -993
  57. package/src/model/element.d.ts +165 -165
  58. package/src/model/element.js +281 -281
  59. package/src/model/history.d.ts +114 -114
  60. package/src/model/history.js +207 -207
  61. package/src/model/item.d.ts +14 -14
  62. package/src/model/item.js +5 -5
  63. package/src/model/liveposition.d.ts +77 -77
  64. package/src/model/liveposition.js +93 -93
  65. package/src/model/liverange.d.ts +102 -102
  66. package/src/model/liverange.js +120 -120
  67. package/src/model/markercollection.d.ts +335 -335
  68. package/src/model/markercollection.js +403 -403
  69. package/src/model/model.d.ts +919 -919
  70. package/src/model/model.js +842 -842
  71. package/src/model/node.d.ts +256 -256
  72. package/src/model/node.js +375 -375
  73. package/src/model/nodelist.d.ts +91 -91
  74. package/src/model/nodelist.js +163 -163
  75. package/src/model/operation/attributeoperation.d.ts +103 -103
  76. package/src/model/operation/attributeoperation.js +148 -148
  77. package/src/model/operation/detachoperation.d.ts +60 -60
  78. package/src/model/operation/detachoperation.js +77 -77
  79. package/src/model/operation/insertoperation.d.ts +90 -90
  80. package/src/model/operation/insertoperation.js +135 -135
  81. package/src/model/operation/markeroperation.d.ts +91 -91
  82. package/src/model/operation/markeroperation.js +107 -107
  83. package/src/model/operation/mergeoperation.d.ts +100 -100
  84. package/src/model/operation/mergeoperation.js +167 -167
  85. package/src/model/operation/moveoperation.d.ts +96 -96
  86. package/src/model/operation/moveoperation.js +164 -164
  87. package/src/model/operation/nooperation.d.ts +38 -38
  88. package/src/model/operation/nooperation.js +48 -48
  89. package/src/model/operation/operation.d.ts +96 -96
  90. package/src/model/operation/operation.js +62 -62
  91. package/src/model/operation/operationfactory.d.ts +18 -18
  92. package/src/model/operation/operationfactory.js +44 -44
  93. package/src/model/operation/renameoperation.d.ts +83 -83
  94. package/src/model/operation/renameoperation.js +115 -115
  95. package/src/model/operation/rootattributeoperation.d.ts +98 -98
  96. package/src/model/operation/rootattributeoperation.js +155 -155
  97. package/src/model/operation/rootoperation.d.ts +76 -76
  98. package/src/model/operation/rootoperation.js +90 -90
  99. package/src/model/operation/splitoperation.d.ts +109 -109
  100. package/src/model/operation/splitoperation.js +194 -194
  101. package/src/model/operation/transform.d.ts +100 -100
  102. package/src/model/operation/transform.js +1985 -1985
  103. package/src/model/operation/utils.d.ts +71 -71
  104. package/src/model/operation/utils.js +213 -213
  105. package/src/model/position.d.ts +539 -539
  106. package/src/model/position.js +979 -979
  107. package/src/model/range.d.ts +458 -458
  108. package/src/model/range.js +875 -875
  109. package/src/model/rootelement.d.ts +60 -60
  110. package/src/model/rootelement.js +74 -74
  111. package/src/model/schema.d.ts +1186 -1186
  112. package/src/model/schema.js +1242 -1242
  113. package/src/model/selection.d.ts +482 -482
  114. package/src/model/selection.js +789 -789
  115. package/src/model/text.d.ts +66 -66
  116. package/src/model/text.js +85 -85
  117. package/src/model/textproxy.d.ts +144 -144
  118. package/src/model/textproxy.js +189 -189
  119. package/src/model/treewalker.d.ts +186 -186
  120. package/src/model/treewalker.js +244 -244
  121. package/src/model/typecheckable.d.ts +285 -285
  122. package/src/model/typecheckable.js +16 -16
  123. package/src/model/utils/autoparagraphing.d.ts +37 -37
  124. package/src/model/utils/autoparagraphing.js +63 -63
  125. package/src/model/utils/deletecontent.d.ts +58 -58
  126. package/src/model/utils/deletecontent.js +488 -488
  127. package/src/model/utils/findoptimalinsertionrange.d.ts +32 -32
  128. package/src/model/utils/findoptimalinsertionrange.js +57 -57
  129. package/src/model/utils/getselectedcontent.d.ts +30 -30
  130. package/src/model/utils/getselectedcontent.js +125 -125
  131. package/src/model/utils/insertcontent.d.ts +46 -46
  132. package/src/model/utils/insertcontent.js +705 -705
  133. package/src/model/utils/insertobject.d.ts +44 -44
  134. package/src/model/utils/insertobject.js +139 -139
  135. package/src/model/utils/modifyselection.d.ts +48 -48
  136. package/src/model/utils/modifyselection.js +186 -186
  137. package/src/model/utils/selection-post-fixer.d.ts +74 -74
  138. package/src/model/utils/selection-post-fixer.js +260 -260
  139. package/src/model/writer.d.ts +851 -851
  140. package/src/model/writer.js +1306 -1306
  141. package/src/view/attributeelement.d.ts +108 -108
  142. package/src/view/attributeelement.js +184 -184
  143. package/src/view/containerelement.d.ts +49 -49
  144. package/src/view/containerelement.js +80 -80
  145. package/src/view/datatransfer.d.ts +79 -79
  146. package/src/view/datatransfer.js +98 -98
  147. package/src/view/document.d.ts +184 -184
  148. package/src/view/document.js +120 -120
  149. package/src/view/documentfragment.d.ts +149 -149
  150. package/src/view/documentfragment.js +228 -228
  151. package/src/view/documentselection.d.ts +306 -306
  152. package/src/view/documentselection.js +256 -256
  153. package/src/view/domconverter.d.ts +640 -640
  154. package/src/view/domconverter.js +1450 -1425
  155. package/src/view/downcastwriter.d.ts +996 -996
  156. package/src/view/downcastwriter.js +1696 -1696
  157. package/src/view/editableelement.d.ts +62 -62
  158. package/src/view/editableelement.js +62 -62
  159. package/src/view/element.d.ts +468 -468
  160. package/src/view/element.js +724 -724
  161. package/src/view/elementdefinition.d.ts +87 -87
  162. package/src/view/elementdefinition.js +5 -5
  163. package/src/view/emptyelement.d.ts +41 -41
  164. package/src/view/emptyelement.js +73 -73
  165. package/src/view/filler.d.ts +111 -111
  166. package/src/view/filler.js +150 -150
  167. package/src/view/item.d.ts +14 -14
  168. package/src/view/item.js +5 -5
  169. package/src/view/matcher.d.ts +486 -486
  170. package/src/view/matcher.js +507 -507
  171. package/src/view/node.d.ts +163 -163
  172. package/src/view/node.js +228 -228
  173. package/src/view/observer/arrowkeysobserver.d.ts +45 -45
  174. package/src/view/observer/arrowkeysobserver.js +40 -40
  175. package/src/view/observer/bubblingemittermixin.d.ts +166 -166
  176. package/src/view/observer/bubblingemittermixin.js +172 -172
  177. package/src/view/observer/bubblingeventinfo.d.ts +47 -47
  178. package/src/view/observer/bubblingeventinfo.js +37 -37
  179. package/src/view/observer/clickobserver.d.ts +43 -43
  180. package/src/view/observer/clickobserver.js +29 -29
  181. package/src/view/observer/compositionobserver.d.ts +82 -82
  182. package/src/view/observer/compositionobserver.js +60 -60
  183. package/src/view/observer/domeventdata.d.ts +50 -50
  184. package/src/view/observer/domeventdata.js +47 -47
  185. package/src/view/observer/domeventobserver.d.ts +73 -73
  186. package/src/view/observer/domeventobserver.js +79 -79
  187. package/src/view/observer/fakeselectionobserver.d.ts +47 -47
  188. package/src/view/observer/fakeselectionobserver.js +91 -91
  189. package/src/view/observer/focusobserver.d.ts +82 -82
  190. package/src/view/observer/focusobserver.js +86 -86
  191. package/src/view/observer/inputobserver.d.ts +86 -86
  192. package/src/view/observer/inputobserver.js +164 -164
  193. package/src/view/observer/keyobserver.d.ts +66 -66
  194. package/src/view/observer/keyobserver.js +39 -39
  195. package/src/view/observer/mouseobserver.d.ts +89 -89
  196. package/src/view/observer/mouseobserver.js +29 -29
  197. package/src/view/observer/mutationobserver.d.ts +86 -86
  198. package/src/view/observer/mutationobserver.js +206 -206
  199. package/src/view/observer/observer.d.ts +89 -89
  200. package/src/view/observer/observer.js +84 -84
  201. package/src/view/observer/selectionobserver.d.ts +148 -148
  202. package/src/view/observer/selectionobserver.js +202 -202
  203. package/src/view/observer/tabobserver.d.ts +46 -46
  204. package/src/view/observer/tabobserver.js +42 -42
  205. package/src/view/placeholder.d.ts +96 -96
  206. package/src/view/placeholder.js +267 -267
  207. package/src/view/position.d.ts +189 -189
  208. package/src/view/position.js +324 -324
  209. package/src/view/range.d.ts +279 -279
  210. package/src/view/range.js +430 -430
  211. package/src/view/rawelement.d.ts +73 -73
  212. package/src/view/rawelement.js +105 -105
  213. package/src/view/renderer.d.ts +265 -265
  214. package/src/view/renderer.js +999 -999
  215. package/src/view/rooteditableelement.d.ts +41 -41
  216. package/src/view/rooteditableelement.js +69 -69
  217. package/src/view/selection.d.ts +375 -375
  218. package/src/view/selection.js +559 -559
  219. package/src/view/styles/background.d.ts +33 -33
  220. package/src/view/styles/background.js +74 -74
  221. package/src/view/styles/border.d.ts +43 -43
  222. package/src/view/styles/border.js +316 -316
  223. package/src/view/styles/margin.d.ts +29 -29
  224. package/src/view/styles/margin.js +34 -34
  225. package/src/view/styles/padding.d.ts +29 -29
  226. package/src/view/styles/padding.js +34 -34
  227. package/src/view/styles/utils.d.ts +93 -93
  228. package/src/view/styles/utils.js +219 -219
  229. package/src/view/stylesmap.d.ts +675 -675
  230. package/src/view/stylesmap.js +766 -766
  231. package/src/view/text.d.ts +74 -74
  232. package/src/view/text.js +93 -93
  233. package/src/view/textproxy.d.ts +97 -97
  234. package/src/view/textproxy.js +124 -124
  235. package/src/view/treewalker.d.ts +195 -195
  236. package/src/view/treewalker.js +327 -327
  237. package/src/view/typecheckable.d.ts +448 -448
  238. package/src/view/typecheckable.js +19 -19
  239. package/src/view/uielement.d.ts +96 -96
  240. package/src/view/uielement.js +182 -182
  241. package/src/view/upcastwriter.d.ts +417 -417
  242. package/src/view/upcastwriter.js +359 -359
  243. package/src/view/view.d.ts +487 -487
  244. package/src/view/view.js +546 -546
@@ -1,481 +1,481 @@
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/controller/datacontroller
7
- */
8
- import { CKEditorError, EmitterMixin, ObservableMixin, logWarning } from '@ckeditor/ckeditor5-utils';
9
- import Mapper from '../conversion/mapper';
10
- import DowncastDispatcher from '../conversion/downcastdispatcher';
11
- import { insertAttributesAndChildren, insertText } from '../conversion/downcasthelpers';
12
- import UpcastDispatcher from '../conversion/upcastdispatcher';
13
- import { convertText, convertToModelFragment } from '../conversion/upcasthelpers';
14
- import ViewDocumentFragment from '../view/documentfragment';
15
- import ViewDocument from '../view/document';
16
- import ViewDowncastWriter from '../view/downcastwriter';
17
- import ModelRange from '../model/range';
18
- import { autoParagraphEmptyRoots } from '../model/utils/autoparagraphing';
19
- import HtmlDataProcessor from '../dataprocessor/htmldataprocessor';
20
- /**
21
- * Controller for the data pipeline. The data pipeline controls how data is retrieved from the document
22
- * and set inside it. Hence, the controller features two methods which allow to {@link ~DataController#get get}
23
- * and {@link ~DataController#set set} data of the {@link ~DataController#model model}
24
- * using the given:
25
- *
26
- * * {@link module:engine/dataprocessor/dataprocessor~DataProcessor data processor},
27
- * * downcast converters,
28
- * * upcast converters.
29
- *
30
- * An instance of the data controller is always available in the {@link module:core/editor/editor~Editor#data `editor.data`}
31
- * property:
32
- *
33
- * ```ts
34
- * editor.data.get( { rootName: 'customRoot' } ); // -> '<p>Hello!</p>'
35
- * ```
36
- */
37
- export default class DataController extends EmitterMixin() {
38
- /**
39
- * Creates a data controller instance.
40
- *
41
- * @param model Data model.
42
- * @param stylesProcessor The styles processor instance.
43
- */
44
- constructor(model, stylesProcessor) {
45
- super();
46
- this.model = model;
47
- this.mapper = new Mapper();
48
- this.downcastDispatcher = new DowncastDispatcher({
49
- mapper: this.mapper,
50
- schema: model.schema
51
- });
52
- this.downcastDispatcher.on('insert:$text', insertText(), { priority: 'lowest' });
53
- this.downcastDispatcher.on('insert', insertAttributesAndChildren(), { priority: 'lowest' });
54
- this.upcastDispatcher = new UpcastDispatcher({
55
- schema: model.schema
56
- });
57
- this.viewDocument = new ViewDocument(stylesProcessor);
58
- this.stylesProcessor = stylesProcessor;
59
- this.htmlProcessor = new HtmlDataProcessor(this.viewDocument);
60
- this.processor = this.htmlProcessor;
61
- this._viewWriter = new ViewDowncastWriter(this.viewDocument);
62
- // Define default converters for text and elements.
63
- //
64
- // Note that if there is no default converter for the element it will be skipped, for instance `<b>foo</b>` will be
65
- // converted to nothing. We therefore add `convertToModelFragment` as a last converter so it converts children of that
66
- // element to the document fragment so `<b>foo</b>` will still be converted to `foo` even if there is no converter for `<b>`.
67
- this.upcastDispatcher.on('text', convertText(), { priority: 'lowest' });
68
- this.upcastDispatcher.on('element', convertToModelFragment(), { priority: 'lowest' });
69
- this.upcastDispatcher.on('documentFragment', convertToModelFragment(), { priority: 'lowest' });
70
- ObservableMixin().prototype.decorate.call(this, 'init');
71
- ObservableMixin().prototype.decorate.call(this, 'set');
72
- ObservableMixin().prototype.decorate.call(this, 'get');
73
- ObservableMixin().prototype.decorate.call(this, 'toView');
74
- ObservableMixin().prototype.decorate.call(this, 'toModel');
75
- // Fire the `ready` event when the initialization has completed. Such low-level listener offers the possibility
76
- // to plug into the initialization pipeline without interrupting the initialization flow.
77
- this.on('init', () => {
78
- this.fire('ready');
79
- }, { priority: 'lowest' });
80
- // Fix empty roots after DataController is 'ready' (note that the init method could be decorated and stopped).
81
- // We need to handle this event because initial data could be empty and the post-fixer would not get triggered.
82
- this.on('ready', () => {
83
- this.model.enqueueChange({ isUndoable: false }, autoParagraphEmptyRoots);
84
- }, { priority: 'lowest' });
85
- }
86
- /**
87
- * Returns the model's data converted by downcast dispatchers attached to {@link #downcastDispatcher} and
88
- * formatted by the {@link #processor data processor}.
89
- *
90
- * A warning is logged when you try to retrieve data for a detached root, as most probably this is a mistake. A detached root should
91
- * be treated like it is removed, and you should not save its data. Note, that the detached root data is always an empty string.
92
- *
93
- * @fires get
94
- * @param options Additional configuration for the retrieved data. `DataController` provides two optional
95
- * properties: `rootName` and `trim`. Other properties of this object are specified by various editor features.
96
- * @param options.rootName Root name. Default 'main'.
97
- * @param options.trim Whether returned data should be trimmed. This option is set to `empty` by default,
98
- * which means whenever editor content is considered empty, an empty string will be returned. To turn off trimming completely
99
- * use `'none'`. In such cases the exact content will be returned (for example a `<p>&nbsp;</p>` for an empty editor).
100
- * @returns Output data.
101
- */
102
- get(options = {}) {
103
- const { rootName = 'main', trim = 'empty' } = options;
104
- if (!this._checkIfRootsExists([rootName])) {
105
- /**
106
- * Cannot get data from a non-existing root. This error is thrown when
107
- * {@link module:engine/controller/datacontroller~DataController#get `DataController#get()` method}
108
- * is called with a non-existent root name. For example, if there is an editor instance with only `main` root,
109
- * calling {@link module:engine/controller/datacontroller~DataController#get} like:
110
- *
111
- * ```ts
112
- * data.get( { rootName: 'root2' } );
113
- * ```
114
- *
115
- * will throw this error.
116
- *
117
- * @error datacontroller-get-non-existent-root
118
- */
119
- throw new CKEditorError('datacontroller-get-non-existent-root', this);
120
- }
121
- const root = this.model.document.getRoot(rootName);
122
- if (!root.isAttached()) {
123
- /**
124
- * Retrieving document data for a detached root.
125
- *
126
- * This usually indicates an error as a detached root should be considered "removed" and should not be included in the
127
- * document data.
128
- *
129
- * @error datacontroller-get-detached-root
130
- */
131
- logWarning('datacontroller-get-detached-root', this);
132
- }
133
- if (trim === 'empty' && !this.model.hasContent(root, { ignoreWhitespaces: true })) {
134
- return '';
135
- }
136
- return this.stringify(root, options);
137
- }
138
- /**
139
- * Returns the content of the given {@link module:engine/model/element~Element model's element} or
140
- * {@link module:engine/model/documentfragment~DocumentFragment model document fragment} converted by the downcast converters
141
- * attached to the {@link #downcastDispatcher} and formatted by the {@link #processor data processor}.
142
- *
143
- * @param modelElementOrFragment The element whose content will be stringified.
144
- * @param options Additional configuration passed to the conversion process.
145
- * @returns Output data.
146
- */
147
- stringify(modelElementOrFragment, options = {}) {
148
- // Model -> view.
149
- const viewDocumentFragment = this.toView(modelElementOrFragment, options);
150
- // View -> data.
151
- return this.processor.toData(viewDocumentFragment);
152
- }
153
- /**
154
- * Returns the content of the given {@link module:engine/model/element~Element model element} or
155
- * {@link module:engine/model/documentfragment~DocumentFragment model document fragment} converted by the downcast
156
- * converters attached to {@link #downcastDispatcher} into a
157
- * {@link module:engine/view/documentfragment~DocumentFragment view document fragment}.
158
- *
159
- * @fires toView
160
- * @param modelElementOrFragment Element or document fragment whose content will be converted.
161
- * @param options Additional configuration that will be available through the
162
- * {@link module:engine/conversion/downcastdispatcher~DowncastConversionApi#options} during the conversion process.
163
- * @returns Output view DocumentFragment.
164
- */
165
- toView(modelElementOrFragment, options = {}) {
166
- const viewDocument = this.viewDocument;
167
- const viewWriter = this._viewWriter;
168
- // Clear bindings so the call to this method returns correct results.
169
- this.mapper.clearBindings();
170
- // First, convert elements.
171
- const modelRange = ModelRange._createIn(modelElementOrFragment);
172
- const viewDocumentFragment = new ViewDocumentFragment(viewDocument);
173
- this.mapper.bindElements(modelElementOrFragment, viewDocumentFragment);
174
- // Prepare list of markers.
175
- // For document fragment, simply take the markers assigned to this document fragment.
176
- // For model root, all markers in that root will be taken.
177
- // For model element, we need to check which markers are intersecting with this element and relatively modify the markers' ranges.
178
- // Collapsed markers at element boundary, although considered as not intersecting with the element, will also be returned.
179
- const markers = modelElementOrFragment.is('documentFragment') ?
180
- modelElementOrFragment.markers :
181
- _getMarkersRelativeToElement(modelElementOrFragment);
182
- this.downcastDispatcher.convert(modelRange, markers, viewWriter, options);
183
- return viewDocumentFragment;
184
- }
185
- /**
186
- * Sets the initial input data parsed by the {@link #processor data processor} and
187
- * converted by the {@link #upcastDispatcher view-to-model converters}.
188
- * Initial data can be only set to a document whose {@link module:engine/model/document~Document#version} is equal 0.
189
- *
190
- * **Note** This method is {@link module:utils/observablemixin~Observable#decorate decorated} which is
191
- * used by e.g. collaborative editing plugin that syncs remote data on init.
192
- *
193
- * When data is passed as a string, it is initialized on the default `main` root:
194
- *
195
- * ```ts
196
- * dataController.init( '<p>Foo</p>' ); // Initializes data on the `main` root only, as no other is specified.
197
- * ```
198
- *
199
- * To initialize data on a different root or multiple roots at once, an object containing `rootName` - `data` pairs should be passed:
200
- *
201
- * ```ts
202
- * dataController.init( { main: '<p>Foo</p>', title: '<h1>Bar</h1>' } ); // Initializes data on both the `main` and `title` roots.
203
- * ```
204
- *
205
- * @fires init
206
- * @param data Input data as a string or an object containing the `rootName` - `data`
207
- * pairs to initialize data on multiple roots at once.
208
- * @returns Promise that is resolved after the data is set on the editor.
209
- */
210
- init(data) {
211
- if (this.model.document.version) {
212
- /**
213
- * Cannot set initial data to a non-empty {@link module:engine/model/document~Document}.
214
- * Initial data should be set once, during the {@link module:core/editor/editor~Editor} initialization,
215
- * when the {@link module:engine/model/document~Document#version} is equal 0.
216
- *
217
- * @error datacontroller-init-document-not-empty
218
- */
219
- throw new CKEditorError('datacontroller-init-document-not-empty', this);
220
- }
221
- let initialData = {};
222
- if (typeof data === 'string') {
223
- initialData.main = data; // Default root is 'main'. To initiate data on a different root, object should be passed.
224
- }
225
- else {
226
- initialData = data;
227
- }
228
- if (!this._checkIfRootsExists(Object.keys(initialData))) {
229
- /**
230
- * Cannot init data on a non-existent root. This error is thrown when
231
- * {@link module:engine/controller/datacontroller~DataController#init DataController#init() method}
232
- * is called with non-existent root name. For example, if there is an editor instance with only `main` root,
233
- * calling {@link module:engine/controller/datacontroller~DataController#init} like:
234
- *
235
- * ```ts
236
- * data.init( { main: '<p>Foo</p>', root2: '<p>Bar</p>' } );
237
- * ```
238
- *
239
- * will throw this error.
240
- *
241
- * @error datacontroller-init-non-existent-root
242
- */
243
- throw new CKEditorError('datacontroller-init-non-existent-root', this);
244
- }
245
- this.model.enqueueChange({ isUndoable: false }, writer => {
246
- for (const rootName of Object.keys(initialData)) {
247
- const modelRoot = this.model.document.getRoot(rootName);
248
- writer.insert(this.parse(initialData[rootName], modelRoot), modelRoot, 0);
249
- }
250
- });
251
- return Promise.resolve();
252
- }
253
- /**
254
- * Sets the input data parsed by the {@link #processor data processor} and
255
- * converted by the {@link #upcastDispatcher view-to-model converters}.
256
- * This method can be used any time to replace existing editor data with the new one without clearing the
257
- * {@link module:engine/model/document~Document#history document history}.
258
- *
259
- * This method also creates a batch with all the changes applied. If all you need is to parse data, use
260
- * the {@link #parse} method.
261
- *
262
- * When data is passed as a string it is set on the default `main` root:
263
- *
264
- * ```ts
265
- * dataController.set( '<p>Foo</p>' ); // Sets data on the `main` root, as no other is specified.
266
- * ```
267
- *
268
- * To set data on a different root or multiple roots at once, an object containing `rootName` - `data` pairs should be passed:
269
- *
270
- * ```ts
271
- * dataController.set( { main: '<p>Foo</p>', title: '<h1>Bar</h1>' } ); // Sets data on the `main` and `title` roots as specified.
272
- * ```
273
- *
274
- * To set the data with a preserved undo stack and add the change to the undo stack, set `{ isUndoable: true }` as a `batchType` option.
275
- *
276
- * ```ts
277
- * dataController.set( '<p>Foo</p>', { batchType: { isUndoable: true } } );
278
- * ```
279
- *
280
- * @fires set
281
- * @param data Input data as a string or an object containing the `rootName` - `data`
282
- * pairs to set data on multiple roots at once.
283
- * @param options Options for setting data.
284
- * @param options.batchType The batch type that will be used to create a batch for the changes applied by this method.
285
- * By default, the batch will be set as {@link module:engine/model/batch~Batch#isUndoable not undoable} and the undo stack will be
286
- * cleared after the new data is applied (all undo steps will be removed). If the batch type `isUndoable` flag is be set to `true`,
287
- * the undo stack will be preserved instead and not cleared when new data is applied.
288
- */
289
- set(data, options = {}) {
290
- let newData = {};
291
- if (typeof data === 'string') {
292
- newData.main = data; // The default root is 'main'. To set data on a different root, an object should be passed.
293
- }
294
- else {
295
- newData = data;
296
- }
297
- if (!this._checkIfRootsExists(Object.keys(newData))) {
298
- /**
299
- * Cannot set data on a non-existent root. This error is thrown when the
300
- * {@link module:engine/controller/datacontroller~DataController#set DataController#set() method}
301
- * is called with non-existent root name. For example, if there is an editor instance with only the default `main` root,
302
- * calling {@link module:engine/controller/datacontroller~DataController#set} like:
303
- *
304
- * ```ts
305
- * data.set( { main: '<p>Foo</p>', root2: '<p>Bar</p>' } );
306
- * ```
307
- *
308
- * will throw this error.
309
- *
310
- * @error datacontroller-set-non-existent-root
311
- */
312
- throw new CKEditorError('datacontroller-set-non-existent-root', this);
313
- }
314
- this.model.enqueueChange(options.batchType || {}, writer => {
315
- writer.setSelection(null);
316
- writer.removeSelectionAttribute(this.model.document.selection.getAttributeKeys());
317
- for (const rootName of Object.keys(newData)) {
318
- // Save to model.
319
- const modelRoot = this.model.document.getRoot(rootName);
320
- writer.remove(writer.createRangeIn(modelRoot));
321
- writer.insert(this.parse(newData[rootName], modelRoot), modelRoot, 0);
322
- }
323
- });
324
- }
325
- /**
326
- * Returns the data parsed by the {@link #processor data processor} and then converted by upcast converters
327
- * attached to the {@link #upcastDispatcher}.
328
- *
329
- * @see #set
330
- * @param data Data to parse.
331
- * @param context Base context in which the view will be converted to the model.
332
- * See: {@link module:engine/conversion/upcastdispatcher~UpcastDispatcher#convert}.
333
- * @returns Parsed data.
334
- */
335
- parse(data, context = '$root') {
336
- // data -> view
337
- const viewDocumentFragment = this.processor.toView(data);
338
- // view -> model
339
- return this.toModel(viewDocumentFragment, context);
340
- }
341
- /**
342
- * Returns the result of the given {@link module:engine/view/element~Element view element} or
343
- * {@link module:engine/view/documentfragment~DocumentFragment view document fragment} converted by the
344
- * {@link #upcastDispatcher view-to-model converters}, wrapped by {@link module:engine/model/documentfragment~DocumentFragment}.
345
- *
346
- * When marker elements were converted during the conversion process, it will be set as a document fragment's
347
- * {@link module:engine/model/documentfragment~DocumentFragment#markers static markers map}.
348
- *
349
- * @fires toModel
350
- * @param viewElementOrFragment The element or document fragment whose content will be converted.
351
- * @param context Base context in which the view will be converted to the model.
352
- * See: {@link module:engine/conversion/upcastdispatcher~UpcastDispatcher#convert}.
353
- * @returns Output document fragment.
354
- */
355
- toModel(viewElementOrFragment, context = '$root') {
356
- return this.model.change(writer => {
357
- return this.upcastDispatcher.convert(viewElementOrFragment, writer, context);
358
- });
359
- }
360
- /**
361
- * Adds the style processor normalization rules.
362
- *
363
- * You can implement your own rules as well as use one of the available processor rules:
364
- *
365
- * * background: {@link module:engine/view/styles/background~addBackgroundRules}
366
- * * border: {@link module:engine/view/styles/border~addBorderRules}
367
- * * margin: {@link module:engine/view/styles/margin~addMarginRules}
368
- * * padding: {@link module:engine/view/styles/padding~addPaddingRules}
369
- */
370
- addStyleProcessorRules(callback) {
371
- callback(this.stylesProcessor);
372
- }
373
- /**
374
- * Registers a {@link module:engine/view/matcher~MatcherPattern} on an {@link #htmlProcessor htmlProcessor}
375
- * and a {@link #processor processor} for view elements whose content should be treated as raw data
376
- * and not processed during the conversion from DOM to view elements.
377
- *
378
- * The raw data can be later accessed by the {@link module:engine/view/element~Element#getCustomProperty view element custom property}
379
- * `"$rawContent"`.
380
- *
381
- * @param pattern Pattern matching all view elements whose content should be treated as a raw data.
382
- */
383
- registerRawContentMatcher(pattern) {
384
- // No need to register the pattern if both the `htmlProcessor` and `processor` are the same instances.
385
- if (this.processor && this.processor !== this.htmlProcessor) {
386
- this.processor.registerRawContentMatcher(pattern);
387
- }
388
- this.htmlProcessor.registerRawContentMatcher(pattern);
389
- }
390
- /**
391
- * Removes all event listeners set by the DataController.
392
- */
393
- destroy() {
394
- this.stopListening();
395
- }
396
- /**
397
- * Checks whether all provided root names are actually existing editor roots.
398
- *
399
- * @param rootNames Root names to check.
400
- * @returns Whether all provided root names are existing editor roots.
401
- */
402
- _checkIfRootsExists(rootNames) {
403
- for (const rootName of rootNames) {
404
- if (!this.model.document.getRoot(rootName)) {
405
- return false;
406
- }
407
- }
408
- return true;
409
- }
410
- }
411
- /**
412
- * Helper function for downcast conversion.
413
- *
414
- * Takes a document element (element that is added to a model document) and checks which markers are inside it. If the marker is collapsed
415
- * at element boundary, it is considered as contained inside the element and marker range is returned. Otherwise, if the marker is
416
- * intersecting with the element, the intersection is returned.
417
- */
418
- function _getMarkersRelativeToElement(element) {
419
- const result = [];
420
- const doc = element.root.document;
421
- if (!doc) {
422
- return new Map();
423
- }
424
- const elementRange = ModelRange._createIn(element);
425
- for (const marker of doc.model.markers) {
426
- const markerRange = marker.getRange();
427
- const isMarkerCollapsed = markerRange.isCollapsed;
428
- const isMarkerAtElementBoundary = markerRange.start.isEqual(elementRange.start) || markerRange.end.isEqual(elementRange.end);
429
- if (isMarkerCollapsed && isMarkerAtElementBoundary) {
430
- result.push([marker.name, markerRange]);
431
- }
432
- else {
433
- const updatedMarkerRange = elementRange.getIntersection(markerRange);
434
- if (updatedMarkerRange) {
435
- result.push([marker.name, updatedMarkerRange]);
436
- }
437
- }
438
- }
439
- // Sort the markers in a stable fashion to ensure that the order in which they are
440
- // added to the model's marker collection does not affect how they are
441
- // downcast. One particular use case that we are targeting here, is one where
442
- // two markers are adjacent but not overlapping, such as an insertion/deletion
443
- // suggestion pair representing the replacement of a range of text. In this
444
- // case, putting the markers in DOM order causes the first marker's end to be
445
- // serialized right after the second marker's start, while putting the markers
446
- // in reverse DOM order causes it to be right before the second marker's
447
- // start. So, we sort these in a way that ensures non-intersecting ranges are in
448
- // reverse DOM order, and intersecting ranges are in something approximating
449
- // reverse DOM order (since reverse DOM order doesn't have a precise meaning
450
- // when working with intersecting ranges).
451
- result.sort(([n1, r1], [n2, r2]) => {
452
- if (r1.end.compareWith(r2.start) !== 'after') {
453
- // m1.end <= m2.start -- m1 is entirely <= m2
454
- return 1;
455
- }
456
- else if (r1.start.compareWith(r2.end) !== 'before') {
457
- // m1.start >= m2.end -- m1 is entirely >= m2
458
- return -1;
459
- }
460
- else {
461
- // they overlap, so use their start positions as the primary sort key and
462
- // end positions as the secondary sort key
463
- switch (r1.start.compareWith(r2.start)) {
464
- case 'before':
465
- return 1;
466
- case 'after':
467
- return -1;
468
- default:
469
- switch (r1.end.compareWith(r2.end)) {
470
- case 'before':
471
- return 1;
472
- case 'after':
473
- return -1;
474
- default:
475
- return n2.localeCompare(n1);
476
- }
477
- }
478
- }
479
- });
480
- return new Map(result);
481
- }
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/controller/datacontroller
7
+ */
8
+ import { CKEditorError, EmitterMixin, ObservableMixin, logWarning } from '@ckeditor/ckeditor5-utils';
9
+ import Mapper from '../conversion/mapper';
10
+ import DowncastDispatcher from '../conversion/downcastdispatcher';
11
+ import { insertAttributesAndChildren, insertText } from '../conversion/downcasthelpers';
12
+ import UpcastDispatcher from '../conversion/upcastdispatcher';
13
+ import { convertText, convertToModelFragment } from '../conversion/upcasthelpers';
14
+ import ViewDocumentFragment from '../view/documentfragment';
15
+ import ViewDocument from '../view/document';
16
+ import ViewDowncastWriter from '../view/downcastwriter';
17
+ import ModelRange from '../model/range';
18
+ import { autoParagraphEmptyRoots } from '../model/utils/autoparagraphing';
19
+ import HtmlDataProcessor from '../dataprocessor/htmldataprocessor';
20
+ /**
21
+ * Controller for the data pipeline. The data pipeline controls how data is retrieved from the document
22
+ * and set inside it. Hence, the controller features two methods which allow to {@link ~DataController#get get}
23
+ * and {@link ~DataController#set set} data of the {@link ~DataController#model model}
24
+ * using the given:
25
+ *
26
+ * * {@link module:engine/dataprocessor/dataprocessor~DataProcessor data processor},
27
+ * * downcast converters,
28
+ * * upcast converters.
29
+ *
30
+ * An instance of the data controller is always available in the {@link module:core/editor/editor~Editor#data `editor.data`}
31
+ * property:
32
+ *
33
+ * ```ts
34
+ * editor.data.get( { rootName: 'customRoot' } ); // -> '<p>Hello!</p>'
35
+ * ```
36
+ */
37
+ export default class DataController extends EmitterMixin() {
38
+ /**
39
+ * Creates a data controller instance.
40
+ *
41
+ * @param model Data model.
42
+ * @param stylesProcessor The styles processor instance.
43
+ */
44
+ constructor(model, stylesProcessor) {
45
+ super();
46
+ this.model = model;
47
+ this.mapper = new Mapper();
48
+ this.downcastDispatcher = new DowncastDispatcher({
49
+ mapper: this.mapper,
50
+ schema: model.schema
51
+ });
52
+ this.downcastDispatcher.on('insert:$text', insertText(), { priority: 'lowest' });
53
+ this.downcastDispatcher.on('insert', insertAttributesAndChildren(), { priority: 'lowest' });
54
+ this.upcastDispatcher = new UpcastDispatcher({
55
+ schema: model.schema
56
+ });
57
+ this.viewDocument = new ViewDocument(stylesProcessor);
58
+ this.stylesProcessor = stylesProcessor;
59
+ this.htmlProcessor = new HtmlDataProcessor(this.viewDocument);
60
+ this.processor = this.htmlProcessor;
61
+ this._viewWriter = new ViewDowncastWriter(this.viewDocument);
62
+ // Define default converters for text and elements.
63
+ //
64
+ // Note that if there is no default converter for the element it will be skipped, for instance `<b>foo</b>` will be
65
+ // converted to nothing. We therefore add `convertToModelFragment` as a last converter so it converts children of that
66
+ // element to the document fragment so `<b>foo</b>` will still be converted to `foo` even if there is no converter for `<b>`.
67
+ this.upcastDispatcher.on('text', convertText(), { priority: 'lowest' });
68
+ this.upcastDispatcher.on('element', convertToModelFragment(), { priority: 'lowest' });
69
+ this.upcastDispatcher.on('documentFragment', convertToModelFragment(), { priority: 'lowest' });
70
+ ObservableMixin().prototype.decorate.call(this, 'init');
71
+ ObservableMixin().prototype.decorate.call(this, 'set');
72
+ ObservableMixin().prototype.decorate.call(this, 'get');
73
+ ObservableMixin().prototype.decorate.call(this, 'toView');
74
+ ObservableMixin().prototype.decorate.call(this, 'toModel');
75
+ // Fire the `ready` event when the initialization has completed. Such low-level listener offers the possibility
76
+ // to plug into the initialization pipeline without interrupting the initialization flow.
77
+ this.on('init', () => {
78
+ this.fire('ready');
79
+ }, { priority: 'lowest' });
80
+ // Fix empty roots after DataController is 'ready' (note that the init method could be decorated and stopped).
81
+ // We need to handle this event because initial data could be empty and the post-fixer would not get triggered.
82
+ this.on('ready', () => {
83
+ this.model.enqueueChange({ isUndoable: false }, autoParagraphEmptyRoots);
84
+ }, { priority: 'lowest' });
85
+ }
86
+ /**
87
+ * Returns the model's data converted by downcast dispatchers attached to {@link #downcastDispatcher} and
88
+ * formatted by the {@link #processor data processor}.
89
+ *
90
+ * A warning is logged when you try to retrieve data for a detached root, as most probably this is a mistake. A detached root should
91
+ * be treated like it is removed, and you should not save its data. Note, that the detached root data is always an empty string.
92
+ *
93
+ * @fires get
94
+ * @param options Additional configuration for the retrieved data. `DataController` provides two optional
95
+ * properties: `rootName` and `trim`. Other properties of this object are specified by various editor features.
96
+ * @param options.rootName Root name. Default 'main'.
97
+ * @param options.trim Whether returned data should be trimmed. This option is set to `empty` by default,
98
+ * which means whenever editor content is considered empty, an empty string will be returned. To turn off trimming completely
99
+ * use `'none'`. In such cases the exact content will be returned (for example a `<p>&nbsp;</p>` for an empty editor).
100
+ * @returns Output data.
101
+ */
102
+ get(options = {}) {
103
+ const { rootName = 'main', trim = 'empty' } = options;
104
+ if (!this._checkIfRootsExists([rootName])) {
105
+ /**
106
+ * Cannot get data from a non-existing root. This error is thrown when
107
+ * {@link module:engine/controller/datacontroller~DataController#get `DataController#get()` method}
108
+ * is called with a non-existent root name. For example, if there is an editor instance with only `main` root,
109
+ * calling {@link module:engine/controller/datacontroller~DataController#get} like:
110
+ *
111
+ * ```ts
112
+ * data.get( { rootName: 'root2' } );
113
+ * ```
114
+ *
115
+ * will throw this error.
116
+ *
117
+ * @error datacontroller-get-non-existent-root
118
+ */
119
+ throw new CKEditorError('datacontroller-get-non-existent-root', this);
120
+ }
121
+ const root = this.model.document.getRoot(rootName);
122
+ if (!root.isAttached()) {
123
+ /**
124
+ * Retrieving document data for a detached root.
125
+ *
126
+ * This usually indicates an error as a detached root should be considered "removed" and should not be included in the
127
+ * document data.
128
+ *
129
+ * @error datacontroller-get-detached-root
130
+ */
131
+ logWarning('datacontroller-get-detached-root', this);
132
+ }
133
+ if (trim === 'empty' && !this.model.hasContent(root, { ignoreWhitespaces: true })) {
134
+ return '';
135
+ }
136
+ return this.stringify(root, options);
137
+ }
138
+ /**
139
+ * Returns the content of the given {@link module:engine/model/element~Element model's element} or
140
+ * {@link module:engine/model/documentfragment~DocumentFragment model document fragment} converted by the downcast converters
141
+ * attached to the {@link #downcastDispatcher} and formatted by the {@link #processor data processor}.
142
+ *
143
+ * @param modelElementOrFragment The element whose content will be stringified.
144
+ * @param options Additional configuration passed to the conversion process.
145
+ * @returns Output data.
146
+ */
147
+ stringify(modelElementOrFragment, options = {}) {
148
+ // Model -> view.
149
+ const viewDocumentFragment = this.toView(modelElementOrFragment, options);
150
+ // View -> data.
151
+ return this.processor.toData(viewDocumentFragment);
152
+ }
153
+ /**
154
+ * Returns the content of the given {@link module:engine/model/element~Element model element} or
155
+ * {@link module:engine/model/documentfragment~DocumentFragment model document fragment} converted by the downcast
156
+ * converters attached to {@link #downcastDispatcher} into a
157
+ * {@link module:engine/view/documentfragment~DocumentFragment view document fragment}.
158
+ *
159
+ * @fires toView
160
+ * @param modelElementOrFragment Element or document fragment whose content will be converted.
161
+ * @param options Additional configuration that will be available through the
162
+ * {@link module:engine/conversion/downcastdispatcher~DowncastConversionApi#options} during the conversion process.
163
+ * @returns Output view DocumentFragment.
164
+ */
165
+ toView(modelElementOrFragment, options = {}) {
166
+ const viewDocument = this.viewDocument;
167
+ const viewWriter = this._viewWriter;
168
+ // Clear bindings so the call to this method returns correct results.
169
+ this.mapper.clearBindings();
170
+ // First, convert elements.
171
+ const modelRange = ModelRange._createIn(modelElementOrFragment);
172
+ const viewDocumentFragment = new ViewDocumentFragment(viewDocument);
173
+ this.mapper.bindElements(modelElementOrFragment, viewDocumentFragment);
174
+ // Prepare list of markers.
175
+ // For document fragment, simply take the markers assigned to this document fragment.
176
+ // For model root, all markers in that root will be taken.
177
+ // For model element, we need to check which markers are intersecting with this element and relatively modify the markers' ranges.
178
+ // Collapsed markers at element boundary, although considered as not intersecting with the element, will also be returned.
179
+ const markers = modelElementOrFragment.is('documentFragment') ?
180
+ modelElementOrFragment.markers :
181
+ _getMarkersRelativeToElement(modelElementOrFragment);
182
+ this.downcastDispatcher.convert(modelRange, markers, viewWriter, options);
183
+ return viewDocumentFragment;
184
+ }
185
+ /**
186
+ * Sets the initial input data parsed by the {@link #processor data processor} and
187
+ * converted by the {@link #upcastDispatcher view-to-model converters}.
188
+ * Initial data can be only set to a document whose {@link module:engine/model/document~Document#version} is equal 0.
189
+ *
190
+ * **Note** This method is {@link module:utils/observablemixin~Observable#decorate decorated} which is
191
+ * used by e.g. collaborative editing plugin that syncs remote data on init.
192
+ *
193
+ * When data is passed as a string, it is initialized on the default `main` root:
194
+ *
195
+ * ```ts
196
+ * dataController.init( '<p>Foo</p>' ); // Initializes data on the `main` root only, as no other is specified.
197
+ * ```
198
+ *
199
+ * To initialize data on a different root or multiple roots at once, an object containing `rootName` - `data` pairs should be passed:
200
+ *
201
+ * ```ts
202
+ * dataController.init( { main: '<p>Foo</p>', title: '<h1>Bar</h1>' } ); // Initializes data on both the `main` and `title` roots.
203
+ * ```
204
+ *
205
+ * @fires init
206
+ * @param data Input data as a string or an object containing the `rootName` - `data`
207
+ * pairs to initialize data on multiple roots at once.
208
+ * @returns Promise that is resolved after the data is set on the editor.
209
+ */
210
+ init(data) {
211
+ if (this.model.document.version) {
212
+ /**
213
+ * Cannot set initial data to a non-empty {@link module:engine/model/document~Document}.
214
+ * Initial data should be set once, during the {@link module:core/editor/editor~Editor} initialization,
215
+ * when the {@link module:engine/model/document~Document#version} is equal 0.
216
+ *
217
+ * @error datacontroller-init-document-not-empty
218
+ */
219
+ throw new CKEditorError('datacontroller-init-document-not-empty', this);
220
+ }
221
+ let initialData = {};
222
+ if (typeof data === 'string') {
223
+ initialData.main = data; // Default root is 'main'. To initiate data on a different root, object should be passed.
224
+ }
225
+ else {
226
+ initialData = data;
227
+ }
228
+ if (!this._checkIfRootsExists(Object.keys(initialData))) {
229
+ /**
230
+ * Cannot init data on a non-existent root. This error is thrown when
231
+ * {@link module:engine/controller/datacontroller~DataController#init DataController#init() method}
232
+ * is called with non-existent root name. For example, if there is an editor instance with only `main` root,
233
+ * calling {@link module:engine/controller/datacontroller~DataController#init} like:
234
+ *
235
+ * ```ts
236
+ * data.init( { main: '<p>Foo</p>', root2: '<p>Bar</p>' } );
237
+ * ```
238
+ *
239
+ * will throw this error.
240
+ *
241
+ * @error datacontroller-init-non-existent-root
242
+ */
243
+ throw new CKEditorError('datacontroller-init-non-existent-root', this);
244
+ }
245
+ this.model.enqueueChange({ isUndoable: false }, writer => {
246
+ for (const rootName of Object.keys(initialData)) {
247
+ const modelRoot = this.model.document.getRoot(rootName);
248
+ writer.insert(this.parse(initialData[rootName], modelRoot), modelRoot, 0);
249
+ }
250
+ });
251
+ return Promise.resolve();
252
+ }
253
+ /**
254
+ * Sets the input data parsed by the {@link #processor data processor} and
255
+ * converted by the {@link #upcastDispatcher view-to-model converters}.
256
+ * This method can be used any time to replace existing editor data with the new one without clearing the
257
+ * {@link module:engine/model/document~Document#history document history}.
258
+ *
259
+ * This method also creates a batch with all the changes applied. If all you need is to parse data, use
260
+ * the {@link #parse} method.
261
+ *
262
+ * When data is passed as a string it is set on the default `main` root:
263
+ *
264
+ * ```ts
265
+ * dataController.set( '<p>Foo</p>' ); // Sets data on the `main` root, as no other is specified.
266
+ * ```
267
+ *
268
+ * To set data on a different root or multiple roots at once, an object containing `rootName` - `data` pairs should be passed:
269
+ *
270
+ * ```ts
271
+ * dataController.set( { main: '<p>Foo</p>', title: '<h1>Bar</h1>' } ); // Sets data on the `main` and `title` roots as specified.
272
+ * ```
273
+ *
274
+ * To set the data with a preserved undo stack and add the change to the undo stack, set `{ isUndoable: true }` as a `batchType` option.
275
+ *
276
+ * ```ts
277
+ * dataController.set( '<p>Foo</p>', { batchType: { isUndoable: true } } );
278
+ * ```
279
+ *
280
+ * @fires set
281
+ * @param data Input data as a string or an object containing the `rootName` - `data`
282
+ * pairs to set data on multiple roots at once.
283
+ * @param options Options for setting data.
284
+ * @param options.batchType The batch type that will be used to create a batch for the changes applied by this method.
285
+ * By default, the batch will be set as {@link module:engine/model/batch~Batch#isUndoable not undoable} and the undo stack will be
286
+ * cleared after the new data is applied (all undo steps will be removed). If the batch type `isUndoable` flag is be set to `true`,
287
+ * the undo stack will be preserved instead and not cleared when new data is applied.
288
+ */
289
+ set(data, options = {}) {
290
+ let newData = {};
291
+ if (typeof data === 'string') {
292
+ newData.main = data; // The default root is 'main'. To set data on a different root, an object should be passed.
293
+ }
294
+ else {
295
+ newData = data;
296
+ }
297
+ if (!this._checkIfRootsExists(Object.keys(newData))) {
298
+ /**
299
+ * Cannot set data on a non-existent root. This error is thrown when the
300
+ * {@link module:engine/controller/datacontroller~DataController#set DataController#set() method}
301
+ * is called with non-existent root name. For example, if there is an editor instance with only the default `main` root,
302
+ * calling {@link module:engine/controller/datacontroller~DataController#set} like:
303
+ *
304
+ * ```ts
305
+ * data.set( { main: '<p>Foo</p>', root2: '<p>Bar</p>' } );
306
+ * ```
307
+ *
308
+ * will throw this error.
309
+ *
310
+ * @error datacontroller-set-non-existent-root
311
+ */
312
+ throw new CKEditorError('datacontroller-set-non-existent-root', this);
313
+ }
314
+ this.model.enqueueChange(options.batchType || {}, writer => {
315
+ writer.setSelection(null);
316
+ writer.removeSelectionAttribute(this.model.document.selection.getAttributeKeys());
317
+ for (const rootName of Object.keys(newData)) {
318
+ // Save to model.
319
+ const modelRoot = this.model.document.getRoot(rootName);
320
+ writer.remove(writer.createRangeIn(modelRoot));
321
+ writer.insert(this.parse(newData[rootName], modelRoot), modelRoot, 0);
322
+ }
323
+ });
324
+ }
325
+ /**
326
+ * Returns the data parsed by the {@link #processor data processor} and then converted by upcast converters
327
+ * attached to the {@link #upcastDispatcher}.
328
+ *
329
+ * @see #set
330
+ * @param data Data to parse.
331
+ * @param context Base context in which the view will be converted to the model.
332
+ * See: {@link module:engine/conversion/upcastdispatcher~UpcastDispatcher#convert}.
333
+ * @returns Parsed data.
334
+ */
335
+ parse(data, context = '$root') {
336
+ // data -> view
337
+ const viewDocumentFragment = this.processor.toView(data);
338
+ // view -> model
339
+ return this.toModel(viewDocumentFragment, context);
340
+ }
341
+ /**
342
+ * Returns the result of the given {@link module:engine/view/element~Element view element} or
343
+ * {@link module:engine/view/documentfragment~DocumentFragment view document fragment} converted by the
344
+ * {@link #upcastDispatcher view-to-model converters}, wrapped by {@link module:engine/model/documentfragment~DocumentFragment}.
345
+ *
346
+ * When marker elements were converted during the conversion process, it will be set as a document fragment's
347
+ * {@link module:engine/model/documentfragment~DocumentFragment#markers static markers map}.
348
+ *
349
+ * @fires toModel
350
+ * @param viewElementOrFragment The element or document fragment whose content will be converted.
351
+ * @param context Base context in which the view will be converted to the model.
352
+ * See: {@link module:engine/conversion/upcastdispatcher~UpcastDispatcher#convert}.
353
+ * @returns Output document fragment.
354
+ */
355
+ toModel(viewElementOrFragment, context = '$root') {
356
+ return this.model.change(writer => {
357
+ return this.upcastDispatcher.convert(viewElementOrFragment, writer, context);
358
+ });
359
+ }
360
+ /**
361
+ * Adds the style processor normalization rules.
362
+ *
363
+ * You can implement your own rules as well as use one of the available processor rules:
364
+ *
365
+ * * background: {@link module:engine/view/styles/background~addBackgroundRules}
366
+ * * border: {@link module:engine/view/styles/border~addBorderRules}
367
+ * * margin: {@link module:engine/view/styles/margin~addMarginRules}
368
+ * * padding: {@link module:engine/view/styles/padding~addPaddingRules}
369
+ */
370
+ addStyleProcessorRules(callback) {
371
+ callback(this.stylesProcessor);
372
+ }
373
+ /**
374
+ * Registers a {@link module:engine/view/matcher~MatcherPattern} on an {@link #htmlProcessor htmlProcessor}
375
+ * and a {@link #processor processor} for view elements whose content should be treated as raw data
376
+ * and not processed during the conversion from DOM to view elements.
377
+ *
378
+ * The raw data can be later accessed by the {@link module:engine/view/element~Element#getCustomProperty view element custom property}
379
+ * `"$rawContent"`.
380
+ *
381
+ * @param pattern Pattern matching all view elements whose content should be treated as a raw data.
382
+ */
383
+ registerRawContentMatcher(pattern) {
384
+ // No need to register the pattern if both the `htmlProcessor` and `processor` are the same instances.
385
+ if (this.processor && this.processor !== this.htmlProcessor) {
386
+ this.processor.registerRawContentMatcher(pattern);
387
+ }
388
+ this.htmlProcessor.registerRawContentMatcher(pattern);
389
+ }
390
+ /**
391
+ * Removes all event listeners set by the DataController.
392
+ */
393
+ destroy() {
394
+ this.stopListening();
395
+ }
396
+ /**
397
+ * Checks whether all provided root names are actually existing editor roots.
398
+ *
399
+ * @param rootNames Root names to check.
400
+ * @returns Whether all provided root names are existing editor roots.
401
+ */
402
+ _checkIfRootsExists(rootNames) {
403
+ for (const rootName of rootNames) {
404
+ if (!this.model.document.getRoot(rootName)) {
405
+ return false;
406
+ }
407
+ }
408
+ return true;
409
+ }
410
+ }
411
+ /**
412
+ * Helper function for downcast conversion.
413
+ *
414
+ * Takes a document element (element that is added to a model document) and checks which markers are inside it. If the marker is collapsed
415
+ * at element boundary, it is considered as contained inside the element and marker range is returned. Otherwise, if the marker is
416
+ * intersecting with the element, the intersection is returned.
417
+ */
418
+ function _getMarkersRelativeToElement(element) {
419
+ const result = [];
420
+ const doc = element.root.document;
421
+ if (!doc) {
422
+ return new Map();
423
+ }
424
+ const elementRange = ModelRange._createIn(element);
425
+ for (const marker of doc.model.markers) {
426
+ const markerRange = marker.getRange();
427
+ const isMarkerCollapsed = markerRange.isCollapsed;
428
+ const isMarkerAtElementBoundary = markerRange.start.isEqual(elementRange.start) || markerRange.end.isEqual(elementRange.end);
429
+ if (isMarkerCollapsed && isMarkerAtElementBoundary) {
430
+ result.push([marker.name, markerRange]);
431
+ }
432
+ else {
433
+ const updatedMarkerRange = elementRange.getIntersection(markerRange);
434
+ if (updatedMarkerRange) {
435
+ result.push([marker.name, updatedMarkerRange]);
436
+ }
437
+ }
438
+ }
439
+ // Sort the markers in a stable fashion to ensure that the order in which they are
440
+ // added to the model's marker collection does not affect how they are
441
+ // downcast. One particular use case that we are targeting here, is one where
442
+ // two markers are adjacent but not overlapping, such as an insertion/deletion
443
+ // suggestion pair representing the replacement of a range of text. In this
444
+ // case, putting the markers in DOM order causes the first marker's end to be
445
+ // serialized right after the second marker's start, while putting the markers
446
+ // in reverse DOM order causes it to be right before the second marker's
447
+ // start. So, we sort these in a way that ensures non-intersecting ranges are in
448
+ // reverse DOM order, and intersecting ranges are in something approximating
449
+ // reverse DOM order (since reverse DOM order doesn't have a precise meaning
450
+ // when working with intersecting ranges).
451
+ result.sort(([n1, r1], [n2, r2]) => {
452
+ if (r1.end.compareWith(r2.start) !== 'after') {
453
+ // m1.end <= m2.start -- m1 is entirely <= m2
454
+ return 1;
455
+ }
456
+ else if (r1.start.compareWith(r2.end) !== 'before') {
457
+ // m1.start >= m2.end -- m1 is entirely >= m2
458
+ return -1;
459
+ }
460
+ else {
461
+ // they overlap, so use their start positions as the primary sort key and
462
+ // end positions as the secondary sort key
463
+ switch (r1.start.compareWith(r2.start)) {
464
+ case 'before':
465
+ return 1;
466
+ case 'after':
467
+ return -1;
468
+ default:
469
+ switch (r1.end.compareWith(r2.end)) {
470
+ case 'before':
471
+ return 1;
472
+ case 'after':
473
+ return -1;
474
+ default:
475
+ return n2.localeCompare(n1);
476
+ }
477
+ }
478
+ }
479
+ });
480
+ return new Map(result);
481
+ }