@ckeditor/ckeditor5-engine 35.0.1 → 35.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/CHANGELOG.md +4 -4
  2. package/package.json +30 -24
  3. package/src/controller/datacontroller.js +467 -561
  4. package/src/controller/editingcontroller.js +168 -204
  5. package/src/conversion/conversion.js +541 -565
  6. package/src/conversion/conversionhelpers.js +24 -28
  7. package/src/conversion/downcastdispatcher.js +457 -686
  8. package/src/conversion/downcasthelpers.js +1583 -1965
  9. package/src/conversion/mapper.js +518 -707
  10. package/src/conversion/modelconsumable.js +240 -283
  11. package/src/conversion/upcastdispatcher.js +372 -718
  12. package/src/conversion/upcasthelpers.js +707 -818
  13. package/src/conversion/viewconsumable.js +524 -581
  14. package/src/dataprocessor/basichtmlwriter.js +12 -16
  15. package/src/dataprocessor/dataprocessor.js +5 -0
  16. package/src/dataprocessor/htmldataprocessor.js +100 -116
  17. package/src/dataprocessor/htmlwriter.js +1 -18
  18. package/src/dataprocessor/xmldataprocessor.js +116 -137
  19. package/src/dev-utils/model.js +260 -352
  20. package/src/dev-utils/operationreplayer.js +106 -126
  21. package/src/dev-utils/utils.js +34 -51
  22. package/src/dev-utils/view.js +632 -753
  23. package/src/index.js +0 -11
  24. package/src/model/batch.js +111 -127
  25. package/src/model/differ.js +988 -1233
  26. package/src/model/document.js +340 -449
  27. package/src/model/documentfragment.js +327 -364
  28. package/src/model/documentselection.js +996 -1189
  29. package/src/model/element.js +306 -410
  30. package/src/model/history.js +224 -262
  31. package/src/model/item.js +5 -0
  32. package/src/model/liveposition.js +84 -145
  33. package/src/model/liverange.js +108 -185
  34. package/src/model/markercollection.js +379 -480
  35. package/src/model/model.js +883 -1034
  36. package/src/model/node.js +419 -463
  37. package/src/model/nodelist.js +176 -201
  38. package/src/model/operation/attributeoperation.js +153 -182
  39. package/src/model/operation/detachoperation.js +64 -83
  40. package/src/model/operation/insertoperation.js +135 -166
  41. package/src/model/operation/markeroperation.js +114 -140
  42. package/src/model/operation/mergeoperation.js +163 -191
  43. package/src/model/operation/moveoperation.js +157 -187
  44. package/src/model/operation/nooperation.js +28 -38
  45. package/src/model/operation/operation.js +106 -125
  46. package/src/model/operation/operationfactory.js +30 -34
  47. package/src/model/operation/renameoperation.js +109 -135
  48. package/src/model/operation/rootattributeoperation.js +155 -188
  49. package/src/model/operation/splitoperation.js +196 -232
  50. package/src/model/operation/transform.js +1833 -2204
  51. package/src/model/operation/utils.js +140 -204
  52. package/src/model/position.js +980 -1053
  53. package/src/model/range.js +910 -1028
  54. package/src/model/rootelement.js +77 -97
  55. package/src/model/schema.js +1189 -1835
  56. package/src/model/selection.js +745 -862
  57. package/src/model/text.js +90 -114
  58. package/src/model/textproxy.js +204 -240
  59. package/src/model/treewalker.js +316 -397
  60. package/src/model/typecheckable.js +16 -0
  61. package/src/model/utils/autoparagraphing.js +32 -44
  62. package/src/model/utils/deletecontent.js +334 -418
  63. package/src/model/utils/findoptimalinsertionrange.js +25 -36
  64. package/src/model/utils/getselectedcontent.js +96 -118
  65. package/src/model/utils/insertcontent.js +757 -773
  66. package/src/model/utils/insertobject.js +96 -119
  67. package/src/model/utils/modifyselection.js +120 -158
  68. package/src/model/utils/selection-post-fixer.js +153 -201
  69. package/src/model/writer.js +1305 -1474
  70. package/src/view/attributeelement.js +189 -225
  71. package/src/view/containerelement.js +75 -85
  72. package/src/view/document.js +172 -215
  73. package/src/view/documentfragment.js +200 -249
  74. package/src/view/documentselection.js +338 -367
  75. package/src/view/domconverter.js +1370 -1617
  76. package/src/view/downcastwriter.js +1747 -2076
  77. package/src/view/editableelement.js +81 -97
  78. package/src/view/element.js +739 -890
  79. package/src/view/elementdefinition.js +5 -0
  80. package/src/view/emptyelement.js +82 -92
  81. package/src/view/filler.js +35 -50
  82. package/src/view/item.js +5 -0
  83. package/src/view/matcher.js +260 -559
  84. package/src/view/node.js +274 -360
  85. package/src/view/observer/arrowkeysobserver.js +19 -28
  86. package/src/view/observer/bubblingemittermixin.js +120 -263
  87. package/src/view/observer/bubblingeventinfo.js +47 -55
  88. package/src/view/observer/clickobserver.js +7 -13
  89. package/src/view/observer/compositionobserver.js +14 -24
  90. package/src/view/observer/domeventdata.js +57 -67
  91. package/src/view/observer/domeventobserver.js +40 -64
  92. package/src/view/observer/fakeselectionobserver.js +81 -96
  93. package/src/view/observer/focusobserver.js +45 -61
  94. package/src/view/observer/inputobserver.js +7 -13
  95. package/src/view/observer/keyobserver.js +17 -27
  96. package/src/view/observer/mouseobserver.js +7 -14
  97. package/src/view/observer/mutationobserver.js +220 -315
  98. package/src/view/observer/observer.js +81 -102
  99. package/src/view/observer/selectionobserver.js +199 -246
  100. package/src/view/observer/tabobserver.js +23 -36
  101. package/src/view/placeholder.js +128 -173
  102. package/src/view/position.js +350 -401
  103. package/src/view/range.js +453 -513
  104. package/src/view/rawelement.js +85 -112
  105. package/src/view/renderer.js +874 -1018
  106. package/src/view/rooteditableelement.js +80 -90
  107. package/src/view/selection.js +608 -689
  108. package/src/view/styles/background.js +43 -44
  109. package/src/view/styles/border.js +220 -276
  110. package/src/view/styles/margin.js +8 -17
  111. package/src/view/styles/padding.js +8 -16
  112. package/src/view/styles/utils.js +127 -160
  113. package/src/view/stylesmap.js +728 -905
  114. package/src/view/text.js +102 -126
  115. package/src/view/textproxy.js +144 -170
  116. package/src/view/treewalker.js +383 -479
  117. package/src/view/typecheckable.js +19 -0
  118. package/src/view/uielement.js +166 -187
  119. package/src/view/upcastwriter.js +395 -449
  120. package/src/view/view.js +569 -664
  121. package/src/dataprocessor/dataprocessor.jsdoc +0 -64
  122. package/src/model/item.jsdoc +0 -14
  123. package/src/view/elementdefinition.jsdoc +0 -59
  124. package/src/view/item.jsdoc +0 -14
