@ckeditor/ckeditor5-engine 38.1.1 → 38.2.0-alpha.1

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