@ckeditor/ckeditor5-engine 30.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/LICENSE.md +17 -0
  2. package/README.md +30 -0
  3. package/package.json +70 -0
  4. package/src/controller/datacontroller.js +563 -0
  5. package/src/controller/editingcontroller.js +149 -0
  6. package/src/conversion/conversion.js +644 -0
  7. package/src/conversion/conversionhelpers.js +40 -0
  8. package/src/conversion/downcastdispatcher.js +914 -0
  9. package/src/conversion/downcasthelpers.js +1706 -0
  10. package/src/conversion/mapper.js +696 -0
  11. package/src/conversion/modelconsumable.js +329 -0
  12. package/src/conversion/upcastdispatcher.js +807 -0
  13. package/src/conversion/upcasthelpers.js +997 -0
  14. package/src/conversion/viewconsumable.js +623 -0
  15. package/src/dataprocessor/basichtmlwriter.js +32 -0
  16. package/src/dataprocessor/dataprocessor.jsdoc +64 -0
  17. package/src/dataprocessor/htmldataprocessor.js +159 -0
  18. package/src/dataprocessor/htmlwriter.js +22 -0
  19. package/src/dataprocessor/xmldataprocessor.js +161 -0
  20. package/src/dev-utils/model.js +482 -0
  21. package/src/dev-utils/operationreplayer.js +140 -0
  22. package/src/dev-utils/utils.js +103 -0
  23. package/src/dev-utils/view.js +1091 -0
  24. package/src/index.js +52 -0
  25. package/src/model/batch.js +82 -0
  26. package/src/model/differ.js +1282 -0
  27. package/src/model/document.js +483 -0
  28. package/src/model/documentfragment.js +390 -0
  29. package/src/model/documentselection.js +1261 -0
  30. package/src/model/element.js +438 -0
  31. package/src/model/history.js +138 -0
  32. package/src/model/item.jsdoc +14 -0
  33. package/src/model/liveposition.js +182 -0
  34. package/src/model/liverange.js +221 -0
  35. package/src/model/markercollection.js +553 -0
  36. package/src/model/model.js +934 -0
  37. package/src/model/node.js +507 -0
  38. package/src/model/nodelist.js +217 -0
  39. package/src/model/operation/attributeoperation.js +202 -0
  40. package/src/model/operation/detachoperation.js +103 -0
  41. package/src/model/operation/insertoperation.js +188 -0
  42. package/src/model/operation/markeroperation.js +154 -0
  43. package/src/model/operation/mergeoperation.js +216 -0
  44. package/src/model/operation/moveoperation.js +209 -0
  45. package/src/model/operation/nooperation.js +58 -0
  46. package/src/model/operation/operation.js +139 -0
  47. package/src/model/operation/operationfactory.js +49 -0
  48. package/src/model/operation/renameoperation.js +155 -0
  49. package/src/model/operation/rootattributeoperation.js +211 -0
  50. package/src/model/operation/splitoperation.js +254 -0
  51. package/src/model/operation/transform.js +2389 -0
  52. package/src/model/operation/utils.js +292 -0
  53. package/src/model/position.js +1164 -0
  54. package/src/model/range.js +1049 -0
  55. package/src/model/rootelement.js +111 -0
  56. package/src/model/schema.js +1851 -0
  57. package/src/model/selection.js +902 -0
  58. package/src/model/text.js +138 -0
  59. package/src/model/textproxy.js +279 -0
  60. package/src/model/treewalker.js +414 -0
  61. package/src/model/utils/autoparagraphing.js +77 -0
  62. package/src/model/utils/deletecontent.js +528 -0
  63. package/src/model/utils/getselectedcontent.js +150 -0
  64. package/src/model/utils/insertcontent.js +824 -0
  65. package/src/model/utils/modifyselection.js +229 -0
  66. package/src/model/utils/selection-post-fixer.js +297 -0
  67. package/src/model/writer.js +1574 -0
  68. package/src/view/attributeelement.js +274 -0
  69. package/src/view/containerelement.js +123 -0
  70. package/src/view/document.js +221 -0
  71. package/src/view/documentfragment.js +273 -0
  72. package/src/view/documentselection.js +387 -0
  73. package/src/view/domconverter.js +1437 -0
  74. package/src/view/downcastwriter.js +2121 -0
  75. package/src/view/editableelement.js +118 -0
  76. package/src/view/element.js +945 -0
  77. package/src/view/elementdefinition.jsdoc +59 -0
  78. package/src/view/emptyelement.js +119 -0
  79. package/src/view/filler.js +161 -0
  80. package/src/view/item.jsdoc +14 -0
  81. package/src/view/matcher.js +776 -0
  82. package/src/view/node.js +391 -0
  83. package/src/view/observer/arrowkeysobserver.js +58 -0
  84. package/src/view/observer/bubblingemittermixin.js +307 -0
  85. package/src/view/observer/bubblingeventinfo.js +71 -0
  86. package/src/view/observer/clickobserver.js +46 -0
  87. package/src/view/observer/compositionobserver.js +79 -0
  88. package/src/view/observer/domeventdata.js +82 -0
  89. package/src/view/observer/domeventobserver.js +99 -0
  90. package/src/view/observer/fakeselectionobserver.js +118 -0
  91. package/src/view/observer/focusobserver.js +106 -0
  92. package/src/view/observer/inputobserver.js +44 -0
  93. package/src/view/observer/keyobserver.js +83 -0
  94. package/src/view/observer/mouseobserver.js +56 -0
  95. package/src/view/observer/mutationobserver.js +345 -0
  96. package/src/view/observer/observer.js +118 -0
  97. package/src/view/observer/selectionobserver.js +242 -0
  98. package/src/view/placeholder.js +285 -0
  99. package/src/view/position.js +426 -0
  100. package/src/view/range.js +533 -0
  101. package/src/view/rawelement.js +148 -0
  102. package/src/view/renderer.js +1037 -0
  103. package/src/view/rooteditableelement.js +107 -0
  104. package/src/view/selection.js +718 -0
  105. package/src/view/styles/background.js +73 -0
  106. package/src/view/styles/border.js +362 -0
  107. package/src/view/styles/margin.js +41 -0
  108. package/src/view/styles/padding.js +40 -0
  109. package/src/view/styles/utils.js +277 -0
  110. package/src/view/stylesmap.js +938 -0
  111. package/src/view/text.js +147 -0
  112. package/src/view/textproxy.js +199 -0
  113. package/src/view/treewalker.js +496 -0
  114. package/src/view/uielement.js +238 -0
  115. package/src/view/upcastwriter.js +484 -0
  116. package/src/view/view.js +721 -0
  117. package/theme/placeholder.css +27 -0