@@ -2,15 +2,12 @@
2
2
  * @license Copyright (c) 2003-2022, CKSource Holding sp. z o.o. All rights reserved.
3
3
  * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4
4
  */
5
-
6
5
  /**
7
6
  * @module engine/dev-utils/model
8
7
  */
9
-
10
8
  /**
11
9
  * Collection of methods for manipulating the {@link module:engine/model/model model} for testing purposes.
12
10
  */
13
-
14
11
  import RootElement from '../model/rootelement';
15
12
  import Model from '../model/model';
16
13
  import ModelRange from '../model/range';
@@ -18,30 +15,17 @@ import ModelPosition from '../model/position';
18
15
  import ModelSelection from '../model/selection';
19
16
  import ModelDocumentFragment from '../model/documentfragment';
20
17
  import DocumentSelection from '../model/documentselection';
21
-
22
18
  import View from '../view/view';
23
19
  import ViewContainerElement from '../view/containerelement';
24
20
  import ViewRootEditableElement from '../view/rooteditableelement';
25
-
26
21
  import { parse as viewParse, stringify as viewStringify } from '../../src/dev-utils/view';
27
-
28
- import DowncastDispatcher from '../conversion/downcastdispatcher';
29
- import UpcastDispatcher from '../conversion/upcastdispatcher';
30
22
  import Mapper from '../conversion/mapper';
31
- import {
32
- convertCollapsedSelection,
33
- convertRangeSelection,
34
- insertAttributesAndChildren,
35
- insertElement,
36
- insertText,
37
- insertUIElement,
38
- wrap
39
- } from '../conversion/downcasthelpers';
40
-
23
+ import { convertCollapsedSelection, convertRangeSelection, insertAttributesAndChildren, insertElement, insertText, insertUIElement, wrap } from '../conversion/downcasthelpers';
41
24
  import { isPlainObject } from 'lodash-es';
42
25
  import toMap from '@ckeditor/ckeditor5-utils/src/tomap';
43
26
  import { StylesProcessor } from '../view/stylesmap';
44
-
27
+ import DowncastDispatcher from '../conversion/downcastdispatcher';
28
+ import UpcastDispatcher from '../conversion/upcastdispatcher';
45
29
  /**
46
30
  * Writes the content of a model {@link module:engine/model/document~Document document} to an HTML-like string.
47
31
  *
@@ -63,24 +47,16 @@ import { StylesProcessor } from '../view/stylesmap';
63
47
  * @param {Boolean} [options.convertMarkers=false] Whether to include markers in the returned string.
64
48
  * @returns {String} The stringified data.
65
49
  */
66
- export function getData( model, options = {} ) {
67
- if ( !( model instanceof Model ) ) {
68
- throw new TypeError( 'Model needs to be an instance of module:engine/model/model~Model.' );
69
- }
70
-
71
- const rootName = options.rootName || 'main';
72
- const root = model.document.getRoot( rootName );
73
-
74
- return getData._stringify(
75
- root,
76
- options.withoutSelection ? null : model.document.selection,
77
- options.convertMarkers ? model.markers : null
78
- );
50
+ export function getData(model, options = {}) {
51
+ if (!(model instanceof Model)) {
52
+ throw new TypeError('Model needs to be an instance of module:engine/model/model~Model.');
53
+ }
54
+ const rootName = options.rootName || 'main';
55
+ const root = model.document.getRoot(rootName);
56
+ return getData._stringify(root, options.withoutSelection ? null : model.document.selection, options.convertMarkers ? model.markers : null);
79
57
  }
80
-
81
58
  // Set stringify as getData private method - needed for testing/spying.
82
59
  getData._stringify = stringify;
83
-
84
60
  /**
85
61
  * Sets the content of a model {@link module:engine/model/document~Document document} provided as an HTML-like string.
86
62
  *
@@ -106,67 +82,57 @@ getData._stringify = stringify;
106
82
  * @param {Object} [options.batchType] Batch type used for inserting elements. See {@link module:engine/model/batch~Batch#constructor}.
107
83
  * See {@link module:engine/model/batch~Batch#type}.
108
84
  */
109
- export function setData( model, data, options = {} ) {
110
- if ( !( model instanceof Model ) ) {
111
- throw new TypeError( 'Model needs to be an instance of module:engine/model/model~Model.' );
112
- }
113
-
114
- let modelDocumentFragment, selection;
115
- const modelRoot = model.document.getRoot( options.rootName || 'main' );
116
-
117
- // Parse data string to model.
118
- const parsedResult = setData._parse( data, model.schema, {
119
- lastRangeBackward: options.lastRangeBackward,
120
- selectionAttributes: options.selectionAttributes,
121
- context: [ modelRoot.name ]
122
- } );
123
-
124
- // Retrieve DocumentFragment and Selection from parsed model.
125
- if ( parsedResult.model ) {
126
- modelDocumentFragment = parsedResult.model;
127
- selection = parsedResult.selection;
128
- } else {
129
- modelDocumentFragment = parsedResult;
130
- }
131
-
132
- if ( options.batchType !== undefined ) {
133
- model.enqueueChange( options.batchType, writeToModel );
134
- } else {
135
- model.change( writeToModel );
136
- }
137
-
138
- function writeToModel( writer ) {
139
- // Replace existing model in document by new one.
140
- writer.remove( writer.createRangeIn( modelRoot ) );
141
- writer.insert( modelDocumentFragment, modelRoot );
142
-
143
- // Clean up previous document selection.
144
- writer.setSelection( null );
145
- writer.removeSelectionAttribute( model.document.selection.getAttributeKeys() );
146
-
147
- // Update document selection if specified.
148
- if ( selection ) {
149
- const ranges = [];
150
-
151
- for ( const range of selection.getRanges() ) {
152
- const start = new ModelPosition( modelRoot, range.start.path );
153
- const end = new ModelPosition( modelRoot, range.end.path );
154
-
155
- ranges.push( new ModelRange( start, end ) );
156
- }
157
-
158
- writer.setSelection( ranges, { backward: selection.isBackward } );
159
-
160
- if ( options.selectionAttributes ) {
161
- writer.setSelectionAttribute( selection.getAttributes() );
162
- }
163
- }
164
- }
85
+ export function setData(model, data, options = {}) {
86
+ if (!(model instanceof Model)) {
87
+ throw new TypeError('Model needs to be an instance of module:engine/model/model~Model.');
88
+ }
89
+ let modelDocumentFragment;
90
+ let selection = null;
91
+ const modelRoot = model.document.getRoot(options.rootName || 'main');
92
+ // Parse data string to model.
93
+ const parsedResult = setData._parse(data, model.schema, {
94
+ lastRangeBackward: options.lastRangeBackward,
95
+ selectionAttributes: options.selectionAttributes,
96
+ context: [modelRoot.name]
97
+ });
98
+ // Retrieve DocumentFragment and Selection from parsed model.
99
+ if ('model' in parsedResult) {
100
+ modelDocumentFragment = parsedResult.model;
101
+ selection = parsedResult.selection;
102
+ }
103
+ else {
104
+ modelDocumentFragment = parsedResult;
105
+ }
106
+ if (options.batchType !== undefined) {
107
+ model.enqueueChange(options.batchType, writeToModel);
108
+ }
109
+ else {
110
+ model.change(writeToModel);
111
+ }
112
+ function writeToModel(writer) {
113
+ // Replace existing model in document by new one.
114
+ writer.remove(writer.createRangeIn(modelRoot));
115
+ writer.insert(modelDocumentFragment, modelRoot);
116
+ // Clean up previous document selection.
117
+ writer.setSelection(null);
118
+ writer.removeSelectionAttribute(model.document.selection.getAttributeKeys());
119
+ // Update document selection if specified.
120
+ if (selection) {
121
+ const ranges = [];
122
+ for (const range of selection.getRanges()) {
123
+ const start = new ModelPosition(modelRoot, range.start.path);
124
+ const end = new ModelPosition(modelRoot, range.end.path);
125
+ ranges.push(new ModelRange(start, end));
126
+ }
127
+ writer.setSelection(ranges, { backward: selection.isBackward });
128
+ if (options.selectionAttributes) {
129
+ writer.setSelectionAttribute(selection.getAttributes());
130
+ }
131
+ }
132
+ }
165
133
  }
166
-
167
134
  // Set parse as setData private method - needed for testing/spying.
168
135
  setData._parse = parse;
169
-
170
136
  /**
171
137
  * Converts model nodes to HTML-like string representation.
172
138
  *
@@ -184,114 +150,94 @@ setData._parse = parse;
184
150
  * @param {Iterable.<module:engine/model/markercollection~Marker>|null} markers Markers to include.
185
151
  * @returns {String} An HTML-like string representing the model.
186
152
  */
187
- export function stringify( node, selectionOrPositionOrRange = null, markers = null ) {
188
- const model = new Model();
189
- const mapper = new Mapper();
190
- let selection, range;
191
-
192
- // Create a range witch wraps passed node.
193
- if ( node instanceof RootElement || node instanceof ModelDocumentFragment ) {
194
- range = model.createRangeIn( node );
195
- } else {
196
- // Node is detached - create new document fragment.
197
- if ( !node.parent ) {
198
- const fragment = new ModelDocumentFragment( node );
199
- range = model.createRangeIn( fragment );
200
- } else {
201
- range = new ModelRange(
202
- model.createPositionBefore( node ),
203
- model.createPositionAfter( node )
204
- );
205
- }
206
- }
207
-
208
- // Get selection from passed selection or position or range if at least one is specified.
209
- if ( selectionOrPositionOrRange instanceof ModelSelection ) {
210
- selection = selectionOrPositionOrRange;
211
- } else if ( selectionOrPositionOrRange instanceof DocumentSelection ) {
212
- selection = selectionOrPositionOrRange;
213
- } else if ( selectionOrPositionOrRange instanceof ModelRange ) {
214
- selection = new ModelSelection( selectionOrPositionOrRange );
215
- } else if ( selectionOrPositionOrRange instanceof ModelPosition ) {
216
- selection = new ModelSelection( selectionOrPositionOrRange );
217
- }
218
-
219
- // Set up conversion.
220
- // Create a temporary view controller.
221
- const stylesProcessor = new StylesProcessor();
222
- const view = new View( stylesProcessor );
223
- const viewDocument = view.document;
224
- const viewRoot = new ViewRootEditableElement( viewDocument, 'div' );
225
-
226
- // Create a temporary root element in view document.
227
- viewRoot.rootName = 'main';
228
- viewDocument.roots.add( viewRoot );
229
-
230
- // Create and setup downcast dispatcher.
231
- const downcastDispatcher = new DowncastDispatcher( { mapper } );
232
-
233
- // Bind root elements.
234
- mapper.bindElements( node.root, viewRoot );
235
-
236
- downcastDispatcher.on( 'insert:$text', insertText() );
237
- downcastDispatcher.on( 'insert', insertAttributesAndChildren(), { priority: 'lowest' } );
238
- downcastDispatcher.on( 'attribute', ( evt, data, conversionApi ) => {
239
- if ( data.item instanceof ModelSelection || data.item instanceof DocumentSelection || data.item.is( '$textProxy' ) ) {
240
- const converter = wrap( ( modelAttributeValue, { writer } ) => {
241
- return writer.createAttributeElement(
242
- 'model-text-with-attributes',
243
- { [ data.attributeKey ]: stringifyAttributeValue( modelAttributeValue ) }
244
- );
245
- } );
246
-
247
- converter( evt, data, conversionApi );
248
- }
249
- } );
250
- downcastDispatcher.on( 'insert', insertElement( modelItem => {
251
- // Stringify object types values for properly display as an output string.
252
- const attributes = convertAttributes( modelItem.getAttributes(), stringifyAttributeValue );
253
-
254
- return new ViewContainerElement( viewDocument, modelItem.name, attributes );
255
- } ) );
256
-
257
- downcastDispatcher.on( 'selection', convertRangeSelection() );
258
- downcastDispatcher.on( 'selection', convertCollapsedSelection() );
259
- downcastDispatcher.on( 'addMarker', insertUIElement( ( data, { writer } ) => {
260
- const name = data.markerName + ':' + ( data.isOpening ? 'start' : 'end' );
261
-
262
- return writer.createUIElement( name );
263
- } ) );
264
-
265
- const markersMap = new Map();
266
-
267
- if ( markers ) {
268
- // To provide stable results, sort markers by name.
269
- for ( const marker of Array.from( markers ).sort( ( a, b ) => a.name < b.name ? 1 : -1 ) ) {
270
- markersMap.set( marker.name, marker.getRange() );
271
- }
272
- }
273
-
274
- // Convert model to view.
275
- const writer = view._writer;
276
- downcastDispatcher.convert( range, markersMap, writer );
277
-
278
- // Convert model selection to view selection.
279
- if ( selection ) {
280
- downcastDispatcher.convertSelection( selection, markers || model.markers, writer );
281
- }
282
-
283
- // Parse view to data string.
284
- let data = viewStringify( viewRoot, viewDocument.selection, { sameSelectionCharacters: true } );
285
-
286
- // Removing unnecessary <div> and </div> added because `viewRoot` was also stringified alongside input data.
287
- data = data.substr( 5, data.length - 11 );
288
-
289
- view.destroy();
290
-
291
- // Replace valid XML `model-text-with-attributes` element name to `$text`.
292
- return data.replace( new RegExp( 'model-text-with-attributes', 'g' ), '$text' );
153
+ export function stringify(node, selectionOrPositionOrRange = null, markers = null) {
154
+ const model = new Model();
155
+ const mapper = new Mapper();
156
+ let selection = null;
157
+ let range;
158
+ // Create a range witch wraps passed node.
159
+ if (node instanceof RootElement || node instanceof ModelDocumentFragment) {
160
+ range = model.createRangeIn(node);
161
+ }
162
+ else {
163
+ // Node is detached - create new document fragment.
164
+ if (!node.parent) {
165
+ const fragment = new ModelDocumentFragment(node);
166
+ range = model.createRangeIn(fragment);
167
+ }
168
+ else {
169
+ range = new ModelRange(model.createPositionBefore(node), model.createPositionAfter(node));
170
+ }
171
+ }
172
+ // Get selection from passed selection or position or range if at least one is specified.
173
+ if (selectionOrPositionOrRange instanceof ModelSelection) {
174
+ selection = selectionOrPositionOrRange;
175
+ }
176
+ else if (selectionOrPositionOrRange instanceof DocumentSelection) {
177
+ selection = selectionOrPositionOrRange;
178
+ }
179
+ else if (selectionOrPositionOrRange instanceof ModelRange) {
180
+ selection = new ModelSelection(selectionOrPositionOrRange);
181
+ }
182
+ else if (selectionOrPositionOrRange instanceof ModelPosition) {
183
+ selection = new ModelSelection(selectionOrPositionOrRange);
184
+ }
185
+ // Set up conversion.
186
+ // Create a temporary view controller.
187
+ const stylesProcessor = new StylesProcessor();
188
+ const view = new View(stylesProcessor);
189
+ const viewDocument = view.document;
190
+ const viewRoot = new ViewRootEditableElement(viewDocument, 'div');
191
+ // Create a temporary root element in view document.
192
+ viewRoot.rootName = 'main';
193
+ viewDocument.roots.add(viewRoot);
194
+ // Create and setup downcast dispatcher.
195
+ const downcastDispatcher = new DowncastDispatcher({ mapper, schema: model.schema });
196
+ // Bind root elements.
197
+ mapper.bindElements(node.root, viewRoot);
198
+ downcastDispatcher.on('insert:$text', insertText());
199
+ downcastDispatcher.on('insert', insertAttributesAndChildren(), { priority: 'lowest' });
200
+ downcastDispatcher.on('attribute', (evt, data, conversionApi) => {
201
+ if (data.item instanceof ModelSelection || data.item instanceof DocumentSelection || data.item.is('$textProxy')) {
202
+ const converter = wrap((modelAttributeValue, { writer }) => {
203
+ return writer.createAttributeElement('model-text-with-attributes', { [data.attributeKey]: stringifyAttributeValue(modelAttributeValue) });
204
+ });
205
+ converter(evt, data, conversionApi);
206
+ }
207
+ });
208
+ downcastDispatcher.on('insert', insertElement(modelItem => {
209
+ // Stringify object types values for properly display as an output string.
210
+ const attributes = convertAttributes(modelItem.getAttributes(), stringifyAttributeValue);
211
+ return new ViewContainerElement(viewDocument, modelItem.name, attributes);
212
+ }));
213
+ downcastDispatcher.on('selection', convertRangeSelection());
214
+ downcastDispatcher.on('selection', convertCollapsedSelection());
215
+ downcastDispatcher.on('addMarker', insertUIElement((data, { writer }) => {
216
+ const name = data.markerName + ':' + (data.isOpening ? 'start' : 'end');
217
+ return writer.createUIElement(name);
218
+ }));
219
+ const markersMap = new Map();
220
+ if (markers) {
221
+ // To provide stable results, sort markers by name.
222
+ for (const marker of Array.from(markers).sort((a, b) => a.name < b.name ? 1 : -1)) {
223
+ markersMap.set(marker.name, marker.getRange());
224
+ }
225
+ }
226
+ // Convert model to view.
227
+ const writer = view._writer;
228
+ downcastDispatcher.convert(range, markersMap, writer);
229
+ // Convert model selection to view selection.
230
+ if (selection) {
231
+ downcastDispatcher.convertSelection(selection, markers || model.markers, writer);
232
+ }
233
+ // Parse view to data string.
234
+ let data = viewStringify(viewRoot, viewDocument.selection, { sameSelectionCharacters: true });
235
+ // Removing unnecessary <div> and </div> added because `viewRoot` was also stringified alongside input data.
236
+ data = data.substr(5, data.length - 11);
237
+ view.destroy();
238
+ // Replace valid XML `model-text-with-attributes` element name to `$text`.
239
+ return data.replace(new RegExp('model-text-with-attributes', 'g'), '$text');
293
240
  }
294
-
295
241
  /**
296
242
  * Parses an HTML-like string and returns the model {@link module:engine/model/rootelement~RootElement rootElement}.
297
243
  *
@@ -310,146 +256,110 @@ export function stringify( node, selectionOrPositionOrRange = null, markers = nu
310
256
  * module:engine/model/documentfragment~DocumentFragment|Object} Returns the parsed model node or
311
257
  * an object with two fields: `model` and `selection`, when selection ranges were included in the data to parse.
312
258
  */
313
- export function parse( data, schema, options = {} ) {
314
- const mapper = new Mapper();
315
-
316
- // Replace not accepted by XML `$text` tag name by valid one `model-text-with-attributes`.
317
- data = data.replace( new RegExp( '\\$text', 'g' ), 'model-text-with-attributes' );
318
-
319
- // Parse data to view using view utils.
320
- const parsedResult = viewParse( data, {
321
- sameSelectionCharacters: true,
322
- lastRangeBackward: !!options.lastRangeBackward
323
- } );
324
-
325
- // Retrieve DocumentFragment and Selection from parsed view.
326
- let viewDocumentFragment, viewSelection, selection;
327
-
328
- if ( parsedResult.view && parsedResult.selection ) {
329
- viewDocumentFragment = parsedResult.view;
330
- viewSelection = parsedResult.selection;
331
- } else {
332
- viewDocumentFragment = parsedResult;
333
- }
334
-
335
- // Set up upcast dispatcher.
336
- const modelController = new Model();
337
- const upcastDispatcher = new UpcastDispatcher( { schema, mapper } );
338
-
339
- upcastDispatcher.on( 'documentFragment', convertToModelFragment() );
340
- upcastDispatcher.on( 'element:model-text-with-attributes', convertToModelText( true ) );
341
- upcastDispatcher.on( 'element', convertToModelElement() );
342
- upcastDispatcher.on( 'text', convertToModelText() );
343
-
344
- upcastDispatcher.isDebug = true;
345
-
346
- // Convert view to model.
347
- let model = modelController.change(
348
- writer => upcastDispatcher.convert( viewDocumentFragment.root, writer, options.context || '$root' )
349
- );
350
-
351
- mapper.bindElements( model, viewDocumentFragment.root );
352
-
353
- // If root DocumentFragment contains only one element - return that element.
354
- if ( model.childCount == 1 ) {
355
- model = model.getChild( 0 );
356
- }
357
-
358
- // Convert view selection to model selection.
359
-
360
- if ( viewSelection ) {
361
- const ranges = [];
362
-
363
- // Convert ranges.
364
- for ( const viewRange of viewSelection.getRanges() ) {
365
- ranges.push( mapper.toModelRange( viewRange ) );
366
- }
367
-
368
- // Create new selection.
369
- selection = new ModelSelection( ranges, { backward: viewSelection.isBackward } );
370
-
371
- // Set attributes to selection if specified.
372
- for ( const [ key, value ] of toMap( options.selectionAttributes || [] ) ) {
373
- selection.setAttribute( key, value );
374
- }
375
- }
376
-
377
- // Return model end selection when selection was specified.
378
- if ( selection ) {
379
- return { model, selection };
380
- }
381
-
382
- // Otherwise return model only.
383
- return model;
259
+ export function parse(data, schema, options = {}) {
260
+ const mapper = new Mapper();
261
+ // Replace not accepted by XML `$text` tag name by valid one `model-text-with-attributes`.
262
+ data = data.replace(new RegExp('\\$text', 'g'), 'model-text-with-attributes');
263
+ // Parse data to view using view utils.
264
+ const parsedResult = viewParse(data, {
265
+ sameSelectionCharacters: true,
266
+ lastRangeBackward: !!options.lastRangeBackward
267
+ });
268
+ // Retrieve DocumentFragment and Selection from parsed view.
269
+ let viewDocumentFragment;
270
+ let viewSelection = null;
271
+ let selection = null;
272
+ if ('view' in parsedResult && 'selection' in parsedResult) {
273
+ viewDocumentFragment = parsedResult.view;
274
+ viewSelection = parsedResult.selection;
275
+ }
276
+ else {
277
+ viewDocumentFragment = parsedResult;
278
+ }
279
+ // Set up upcast dispatcher.
280
+ const modelController = new Model();
281
+ const upcastDispatcher = new UpcastDispatcher({ schema });
282
+ upcastDispatcher.on('documentFragment', convertToModelFragment(mapper));
283
+ upcastDispatcher.on('element:model-text-with-attributes', convertToModelText());
284
+ upcastDispatcher.on('element', convertToModelElement(mapper));
285
+ upcastDispatcher.on('text', convertToModelText());
286
+ // Convert view to model.
287
+ let model = modelController.change(writer => upcastDispatcher.convert(viewDocumentFragment.root, writer, options.context || '$root'));
288
+ mapper.bindElements(model, viewDocumentFragment.root);
289
+ // If root DocumentFragment contains only one element - return that element.
290
+ if (model.childCount == 1) {
291
+ model = model.getChild(0);
292
+ }
293
+ // Convert view selection to model selection.
294
+ if (viewSelection) {
295
+ const ranges = [];
296
+ // Convert ranges.
297
+ for (const viewRange of viewSelection.getRanges()) {
298
+ ranges.push(mapper.toModelRange(viewRange));
299
+ }
300
+ // Create new selection.
301
+ selection = new ModelSelection(ranges, { backward: viewSelection.isBackward });
302
+ // Set attributes to selection if specified.
303
+ for (const [key, value] of toMap(options.selectionAttributes || [])) {
304
+ selection.setAttribute(key, value);
305
+ }
306
+ }
307
+ // Return model end selection when selection was specified.
308
+ if (selection) {
309
+ return { model, selection };
310
+ }
311
+ // Otherwise return model only.
312
+ return model;
384
313
  }
385
-
386
314
  // -- Converters view -> model -----------------------------------------------------
387
-
388
- function convertToModelFragment() {
389
- return ( evt, data, conversionApi ) => {
390
- const childrenResult = conversionApi.convertChildren( data.viewItem, data.modelCursor );
391
-
392
- conversionApi.mapper.bindElements( data.modelCursor.parent, data.viewItem );
393
-
394
- data = Object.assign( data, childrenResult );
395
-
396
- evt.stop();
397
- };
315
+ function convertToModelFragment(mapper) {
316
+ return (evt, data, conversionApi) => {
317
+ const childrenResult = conversionApi.convertChildren(data.viewItem, data.modelCursor);
318
+ mapper.bindElements(data.modelCursor.parent, data.viewItem);
319
+ data = Object.assign(data, childrenResult);
320
+ evt.stop();
321
+ };
398
322
  }
399
-
400
- function convertToModelElement() {
401
- return ( evt, data, conversionApi ) => {
402
- const elementName = data.viewItem.name;
403
-
404
- if ( !conversionApi.schema.checkChild( data.modelCursor, elementName ) ) {
405
- throw new Error( `Element '${ elementName }' was not allowed in given position.` );
406
- }
407
-
408
- // View attribute value is a string so we want to typecast it to the original type.
409
- // E.g. `bold="true"` - value will be parsed from string `"true"` to boolean `true`.
410
- const attributes = convertAttributes( data.viewItem.getAttributes(), parseAttributeValue );
411
- const element = conversionApi.writer.createElement( data.viewItem.name, attributes );
412
-
413
- conversionApi.writer.insert( element, data.modelCursor );
414
-
415
- conversionApi.mapper.bindElements( element, data.viewItem );
416
-
417
- conversionApi.convertChildren( data.viewItem, element );
418
-
419
- data.modelRange = ModelRange._createOn( element );
420
- data.modelCursor = data.modelRange.end;
421
-
422
- evt.stop();
423
- };
323
+ function convertToModelElement(mapper) {
324
+ return (evt, data, conversionApi) => {
325
+ const elementName = data.viewItem.name;
326
+ if (!conversionApi.schema.checkChild(data.modelCursor, elementName)) {
327
+ throw new Error(`Element '${elementName}' was not allowed in given position.`);
328
+ }
329
+ // View attribute value is a string so we want to typecast it to the original type.
330
+ // E.g. `bold="true"` - value will be parsed from string `"true"` to boolean `true`.
331
+ const attributes = convertAttributes(data.viewItem.getAttributes(), parseAttributeValue);
332
+ const element = conversionApi.writer.createElement(data.viewItem.name, attributes);
333
+ conversionApi.writer.insert(element, data.modelCursor);
334
+ mapper.bindElements(element, data.viewItem);
335
+ conversionApi.convertChildren(data.viewItem, element);
336
+ data.modelRange = ModelRange._createOn(element);
337
+ data.modelCursor = data.modelRange.end;
338
+ evt.stop();
339
+ };
424
340
  }
425
-
426
- function convertToModelText( withAttributes = false ) {
427
- return ( evt, data, conversionApi ) => {
428
- if ( !conversionApi.schema.checkChild( data.modelCursor, '$text' ) ) {
429
- throw new Error( 'Text was not allowed in given position.' );
430
- }
431
-
432
- let node;
433
-
434
- if ( withAttributes ) {
435
- // View attribute value is a string so we want to typecast it to the original type.
436
- // E.g. `bold="true"` - value will be parsed from string `"true"` to boolean `true`.
437
- const attributes = convertAttributes( data.viewItem.getAttributes(), parseAttributeValue );
438
-
439
- node = conversionApi.writer.createText( data.viewItem.getChild( 0 ).data, attributes );
440
- } else {
441
- node = conversionApi.writer.createText( data.viewItem.data );
442
- }
443
-
444
- conversionApi.writer.insert( node, data.modelCursor );
445
-
446
- data.modelRange = ModelRange._createFromPositionAndShift( data.modelCursor, node.offsetSize );
447
- data.modelCursor = data.modelRange.end;
448
-
449
- evt.stop();
450
- };
341
+ function convertToModelText() {
342
+ return (evt, data, conversionApi) => {
343
+ if (!conversionApi.schema.checkChild(data.modelCursor, '$text')) {
344
+ throw new Error('Text was not allowed in given position.');
345
+ }
346
+ let node;
347
+ if (data.viewItem.is('element')) {
348
+ // View attribute value is a string so we want to typecast it to the original type.
349
+ // E.g. `bold="true"` - value will be parsed from string `"true"` to boolean `true`.
350
+ const attributes = convertAttributes(data.viewItem.getAttributes(), parseAttributeValue);
351
+ const viewText = data.viewItem.getChild(0);
352
+ node = conversionApi.writer.createText(viewText.data, attributes);
353
+ }
354
+ else {
355
+ node = conversionApi.writer.createText(data.viewItem.data);
356
+ }
357
+ conversionApi.writer.insert(node, data.modelCursor);
358
+ data.modelRange = ModelRange._createFromPositionAndShift(data.modelCursor, node.offsetSize);
359
+ data.modelCursor = data.modelRange.end;
360
+ evt.stop();
361
+ };
451
362
  }
452
-
453
363
  // Tries to get original type of attribute value using JSON parsing:
454
364
  //
455
365
  // `'true'` => `true`
@@ -459,26 +369,24 @@ function convertToModelText( withAttributes = false ) {
459
369
  // Parse error means that value should be a string:
460
370
  //
461
371
  // `'foobar'` => `'foobar'`
462
- function parseAttributeValue( attribute ) {
463
- try {
464
- return JSON.parse( attribute );
465
- } catch ( e ) {
466
- return attribute;
467
- }
372
+ function parseAttributeValue(attribute) {
373
+ try {
374
+ return JSON.parse(attribute);
375
+ }
376
+ catch (e) {
377
+ return attribute;
378
+ }
468
379
  }
469
-
470
380
  // When value is an Object stringify it.
471
- function stringifyAttributeValue( data ) {
472
- if ( isPlainObject( data ) ) {
473
- return JSON.stringify( data );
474
- }
475
-
476
- return data;
381
+ function stringifyAttributeValue(data) {
382
+ if (isPlainObject(data)) {
383
+ return JSON.stringify(data);
384
+ }
385
+ return data;
477
386
  }
478
-
479
387
  // Loop trough attributes map and converts each value by passed converter.
480
- function* convertAttributes( attributes, converter ) {
481
- for ( const [ key, value ] of attributes ) {
482
- yield [ key, converter( value ) ];
483
- }
388
+ function* convertAttributes(attributes, converter) {
389
+ for (const [key, value] of attributes) {
390
+ yield [key, converter(value)];
391
+ }
484
392
  }