@@ -0,0 +1,1091 @@
1
+ /**
2
+ * @license Copyright (c) 2003-2021, CKSource - Frederico Knabben. All rights reserved.
3
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4
+ */
5
+
6
+ /**
7
+ * @module engine/dev-utils/view
8
+ */
9
+
10
+ /* globals document */
11
+
12
+ /**
13
+ * Collection of methods for manipulating the {@link module:engine/view/view view} for testing purposes.
14
+ */
15
+
16
+ import View from '../view/view';
17
+ import ViewDocument from '../view/document';
18
+ import ViewDocumentFragment from '../view/documentfragment';
19
+ import XmlDataProcessor from '../dataprocessor/xmldataprocessor';
20
+ import ViewElement from '../view/element';
21
+ import DocumentSelection from '../view/documentselection';
22
+ import Range from '../view/range';
23
+ import Position from '../view/position';
24
+ import AttributeElement from '../view/attributeelement';
25
+ import ContainerElement from '../view/containerelement';
26
+ import EmptyElement from '../view/emptyelement';
27
+ import UIElement from '../view/uielement';
28
+ import RawElement from '../view/rawelement';
29
+ import { StylesProcessor } from '../view/stylesmap';
30
+
31
+ const ELEMENT_RANGE_START_TOKEN = '[';
32
+ const ELEMENT_RANGE_END_TOKEN = ']';
33
+ const TEXT_RANGE_START_TOKEN = '{';
34
+ const TEXT_RANGE_END_TOKEN = '}';
35
+ const allowedTypes = {
36
+ 'container': ContainerElement,
37
+ 'attribute': AttributeElement,
38
+ 'empty': EmptyElement,
39
+ 'ui': UIElement,
40
+ 'raw': RawElement
41
+ };
42
+
43
+ /**
44
+ * Writes the content of the {@link module:engine/view/document~Document document} to an HTML-like string.
45
+ *
46
+ * @param {module:engine/view/view~View} view
47
+ * @param {Object} [options]
48
+ * @param {Boolean} [options.withoutSelection=false] Whether to write the selection. When set to `true`, the selection will
49
+ * not be included in the returned string.
50
+ * @param {Boolean} [options.rootName='main'] The name of the root from which the data should be stringified. If not provided,
51
+ * the default `main` name will be used.
52
+ * @param {Boolean} [options.showType=false] When set to `true`, the type of elements will be printed (`<container:p>`
53
+ * instead of `<p>`, `<attribute:b>` instead of `<b>` and `<empty:img>` instead of `<img>`).
54
+ * @param {Boolean} [options.showPriority=false] When set to `true`, the attribute element's priority will be printed
55
+ * (`<span view-priority="12">`, `<b view-priority="10">`).
56
+ * @param {Boolean} [options.showAttributeElementId=false] When set to `true`, the attribute element's ID will be printed
57
+ * (`<span id="marker:foo">`).
58
+ * @param {Boolean} [options.renderUIElements=false] When set to `true`, the inner content of each
59
+ * {@link module:engine/view/uielement~UIElement} will be printed.
60
+ * @param {Boolean} [options.renderRawElements=false] When set to `true`, the inner content of each
61
+ * {@link module:engine/view/rawelement~RawElement} will be printed.
62
+ * @returns {String} The stringified data.
63
+ */
64
+ export function getData( view, options = {} ) {
65
+ if ( !( view instanceof View ) ) {
66
+ throw new TypeError( 'View needs to be an instance of module:engine/view/view~View.' );
67
+ }
68
+
69
+ const document = view.document;
70
+ const withoutSelection = !!options.withoutSelection;
71
+ const rootName = options.rootName || 'main';
72
+ const root = document.getRoot( rootName );
73
+ const stringifyOptions = {
74
+ showType: options.showType,
75
+ showPriority: options.showPriority,
76
+ renderUIElements: options.renderUIElements,
77
+ renderRawElements: options.renderRawElements,
78
+ ignoreRoot: true
79
+ };
80
+
81
+ return withoutSelection ?
82
+ getData._stringify( root, null, stringifyOptions ) :
83
+ getData._stringify( root, document.selection, stringifyOptions );
84
+ }
85
+
86
+ // Set stringify as getData private method - needed for testing/spying.
87
+ getData._stringify = stringify;
88
+
89
+ /**
90
+ * Sets the content of a view {@link module:engine/view/document~Document document} provided as an HTML-like string.
91
+ *
92
+ * @param {module:engine/view/view~View} view
93
+ * @param {String} data An HTML-like string to write into the document.
94
+ * @param {Object} options
95
+ * @param {String} [options.rootName='main'] The root name where parsed data will be stored. If not provided,
96
+ * the default `main` name will be used.
97
+ */
98
+ export function setData( view, data, options = {} ) {
99
+ if ( !( view instanceof View ) ) {
100
+ throw new TypeError( 'View needs to be an instance of module:engine/view/view~View.' );
101
+ }
102
+
103
+ const document = view.document;
104
+ const rootName = options.rootName || 'main';
105
+ const root = document.getRoot( rootName );
106
+
107
+ view.change( writer => {
108
+ const result = setData._parse( data, { rootElement: root } );
109
+
110
+ if ( result.view && result.selection ) {
111
+ writer.setSelection( result.selection );
112
+ }
113
+ } );
114
+ }
115
+
116
+ // Set parse as setData private method - needed for testing/spying.
117
+ setData._parse = parse;
118
+
119
+ /**
120
+ * Converts view elements to HTML-like string representation.
121
+ *
122
+ * A root element can be provided as {@link module:engine/view/text~Text text}:
123
+ *
124
+ * const text = downcastWriter.createText( 'foobar' );
125
+ * stringify( text ); // 'foobar'
126
+ *
127
+ * or as an {@link module:engine/view/element~Element element}:
128
+ *
129
+ * const element = downcastWriter.createElement( 'p', null, downcastWriter.createText( 'foobar' ) );
130
+ * stringify( element ); // '<p>foobar</p>'
131
+ *
132
+ * or as a {@link module:engine/view/documentfragment~DocumentFragment document fragment}:
133
+ *
134
+ * const text = downcastWriter.createText( 'foobar' );
135
+ * const b = downcastWriter.createElement( 'b', { name: 'test' }, text );
136
+ * const p = downcastWriter.createElement( 'p', { style: 'color:red;' } );
137
+ * const fragment = downcastWriter.createDocumentFragment( [ p, b ] );
138
+ *
139
+ * stringify( fragment ); // '<p style="color:red;"></p><b name="test">foobar</b>'
140
+ *
141
+ * Additionally, a {@link module:engine/view/documentselection~DocumentSelection selection} instance can be provided.
142
+ * Ranges from the selection will then be included in the output data.
143
+ * If a range position is placed inside the element node, it will be represented with `[` and `]`:
144
+ *
145
+ * const text = downcastWriter.createText( 'foobar' );
146
+ * const b = downcastWriter.createElement( 'b', null, text );
147
+ * const p = downcastWriter.createElement( 'p', null, b );
148
+ * const selection = downcastWriter.createSelection(
149
+ * downcastWriter.createRangeIn( p )
150
+ * );
151
+ *
152
+ * stringify( p, selection ); // '<p>[<b>foobar</b>]</p>'
153
+ *
154
+ * If a range is placed inside the text node, it will be represented with `{` and `}`:
155
+ *
156
+ * const text = downcastWriter.createText( 'foobar' );
157
+ * const b = downcastWriter.createElement( 'b', null, text );
158
+ * const p = downcastWriter.createElement( 'p', null, b );
159
+ * const selection = downcastWriter.createSelection(
160
+ * downcastWriter.createRange( downcastWriter.createPositionAt( text, 1 ), downcastWriter.createPositionAt( text, 5 ) )
161
+ * );
162
+ *
163
+ * stringify( p, selection ); // '<p><b>f{ooba}r</b></p>'
164
+ *
165
+ * ** Note: **
166
+ * It is possible to unify selection markers to `[` and `]` for both (inside and outside text)
167
+ * by setting the `sameSelectionCharacters=true` option. It is mainly used when the view stringify option is used by
168
+ * model utilities.
169
+ *
170
+ * Multiple ranges are supported:
171
+ *
172
+ * const text = downcastWriter.createText( 'foobar' );
173
+ * const selection = downcastWriter.createSelection( [
174
+ * downcastWriter.createRange( downcastWriter.createPositionAt( text, 0 ), downcastWriter.createPositionAt( text, 1 ) ),
175
+ * downcastWriter.createRange( downcastWriter.createPositionAt( text, 3 ), downcastWriter.createPositionAt( text, 5 ) )
176
+ * ] );
177
+ *
178
+ * stringify( text, selection ); // '{f}oo{ba}r'
179
+ *
180
+ * A {@link module:engine/view/range~Range range} or {@link module:engine/view/position~Position position} instance can be provided
181
+ * instead of the {@link module:engine/view/documentselection~DocumentSelection selection} instance. If a range instance
182
+ * is provided, it will be converted to a selection containing this range. If a position instance is provided, it will
183
+ * be converted to a selection containing one range collapsed at this position.
184
+ *
185
+ * const text = downcastWriter.createText( 'foobar' );
186
+ * const range = downcastWriter.createRange( downcastWriter.createPositionAt( text, 0 ), downcastWriter.createPositionAt( text, 1 ) );
187
+ * const position = downcastWriter.createPositionAt( text, 3 );
188
+ *
189
+ * stringify( text, range ); // '{f}oobar'
190
+ * stringify( text, position ); // 'foo{}bar'
191
+ *
192
+ * An additional `options` object can be provided.
193
+ * If `options.showType` is set to `true`, element's types will be
194
+ * presented for {@link module:engine/view/attributeelement~AttributeElement attribute elements},
195
+ * {@link module:engine/view/containerelement~ContainerElement container elements}
196
+ * {@link module:engine/view/emptyelement~EmptyElement empty elements}
197
+ * and {@link module:engine/view/uielement~UIElement UI elements}:
198
+ *
199
+ * const attribute = downcastWriter.createAttributeElement( 'b' );
200
+ * const container = downcastWriter.createContainerElement( 'p' );
201
+ * const empty = downcastWriter.createEmptyElement( 'img' );
202
+ * const ui = downcastWriter.createUIElement( 'span' );
203
+ * getData( attribute, null, { showType: true } ); // '<attribute:b></attribute:b>'
204
+ * getData( container, null, { showType: true } ); // '<container:p></container:p>'
205
+ * getData( empty, null, { showType: true } ); // '<empty:img></empty:img>'
206
+ * getData( ui, null, { showType: true } ); // '<ui:span></ui:span>'
207
+ *
208
+ * If `options.showPriority` is set to `true`, a priority will be displayed for all
209
+ * {@link module:engine/view/attributeelement~AttributeElement attribute elements}.
210
+ *
211
+ * const attribute = downcastWriter.createAttributeElement( 'b' );
212
+ * attribute._priority = 20;
213
+ * getData( attribute, null, { showPriority: true } ); // <b view-priority="20"></b>
214
+ *
215
+ * If `options.showAttributeElementId` is set to `true`, the attribute element's id will be displayed for all
216
+ * {@link module:engine/view/attributeelement~AttributeElement attribute elements} that have it set.
217
+ *
218
+ * const attribute = downcastWriter.createAttributeElement( 'span' );
219
+ * attribute._id = 'marker:foo';
220
+ * getData( attribute, null, { showAttributeElementId: true } ); // <span view-id="marker:foo"></span>
221
+ *
222
+ * @param {module:engine/view/text~Text|module:engine/view/element~Element|module:engine/view/documentfragment~DocumentFragment}
223
+ * node The node to stringify.
224
+ * @param {module:engine/view/documentselection~DocumentSelection|module:engine/view/position~Position|module:engine/view/range~Range}
225
+ * [selectionOrPositionOrRange = null ]
226
+ * A selection instance whose ranges will be included in the returned string data. If a range instance is provided, it will be
227
+ * converted to a selection containing this range. If a position instance is provided, it will be converted to a selection
228
+ * containing one range collapsed at this position.
229
+ * @param {Object} [options] An object with additional options.
230
+ * @param {Boolean} [options.showType=false] When set to `true`, the type of elements will be printed (`<container:p>`
231
+ * instead of `<p>`, `<attribute:b>` instead of `<b>` and `<empty:img>` instead of `<img>`).
232
+ * @param {Boolean} [options.showPriority=false] When set to `true`, the attribute element's priority will be printed
233
+ * (`<span view-priority="12">`, `<b view-priority="10">`).
234
+ * @param {Boolean} [options.showAttributeElementId=false] When set to `true`, attribute element's id will be printed
235
+ * (`<span id="marker:foo">`).
236
+ * @param {Boolean} [options.ignoreRoot=false] When set to `true`, the root's element opening and closing will not be printed.
237
+ * Mainly used by the `getData` function to ignore the {@link module:engine/view/document~Document document's} root element.
238
+ * @param {Boolean} [options.sameSelectionCharacters=false] When set to `true`, the selection inside the text will be marked as
239
+ * `{` and `}` and the selection outside the text as `[` and `]`. When set to `false`, both will be marked as `[` and `]` only.
240
+ * @param {Boolean} [options.renderUIElements=false] When set to `true`, the inner content of each
241
+ * {@link module:engine/view/uielement~UIElement} will be printed.
242
+ * @param {Boolean} [options.renderRawElements=false] When set to `true`, the inner content of each
243
+ * {@link module:engine/view/rawelement~RawElement} will be printed.
244
+ * @returns {String} An HTML-like string representing the view.
245
+ */
246
+ export function stringify( node, selectionOrPositionOrRange = null, options = {} ) {
247
+ let selection;
248
+
249
+ if (
250
+ selectionOrPositionOrRange instanceof Position ||
251
+ selectionOrPositionOrRange instanceof Range
252
+ ) {
253
+ selection = new DocumentSelection( selectionOrPositionOrRange );
254
+ } else {
255
+ selection = selectionOrPositionOrRange;
256
+ }
257
+
258
+ const viewStringify = new ViewStringify( node, selection, options );
259
+
260
+ return viewStringify.stringify();
261
+ }
262
+
263
+ /**
264
+ * Parses an HTML-like string and returns a view tree.
265
+ * A simple string will be converted to a {@link module:engine/view/text~Text text} node:
266
+ *
267
+ * parse( 'foobar' ); // Returns an instance of text.
268
+ *
269
+ * {@link module:engine/view/element~Element Elements} will be parsed with attributes as children:
270
+ *
271
+ * parse( '<b name="baz">foobar</b>' ); // Returns an instance of element with the `baz` attribute and a text child node.
272
+ *
273
+ * Multiple nodes provided on root level will be converted to a
274
+ * {@link module:engine/view/documentfragment~DocumentFragment document fragment}:
275
+ *
276
+ * parse( '<b>foo</b><i>bar</i>' ); // Returns a document fragment with two child elements.
277
+ *
278
+ * The method can parse multiple {@link module:engine/view/range~Range ranges} provided in string data and return a
279
+ * {@link module:engine/view/documentselection~DocumentSelection selection} instance containing these ranges. Ranges placed inside
280
+ * {@link module:engine/view/text~Text text} nodes should be marked using `{` and `}` brackets:
281
+ *
282
+ * const { text, selection } = parse( 'f{ooba}r' );
283
+ *
284
+ * Ranges placed outside text nodes should be marked using `[` and `]` brackets:
285
+ *
286
+ * const { root, selection } = parse( '<p>[<b>foobar</b>]</p>' );
287
+ *
288
+ * ** Note: **
289
+ * It is possible to unify selection markers to `[` and `]` for both (inside and outside text)
290
+ * by setting `sameSelectionCharacters=true` option. It is mainly used when the view parse option is used by model utilities.
291
+ *
292
+ * Sometimes there is a need for defining the order of ranges inside the created selection. This can be achieved by providing
293
+ * the range order array as an additional parameter:
294
+ *
295
+ * const { root, selection } = parse( '{fo}ob{ar}{ba}z', { order: [ 2, 3, 1 ] } );
296
+ *
297
+ * In the example above, the first range (`{fo}`) will be added to the selection as the second one, the second range (`{ar}`) will be
298
+ * added as the third and the third range (`{ba}`) will be added as the first one.
299
+ *
300
+ * If the selection's last range should be added as a backward one
301
+ * (so the {@link module:engine/view/documentselection~DocumentSelection#anchor selection anchor} is represented
302
+ * by the `end` position and {@link module:engine/view/documentselection~DocumentSelection#focus selection focus} is
303
+ * represented by the `start` position), use the `lastRangeBackward` flag:
304
+ *
305
+ * const { root, selection } = parse( `{foo}bar{baz}`, { lastRangeBackward: true } );
306
+ *
307
+ * Some more examples and edge cases:
308
+ *
309
+ * // Returns an empty document fragment.
310
+ * parse( '' );
311
+ *
312
+ * // Returns an empty document fragment and a collapsed selection.
313
+ * const { root, selection } = parse( '[]' );
314
+ *
315
+ * // Returns an element and a selection that is placed inside the document fragment containing that element.
316
+ * const { root, selection } = parse( '[<a></a>]' );
317
+ *
318
+ * @param {String} data An HTML-like string to be parsed.
319
+ * @param {Object} options
320
+ * @param {Array.<Number>} [options.order] An array with the order of parsed ranges added to the returned
321
+ * {@link module:engine/view/documentselection~DocumentSelection Selection} instance. Each element should represent the
322
+ * desired position of each range in the selection instance. For example: `[2, 3, 1]` means that the first range will be
323
+ * placed as the second, the second as the third and the third as the first.
324
+ * @param {Boolean} [options.lastRangeBackward=false] If set to `true`, the last range will be added as backward to the returned
325
+ * {@link module:engine/view/documentselection~DocumentSelection selection} instance.
326
+ * @param {module:engine/view/element~Element|module:engine/view/documentfragment~DocumentFragment}
327
+ * [options.rootElement=null] The default root to use when parsing elements.
328
+ * When set to `null`, the root element will be created automatically. If set to
329
+ * {@link module:engine/view/element~Element Element} or {@link module:engine/view/documentfragment~DocumentFragment DocumentFragment},
330
+ * this node will be used as the root for all parsed nodes.
331
+ * @param {Boolean} [options.sameSelectionCharacters=false] When set to `false`, the selection inside the text should be marked using
332
+ * `{` and `}` and the selection outside the ext using `[` and `]`. When set to `true`, both should be marked with `[` and `]` only.
333
+ * @param {module:engine/view/stylesmap~StylesProcessor} [options.stylesProcessor] Styles processor.
334
+ * @returns {module:engine/view/text~Text|module:engine/view/element~Element|module:engine/view/documentfragment~DocumentFragment|Object}
335
+ * Returns the parsed view node or an object with two fields: `view` and `selection` when selection ranges were included in the data
336
+ * to parse.
337
+ */
338
+ export function parse( data, options = {} ) {
339
+ const viewDocument = new ViewDocument( new StylesProcessor() );
340
+
341
+ options.order = options.order || [];
342
+ const rangeParser = new RangeParser( {
343
+ sameSelectionCharacters: options.sameSelectionCharacters
344
+ } );
345
+ const processor = new XmlDataProcessor( viewDocument, {
346
+ namespaces: Object.keys( allowedTypes )
347
+ } );
348
+
349
+ // Convert data to view.
350
+ let view = processor.toView( data );
351
+
352
+ // At this point we have a view tree with Elements that could have names like `attribute:b:1`. In the next step
353
+ // we need to parse Element's names and convert them to AttributeElements and ContainerElements.
354
+ view = _convertViewElements( view );
355
+
356
+ // If custom root is provided - move all nodes there.
357
+ if ( options.rootElement ) {
358
+ const root = options.rootElement;
359
+ const nodes = view._removeChildren( 0, view.childCount );
360
+
361
+ root._removeChildren( 0, root.childCount );
362
+ root._appendChild( nodes );
363
+
364
+ view = root;
365
+ }
366
+
367
+ // Parse ranges included in view text nodes.
368
+ const ranges = rangeParser.parse( view, options.order );
369
+
370
+ // If only one element is returned inside DocumentFragment - return that element.
371
+ if ( view.is( 'documentFragment' ) && view.childCount === 1 ) {
372
+ view = view.getChild( 0 );
373
+ }
374
+
375
+ // When ranges are present - return object containing view, and selection.
376
+ if ( ranges.length ) {
377
+ const selection = new DocumentSelection( ranges, { backward: !!options.lastRangeBackward } );
378
+
379
+ return {
380
+ view,
381
+ selection
382
+ };
383
+ }
384
+
385
+ // If single element is returned without selection - remove it from parent and return detached element.
386
+ if ( view.parent ) {
387
+ view._remove();
388
+ }
389
+
390
+ return view;
391
+ }
392
+
393
+ /**
394
+ * Private helper class used for converting ranges represented as text inside view {@link module:engine/view/text~Text text nodes}.
395
+ *
396
+ * @private
397
+ */
398
+ class RangeParser {
399
+ /**
400
+ * Creates a range parser instance.
401
+ *
402
+ * @param {Object} options The range parser configuration.
403
+ * @param {Boolean} [options.sameSelectionCharacters=false] When set to `true`, the selection inside the text is marked as
404
+ * `{` and `}` and the selection outside the text as `[` and `]`. When set to `false`, both are marked as `[` and `]`.
405
+ */
406
+ constructor( options ) {
407
+ this.sameSelectionCharacters = !!options.sameSelectionCharacters;
408
+ }
409
+
410
+ /**
411
+ * Parses the view and returns ranges represented inside {@link module:engine/view/text~Text text nodes}.
412
+ * The method will remove all occurrences of `{`, `}`, `[` and `]` from found text nodes. If a text node is empty after
413
+ * the process, it will be removed, too.
414
+ *
415
+ * @param {module:engine/view/node~Node} node The starting node.
416
+ * @param {Array.<Number>} order The order of ranges. Each element should represent the desired position of the range after
417
+ * sorting. For example: `[2, 3, 1]` means that the first range will be placed as the second, the second as the third and the third
418
+ * as the first.
419
+ * @returns {Array.<module:engine/view/range~Range>} An array with ranges found.
420
+ */
421
+ parse( node, order ) {
422
+ this._positions = [];
423
+
424
+ // Remove all range brackets from view nodes and save their positions.
425
+ this._getPositions( node );
426
+
427
+ // Create ranges using gathered positions.
428
+ let ranges = this._createRanges();
429
+
430
+ // Sort ranges if needed.
431
+ if ( order.length ) {
432
+ if ( order.length != ranges.length ) {
433
+ throw new Error(
434
+ `Parse error - there are ${ ranges.length } ranges found, but ranges order array contains ${ order.length } elements.`
435
+ );
436
+ }
437
+
438
+ ranges = this._sortRanges( ranges, order );
439
+ }
440
+
441
+ return ranges;
442
+ }
443
+
444
+ /**
445
+ * Gathers positions of brackets inside the view tree starting from the provided node. The method will remove all occurrences of
446
+ * `{`, `}`, `[` and `]` from found text nodes. If a text node is empty after the process, it will be removed, too.
447
+ *
448
+ * @private
449
+ * @param {module:engine/view/node~Node} node Staring node.
450
+ */
451
+ _getPositions( node ) {
452
+ if ( node.is( 'documentFragment' ) || node.is( 'element' ) ) {
453
+ // Copy elements into the array, when nodes will be removed from parent node this array will still have all the
454
+ // items needed for iteration.
455
+ const children = [ ...node.getChildren() ];
456
+
457
+ for ( const child of children ) {
458
+ this._getPositions( child );
459
+ }
460
+ }
461
+
462
+ if ( node.is( '$text' ) ) {
463
+ const regexp = new RegExp(
464
+ `[${ TEXT_RANGE_START_TOKEN }${ TEXT_RANGE_END_TOKEN }\\${ ELEMENT_RANGE_END_TOKEN }\\${ ELEMENT_RANGE_START_TOKEN }]`,
465
+ 'g'
466
+ );
467
+ let text = node.data;
468
+ let match;
469
+ let offset = 0;
470
+ const brackets = [];
471
+
472
+ // Remove brackets from text and store info about offset inside text node.
473
+ while ( ( match = regexp.exec( text ) ) ) {
474
+ const index = match.index;
475
+ const bracket = match[ 0 ];
476
+
477
+ brackets.push( {
478
+ bracket,
479
+ textOffset: index - offset
480
+ } );
481
+
482
+ offset++;
483
+ }
484
+
485
+ text = text.replace( regexp, '' );
486
+ node._data = text;
487
+ const index = node.index;
488
+ const parent = node.parent;
489
+
490
+ // Remove empty text nodes.
491
+ if ( !text ) {
492
+ node._remove();
493
+ }
494
+
495
+ for ( const item of brackets ) {
496
+ // Non-empty text node.
497
+ if ( text ) {
498
+ if (
499
+ this.sameSelectionCharacters ||
500
+ (
501
+ !this.sameSelectionCharacters &&
502
+ ( item.bracket == TEXT_RANGE_START_TOKEN || item.bracket == TEXT_RANGE_END_TOKEN )
503
+ )
504
+ ) {
505
+ // Store information about text range delimiter.
506
+ this._positions.push( {
507
+ bracket: item.bracket,
508
+ position: new Position( node, item.textOffset )
509
+ } );
510
+ } else {
511
+ // Check if element range delimiter is not placed inside text node.
512
+ if ( !this.sameSelectionCharacters && item.textOffset !== 0 && item.textOffset !== text.length ) {
513
+ throw new Error( `Parse error - range delimiter '${ item.bracket }' is placed inside text node.` );
514
+ }
515
+
516
+ // If bracket is placed at the end of the text node - it should be positioned after it.
517
+ const offset = ( item.textOffset === 0 ? index : index + 1 );
518
+
519
+ // Store information about element range delimiter.
520
+ this._positions.push( {
521
+ bracket: item.bracket,
522
+ position: new Position( parent, offset )
523
+ } );
524
+ }
525
+ } else {
526
+ if ( !this.sameSelectionCharacters &&
527
+ item.bracket == TEXT_RANGE_START_TOKEN ||
528
+ item.bracket == TEXT_RANGE_END_TOKEN
529
+ ) {
530
+ throw new Error( `Parse error - text range delimiter '${ item.bracket }' is placed inside empty text node. ` );
531
+ }
532
+
533
+ // Store information about element range delimiter.
534
+ this._positions.push( {
535
+ bracket: item.bracket,
536
+ position: new Position( parent, index )
537
+ } );
538
+ }
539
+ }
540
+ }
541
+ }
542
+
543
+ /**
544
+ * Sorts ranges in a given order. Range order should be an array and each element should represent the desired position
545
+ * of the range after sorting.
546
+ * For example: `[2, 3, 1]` means that the first range will be placed as the second, the second as the third and the third
547
+ * as the first.
548
+ *
549
+ * @private
550
+ * @param {Array.<module:engine/view/range~Range>} ranges Ranges to sort.
551
+ * @param {Array.<Number>} rangesOrder An array with new range order.
552
+ * @returns {Array} Sorted ranges array.
553
+ */
554
+ _sortRanges( ranges, rangesOrder ) {
555
+ const sortedRanges = [];
556
+ let index = 0;
557
+
558
+ for ( const newPosition of rangesOrder ) {
559
+ if ( ranges[ newPosition - 1 ] === undefined ) {
560
+ throw new Error( 'Parse error - provided ranges order is invalid.' );
561
+ }
562
+
563
+ sortedRanges[ newPosition - 1 ] = ranges[ index ];
564
+ index++;
565
+ }
566
+
567
+ return sortedRanges;
568
+ }
569
+
570
+ /**
571
+ * Uses all found bracket positions to create ranges from them.
572
+ *
573
+ * @private
574
+ * @returns {Array.<module:engine/view/range~Range>}
575
+ */
576
+ _createRanges() {
577
+ const ranges = [];
578
+ let range = null;
579
+
580
+ for ( const item of this._positions ) {
581
+ // When end of range is found without opening.
582
+ if ( !range && ( item.bracket == ELEMENT_RANGE_END_TOKEN || item.bracket == TEXT_RANGE_END_TOKEN ) ) {
583
+ throw new Error( `Parse error - end of range was found '${ item.bracket }' but range was not started before.` );
584
+ }
585
+
586
+ // When second start of range is found when one is already opened - selection does not allow intersecting
587
+ // ranges.
588
+ if ( range && ( item.bracket == ELEMENT_RANGE_START_TOKEN || item.bracket == TEXT_RANGE_START_TOKEN ) ) {
589
+ throw new Error( `Parse error - start of range was found '${ item.bracket }' but one range is already started.` );
590
+ }
591
+
592
+ if ( item.bracket == ELEMENT_RANGE_START_TOKEN || item.bracket == TEXT_RANGE_START_TOKEN ) {
593
+ range = new Range( item.position, item.position );
594
+ } else {
595
+ range.end = item.position;
596
+ ranges.push( range );
597
+ range = null;
598
+ }
599
+ }
600
+
601
+ // Check if all ranges have proper ending.
602
+ if ( range !== null ) {
603
+ throw new Error( 'Parse error - range was started but no end delimiter was found.' );
604
+ }
605
+
606
+ return ranges;
607
+ }
608
+ }
609
+
610
+ /**
611
+ * Private helper class used for converting the view tree to a string.
612
+ *
613
+ * @private
614
+ */
615
+ class ViewStringify {
616
+ /**
617
+ * Creates a view stringify instance.
618
+ *
619
+ * @param root
620
+ * @param {module:engine/view/documentselection~DocumentSelection} selection A selection whose ranges
621
+ * should also be converted to a string.
622
+ * @param {Object} options An options object.
623
+ * @param {Boolean} [options.showType=false] When set to `true`, the type of elements will be printed (`<container:p>`
624
+ * instead of `<p>`, `<attribute:b>` instead of `<b>` and `<empty:img>` instead of `<img>`).
625
+ * @param {Boolean} [options.showPriority=false] When set to `true`, the attribute element's priority will be printed.
626
+ * @param {Boolean} [options.ignoreRoot=false] When set to `true`, the root's element opening and closing tag will not
627
+ * be outputted.
628
+ * @param {Boolean} [options.sameSelectionCharacters=false] When set to `true`, the selection inside the text is marked as
629
+ * `{` and `}` and the selection outside the text as `[` and `]`. When set to `false`, both are marked as `[` and `]`.
630
+ * @param {Boolean} [options.renderUIElements=false] When set to `true`, the inner content of each
631
+ * {@link module:engine/view/uielement~UIElement} will be printed.
632
+ * @param {Boolean} [options.renderRawElements=false] When set to `true`, the inner content of each
633
+ * {@link module:engine/view/rawelement~RawElement} will be printed.
634
+ */
635
+ constructor( root, selection, options ) {
636
+ this.root = root;
637
+ this.selection = selection;
638
+ this.ranges = [];
639
+
640
+ if ( this.selection ) {
641
+ this.ranges = [ ...selection.getRanges() ];
642
+ }
643
+
644
+ this.showType = !!options.showType;
645
+ this.showPriority = !!options.showPriority;
646
+ this.showAttributeElementId = !!options.showAttributeElementId;
647
+ this.ignoreRoot = !!options.ignoreRoot;
648
+ this.sameSelectionCharacters = !!options.sameSelectionCharacters;
649
+ this.renderUIElements = !!options.renderUIElements;
650
+ this.renderRawElements = !!options.renderRawElements;
651
+ }
652
+
653
+ /**
654
+ * Converts the view to a string.
655
+ *
656
+ * @returns {String} String representation of the view elements.
657
+ */
658
+ stringify() {
659
+ let result = '';
660
+ this._walkView( this.root, chunk => {
661
+ result += chunk;
662
+ } );
663
+
664
+ return result;
665
+ }
666
+
667
+ /**
668
+ * Executes a simple walker that iterates over all elements in the view tree starting from the root element.
669
+ * Calls the `callback` with parsed chunks of string data.
670
+ *
671
+ * @private
672
+ * @param {module:engine/view/documentfragment~DocumentFragment|module:engine/view/element~Element|module:engine/view/text~Text} root
673
+ * @param {Function} callback
674
+ */
675
+ _walkView( root, callback ) {
676
+ const ignore = this.ignoreRoot && this.root === root;
677
+
678
+ if ( root.is( 'element' ) || root.is( 'documentFragment' ) ) {
679
+ if ( root.is( 'element' ) && !ignore ) {
680
+ callback( this._stringifyElementOpen( root ) );
681
+ }
682
+
683
+ if ( ( this.renderUIElements && root.is( 'uiElement' ) ) ) {
684
+ callback( root.render( document ).innerHTML );
685
+ } else if ( this.renderRawElements && root.is( 'rawElement' ) ) {
686
+ // There's no DOM element for "root" to pass to render(). Creating
687
+ // a surrogate container to render the children instead.
688
+ const rawContentContainer = document.createElement( 'div' );
689
+ root.render( rawContentContainer );
690
+
691
+ callback( rawContentContainer.innerHTML );
692
+ } else {
693
+ let offset = 0;
694
+ callback( this._stringifyElementRanges( root, offset ) );
695
+
696
+ for ( const child of root.getChildren() ) {
697
+ this._walkView( child, callback );
698
+ offset++;
699
+ callback( this._stringifyElementRanges( root, offset ) );
700
+ }
701
+ }
702
+
703
+ if ( root.is( 'element' ) && !ignore ) {
704
+ callback( this._stringifyElementClose( root ) );
705
+ }
706
+ }
707
+
708
+ if ( root.is( '$text' ) ) {
709
+ callback( this._stringifyTextRanges( root ) );
710
+ }
711
+ }
712
+
713
+ /**
714
+ * Checks if a given {@link module:engine/view/element~Element element} has a {@link module:engine/view/range~Range#start range start}
715
+ * or a {@link module:engine/view/range~Range#start range end} placed at a given offset and returns its string representation.
716
+ *
717
+ * @private
718
+ * @param {module:engine/view/element~Element} element
719
+ * @param {Number} offset
720
+ */
721
+ _stringifyElementRanges( element, offset ) {
722
+ let start = '';
723
+ let end = '';
724
+ let collapsed = '';
725
+
726
+ for ( const range of this.ranges ) {
727
+ if ( range.start.parent == element && range.start.offset === offset ) {
728
+ if ( range.isCollapsed ) {
729
+ collapsed += ELEMENT_RANGE_START_TOKEN + ELEMENT_RANGE_END_TOKEN;
730
+ } else {
731
+ start += ELEMENT_RANGE_START_TOKEN;
732
+ }
733
+ }
734
+
735
+ if ( range.end.parent === element && range.end.offset === offset && !range.isCollapsed ) {
736
+ end += ELEMENT_RANGE_END_TOKEN;
737
+ }
738
+ }
739
+
740
+ return end + collapsed + start;
741
+ }
742
+
743
+ /**
744
+ * Checks if a given {@link module:engine/view/element~Element Text node} has a
745
+ * {@link module:engine/view/range~Range#start range start} or a
746
+ * {@link module:engine/view/range~Range#start range end} placed somewhere inside. Returns a string representation of text
747
+ * with range delimiters placed inside.
748
+ *
749
+ * @private
750
+ * @param {module:engine/view/text~Text} node
751
+ */
752
+ _stringifyTextRanges( node ) {
753
+ const length = node.data.length;
754
+ let result = node.data.split( '' );
755
+ let rangeStartToken, rangeEndToken;
756
+
757
+ if ( this.sameSelectionCharacters ) {
758
+ rangeStartToken = ELEMENT_RANGE_START_TOKEN;
759
+ rangeEndToken = ELEMENT_RANGE_END_TOKEN;
760
+ } else {
761
+ rangeStartToken = TEXT_RANGE_START_TOKEN;
762
+ rangeEndToken = TEXT_RANGE_END_TOKEN;
763
+ }
764
+
765
+ // Add one more element for ranges ending after last character in text.
766
+ result[ length ] = '';
767
+
768
+ // Represent each letter as object with information about opening/closing ranges at each offset.
769
+ result = result.map( letter => {
770
+ return {
771
+ letter,
772
+ start: '',
773
+ end: '',
774
+ collapsed: ''
775
+ };
776
+ } );
777
+
778
+ for ( const range of this.ranges ) {
779
+ const start = range.start;
780
+ const end = range.end;
781
+
782
+ if ( start.parent == node && start.offset >= 0 && start.offset <= length ) {
783
+ if ( range.isCollapsed ) {
784
+ result[ end.offset ].collapsed += rangeStartToken + rangeEndToken;
785
+ } else {
786
+ result[ start.offset ].start += rangeStartToken;
787
+ }
788
+ }
789
+
790
+ if ( end.parent == node && end.offset >= 0 && end.offset <= length && !range.isCollapsed ) {
791
+ result[ end.offset ].end += rangeEndToken;
792
+ }
793
+ }
794
+
795
+ return result.map( item => item.end + item.collapsed + item.start + item.letter ).join( '' );
796
+ }
797
+
798
+ /**
799
+ * Converts the passed {@link module:engine/view/element~Element element} to an opening tag.
800
+ *
801
+ * Depending on the current configuration, the opening tag can be simple (`<a>`), contain a type prefix (`<container:p>`,
802
+ * `<attribute:a>` or `<empty:img>`), contain priority information ( `<attribute:a view-priority="20">` ),
803
+ * or contain element id ( `<attribute:span view-id="foo">` ). Element attributes will also be included
804
+ * (`<a href="https://ckeditor.com" name="foobar">`).
805
+ *
806
+ * @private
807
+ * @param {module:engine/view/element~Element} element
808
+ * @returns {String}
809
+ */
810
+ _stringifyElementOpen( element ) {
811
+ const priority = this._stringifyElementPriority( element );
812
+ const id = this._stringifyElementId( element );
813
+
814
+ const type = this._stringifyElementType( element );
815
+ const name = [ type, element.name ].filter( i => i !== '' ).join( ':' );
816
+ const attributes = this._stringifyElementAttributes( element );
817
+ const parts = [ name, priority, id, attributes ];
818
+
819
+ return `<${ parts.filter( i => i !== '' ).join( ' ' ) }>`;
820
+ }
821
+
822
+ /**
823
+ * Converts the passed {@link module:engine/view/element~Element element} to a closing tag.
824
+ * Depending on the current configuration, the closing tag can be simple (`</a>`) or contain a type prefix (`</container:p>`,
825
+ * `</attribute:a>` or `</empty:img>`).
826
+ *
827
+ * @private
828
+ * @param {module:engine/view/element~Element} element
829
+ * @returns {String}
830
+ */
831
+ _stringifyElementClose( element ) {
832
+ const type = this._stringifyElementType( element );
833
+ const name = [ type, element.name ].filter( i => i !== '' ).join( ':' );
834
+
835
+ return `</${ name }>`;
836
+ }
837
+
838
+ /**
839
+ * Converts the passed {@link module:engine/view/element~Element element's} type to its string representation
840
+ *
841
+ * Returns:
842
+ * * 'attribute' for {@link module:engine/view/attributeelement~AttributeElement attribute elements},
843
+ * * 'container' for {@link module:engine/view/containerelement~ContainerElement container elements},
844
+ * * 'empty' for {@link module:engine/view/emptyelement~EmptyElement empty elements},
845
+ * * 'ui' for {@link module:engine/view/uielement~UIElement UI elements},
846
+ * * 'raw' for {@link module:engine/view/rawelement~RawElement raw elements},
847
+ * * an empty string when the current configuration is preventing showing elements' types.
848
+ *
849
+ * @private
850
+ * @param {module:engine/view/element~Element} element
851
+ * @returns {String}
852
+ */
853
+ _stringifyElementType( element ) {
854
+ if ( this.showType ) {
855
+ for ( const type in allowedTypes ) {
856
+ if ( element instanceof allowedTypes[ type ] ) {
857
+ return type;
858
+ }
859
+ }
860
+ }
861
+
862
+ return '';
863
+ }
864
+
865
+ /**
866
+ * Converts the passed {@link module:engine/view/element~Element element} to its priority representation.
867
+ *
868
+ * The priority string representation will be returned when the passed element is an instance of
869
+ * {@link module:engine/view/attributeelement~AttributeElement attribute element} and the current configuration allows to show the
870
+ * priority. Otherwise returns an empty string.
871
+ *
872
+ * @private
873
+ * @param {module:engine/view/element~Element} element
874
+ * @returns {String}
875
+ */
876
+ _stringifyElementPriority( element ) {
877
+ if ( this.showPriority && element.is( 'attributeElement' ) ) {
878
+ return `view-priority="${ element.priority }"`;
879
+ }
880
+
881
+ return '';
882
+ }
883
+
884
+ /**
885
+ * Converts the passed {@link module:engine/view/element~Element element} to its id representation.
886
+ *
887
+ * The id string representation will be returned when the passed element is an instance of
888
+ * {@link module:engine/view/attributeelement~AttributeElement attribute element}, the element has an id
889
+ * and the current configuration allows to show the id. Otherwise returns an empty string.
890
+ *
891
+ * @private
892
+ * @param {module:engine/view/element~Element} element
893
+ * @returns {String}
894
+ */
895
+ _stringifyElementId( element ) {
896
+ if ( this.showAttributeElementId && element.is( 'attributeElement' ) && element.id ) {
897
+ return `view-id="${ element.id }"`;
898
+ }
899
+
900
+ return '';
901
+ }
902
+
903
+ /**
904
+ * Converts the passed {@link module:engine/view/element~Element element} attributes to their string representation.
905
+ * If an element has no attributes, an empty string is returned.
906
+ *
907
+ * @private
908
+ * @param {module:engine/view/element~Element} element
909
+ * @returns {String}
910
+ */
911
+ _stringifyElementAttributes( element ) {
912
+ const attributes = [];
913
+ const keys = [ ...element.getAttributeKeys() ].sort();
914
+
915
+ for ( const attribute of keys ) {
916
+ let attributeValue;
917
+
918
+ if ( attribute === 'class' ) {
919
+ attributeValue = [ ...element.getClassNames() ]
920
+ .sort()
921
+ .join( ' ' );
922
+ } else if ( attribute === 'style' ) {
923
+ attributeValue = [ ...element.getStyleNames() ]
924
+ .sort()
925
+ .map( style => `${ style }:${ element.getStyle( style ) }` )
926
+ .join( ';' );
927
+ } else {
928
+ attributeValue = element.getAttribute( attribute );
929
+ }
930
+
931
+ attributes.push( `${ attribute }="${ attributeValue }"` );
932
+ }
933
+
934
+ return attributes.join( ' ' );
935
+ }
936
+ }
937
+
938
+ // Converts {@link module:engine/view/element~Element elements} to
939
+ // {@link module:engine/view/attributeelement~AttributeElement attribute elements},
940
+ // {@link module:engine/view/containerelement~ContainerElement container elements},
941
+ // {@link module:engine/view/emptyelement~EmptyElement empty elements} or
942
+ // {@link module:engine/view/uielement~UIElement UI elements}.
943
+ // It converts the whole tree starting from the `rootNode`. The conversion is based on element names.
944
+ // See the `_convertElement` method for more details.
945
+ //
946
+ // @param {module:engine/view/element~Element|module:engine/view/documentfragment~DocumentFragment|module:engine/view/text~Text}
947
+ // rootNode The root node to convert.
948
+ // @returns {module:engine/view/element~Element|module:engine/view/documentfragment~DocumentFragment|
949
+ // module:engine/view/text~Text} The root node of converted elements.
950
+ function _convertViewElements( rootNode ) {
951
+ if ( rootNode.is( 'element' ) || rootNode.is( 'documentFragment' ) ) {
952
+ // Convert element or leave document fragment.
953
+
954
+ const convertedElement = rootNode.is( 'documentFragment' ) ?
955
+ new ViewDocumentFragment( rootNode.document ) :
956
+ _convertElement( rootNode.document, rootNode );
957
+
958
+ // Convert all child nodes.
959
+ // Cache the nodes in array. Otherwise, we would skip some nodes because during iteration we move nodes
960
+ // from `rootNode` to `convertedElement`. This would interfere with iteration.
961
+ for ( const child of [ ...rootNode.getChildren() ] ) {
962
+ if ( convertedElement.is( 'emptyElement' ) ) {
963
+ throw new Error( 'Parse error - cannot parse inside EmptyElement.' );
964
+ } else if ( convertedElement.is( 'uiElement' ) ) {
965
+ throw new Error( 'Parse error - cannot parse inside UIElement.' );
966
+ } else if ( convertedElement.is( 'rawElement' ) ) {
967
+ throw new Error( 'Parse error - cannot parse inside RawElement.' );
968
+ }
969
+
970
+ convertedElement._appendChild( _convertViewElements( child ) );
971
+ }
972
+
973
+ return convertedElement;
974
+ }
975
+
976
+ return rootNode;
977
+ }
978
+
979
+ // Converts an {@link module:engine/view/element~Element element} to
980
+ // {@link module:engine/view/attributeelement~AttributeElement attribute element},
981
+ // {@link module:engine/view/containerelement~ContainerElement container element},
982
+ // {@link module:engine/view/emptyelement~EmptyElement empty element} or
983
+ // {@link module:engine/view/uielement~UIElement UI element}.
984
+ // If the element's name is in the format of `attribute:b`, it will be converted to
985
+ // an {@link module:engine/view/attributeelement~AttributeElement attribute element} with a priority of 11.
986
+ // Additionally, attribute elements may have specified priority (for example `view-priority="11"`) and/or
987
+ // id (for example `view-id="foo"`).
988
+ // If the element's name is in the format of `container:p`, it will be converted to
989
+ // a {@link module:engine/view/containerelement~ContainerElement container element}.
990
+ // If the element's name is in the format of `empty:img`, it will be converted to
991
+ // an {@link module:engine/view/emptyelement~EmptyElement empty element}.
992
+ // If the element's name is in the format of `ui:span`, it will be converted to
993
+ // a {@link module:engine/view/uielement~UIElement UI element}.
994
+ // If the element's name does not contain any additional information, a {@link module:engine/view/element~Element view Element} will be
995
+ // returned.
996
+ //
997
+ // @param {module:engine/view/element~Element} viewElement A view element to convert.
998
+ // @returns {module:engine/view/element~Element|module:engine/view/attributeelement~AttributeElement|
999
+ // module:engine/view/emptyelement~EmptyElement|module:engine/view/uielement~UIElement|
1000
+ // module:engine/view/containerelement~ContainerElement} A tree view
1001
+ // element converted according to its name.
1002
+ function _convertElement( viewDocument, viewElement ) {
1003
+ const info = _convertElementNameAndInfo( viewElement );
1004
+ const ElementConstructor = allowedTypes[ info.type ];
1005
+ const newElement = ElementConstructor ? new ElementConstructor( viewDocument, info.name ) : new ViewElement( viewDocument, info.name );
1006
+
1007
+ if ( newElement.is( 'attributeElement' ) ) {
1008
+ if ( info.priority !== null ) {
1009
+ newElement._priority = info.priority;
1010
+ }
1011
+
1012
+ if ( info.id !== null ) {
1013
+ newElement._id = info.id;
1014
+ }
1015
+ }
1016
+
1017
+ // Move attributes.
1018
+ for ( const attributeKey of viewElement.getAttributeKeys() ) {
1019
+ newElement._setAttribute( attributeKey, viewElement.getAttribute( attributeKey ) );
1020
+ }
1021
+
1022
+ return newElement;
1023
+ }
1024
+
1025
+ // Converts the `view-priority` attribute and the {@link module:engine/view/element~Element#name element's name} information needed for
1026
+ // creating {@link module:engine/view/attributeelement~AttributeElement attribute element},
1027
+ // {@link module:engine/view/containerelement~ContainerElement container element},
1028
+ // {@link module:engine/view/emptyelement~EmptyElement empty element} or
1029
+ // {@link module:engine/view/uielement~UIElement UI element}.
1030
+ // The name can be provided in two formats: as a simple element's name (`div`), or as a type and name (`container:div`,
1031
+ // `attribute:span`, `empty:img`, `ui:span`);
1032
+ //
1033
+ // @param {module:engine/view/element~Element} element The element whose name should be converted.
1034
+ // @returns {Object} info An object with parsed information.
1035
+ // @returns {String} info.name The parsed name of the element.
1036
+ // @returns {String|null} info.type The parsed type of the element. It can be `attribute`, `container` or `empty`.
1037
+ // returns {Number|null} info.priority The parsed priority of the element.
1038
+ function _convertElementNameAndInfo( viewElement ) {
1039
+ const parts = viewElement.name.split( ':' );
1040
+
1041
+ const priority = _convertPriority( viewElement.getAttribute( 'view-priority' ) );
1042
+ const id = viewElement.hasAttribute( 'view-id' ) ? viewElement.getAttribute( 'view-id' ) : null;
1043
+
1044
+ viewElement._removeAttribute( 'view-priority' );
1045
+ viewElement._removeAttribute( 'view-id' );
1046
+
1047
+ if ( parts.length == 1 ) {
1048
+ return {
1049
+ name: parts[ 0 ],
1050
+ type: priority !== null ? 'attribute' : null,
1051
+ priority,
1052
+ id
1053
+ };
1054
+ }
1055
+
1056
+ // Check if type and name: container:div.
1057
+ const type = _convertType( parts[ 0 ] );
1058
+
1059
+ if ( type ) {
1060
+ return {
1061
+ name: parts[ 1 ],
1062
+ type,
1063
+ priority,
1064
+ id
1065
+ };
1066
+ }
1067
+
1068
+ throw new Error( `Parse error - cannot parse element's name: ${ viewElement.name }.` );
1069
+ }
1070
+
1071
+ // Checks if the element's type is allowed. Returns `attribute`, `container`, `empty` or `null`.
1072
+ //
1073
+ // @param {String} type
1074
+ // @returns {String|null}
1075
+ function _convertType( type ) {
1076
+ return allowedTypes[ type ] ? type : null;
1077
+ }
1078
+
1079
+ // Checks if a given priority is allowed. Returns null if the priority cannot be converted.
1080
+ //
1081
+ // @param {String} priorityString
1082
+ // returns {Number|null}
1083
+ function _convertPriority( priorityString ) {
1084
+ const priority = parseInt( priorityString, 10 );
1085
+
1086
+ if ( !isNaN( priority ) ) {
1087
+ return priority;
1088
+ }
1089
+
1090
+ return null;
1091
+ }