@ckeditor/ckeditor5-engine 35.0.1 → 35.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +175 -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 +899 -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 +654 -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 +191 -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,21 +2,16 @@
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/model/schema
8
7
  */
9
-
10
- import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
11
- import ObservableMixin from '@ckeditor/ckeditor5-utils/src/observablemixin';
12
- import mix from '@ckeditor/ckeditor5-utils/src/mix';
13
-
14
- import Range from './range';
15
- import Position from './position';
16
8
  import Element from './element';
9
+ import Position from './position';
10
+ import Range from './range';
17
11
  import Text from './text';
18
12
  import TreeWalker from './treewalker';
19
-
13
+ import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
14
+ import { Observable } from '@ckeditor/ckeditor5-utils/src/observablemixin';
20
15
  /**
21
16
  * The model's schema. It defines the allowed and disallowed structures of nodes as well as nodes' attributes.
22
17
  * The schema is usually defined by the features and based on them, the editing framework and features
@@ -32,1358 +27,887 @@ import TreeWalker from './treewalker';
32
27
  *
33
28
  * @mixes module:utils/observablemixin~ObservableMixin
34
29
  */
35
- export default class Schema {
36
- /**
37
- * Creates a schema instance.
38
- */
39
- constructor() {
40
- this._sourceDefinitions = {};
41
-
42
- /**
43
- * A dictionary containing attribute properties.
44
- *
45
- * @private
46
- * @member {Object.<String,String>}
47
- */
48
- this._attributeProperties = {};
49
-
50
- this.decorate( 'checkChild' );
51
- this.decorate( 'checkAttribute' );
52
-
53
- this.on( 'checkAttribute', ( evt, args ) => {
54
- args[ 0 ] = new SchemaContext( args[ 0 ] );
55
- }, { priority: 'highest' } );
56
-
57
- this.on( 'checkChild', ( evt, args ) => {
58
- args[ 0 ] = new SchemaContext( args[ 0 ] );
59
- args[ 1 ] = this.getDefinition( args[ 1 ] );
60
- }, { priority: 'highest' } );
61
- }
62
-
63
- /**
64
- * Registers a schema item. Can only be called once for every item name.
65
- *
66
- * schema.register( 'paragraph', {
67
- * inheritAllFrom: '$block'
68
- * } );
69
- *
70
- * @param {String} itemName
71
- * @param {module:engine/model/schema~SchemaItemDefinition} definition
72
- */
73
- register( itemName, definition ) {
74
- if ( this._sourceDefinitions[ itemName ] ) {
75
- /**
76
- * A single item cannot be registered twice in the schema.
77
- *
78
- * This situation may happen when:
79
- *
80
- * * Two or more plugins called {@link #register `register()`} with the same name. This will usually mean that
81
- * there is a collision between plugins which try to use the same element in the model. Unfortunately,
82
- * the only way to solve this is by modifying one of these plugins to use a unique model element name.
83
- * * A single plugin was loaded twice. This happens when it is installed by npm/yarn in two versions
84
- * and usually means one or more of the following issues:
85
- * * a version mismatch (two of your dependencies require two different versions of this plugin),
86
- * * incorrect imports (this plugin is somehow imported twice in a way which confuses webpack),
87
- * * mess in `node_modules/` (`rm -rf node_modules/` may help).
88
- *
89
- * **Note:** Check the logged `itemName` to better understand which plugin was duplicated/conflicting.
90
- *
91
- * @param itemName The name of the model element that is being registered twice.
92
- * @error schema-cannot-register-item-twice
93
- */
94
- throw new CKEditorError(
95
- 'schema-cannot-register-item-twice',
96
- this,
97
- {
98
- itemName
99
- }
100
- );
101
- }
102
-
103
- this._sourceDefinitions[ itemName ] = [
104
- Object.assign( {}, definition )
105
- ];
106
-
107
- this._clearCache();
108
- }
109
-
110
- /**
111
- * Extends a {@link #register registered} item's definition.
112
- *
113
- * Extending properties such as `allowIn` will add more items to the existing properties,
114
- * while redefining properties such as `isBlock` will override the previously defined ones.
115
- *
116
- * schema.register( 'foo', {
117
- * allowIn: '$root',
118
- * isBlock: true;
119
- * } );
120
- * schema.extend( 'foo', {
121
- * allowIn: 'blockQuote',
122
- * isBlock: false
123
- * } );
124
- *
125
- * schema.getDefinition( 'foo' );
126
- * // {
127
- * // allowIn: [ '$root', 'blockQuote' ],
128
- * // isBlock: false
129
- * // }
130
- *
131
- * @param {String} itemName
132
- * @param {module:engine/model/schema~SchemaItemDefinition} definition
133
- */
134
- extend( itemName, definition ) {
135
- if ( !this._sourceDefinitions[ itemName ] ) {
136
- /**
137
- * Cannot extend an item which was not registered yet.
138
- *
139
- * This error happens when a plugin tries to extend the schema definition of an item which was not
140
- * {@link #register registered} yet.
141
- *
142
- * @param itemName The name of the model element which is being extended.
143
- * @error schema-cannot-extend-missing-item
144
- */
145
- throw new CKEditorError( 'schema-cannot-extend-missing-item', this, {
146
- itemName
147
- } );
148
- }
149
-
150
- this._sourceDefinitions[ itemName ].push( Object.assign( {}, definition ) );
151
-
152
- this._clearCache();
153
- }
154
-
155
- /**
156
- * Returns data of all registered items.
157
- *
158
- * This method should normally be used for reflection purposes (e.g. defining a clone of a certain element,
159
- * checking a list of all block elements, etc).
160
- * Use specific methods (such as {@link #checkChild `checkChild()`} or {@link #isLimit `isLimit()`})
161
- * in other cases.
162
- *
163
- * @returns {Object.<String,module:engine/model/schema~SchemaCompiledItemDefinition>}
164
- */
165
- getDefinitions() {
166
- if ( !this._compiledDefinitions ) {
167
- this._compile();
168
- }
169
-
170
- return this._compiledDefinitions;
171
- }
172
-
173
- /**
174
- * Returns a definition of the given item or `undefined` if an item is not registered.
175
- *
176
- * This method should normally be used for reflection purposes (e.g. defining a clone of a certain element,
177
- * checking a list of all block elements, etc).
178
- * Use specific methods (such as {@link #checkChild `checkChild()`} or {@link #isLimit `isLimit()`})
179
- * in other cases.
180
- *
181
- * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
182
- * @returns {module:engine/model/schema~SchemaCompiledItemDefinition}
183
- */
184
- getDefinition( item ) {
185
- let itemName;
186
-
187
- if ( typeof item == 'string' ) {
188
- itemName = item;
189
- } else if ( item.is && ( item.is( '$text' ) || item.is( '$textProxy' ) ) ) {
190
- itemName = '$text';
191
- }
192
- // Element or module:engine/model/schema~SchemaContextItem.
193
- else {
194
- itemName = item.name;
195
- }
196
-
197
- return this.getDefinitions()[ itemName ];
198
- }
199
-
200
- /**
201
- * Returns `true` if the given item is registered in the schema.
202
- *
203
- * schema.isRegistered( 'paragraph' ); // -> true
204
- * schema.isRegistered( editor.model.document.getRoot() ); // -> true
205
- * schema.isRegistered( 'foo' ); // -> false
206
- *
207
- * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
208
- * @returns {Boolean}
209
- */
210
- isRegistered( item ) {
211
- return !!this.getDefinition( item );
212
- }
213
-
214
- /**
215
- * Returns `true` if the given item is defined to be
216
- * a block by the {@link module:engine/model/schema~SchemaItemDefinition}'s `isBlock` property.
217
- *
218
- * schema.isBlock( 'paragraph' ); // -> true
219
- * schema.isBlock( '$root' ); // -> false
220
- *
221
- * const paragraphElement = writer.createElement( 'paragraph' );
222
- * schema.isBlock( paragraphElement ); // -> true
223
- *
224
- * See the {@glink framework/guides/deep-dive/schema#block-elements Block elements} section of
225
- * the {@glink framework/guides/deep-dive/schema Schema deep dive} guide for more details.
226
- *
227
- * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
228
- * @returns {Boolean}
229
- */
230
- isBlock( item ) {
231
- const def = this.getDefinition( item );
232
-
233
- return !!( def && def.isBlock );
234
- }
235
-
236
- /**
237
- * Returns `true` if the given item should be treated as a limit element.
238
- *
239
- * It considers an item to be a limit element if its
240
- * {@link module:engine/model/schema~SchemaItemDefinition}'s
241
- * {@link module:engine/model/schema~SchemaItemDefinition#isLimit `isLimit`} or
242
- * {@link module:engine/model/schema~SchemaItemDefinition#isObject `isObject`} property
243
- * was set to `true`.
244
- *
245
- * schema.isLimit( 'paragraph' ); // -> false
246
- * schema.isLimit( '$root' ); // -> true
247
- * schema.isLimit( editor.model.document.getRoot() ); // -> true
248
- * schema.isLimit( 'imageBlock' ); // -> true
249
- *
250
- * See the {@glink framework/guides/deep-dive/schema#limit-elements Limit elements} section of
251
- * the {@glink framework/guides/deep-dive/schema Schema deep dive} guide for more details.
252
- *
253
- * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
254
- * @returns {Boolean}
255
- */
256
- isLimit( item ) {
257
- const def = this.getDefinition( item );
258
-
259
- if ( !def ) {
260
- return false;
261
- }
262
-
263
- return !!( def.isLimit || def.isObject );
264
- }
265
-
266
- /**
267
- * Returns `true` if the given item should be treated as an object element.
268
- *
269
- * It considers an item to be an object element if its
270
- * {@link module:engine/model/schema~SchemaItemDefinition}'s
271
- * {@link module:engine/model/schema~SchemaItemDefinition#isObject `isObject`} property
272
- * was set to `true`.
273
- *
274
- * schema.isObject( 'paragraph' ); // -> false
275
- * schema.isObject( 'imageBlock' ); // -> true
276
- *
277
- * const imageElement = writer.createElement( 'imageBlock' );
278
- * schema.isObject( imageElement ); // -> true
279
- *
280
- * See the {@glink framework/guides/deep-dive/schema#object-elements Object elements} section of
281
- * the {@glink framework/guides/deep-dive/schema Schema deep dive} guide for more details.
282
- *
283
- * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
284
- * @returns {Boolean}
285
- */
286
- isObject( item ) {
287
- const def = this.getDefinition( item );
288
-
289
- if ( !def ) {
290
- return false;
291
- }
292
-
293
- // Note: Check out the implementation of #isLimit(), #isSelectable(), and #isContent()
294
- // to understand why these three constitute an object.
295
- return !!( def.isObject || ( def.isLimit && def.isSelectable && def.isContent ) );
296
- }
297
-
298
- /**
299
- * Returns `true` if the given item is defined to be
300
- * an inline element by the {@link module:engine/model/schema~SchemaItemDefinition}'s `isInline` property.
301
- *
302
- * schema.isInline( 'paragraph' ); // -> false
303
- * schema.isInline( 'softBreak' ); // -> true
304
- *
305
- * const text = writer.createText( 'foo' );
306
- * schema.isInline( text ); // -> true
307
- *
308
- * See the {@glink framework/guides/deep-dive/schema#inline-elements Inline elements} section of
309
- * the {@glink framework/guides/deep-dive/schema Schema deep dive} guide for more details.
310
- *
311
- * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
312
- * @returns {Boolean}
313
- */
314
- isInline( item ) {
315
- const def = this.getDefinition( item );
316
-
317
- return !!( def && def.isInline );
318
- }
319
-
320
- /**
321
- * Returns `true` if the given item is defined to be
322
- * a selectable element by the {@link module:engine/model/schema~SchemaItemDefinition}'s `isSelectable` property.
323
- *
324
- * schema.isSelectable( 'paragraph' ); // -> false
325
- * schema.isSelectable( 'heading1' ); // -> false
326
- * schema.isSelectable( 'imageBlock' ); // -> true
327
- * schema.isSelectable( 'tableCell' ); // -> true
328
- *
329
- * const text = writer.createText( 'foo' );
330
- * schema.isSelectable( text ); // -> false
331
- *
332
- * See the {@glink framework/guides/deep-dive/schema#selectable-elements Selectable elements section} of
333
- * the {@glink framework/guides/deep-dive/schema Schema deep dive} guide for more details.
334
- *
335
- * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
336
- * @returns {Boolean}
337
- */
338
- isSelectable( item ) {
339
- const def = this.getDefinition( item );
340
-
341
- if ( !def ) {
342
- return false;
343
- }
344
-
345
- return !!( def.isSelectable || def.isObject );
346
- }
347
-
348
- /**
349
- * Returns `true` if the given item is defined to be
350
- * a content by the {@link module:engine/model/schema~SchemaItemDefinition}'s `isContent` property.
351
- *
352
- * schema.isContent( 'paragraph' ); // -> false
353
- * schema.isContent( 'heading1' ); // -> false
354
- * schema.isContent( 'imageBlock' ); // -> true
355
- * schema.isContent( 'horizontalLine' ); // -> true
356
- *
357
- * const text = writer.createText( 'foo' );
358
- * schema.isContent( text ); // -> true
359
- *
360
- * See the {@glink framework/guides/deep-dive/schema#content-elements Content elements section} of
361
- * the {@glink framework/guides/deep-dive/schema Schema deep dive} guide for more details.
362
- *
363
- * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
364
- * @returns {Boolean}
365
- */
366
- isContent( item ) {
367
- const def = this.getDefinition( item );
368
-
369
- if ( !def ) {
370
- return false;
371
- }
372
-
373
- return !!( def.isContent || def.isObject );
374
- }
375
-
376
- /**
377
- * Checks whether the given node (`child`) can be a child of the given context.
378
- *
379
- * schema.checkChild( model.document.getRoot(), paragraph ); // -> false
380
- *
381
- * schema.register( 'paragraph', {
382
- * allowIn: '$root'
383
- * } );
384
- * schema.checkChild( model.document.getRoot(), paragraph ); // -> true
385
- *
386
- * Note: When verifying whether the given node can be a child of the given context, the
387
- * schema also verifies the entire context &mdash; from its root to its last element. Therefore, it is possible
388
- * for `checkChild()` to return `false` even though the context's last element can contain the checked child.
389
- * It happens if one of the context's elements does not allow its child.
390
- *
391
- * @fires checkChild
392
- * @param {module:engine/model/schema~SchemaContextDefinition} context The context in which the child will be checked.
393
- * @param {module:engine/model/node~Node|String} def The child to check.
394
- * @returns {Boolean}
395
- */
396
- checkChild( context, def ) {
397
- // Note: context and child are already normalized here to a SchemaContext and SchemaCompiledItemDefinition.
398
- if ( !def ) {
399
- return false;
400
- }
401
-
402
- return this._checkContextMatch( def, context );
403
- }
404
-
405
- /**
406
- * Checks whether the given attribute can be applied in the given context (on the last
407
- * item of the context).
408
- *
409
- * schema.checkAttribute( textNode, 'bold' ); // -> false
410
- *
411
- * schema.extend( '$text', {
412
- * allowAttributes: 'bold'
413
- * } );
414
- * schema.checkAttribute( textNode, 'bold' ); // -> true
415
- *
416
- * @fires checkAttribute
417
- * @param {module:engine/model/schema~SchemaContextDefinition} context The context in which the attribute will be checked.
418
- * @param {String} attributeName
419
- * @returns {Boolean}
420
- */
421
- checkAttribute( context, attributeName ) {
422
- const def = this.getDefinition( context.last );
423
-
424
- if ( !def ) {
425
- return false;
426
- }
427
-
428
- return def.allowAttributes.includes( attributeName );
429
- }
430
-
431
- /**
432
- * Checks whether the given element (`elementToMerge`) can be merged with the specified base element (`positionOrBaseElement`).
433
- *
434
- * In other words &mdash; whether `elementToMerge`'s children {@link #checkChild are allowed} in the `positionOrBaseElement`.
435
- *
436
- * This check ensures that elements merged with {@link module:engine/model/writer~Writer#merge `Writer#merge()`}
437
- * will be valid.
438
- *
439
- * Instead of elements, you can pass the instance of the {@link module:engine/model/position~Position} class as the
440
- * `positionOrBaseElement`. It means that the elements before and after the position will be checked whether they can be merged.
441
- *
442
- * @param {module:engine/model/position~Position|module:engine/model/element~Element} positionOrBaseElement The position or base
443
- * element to which the `elementToMerge` will be merged.
444
- * @param {module:engine/model/element~Element} elementToMerge The element to merge. Required if `positionOrBaseElement` is an element.
445
- * @returns {Boolean}
446
- */
447
- checkMerge( positionOrBaseElement, elementToMerge = null ) {
448
- if ( positionOrBaseElement instanceof Position ) {
449
- const nodeBefore = positionOrBaseElement.nodeBefore;
450
- const nodeAfter = positionOrBaseElement.nodeAfter;
451
-
452
- if ( !( nodeBefore instanceof Element ) ) {
453
- /**
454
- * The node before the merge position must be an element.
455
- *
456
- * @error schema-check-merge-no-element-before
457
- */
458
- throw new CKEditorError(
459
- 'schema-check-merge-no-element-before',
460
- this
461
- );
462
- }
463
-
464
- if ( !( nodeAfter instanceof Element ) ) {
465
- /**
466
- * The node after the merge position must be an element.
467
- *
468
- * @error schema-check-merge-no-element-after
469
- */
470
- throw new CKEditorError(
471
- 'schema-check-merge-no-element-after',
472
- this
473
- );
474
- }
475
-
476
- return this.checkMerge( nodeBefore, nodeAfter );
477
- }
478
-
479
- for ( const child of elementToMerge.getChildren() ) {
480
- if ( !this.checkChild( positionOrBaseElement, child ) ) {
481
- return false;
482
- }
483
- }
484
-
485
- return true;
486
- }
487
-
488
- /**
489
- * Allows registering a callback to the {@link #checkChild} method calls.
490
- *
491
- * Callbacks allow you to implement rules which are not otherwise possible to achieve
492
- * by using the declarative API of {@link module:engine/model/schema~SchemaItemDefinition}.
493
- * For example, by using this method you can disallow elements in specific contexts.
494
- *
495
- * This method is a shorthand for using the {@link #event:checkChild} event. For even better control,
496
- * you can use that event instead.
497
- *
498
- * Example:
499
- *
500
- * // Disallow heading1 directly inside a blockQuote.
501
- * schema.addChildCheck( ( context, childDefinition ) => {
502
- * if ( context.endsWith( 'blockQuote' ) && childDefinition.name == 'heading1' ) {
503
- * return false;
504
- * }
505
- * } );
506
- *
507
- * Which translates to:
508
- *
509
- * schema.on( 'checkChild', ( evt, args ) => {
510
- * const context = args[ 0 ];
511
- * const childDefinition = args[ 1 ];
512
- *
513
- * if ( context.endsWith( 'blockQuote' ) && childDefinition && childDefinition.name == 'heading1' ) {
514
- * // Prevent next listeners from being called.
515
- * evt.stop();
516
- * // Set the checkChild()'s return value.
517
- * evt.return = false;
518
- * }
519
- * }, { priority: 'high' } );
520
- *
521
- * @param {Function} callback The callback to be called. It is called with two parameters:
522
- * {@link module:engine/model/schema~SchemaContext} (context) instance and
523
- * {@link module:engine/model/schema~SchemaCompiledItemDefinition} (child-to-check definition).
524
- * The callback may return `true/false` to override `checkChild()`'s return value. If it does not return
525
- * a boolean value, the default algorithm (or other callbacks) will define `checkChild()`'s return value.
526
- */
527
- addChildCheck( callback ) {
528
- this.on( 'checkChild', ( evt, [ ctx, childDef ] ) => {
529
- // checkChild() was called with a non-registered child.
530
- // In 99% cases such check should return false, so not to overcomplicate all callbacks
531
- // don't even execute them.
532
- if ( !childDef ) {
533
- return;
534
- }
535
-
536
- const retValue = callback( ctx, childDef );
537
-
538
- if ( typeof retValue == 'boolean' ) {
539
- evt.stop();
540
- evt.return = retValue;
541
- }
542
- }, { priority: 'high' } );
543
- }
544
-
545
- /**
546
- * Allows registering a callback to the {@link #checkAttribute} method calls.
547
- *
548
- * Callbacks allow you to implement rules which are not otherwise possible to achieve
549
- * by using the declarative API of {@link module:engine/model/schema~SchemaItemDefinition}.
550
- * For example, by using this method you can disallow attribute if node to which it is applied
551
- * is contained within some other element (e.g. you want to disallow `bold` on `$text` within `heading1`).
552
- *
553
- * This method is a shorthand for using the {@link #event:checkAttribute} event. For even better control,
554
- * you can use that event instead.
555
- *
556
- * Example:
557
- *
558
- * // Disallow bold on $text inside heading1.
559
- * schema.addAttributeCheck( ( context, attributeName ) => {
560
- * if ( context.endsWith( 'heading1 $text' ) && attributeName == 'bold' ) {
561
- * return false;
562
- * }
563
- * } );
564
- *
565
- * Which translates to:
566
- *
567
- * schema.on( 'checkAttribute', ( evt, args ) => {
568
- * const context = args[ 0 ];
569
- * const attributeName = args[ 1 ];
570
- *
571
- * if ( context.endsWith( 'heading1 $text' ) && attributeName == 'bold' ) {
572
- * // Prevent next listeners from being called.
573
- * evt.stop();
574
- * // Set the checkAttribute()'s return value.
575
- * evt.return = false;
576
- * }
577
- * }, { priority: 'high' } );
578
- *
579
- * @param {Function} callback The callback to be called. It is called with two parameters:
580
- * {@link module:engine/model/schema~SchemaContext} (context) instance and attribute name.
581
- * The callback may return `true/false` to override `checkAttribute()`'s return value. If it does not return
582
- * a boolean value, the default algorithm (or other callbacks) will define `checkAttribute()`'s return value.
583
- */
584
- addAttributeCheck( callback ) {
585
- this.on( 'checkAttribute', ( evt, [ ctx, attributeName ] ) => {
586
- const retValue = callback( ctx, attributeName );
587
-
588
- if ( typeof retValue == 'boolean' ) {
589
- evt.stop();
590
- evt.return = retValue;
591
- }
592
- }, { priority: 'high' } );
593
- }
594
-
595
- /**
596
- * This method allows assigning additional metadata to the model attributes. For example,
597
- * {@link module:engine/model/schema~AttributeProperties `AttributeProperties#isFormatting` property} is
598
- * used to mark formatting attributes (like `bold` or `italic`).
599
- *
600
- * // Mark bold as a formatting attribute.
601
- * schema.setAttributeProperties( 'bold', {
602
- * isFormatting: true
603
- * } );
604
- *
605
- * // Override code not to be considered a formatting markup.
606
- * schema.setAttributeProperties( 'code', {
607
- * isFormatting: false
608
- * } );
609
- *
610
- * Properties are not limited to members defined in the
611
- * {@link module:engine/model/schema~AttributeProperties `AttributeProperties` type} and you can also use custom properties:
612
- *
613
- * schema.setAttributeProperties( 'blockQuote', {
614
- * customProperty: 'value'
615
- * } );
616
- *
617
- * Subsequent calls with the same attribute will extend its custom properties:
618
- *
619
- * schema.setAttributeProperties( 'blockQuote', {
620
- * one: 1
621
- * } );
622
- *
623
- * schema.setAttributeProperties( 'blockQuote', {
624
- * two: 2
625
- * } );
626
- *
627
- * console.log( schema.getAttributeProperties( 'blockQuote' ) );
628
- * // Logs: { one: 1, two: 2 }
629
- *
630
- * @param {String} attributeName A name of the attribute to receive the properties.
631
- * @param {module:engine/model/schema~AttributeProperties} properties A dictionary of properties.
632
- */
633
- setAttributeProperties( attributeName, properties ) {
634
- this._attributeProperties[ attributeName ] = Object.assign( this.getAttributeProperties( attributeName ), properties );
635
- }
636
-
637
- /**
638
- * Returns properties associated with a given model attribute. See {@link #setAttributeProperties `setAttributeProperties()`}.
639
- *
640
- * @param {String} attributeName A name of the attribute.
641
- * @returns {module:engine/model/schema~AttributeProperties}
642
- */
643
- getAttributeProperties( attributeName ) {
644
- return this._attributeProperties[ attributeName ] || {};
645
- }
646
-
647
- /**
648
- * Returns the lowest {@link module:engine/model/schema~Schema#isLimit limit element} containing the entire
649
- * selection/range/position or the root otherwise.
650
- *
651
- * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection|
652
- * module:engine/model/range~Range|module:engine/model/position~Position} selectionOrRangeOrPosition
653
- * The selection/range/position to check.
654
- * @returns {module:engine/model/element~Element} The lowest limit element containing
655
- * the entire `selectionOrRangeOrPosition`.
656
- */
657
- getLimitElement( selectionOrRangeOrPosition ) {
658
- let element;
659
-
660
- if ( selectionOrRangeOrPosition instanceof Position ) {
661
- element = selectionOrRangeOrPosition.parent;
662
- } else {
663
- const ranges = selectionOrRangeOrPosition instanceof Range ?
664
- [ selectionOrRangeOrPosition ] :
665
- Array.from( selectionOrRangeOrPosition.getRanges() );
666
-
667
- // Find the common ancestor for all selection's ranges.
668
- element = ranges
669
- .reduce( ( element, range ) => {
670
- const rangeCommonAncestor = range.getCommonAncestor();
671
-
672
- if ( !element ) {
673
- return rangeCommonAncestor;
674
- }
675
-
676
- return element.getCommonAncestor( rangeCommonAncestor, { includeSelf: true } );
677
- }, null );
678
- }
679
-
680
- while ( !this.isLimit( element ) ) {
681
- if ( element.parent ) {
682
- element = element.parent;
683
- } else {
684
- break;
685
- }
686
- }
687
-
688
- return element;
689
- }
690
-
691
- /**
692
- * Checks whether the attribute is allowed in selection:
693
- *
694
- * * if the selection is not collapsed, then checks if the attribute is allowed on any of nodes in that range,
695
- * * if the selection is collapsed, then checks if on the selection position there's a text with the
696
- * specified attribute allowed.
697
- *
698
- * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection} selection
699
- * Selection which will be checked.
700
- * @param {String} attribute The name of the attribute to check.
701
- * @returns {Boolean}
702
- */
703
- checkAttributeInSelection( selection, attribute ) {
704
- if ( selection.isCollapsed ) {
705
- const firstPosition = selection.getFirstPosition();
706
- const context = [
707
- ...firstPosition.getAncestors(),
708
- new Text( '', selection.getAttributes() )
709
- ];
710
-
711
- // Check whether schema allows for a text with the attribute in the selection.
712
- return this.checkAttribute( context, attribute );
713
- } else {
714
- const ranges = selection.getRanges();
715
-
716
- // For all ranges, check nodes in them until you find a node that is allowed to have the attribute.
717
- for ( const range of ranges ) {
718
- for ( const value of range ) {
719
- if ( this.checkAttribute( value.item, attribute ) ) {
720
- // If we found a node that is allowed to have the attribute, return true.
721
- return true;
722
- }
723
- }
724
- }
725
- }
726
-
727
- // If we haven't found such node, return false.
728
- return false;
729
- }
730
-
731
- /**
732
- * Transforms the given set of ranges into a set of ranges where the given attribute is allowed (and can be applied).
733
- *
734
- * @param {Array.<module:engine/model/range~Range>} ranges Ranges to be validated.
735
- * @param {String} attribute The name of the attribute to check.
736
- * @returns {Iterable.<module:engine/model/range~Range>} Ranges in which the attribute is allowed.
737
- */
738
- * getValidRanges( ranges, attribute ) {
739
- ranges = convertToMinimalFlatRanges( ranges );
740
-
741
- for ( const range of ranges ) {
742
- yield* this._getValidRangesForRange( range, attribute );
743
- }
744
- }
745
-
746
- /**
747
- * Basing on given `position`, finds and returns a {@link module:engine/model/range~Range range} which is
748
- * nearest to that `position` and is a correct range for selection.
749
- *
750
- * The correct selection range might be collapsed when it is located in a position where the text node can be placed.
751
- * Non-collapsed range is returned when selection can be placed around element marked as an "object" in
752
- * the {@link module:engine/model/schema~Schema schema}.
753
- *
754
- * Direction of searching for the nearest correct selection range can be specified as:
755
- *
756
- * * `both` - searching will be performed in both ways,
757
- * * `forward` - searching will be performed only forward,
758
- * * `backward` - searching will be performed only backward.
759
- *
760
- * When valid selection range cannot be found, `null` is returned.
761
- *
762
- * @param {module:engine/model/position~Position} position Reference position where new selection range should be looked for.
763
- * @param {'both'|'forward'|'backward'} [direction='both'] Search direction.
764
- * @returns {module:engine/model/range~Range|null} Nearest selection range or `null` if one cannot be found.
765
- */
766
- getNearestSelectionRange( position, direction = 'both' ) {
767
- // Return collapsed range if provided position is valid.
768
- if ( this.checkChild( position, '$text' ) ) {
769
- return new Range( position );
770
- }
771
-
772
- let backwardWalker, forwardWalker;
773
-
774
- // Never leave a limit element.
775
- const limitElement = position.getAncestors().reverse().find( item => this.isLimit( item ) ) || position.root;
776
-
777
- if ( direction == 'both' || direction == 'backward' ) {
778
- backwardWalker = new TreeWalker( {
779
- boundaries: Range._createIn( limitElement ),
780
- startPosition: position,
781
- direction: 'backward'
782
- } );
783
- }
784
-
785
- if ( direction == 'both' || direction == 'forward' ) {
786
- forwardWalker = new TreeWalker( {
787
- boundaries: Range._createIn( limitElement ),
788
- startPosition: position
789
- } );
790
- }
791
-
792
- for ( const data of combineWalkers( backwardWalker, forwardWalker ) ) {
793
- const type = ( data.walker == backwardWalker ? 'elementEnd' : 'elementStart' );
794
- const value = data.value;
795
-
796
- if ( value.type == type && this.isObject( value.item ) ) {
797
- return Range._createOn( value.item );
798
- }
799
-
800
- if ( this.checkChild( value.nextPosition, '$text' ) ) {
801
- return new Range( value.nextPosition );
802
- }
803
- }
804
-
805
- return null;
806
- }
807
-
808
- /**
809
- * Tries to find position ancestors that allow to insert a given node.
810
- * It starts searching from the given position and goes node by node to the top of the model tree
811
- * as long as a {@link module:engine/model/schema~Schema#isLimit limit element}, an
812
- * {@link module:engine/model/schema~Schema#isObject object element} or a topmost ancestor is not reached.
813
- *
814
- * @param {module:engine/model/position~Position} position The position that the search will start from.
815
- * @param {module:engine/model/node~Node|String} node The node for which an allowed parent should be found or its name.
816
- * @returns {module:engine/model/element~Element|null} element Allowed parent or null if nothing was found.
817
- */
818
- findAllowedParent( position, node ) {
819
- let parent = position.parent;
820
-
821
- while ( parent ) {
822
- if ( this.checkChild( parent, node ) ) {
823
- return parent;
824
- }
825
-
826
- // Do not split limit elements.
827
- if ( this.isLimit( parent ) ) {
828
- return null;
829
- }
830
-
831
- parent = parent.parent;
832
- }
833
-
834
- return null;
835
- }
836
-
837
- /**
838
- * Sets attributes allowed by the schema on a given node.
839
- *
840
- * @param {module:engine/model/node~Node} node A node to set attributes on.
841
- * @param {Object} attributes Attributes keys and values.
842
- * @param {module:engine/model/writer~Writer} writer An instance of the model writer.
843
- */
844
- setAllowedAttributes( node, attributes, writer ) {
845
- const model = writer.model;
846
-
847
- for ( const [ attributeName, attributeValue ] of Object.entries( attributes ) ) {
848
- if ( model.schema.checkAttribute( node, attributeName ) ) {
849
- writer.setAttribute( attributeName, attributeValue, node );
850
- }
851
- }
852
- }
853
-
854
- /**
855
- * Removes attributes disallowed by the schema.
856
- *
857
- * @param {Iterable.<module:engine/model/node~Node>} nodes Nodes that will be filtered.
858
- * @param {module:engine/model/writer~Writer} writer
859
- */
860
- removeDisallowedAttributes( nodes, writer ) {
861
- for ( const node of nodes ) {
862
- // When node is a `Text` it has no children, so just filter it out.
863
- if ( node.is( '$text' ) ) {
864
- removeDisallowedAttributeFromNode( this, node, writer );
865
- }
866
- // In a case of `Element` iterates through positions between nodes inside this element
867
- // and filter out node before the current position, or position parent when position
868
- // is at start of an element. Using positions prevent from omitting merged nodes
869
- // see https://github.com/ckeditor/ckeditor5-engine/issues/1789.
870
- else {
871
- const rangeInNode = Range._createIn( node );
872
- const positionsInRange = rangeInNode.getPositions();
873
-
874
- for ( const position of positionsInRange ) {
875
- const item = position.nodeBefore || position.parent;
876
-
877
- removeDisallowedAttributeFromNode( this, item, writer );
878
- }
879
- }
880
- }
881
- }
882
-
883
- /**
884
- * Gets attributes of a node that have a given property.
885
- *
886
- * @param {module:engine/model/node~Node} node Node to get attributes from.
887
- * @param {String} propertyName Name of the property that attribute must have to return it.
888
- * @param {Boolean|Symbol|String|Number|Object|null|undefined} propertyValue Desired value of the property that we want to check.
889
- * When `undefined` attributes will be returned if they have set a given property no matter what the value is. If specified it will
890
- * return attributes which given property's value is equal to this parameter.
891
- * @returns {Object} Object with attributes' names as key and attributes' values as value.
892
- */
893
- getAttributesWithProperty( node, propertyName, propertyValue ) {
894
- const attributes = {};
895
-
896
- for ( const [ attributeName, attributeValue ] of node.getAttributes() ) {
897
- const attributeProperties = this.getAttributeProperties( attributeName );
898
-
899
- if ( attributeProperties[ propertyName ] === undefined ) {
900
- continue;
901
- }
902
-
903
- if ( propertyValue === undefined || propertyValue === attributeProperties[ propertyName ] ) {
904
- attributes[ attributeName ] = attributeValue;
905
- }
906
- }
907
-
908
- return attributes;
909
- }
910
-
911
- /**
912
- * Creates an instance of the schema context.
913
- *
914
- * @param {module:engine/model/schema~SchemaContextDefinition} context
915
- * @returns {module:engine/model/schema~SchemaContext}
916
- */
917
- createContext( context ) {
918
- return new SchemaContext( context );
919
- }
920
-
921
- /**
922
- * @private
923
- */
924
- _clearCache() {
925
- this._compiledDefinitions = null;
926
- }
927
-
928
- /**
929
- * @private
930
- */
931
- _compile() {
932
- const compiledDefinitions = {};
933
- const sourceRules = this._sourceDefinitions;
934
- const itemNames = Object.keys( sourceRules );
935
-
936
- for ( const itemName of itemNames ) {
937
- compiledDefinitions[ itemName ] = compileBaseItemRule( sourceRules[ itemName ], itemName );
938
- }
939
-
940
- for ( const itemName of itemNames ) {
941
- compileAllowChildren( compiledDefinitions, itemName );
942
- }
943
-
944
- for ( const itemName of itemNames ) {
945
- compileAllowContentOf( compiledDefinitions, itemName );
946
- }
947
-
948
- for ( const itemName of itemNames ) {
949
- compileAllowWhere( compiledDefinitions, itemName );
950
- }
951
-
952
- for ( const itemName of itemNames ) {
953
- compileAllowAttributesOf( compiledDefinitions, itemName );
954
- compileInheritPropertiesFrom( compiledDefinitions, itemName );
955
- }
956
-
957
- for ( const itemName of itemNames ) {
958
- cleanUpAllowIn( compiledDefinitions, itemName );
959
- setupAllowChildren( compiledDefinitions, itemName );
960
- cleanUpAllowAttributes( compiledDefinitions, itemName );
961
- }
962
-
963
- this._compiledDefinitions = compiledDefinitions;
964
- }
965
-
966
- /**
967
- * @private
968
- * @param {module:engine/model/schema~SchemaCompiledItemDefinition} def
969
- * @param {module:engine/model/schema~SchemaContext} context
970
- * @param {Number} contextItemIndex
971
- */
972
- _checkContextMatch( def, context, contextItemIndex = context.length - 1 ) {
973
- const contextItem = context.getItem( contextItemIndex );
974
-
975
- if ( def.allowIn.includes( contextItem.name ) ) {
976
- if ( contextItemIndex == 0 ) {
977
- return true;
978
- } else {
979
- const parentRule = this.getDefinition( contextItem );
980
-
981
- return this._checkContextMatch( parentRule, context, contextItemIndex - 1 );
982
- }
983
- } else {
984
- return false;
985
- }
986
- }
987
-
988
- /**
989
- * Takes a flat range and an attribute name. Traverses the range recursively and deeply to find and return all ranges
990
- * inside the given range on which the attribute can be applied.
991
- *
992
- * This is a helper function for {@link ~Schema#getValidRanges}.
993
- *
994
- * @private
995
- * @param {module:engine/model/range~Range} range The range to process.
996
- * @param {String} attribute The name of the attribute to check.
997
- * @returns {Iterable.<module:engine/model/range~Range>} Ranges in which the attribute is allowed.
998
- */
999
- * _getValidRangesForRange( range, attribute ) {
1000
- let start = range.start;
1001
- let end = range.start;
1002
-
1003
- for ( const item of range.getItems( { shallow: true } ) ) {
1004
- if ( item.is( 'element' ) ) {
1005
- yield* this._getValidRangesForRange( Range._createIn( item ), attribute );
1006
- }
1007
-
1008
- if ( !this.checkAttribute( item, attribute ) ) {
1009
- if ( !start.isEqual( end ) ) {
1010
- yield new Range( start, end );
1011
- }
1012
-
1013
- start = Position._createAfter( item );
1014
- }
1015
-
1016
- end = Position._createAfter( item );
1017
- }
1018
-
1019
- if ( !start.isEqual( end ) ) {
1020
- yield new Range( start, end );
1021
- }
1022
- }
30
+ export default class Schema extends Observable {
31
+ /**
32
+ * Creates a schema instance.
33
+ */
34
+ constructor() {
35
+ super();
36
+ this._sourceDefinitions = {};
37
+ /**
38
+ * A dictionary containing attribute properties.
39
+ *
40
+ * @private
41
+ * @member {Object.<String,AttributeProperties>}
42
+ */
43
+ this._attributeProperties = {};
44
+ this.decorate('checkChild');
45
+ this.decorate('checkAttribute');
46
+ this.on('checkAttribute', (evt, args) => {
47
+ args[0] = new SchemaContext(args[0]);
48
+ }, { priority: 'highest' });
49
+ this.on('checkChild', (evt, args) => {
50
+ args[0] = new SchemaContext(args[0]);
51
+ args[1] = this.getDefinition(args[1]);
52
+ }, { priority: 'highest' });
53
+ }
54
+ /**
55
+ * Registers a schema item. Can only be called once for every item name.
56
+ *
57
+ * schema.register( 'paragraph', {
58
+ * inheritAllFrom: '$block'
59
+ * } );
60
+ *
61
+ * @param {String} itemName
62
+ * @param {module:engine/model/schema~SchemaItemDefinition} definition
63
+ */
64
+ register(itemName, definition) {
65
+ if (this._sourceDefinitions[itemName]) {
66
+ /**
67
+ * A single item cannot be registered twice in the schema.
68
+ *
69
+ * This situation may happen when:
70
+ *
71
+ * * Two or more plugins called {@link #register `register()`} with the same name. This will usually mean that
72
+ * there is a collision between plugins which try to use the same element in the model. Unfortunately,
73
+ * the only way to solve this is by modifying one of these plugins to use a unique model element name.
74
+ * * A single plugin was loaded twice. This happens when it is installed by npm/yarn in two versions
75
+ * and usually means one or more of the following issues:
76
+ * * a version mismatch (two of your dependencies require two different versions of this plugin),
77
+ * * incorrect imports (this plugin is somehow imported twice in a way which confuses webpack),
78
+ * * mess in `node_modules/` (`rm -rf node_modules/` may help).
79
+ *
80
+ * **Note:** Check the logged `itemName` to better understand which plugin was duplicated/conflicting.
81
+ *
82
+ * @param itemName The name of the model element that is being registered twice.
83
+ * @error schema-cannot-register-item-twice
84
+ */
85
+ throw new CKEditorError('schema-cannot-register-item-twice', this, {
86
+ itemName
87
+ });
88
+ }
89
+ this._sourceDefinitions[itemName] = [
90
+ Object.assign({}, definition)
91
+ ];
92
+ this._clearCache();
93
+ }
94
+ /**
95
+ * Extends a {@link #register registered} item's definition.
96
+ *
97
+ * Extending properties such as `allowIn` will add more items to the existing properties,
98
+ * while redefining properties such as `isBlock` will override the previously defined ones.
99
+ *
100
+ * schema.register( 'foo', {
101
+ * allowIn: '$root',
102
+ * isBlock: true;
103
+ * } );
104
+ * schema.extend( 'foo', {
105
+ * allowIn: 'blockQuote',
106
+ * isBlock: false
107
+ * } );
108
+ *
109
+ * schema.getDefinition( 'foo' );
110
+ * // {
111
+ * // allowIn: [ '$root', 'blockQuote' ],
112
+ * // isBlock: false
113
+ * // }
114
+ *
115
+ * @param {String} itemName
116
+ * @param {module:engine/model/schema~SchemaItemDefinition} definition
117
+ */
118
+ extend(itemName, definition) {
119
+ if (!this._sourceDefinitions[itemName]) {
120
+ /**
121
+ * Cannot extend an item which was not registered yet.
122
+ *
123
+ * This error happens when a plugin tries to extend the schema definition of an item which was not
124
+ * {@link #register registered} yet.
125
+ *
126
+ * @param itemName The name of the model element which is being extended.
127
+ * @error schema-cannot-extend-missing-item
128
+ */
129
+ throw new CKEditorError('schema-cannot-extend-missing-item', this, {
130
+ itemName
131
+ });
132
+ }
133
+ this._sourceDefinitions[itemName].push(Object.assign({}, definition));
134
+ this._clearCache();
135
+ }
136
+ /**
137
+ * Returns data of all registered items.
138
+ *
139
+ * This method should normally be used for reflection purposes (e.g. defining a clone of a certain element,
140
+ * checking a list of all block elements, etc).
141
+ * Use specific methods (such as {@link #checkChild `checkChild()`} or {@link #isLimit `isLimit()`})
142
+ * in other cases.
143
+ *
144
+ * @returns {Object.<String,module:engine/model/schema~SchemaCompiledItemDefinition>}
145
+ */
146
+ getDefinitions() {
147
+ if (!this._compiledDefinitions) {
148
+ this._compile();
149
+ }
150
+ return this._compiledDefinitions;
151
+ }
152
+ /**
153
+ * Returns a definition of the given item or `undefined` if an item is not registered.
154
+ *
155
+ * This method should normally be used for reflection purposes (e.g. defining a clone of a certain element,
156
+ * checking a list of all block elements, etc).
157
+ * Use specific methods (such as {@link #checkChild `checkChild()`} or {@link #isLimit `isLimit()`})
158
+ * in other cases.
159
+ *
160
+ * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
161
+ * @returns {module:engine/model/schema~SchemaCompiledItemDefinition}
162
+ */
163
+ getDefinition(item) {
164
+ let itemName;
165
+ if (typeof item == 'string') {
166
+ itemName = item;
167
+ }
168
+ else if ('is' in item && (item.is('$text') || item.is('$textProxy'))) {
169
+ itemName = '$text';
170
+ }
171
+ // Element or module:engine/model/schema~SchemaContextItem.
172
+ else {
173
+ itemName = item.name;
174
+ }
175
+ return this.getDefinitions()[itemName];
176
+ }
177
+ /**
178
+ * Returns `true` if the given item is registered in the schema.
179
+ *
180
+ * schema.isRegistered( 'paragraph' ); // -> true
181
+ * schema.isRegistered( editor.model.document.getRoot() ); // -> true
182
+ * schema.isRegistered( 'foo' ); // -> false
183
+ *
184
+ * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
185
+ * @returns {Boolean}
186
+ */
187
+ isRegistered(item) {
188
+ return !!this.getDefinition(item);
189
+ }
190
+ /**
191
+ * Returns `true` if the given item is defined to be
192
+ * a block by the {@link module:engine/model/schema~SchemaItemDefinition}'s `isBlock` property.
193
+ *
194
+ * schema.isBlock( 'paragraph' ); // -> true
195
+ * schema.isBlock( '$root' ); // -> false
196
+ *
197
+ * const paragraphElement = writer.createElement( 'paragraph' );
198
+ * schema.isBlock( paragraphElement ); // -> true
199
+ *
200
+ * See the {@glink framework/guides/deep-dive/schema#block-elements Block elements} section of
201
+ * the {@glink framework/guides/deep-dive/schema Schema deep dive} guide for more details.
202
+ *
203
+ * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
204
+ * @returns {Boolean}
205
+ */
206
+ isBlock(item) {
207
+ const def = this.getDefinition(item);
208
+ return !!(def && def.isBlock);
209
+ }
210
+ /**
211
+ * Returns `true` if the given item should be treated as a limit element.
212
+ *
213
+ * It considers an item to be a limit element if its
214
+ * {@link module:engine/model/schema~SchemaItemDefinition}'s
215
+ * {@link module:engine/model/schema~SchemaItemDefinition#isLimit `isLimit`} or
216
+ * {@link module:engine/model/schema~SchemaItemDefinition#isObject `isObject`} property
217
+ * was set to `true`.
218
+ *
219
+ * schema.isLimit( 'paragraph' ); // -> false
220
+ * schema.isLimit( '$root' ); // -> true
221
+ * schema.isLimit( editor.model.document.getRoot() ); // -> true
222
+ * schema.isLimit( 'imageBlock' ); // -> true
223
+ *
224
+ * See the {@glink framework/guides/deep-dive/schema#limit-elements Limit elements} section of
225
+ * the {@glink framework/guides/deep-dive/schema Schema deep dive} guide for more details.
226
+ *
227
+ * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
228
+ * @returns {Boolean}
229
+ */
230
+ isLimit(item) {
231
+ const def = this.getDefinition(item);
232
+ if (!def) {
233
+ return false;
234
+ }
235
+ return !!(def.isLimit || def.isObject);
236
+ }
237
+ /**
238
+ * Returns `true` if the given item should be treated as an object element.
239
+ *
240
+ * It considers an item to be an object element if its
241
+ * {@link module:engine/model/schema~SchemaItemDefinition}'s
242
+ * {@link module:engine/model/schema~SchemaItemDefinition#isObject `isObject`} property
243
+ * was set to `true`.
244
+ *
245
+ * schema.isObject( 'paragraph' ); // -> false
246
+ * schema.isObject( 'imageBlock' ); // -> true
247
+ *
248
+ * const imageElement = writer.createElement( 'imageBlock' );
249
+ * schema.isObject( imageElement ); // -> true
250
+ *
251
+ * See the {@glink framework/guides/deep-dive/schema#object-elements Object elements} section of
252
+ * the {@glink framework/guides/deep-dive/schema Schema deep dive} guide for more details.
253
+ *
254
+ * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
255
+ * @returns {Boolean}
256
+ */
257
+ isObject(item) {
258
+ const def = this.getDefinition(item);
259
+ if (!def) {
260
+ return false;
261
+ }
262
+ // Note: Check out the implementation of #isLimit(), #isSelectable(), and #isContent()
263
+ // to understand why these three constitute an object.
264
+ return !!(def.isObject || (def.isLimit && def.isSelectable && def.isContent));
265
+ }
266
+ /**
267
+ * Returns `true` if the given item is defined to be
268
+ * an inline element by the {@link module:engine/model/schema~SchemaItemDefinition}'s `isInline` property.
269
+ *
270
+ * schema.isInline( 'paragraph' ); // -> false
271
+ * schema.isInline( 'softBreak' ); // -> true
272
+ *
273
+ * const text = writer.createText( 'foo' );
274
+ * schema.isInline( text ); // -> true
275
+ *
276
+ * See the {@glink framework/guides/deep-dive/schema#inline-elements Inline elements} section of
277
+ * the {@glink framework/guides/deep-dive/schema Schema deep dive} guide for more details.
278
+ *
279
+ * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
280
+ * @returns {Boolean}
281
+ */
282
+ isInline(item) {
283
+ const def = this.getDefinition(item);
284
+ return !!(def && def.isInline);
285
+ }
286
+ /**
287
+ * Returns `true` if the given item is defined to be
288
+ * a selectable element by the {@link module:engine/model/schema~SchemaItemDefinition}'s `isSelectable` property.
289
+ *
290
+ * schema.isSelectable( 'paragraph' ); // -> false
291
+ * schema.isSelectable( 'heading1' ); // -> false
292
+ * schema.isSelectable( 'imageBlock' ); // -> true
293
+ * schema.isSelectable( 'tableCell' ); // -> true
294
+ *
295
+ * const text = writer.createText( 'foo' );
296
+ * schema.isSelectable( text ); // -> false
297
+ *
298
+ * See the {@glink framework/guides/deep-dive/schema#selectable-elements Selectable elements section} of
299
+ * the {@glink framework/guides/deep-dive/schema Schema deep dive} guide for more details.
300
+ *
301
+ * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
302
+ * @returns {Boolean}
303
+ */
304
+ isSelectable(item) {
305
+ const def = this.getDefinition(item);
306
+ if (!def) {
307
+ return false;
308
+ }
309
+ return !!(def.isSelectable || def.isObject);
310
+ }
311
+ /**
312
+ * Returns `true` if the given item is defined to be
313
+ * a content by the {@link module:engine/model/schema~SchemaItemDefinition}'s `isContent` property.
314
+ *
315
+ * schema.isContent( 'paragraph' ); // -> false
316
+ * schema.isContent( 'heading1' ); // -> false
317
+ * schema.isContent( 'imageBlock' ); // -> true
318
+ * schema.isContent( 'horizontalLine' ); // -> true
319
+ *
320
+ * const text = writer.createText( 'foo' );
321
+ * schema.isContent( text ); // -> true
322
+ *
323
+ * See the {@glink framework/guides/deep-dive/schema#content-elements Content elements section} of
324
+ * the {@glink framework/guides/deep-dive/schema Schema deep dive} guide for more details.
325
+ *
326
+ * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
327
+ * @returns {Boolean}
328
+ */
329
+ isContent(item) {
330
+ const def = this.getDefinition(item);
331
+ if (!def) {
332
+ return false;
333
+ }
334
+ return !!(def.isContent || def.isObject);
335
+ }
336
+ /**
337
+ * Checks whether the given node (`child`) can be a child of the given context.
338
+ *
339
+ * schema.checkChild( model.document.getRoot(), paragraph ); // -> false
340
+ *
341
+ * schema.register( 'paragraph', {
342
+ * allowIn: '$root'
343
+ * } );
344
+ * schema.checkChild( model.document.getRoot(), paragraph ); // -> true
345
+ *
346
+ * Note: When verifying whether the given node can be a child of the given context, the
347
+ * schema also verifies the entire context &mdash; from its root to its last element. Therefore, it is possible
348
+ * for `checkChild()` to return `false` even though the context's last element can contain the checked child.
349
+ * It happens if one of the context's elements does not allow its child.
350
+ *
351
+ * @fires checkChild
352
+ * @param {module:engine/model/schema~SchemaContextDefinition} context The context in which the child will be checked.
353
+ * @param {module:engine/model/node~Node|String} def The child to check.
354
+ * @returns {Boolean}
355
+ */
356
+ checkChild(context, def) {
357
+ // Note: context and child are already normalized here to a SchemaContext and SchemaCompiledItemDefinition.
358
+ if (!def) {
359
+ return false;
360
+ }
361
+ return this._checkContextMatch(def, context);
362
+ }
363
+ /**
364
+ * Checks whether the given attribute can be applied in the given context (on the last
365
+ * item of the context).
366
+ *
367
+ * schema.checkAttribute( textNode, 'bold' ); // -> false
368
+ *
369
+ * schema.extend( '$text', {
370
+ * allowAttributes: 'bold'
371
+ * } );
372
+ * schema.checkAttribute( textNode, 'bold' ); // -> true
373
+ *
374
+ * @fires checkAttribute
375
+ * @param {module:engine/model/schema~SchemaContextDefinition} context The context in which the attribute will be checked.
376
+ * @param {String} attributeName
377
+ * @returns {Boolean}
378
+ */
379
+ checkAttribute(context, attributeName) {
380
+ const def = this.getDefinition(context.last);
381
+ if (!def) {
382
+ return false;
383
+ }
384
+ return def.allowAttributes.includes(attributeName);
385
+ }
386
+ /**
387
+ * Checks whether the given element (`elementToMerge`) can be merged with the specified base element (`positionOrBaseElement`).
388
+ *
389
+ * In other words &mdash; whether `elementToMerge`'s children {@link #checkChild are allowed} in the `positionOrBaseElement`.
390
+ *
391
+ * This check ensures that elements merged with {@link module:engine/model/writer~Writer#merge `Writer#merge()`}
392
+ * will be valid.
393
+ *
394
+ * Instead of elements, you can pass the instance of the {@link module:engine/model/position~Position} class as the
395
+ * `positionOrBaseElement`. It means that the elements before and after the position will be checked whether they can be merged.
396
+ *
397
+ * @param {module:engine/model/position~Position|module:engine/model/element~Element} positionOrBaseElement The position or base
398
+ * element to which the `elementToMerge` will be merged.
399
+ * @param {module:engine/model/element~Element} elementToMerge The element to merge. Required if `positionOrBaseElement` is an element.
400
+ * @returns {Boolean}
401
+ */
402
+ checkMerge(positionOrBaseElement, elementToMerge) {
403
+ if (positionOrBaseElement instanceof Position) {
404
+ const nodeBefore = positionOrBaseElement.nodeBefore;
405
+ const nodeAfter = positionOrBaseElement.nodeAfter;
406
+ if (!(nodeBefore instanceof Element)) {
407
+ /**
408
+ * The node before the merge position must be an element.
409
+ *
410
+ * @error schema-check-merge-no-element-before
411
+ */
412
+ throw new CKEditorError('schema-check-merge-no-element-before', this);
413
+ }
414
+ if (!(nodeAfter instanceof Element)) {
415
+ /**
416
+ * The node after the merge position must be an element.
417
+ *
418
+ * @error schema-check-merge-no-element-after
419
+ */
420
+ throw new CKEditorError('schema-check-merge-no-element-after', this);
421
+ }
422
+ return this.checkMerge(nodeBefore, nodeAfter);
423
+ }
424
+ for (const child of elementToMerge.getChildren()) {
425
+ if (!this.checkChild(positionOrBaseElement, child)) {
426
+ return false;
427
+ }
428
+ }
429
+ return true;
430
+ }
431
+ /**
432
+ * Allows registering a callback to the {@link #checkChild} method calls.
433
+ *
434
+ * Callbacks allow you to implement rules which are not otherwise possible to achieve
435
+ * by using the declarative API of {@link module:engine/model/schema~SchemaItemDefinition}.
436
+ * For example, by using this method you can disallow elements in specific contexts.
437
+ *
438
+ * This method is a shorthand for using the {@link #event:checkChild} event. For even better control,
439
+ * you can use that event instead.
440
+ *
441
+ * Example:
442
+ *
443
+ * // Disallow heading1 directly inside a blockQuote.
444
+ * schema.addChildCheck( ( context, childDefinition ) => {
445
+ * if ( context.endsWith( 'blockQuote' ) && childDefinition.name == 'heading1' ) {
446
+ * return false;
447
+ * }
448
+ * } );
449
+ *
450
+ * Which translates to:
451
+ *
452
+ * schema.on( 'checkChild', ( evt, args ) => {
453
+ * const context = args[ 0 ];
454
+ * const childDefinition = args[ 1 ];
455
+ *
456
+ * if ( context.endsWith( 'blockQuote' ) && childDefinition && childDefinition.name == 'heading1' ) {
457
+ * // Prevent next listeners from being called.
458
+ * evt.stop();
459
+ * // Set the checkChild()'s return value.
460
+ * evt.return = false;
461
+ * }
462
+ * }, { priority: 'high' } );
463
+ *
464
+ * @param {Function} callback The callback to be called. It is called with two parameters:
465
+ * {@link module:engine/model/schema~SchemaContext} (context) instance and
466
+ * {@link module:engine/model/schema~SchemaCompiledItemDefinition} (child-to-check definition).
467
+ * The callback may return `true/false` to override `checkChild()`'s return value. If it does not return
468
+ * a boolean value, the default algorithm (or other callbacks) will define `checkChild()`'s return value.
469
+ */
470
+ addChildCheck(callback) {
471
+ this.on('checkChild', (evt, [ctx, childDef]) => {
472
+ // checkChild() was called with a non-registered child.
473
+ // In 99% cases such check should return false, so not to overcomplicate all callbacks
474
+ // don't even execute them.
475
+ if (!childDef) {
476
+ return;
477
+ }
478
+ const retValue = callback(ctx, childDef);
479
+ if (typeof retValue == 'boolean') {
480
+ evt.stop();
481
+ evt.return = retValue;
482
+ }
483
+ }, { priority: 'high' });
484
+ }
485
+ /**
486
+ * Allows registering a callback to the {@link #checkAttribute} method calls.
487
+ *
488
+ * Callbacks allow you to implement rules which are not otherwise possible to achieve
489
+ * by using the declarative API of {@link module:engine/model/schema~SchemaItemDefinition}.
490
+ * For example, by using this method you can disallow attribute if node to which it is applied
491
+ * is contained within some other element (e.g. you want to disallow `bold` on `$text` within `heading1`).
492
+ *
493
+ * This method is a shorthand for using the {@link #event:checkAttribute} event. For even better control,
494
+ * you can use that event instead.
495
+ *
496
+ * Example:
497
+ *
498
+ * // Disallow bold on $text inside heading1.
499
+ * schema.addAttributeCheck( ( context, attributeName ) => {
500
+ * if ( context.endsWith( 'heading1 $text' ) && attributeName == 'bold' ) {
501
+ * return false;
502
+ * }
503
+ * } );
504
+ *
505
+ * Which translates to:
506
+ *
507
+ * schema.on( 'checkAttribute', ( evt, args ) => {
508
+ * const context = args[ 0 ];
509
+ * const attributeName = args[ 1 ];
510
+ *
511
+ * if ( context.endsWith( 'heading1 $text' ) && attributeName == 'bold' ) {
512
+ * // Prevent next listeners from being called.
513
+ * evt.stop();
514
+ * // Set the checkAttribute()'s return value.
515
+ * evt.return = false;
516
+ * }
517
+ * }, { priority: 'high' } );
518
+ *
519
+ * @param {Function} callback The callback to be called. It is called with two parameters:
520
+ * {@link module:engine/model/schema~SchemaContext} (context) instance and attribute name.
521
+ * The callback may return `true/false` to override `checkAttribute()`'s return value. If it does not return
522
+ * a boolean value, the default algorithm (or other callbacks) will define `checkAttribute()`'s return value.
523
+ */
524
+ addAttributeCheck(callback) {
525
+ this.on('checkAttribute', (evt, [ctx, attributeName]) => {
526
+ const retValue = callback(ctx, attributeName);
527
+ if (typeof retValue == 'boolean') {
528
+ evt.stop();
529
+ evt.return = retValue;
530
+ }
531
+ }, { priority: 'high' });
532
+ }
533
+ /**
534
+ * This method allows assigning additional metadata to the model attributes. For example,
535
+ * {@link module:engine/model/schema~AttributeProperties `AttributeProperties#isFormatting` property} is
536
+ * used to mark formatting attributes (like `bold` or `italic`).
537
+ *
538
+ * // Mark bold as a formatting attribute.
539
+ * schema.setAttributeProperties( 'bold', {
540
+ * isFormatting: true
541
+ * } );
542
+ *
543
+ * // Override code not to be considered a formatting markup.
544
+ * schema.setAttributeProperties( 'code', {
545
+ * isFormatting: false
546
+ * } );
547
+ *
548
+ * Properties are not limited to members defined in the
549
+ * {@link module:engine/model/schema~AttributeProperties `AttributeProperties` type} and you can also use custom properties:
550
+ *
551
+ * schema.setAttributeProperties( 'blockQuote', {
552
+ * customProperty: 'value'
553
+ * } );
554
+ *
555
+ * Subsequent calls with the same attribute will extend its custom properties:
556
+ *
557
+ * schema.setAttributeProperties( 'blockQuote', {
558
+ * one: 1
559
+ * } );
560
+ *
561
+ * schema.setAttributeProperties( 'blockQuote', {
562
+ * two: 2
563
+ * } );
564
+ *
565
+ * console.log( schema.getAttributeProperties( 'blockQuote' ) );
566
+ * // Logs: { one: 1, two: 2 }
567
+ *
568
+ * @param {String} attributeName A name of the attribute to receive the properties.
569
+ * @param {module:engine/model/schema~AttributeProperties} properties A dictionary of properties.
570
+ */
571
+ setAttributeProperties(attributeName, properties) {
572
+ this._attributeProperties[attributeName] = Object.assign(this.getAttributeProperties(attributeName), properties);
573
+ }
574
+ /**
575
+ * Returns properties associated with a given model attribute. See {@link #setAttributeProperties `setAttributeProperties()`}.
576
+ *
577
+ * @param {String} attributeName A name of the attribute.
578
+ * @returns {module:engine/model/schema~AttributeProperties}
579
+ */
580
+ getAttributeProperties(attributeName) {
581
+ return this._attributeProperties[attributeName] || {};
582
+ }
583
+ /**
584
+ * Returns the lowest {@link module:engine/model/schema~Schema#isLimit limit element} containing the entire
585
+ * selection/range/position or the root otherwise.
586
+ *
587
+ * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection|
588
+ * module:engine/model/range~Range|module:engine/model/position~Position} selectionOrRangeOrPosition
589
+ * The selection/range/position to check.
590
+ * @returns {module:engine/model/element~Element} The lowest limit element containing
591
+ * the entire `selectionOrRangeOrPosition`.
592
+ */
593
+ getLimitElement(selectionOrRangeOrPosition) {
594
+ let element;
595
+ if (selectionOrRangeOrPosition instanceof Position) {
596
+ element = selectionOrRangeOrPosition.parent;
597
+ }
598
+ else {
599
+ const ranges = selectionOrRangeOrPosition instanceof Range ?
600
+ [selectionOrRangeOrPosition] :
601
+ Array.from(selectionOrRangeOrPosition.getRanges());
602
+ // Find the common ancestor for all selection's ranges.
603
+ element = ranges
604
+ .reduce((element, range) => {
605
+ const rangeCommonAncestor = range.getCommonAncestor();
606
+ if (!element) {
607
+ return rangeCommonAncestor;
608
+ }
609
+ return element.getCommonAncestor(rangeCommonAncestor, { includeSelf: true });
610
+ }, null);
611
+ }
612
+ while (!this.isLimit(element)) {
613
+ if (element.parent) {
614
+ element = element.parent;
615
+ }
616
+ else {
617
+ break;
618
+ }
619
+ }
620
+ return element;
621
+ }
622
+ /**
623
+ * Checks whether the attribute is allowed in selection:
624
+ *
625
+ * * if the selection is not collapsed, then checks if the attribute is allowed on any of nodes in that range,
626
+ * * if the selection is collapsed, then checks if on the selection position there's a text with the
627
+ * specified attribute allowed.
628
+ *
629
+ * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection} selection
630
+ * Selection which will be checked.
631
+ * @param {String} attribute The name of the attribute to check.
632
+ * @returns {Boolean}
633
+ */
634
+ checkAttributeInSelection(selection, attribute) {
635
+ if (selection.isCollapsed) {
636
+ const firstPosition = selection.getFirstPosition();
637
+ const context = [
638
+ ...firstPosition.getAncestors(),
639
+ new Text('', selection.getAttributes())
640
+ ];
641
+ // Check whether schema allows for a text with the attribute in the selection.
642
+ return this.checkAttribute(context, attribute);
643
+ }
644
+ else {
645
+ const ranges = selection.getRanges();
646
+ // For all ranges, check nodes in them until you find a node that is allowed to have the attribute.
647
+ for (const range of ranges) {
648
+ for (const value of range) {
649
+ if (this.checkAttribute(value.item, attribute)) {
650
+ // If we found a node that is allowed to have the attribute, return true.
651
+ return true;
652
+ }
653
+ }
654
+ }
655
+ }
656
+ // If we haven't found such node, return false.
657
+ return false;
658
+ }
659
+ /**
660
+ * Transforms the given set of ranges into a set of ranges where the given attribute is allowed (and can be applied).
661
+ *
662
+ * @param {Iterable.<module:engine/model/range~Range>} ranges Ranges to be validated.
663
+ * @param {String} attribute The name of the attribute to check.
664
+ * @returns {Iterable.<module:engine/model/range~Range>} Ranges in which the attribute is allowed.
665
+ */
666
+ *getValidRanges(ranges, attribute) {
667
+ ranges = convertToMinimalFlatRanges(ranges);
668
+ for (const range of ranges) {
669
+ yield* this._getValidRangesForRange(range, attribute);
670
+ }
671
+ }
672
+ /**
673
+ * Basing on given `position`, finds and returns a {@link module:engine/model/range~Range range} which is
674
+ * nearest to that `position` and is a correct range for selection.
675
+ *
676
+ * The correct selection range might be collapsed when it is located in a position where the text node can be placed.
677
+ * Non-collapsed range is returned when selection can be placed around element marked as an "object" in
678
+ * the {@link module:engine/model/schema~Schema schema}.
679
+ *
680
+ * Direction of searching for the nearest correct selection range can be specified as:
681
+ *
682
+ * * `both` - searching will be performed in both ways,
683
+ * * `forward` - searching will be performed only forward,
684
+ * * `backward` - searching will be performed only backward.
685
+ *
686
+ * When valid selection range cannot be found, `null` is returned.
687
+ *
688
+ * @param {module:engine/model/position~Position} position Reference position where new selection range should be looked for.
689
+ * @param {'both'|'forward'|'backward'} [direction='both'] Search direction.
690
+ * @returns {module:engine/model/range~Range|null} Nearest selection range or `null` if one cannot be found.
691
+ */
692
+ getNearestSelectionRange(position, direction = 'both') {
693
+ // Return collapsed range if provided position is valid.
694
+ if (this.checkChild(position, '$text')) {
695
+ return new Range(position);
696
+ }
697
+ let backwardWalker, forwardWalker;
698
+ // Never leave a limit element.
699
+ const limitElement = position.getAncestors().reverse().find(item => this.isLimit(item)) ||
700
+ position.root;
701
+ if (direction == 'both' || direction == 'backward') {
702
+ backwardWalker = new TreeWalker({
703
+ boundaries: Range._createIn(limitElement),
704
+ startPosition: position,
705
+ direction: 'backward'
706
+ });
707
+ }
708
+ if (direction == 'both' || direction == 'forward') {
709
+ forwardWalker = new TreeWalker({
710
+ boundaries: Range._createIn(limitElement),
711
+ startPosition: position
712
+ });
713
+ }
714
+ for (const data of combineWalkers(backwardWalker, forwardWalker)) {
715
+ const type = (data.walker == backwardWalker ? 'elementEnd' : 'elementStart');
716
+ const value = data.value;
717
+ if (value.type == type && this.isObject(value.item)) {
718
+ return Range._createOn(value.item);
719
+ }
720
+ if (this.checkChild(value.nextPosition, '$text')) {
721
+ return new Range(value.nextPosition);
722
+ }
723
+ }
724
+ return null;
725
+ }
726
+ /**
727
+ * Tries to find position ancestors that allow to insert a given node.
728
+ * It starts searching from the given position and goes node by node to the top of the model tree
729
+ * as long as a {@link module:engine/model/schema~Schema#isLimit limit element}, an
730
+ * {@link module:engine/model/schema~Schema#isObject object element} or a topmost ancestor is not reached.
731
+ *
732
+ * @param {module:engine/model/position~Position} position The position that the search will start from.
733
+ * @param {module:engine/model/node~Node|String} node The node for which an allowed parent should be found or its name.
734
+ * @returns {module:engine/model/element~Element|null} element Allowed parent or null if nothing was found.
735
+ */
736
+ findAllowedParent(position, node) {
737
+ let parent = position.parent;
738
+ while (parent) {
739
+ if (this.checkChild(parent, node)) {
740
+ return parent;
741
+ }
742
+ // Do not split limit elements.
743
+ if (this.isLimit(parent)) {
744
+ return null;
745
+ }
746
+ parent = parent.parent;
747
+ }
748
+ return null;
749
+ }
750
+ /**
751
+ * Sets attributes allowed by the schema on a given node.
752
+ *
753
+ * @param {module:engine/model/node~Node} node A node to set attributes on.
754
+ * @param {Object} attributes Attributes keys and values.
755
+ * @param {module:engine/model/writer~Writer} writer An instance of the model writer.
756
+ */
757
+ setAllowedAttributes(node, attributes, writer) {
758
+ const model = writer.model;
759
+ for (const [attributeName, attributeValue] of Object.entries(attributes)) {
760
+ if (model.schema.checkAttribute(node, attributeName)) {
761
+ writer.setAttribute(attributeName, attributeValue, node);
762
+ }
763
+ }
764
+ }
765
+ /**
766
+ * Removes attributes disallowed by the schema.
767
+ *
768
+ * @param {Iterable.<module:engine/model/node~Node>} nodes Nodes that will be filtered.
769
+ * @param {module:engine/model/writer~Writer} writer
770
+ */
771
+ removeDisallowedAttributes(nodes, writer) {
772
+ for (const node of nodes) {
773
+ // When node is a `Text` it has no children, so just filter it out.
774
+ if (node.is('$text')) {
775
+ removeDisallowedAttributeFromNode(this, node, writer);
776
+ }
777
+ // In a case of `Element` iterates through positions between nodes inside this element
778
+ // and filter out node before the current position, or position parent when position
779
+ // is at start of an element. Using positions prevent from omitting merged nodes
780
+ // see https://github.com/ckeditor/ckeditor5-engine/issues/1789.
781
+ else {
782
+ const rangeInNode = Range._createIn(node);
783
+ const positionsInRange = rangeInNode.getPositions();
784
+ for (const position of positionsInRange) {
785
+ const item = position.nodeBefore || position.parent;
786
+ removeDisallowedAttributeFromNode(this, item, writer);
787
+ }
788
+ }
789
+ }
790
+ }
791
+ /**
792
+ * Gets attributes of a node that have a given property.
793
+ *
794
+ * @param {module:engine/model/node~Node} node Node to get attributes from.
795
+ * @param {String} propertyName Name of the property that attribute must have to return it.
796
+ * @param {Boolean|Symbol|String|Number|Object|null|undefined} propertyValue Desired value of the property that we want to check.
797
+ * When `undefined` attributes will be returned if they have set a given property no matter what the value is. If specified it will
798
+ * return attributes which given property's value is equal to this parameter.
799
+ * @returns {Object} Object with attributes' names as key and attributes' values as value.
800
+ */
801
+ getAttributesWithProperty(node, propertyName, propertyValue) {
802
+ const attributes = {};
803
+ for (const [attributeName, attributeValue] of node.getAttributes()) {
804
+ const attributeProperties = this.getAttributeProperties(attributeName);
805
+ if (attributeProperties[propertyName] === undefined) {
806
+ continue;
807
+ }
808
+ if (propertyValue === undefined || propertyValue === attributeProperties[propertyName]) {
809
+ attributes[attributeName] = attributeValue;
810
+ }
811
+ }
812
+ return attributes;
813
+ }
814
+ /**
815
+ * Creates an instance of the schema context.
816
+ *
817
+ * @param {module:engine/model/schema~SchemaContextDefinition} context
818
+ * @returns {module:engine/model/schema~SchemaContext}
819
+ */
820
+ createContext(context) {
821
+ return new SchemaContext(context);
822
+ }
823
+ /**
824
+ * @private
825
+ */
826
+ _clearCache() {
827
+ this._compiledDefinitions = null;
828
+ }
829
+ /**
830
+ * @private
831
+ */
832
+ _compile() {
833
+ const compiledDefinitions = {};
834
+ const sourceRules = this._sourceDefinitions;
835
+ const itemNames = Object.keys(sourceRules);
836
+ for (const itemName of itemNames) {
837
+ compiledDefinitions[itemName] = compileBaseItemRule(sourceRules[itemName], itemName);
838
+ }
839
+ for (const itemName of itemNames) {
840
+ compileAllowChildren(compiledDefinitions, itemName);
841
+ }
842
+ for (const itemName of itemNames) {
843
+ compileAllowContentOf(compiledDefinitions, itemName);
844
+ }
845
+ for (const itemName of itemNames) {
846
+ compileAllowWhere(compiledDefinitions, itemName);
847
+ }
848
+ for (const itemName of itemNames) {
849
+ compileAllowAttributesOf(compiledDefinitions, itemName);
850
+ compileInheritPropertiesFrom(compiledDefinitions, itemName);
851
+ }
852
+ for (const itemName of itemNames) {
853
+ cleanUpAllowIn(compiledDefinitions, itemName);
854
+ setupAllowChildren(compiledDefinitions, itemName);
855
+ cleanUpAllowAttributes(compiledDefinitions, itemName);
856
+ }
857
+ this._compiledDefinitions = compiledDefinitions;
858
+ }
859
+ /**
860
+ * @private
861
+ * @param {module:engine/model/schema~SchemaCompiledItemDefinition} def
862
+ * @param {module:engine/model/schema~SchemaContext} context
863
+ * @param {Number} contextItemIndex
864
+ */
865
+ _checkContextMatch(def, context, contextItemIndex = context.length - 1) {
866
+ const contextItem = context.getItem(contextItemIndex);
867
+ if (def.allowIn.includes(contextItem.name)) {
868
+ if (contextItemIndex == 0) {
869
+ return true;
870
+ }
871
+ else {
872
+ const parentRule = this.getDefinition(contextItem);
873
+ return this._checkContextMatch(parentRule, context, contextItemIndex - 1);
874
+ }
875
+ }
876
+ else {
877
+ return false;
878
+ }
879
+ }
880
+ /**
881
+ * Takes a flat range and an attribute name. Traverses the range recursively and deeply to find and return all ranges
882
+ * inside the given range on which the attribute can be applied.
883
+ *
884
+ * This is a helper function for {@link ~Schema#getValidRanges}.
885
+ *
886
+ * @private
887
+ * @param {module:engine/model/range~Range} range The range to process.
888
+ * @param {String} attribute The name of the attribute to check.
889
+ * @returns {Iterable.<module:engine/model/range~Range>} Ranges in which the attribute is allowed.
890
+ */
891
+ *_getValidRangesForRange(range, attribute) {
892
+ let start = range.start;
893
+ let end = range.start;
894
+ for (const item of range.getItems({ shallow: true })) {
895
+ if (item.is('element')) {
896
+ yield* this._getValidRangesForRange(Range._createIn(item), attribute);
897
+ }
898
+ if (!this.checkAttribute(item, attribute)) {
899
+ if (!start.isEqual(end)) {
900
+ yield new Range(start, end);
901
+ }
902
+ start = Position._createAfter(item);
903
+ }
904
+ end = Position._createAfter(item);
905
+ }
906
+ if (!start.isEqual(end)) {
907
+ yield new Range(start, end);
908
+ }
909
+ }
1023
910
  }
1024
-
1025
- mix( Schema, ObservableMixin );
1026
-
1027
- /**
1028
- * Event fired when the {@link #checkChild} method is called. It allows plugging in
1029
- * additional behavior, for example implementing rules which cannot be defined using the declarative
1030
- * {@link module:engine/model/schema~SchemaItemDefinition} interface.
1031
- *
1032
- * **Note:** The {@link #addChildCheck} method is a more handy way to register callbacks. Internally,
1033
- * it registers a listener to this event but comes with a simpler API and it is the recommended choice
1034
- * in most of the cases.
1035
- *
1036
- * The {@link #checkChild} method fires an event because it is
1037
- * {@link module:utils/observablemixin~ObservableMixin#decorate decorated} with it. Thanks to that you can
1038
- * use this event in various ways, but the most important use case is overriding standard behavior of the
1039
- * `checkChild()` method. Let's see a typical listener template:
1040
- *
1041
- * schema.on( 'checkChild', ( evt, args ) => {
1042
- * const context = args[ 0 ];
1043
- * const childDefinition = args[ 1 ];
1044
- * }, { priority: 'high' } );
1045
- *
1046
- * The listener is added with a `high` priority to be executed before the default method is really called. The `args` callback
1047
- * parameter contains arguments passed to `checkChild( context, child )`. However, the `context` parameter is already
1048
- * normalized to a {@link module:engine/model/schema~SchemaContext} instance and `child` to a
1049
- * {@link module:engine/model/schema~SchemaCompiledItemDefinition} instance, so you do not have to worry about
1050
- * the various ways how `context` and `child` may be passed to `checkChild()`.
1051
- *
1052
- * **Note:** `childDefinition` may be `undefined` if `checkChild()` was called with a non-registered element.
1053
- *
1054
- * So, in order to implement a rule "disallow `heading1` in `blockQuote`", you can add such a listener:
1055
- *
1056
- * schema.on( 'checkChild', ( evt, args ) => {
1057
- * const context = args[ 0 ];
1058
- * const childDefinition = args[ 1 ];
1059
- *
1060
- * if ( context.endsWith( 'blockQuote' ) && childDefinition && childDefinition.name == 'heading1' ) {
1061
- * // Prevent next listeners from being called.
1062
- * evt.stop();
1063
- * // Set the checkChild()'s return value.
1064
- * evt.return = false;
1065
- * }
1066
- * }, { priority: 'high' } );
1067
- *
1068
- * Allowing elements in specific contexts will be a far less common use case, because it is normally handled by the
1069
- * `allowIn` rule from {@link module:engine/model/schema~SchemaItemDefinition}. But if you have a complex scenario
1070
- * where `listItem` should be allowed only in element `foo` which must be in element `bar`, then this would be the way:
1071
- *
1072
- * schema.on( 'checkChild', ( evt, args ) => {
1073
- * const context = args[ 0 ];
1074
- * const childDefinition = args[ 1 ];
1075
- *
1076
- * if ( context.endsWith( 'bar foo' ) && childDefinition.name == 'listItem' ) {
1077
- * // Prevent next listeners from being called.
1078
- * evt.stop();
1079
- * // Set the checkChild()'s return value.
1080
- * evt.return = true;
1081
- * }
1082
- * }, { priority: 'high' } );
1083
- *
1084
- * @event checkChild
1085
- * @param {Array} args The `checkChild()`'s arguments.
1086
- */
1087
-
1088
- /**
1089
- * Event fired when the {@link #checkAttribute} method is called. It allows plugging in
1090
- * additional behavior, for example implementing rules which cannot be defined using the declarative
1091
- * {@link module:engine/model/schema~SchemaItemDefinition} interface.
1092
- *
1093
- * **Note:** The {@link #addAttributeCheck} method is a more handy way to register callbacks. Internally,
1094
- * it registers a listener to this event but comes with a simpler API and it is the recommended choice
1095
- * in most of the cases.
1096
- *
1097
- * The {@link #checkAttribute} method fires an event because it is
1098
- * {@link module:utils/observablemixin~ObservableMixin#decorate decorated} with it. Thanks to that you can
1099
- * use this event in various ways, but the most important use case is overriding the standard behavior of the
1100
- * `checkAttribute()` method. Let's see a typical listener template:
1101
- *
1102
- * schema.on( 'checkAttribute', ( evt, args ) => {
1103
- * const context = args[ 0 ];
1104
- * const attributeName = args[ 1 ];
1105
- * }, { priority: 'high' } );
1106
- *
1107
- * The listener is added with a `high` priority to be executed before the default method is really called. The `args` callback
1108
- * parameter contains arguments passed to `checkAttribute( context, attributeName )`. However, the `context` parameter is already
1109
- * normalized to a {@link module:engine/model/schema~SchemaContext} instance, so you do not have to worry about
1110
- * the various ways how `context` may be passed to `checkAttribute()`.
1111
- *
1112
- * So, in order to implement a rule "disallow `bold` in a text which is in a `heading1`, you can add such a listener:
1113
- *
1114
- * schema.on( 'checkAttribute', ( evt, args ) => {
1115
- * const context = args[ 0 ];
1116
- * const attributeName = args[ 1 ];
1117
- *
1118
- * if ( context.endsWith( 'heading1 $text' ) && attributeName == 'bold' ) {
1119
- * // Prevent next listeners from being called.
1120
- * evt.stop();
1121
- * // Set the checkAttribute()'s return value.
1122
- * evt.return = false;
1123
- * }
1124
- * }, { priority: 'high' } );
1125
- *
1126
- * Allowing attributes in specific contexts will be a far less common use case, because it is normally handled by the
1127
- * `allowAttributes` rule from {@link module:engine/model/schema~SchemaItemDefinition}. But if you have a complex scenario
1128
- * where `bold` should be allowed only in element `foo` which must be in element `bar`, then this would be the way:
1129
- *
1130
- * schema.on( 'checkAttribute', ( evt, args ) => {
1131
- * const context = args[ 0 ];
1132
- * const attributeName = args[ 1 ];
1133
- *
1134
- * if ( context.endsWith( 'bar foo $text' ) && attributeName == 'bold' ) {
1135
- * // Prevent next listeners from being called.
1136
- * evt.stop();
1137
- * // Set the checkAttribute()'s return value.
1138
- * evt.return = true;
1139
- * }
1140
- * }, { priority: 'high' } );
1141
- *
1142
- * @event checkAttribute
1143
- * @param {Array} args The `checkAttribute()`'s arguments.
1144
- */
1145
-
1146
- /**
1147
- * A definition of a {@link module:engine/model/schema~Schema schema} item.
1148
- *
1149
- * You can define the following rules:
1150
- *
1151
- * * {@link ~SchemaItemDefinition#allowIn `allowIn`} &ndash; Defines in which other items this item will be allowed.
1152
- * * {@link ~SchemaItemDefinition#allowChildren `allowChildren`} &ndash; Defines which other items are allowed inside this item.
1153
- * * {@link ~SchemaItemDefinition#allowAttributes `allowAttributes`} &ndash; Defines allowed attributes of the given item.
1154
- * * {@link ~SchemaItemDefinition#allowContentOf `allowContentOf`} &ndash; Inherits "allowed children" from other items.
1155
- * * {@link ~SchemaItemDefinition#allowWhere `allowWhere`} &ndash; Inherits "allowed in" from other items.
1156
- * * {@link ~SchemaItemDefinition#allowAttributesOf `allowAttributesOf`} &ndash; Inherits attributes from other items.
1157
- * * {@link ~SchemaItemDefinition#inheritTypesFrom `inheritTypesFrom`} &ndash; Inherits `is*` properties of other items.
1158
- * * {@link ~SchemaItemDefinition#inheritAllFrom `inheritAllFrom`} &ndash;
1159
- * A shorthand for `allowContentOf`, `allowWhere`, `allowAttributesOf`, `inheritTypesFrom`.
1160
- *
1161
- * # The `is*` properties
1162
- *
1163
- * There are a couple commonly used `is*` properties. Their role is to assign additional semantics to schema items.
1164
- * You can define more properties but you will also need to implement support for them in the existing editor features.
1165
- *
1166
- * * {@link ~SchemaItemDefinition#isBlock `isBlock`} &ndash; Whether this item is paragraph-like.
1167
- * Generally speaking, content is usually made out of blocks like paragraphs, list items, images, headings, etc.
1168
- * * {@link ~SchemaItemDefinition#isInline `isInline`} &ndash; Whether an item is "text-like" and should be treated as an inline node.
1169
- * Examples of inline elements: `$text`, `softBreak` (`<br>`), etc.
1170
- * * {@link ~SchemaItemDefinition#isLimit `isLimit`} &ndash; It can be understood as whether this element
1171
- * should not be split by <kbd>Enter</kbd>. Examples of limit elements: `$root`, table cell, image caption, etc.
1172
- * In other words, all actions that happen inside a limit element are limited to its content.
1173
- * All objects are treated as limit elements, too.
1174
- * * {@link ~SchemaItemDefinition#isObject `isObject`} &ndash; Whether an item is "self-contained" and should be treated as a whole.
1175
- * Examples of object elements: `imageBlock`, `table`, `video`, etc. An object is also a limit, so
1176
- * {@link module:engine/model/schema~Schema#isLimit `isLimit()`} returns `true` for object elements automatically.
1177
- *
1178
- * Read more about the meaning of these types in the
1179
- * {@glink framework/guides/deep-dive/schema#defining-additional-semantics dedicated section of the Schema deep dive} guide.
1180
- *
1181
- * # Generic items
1182
- *
1183
- * There are several generic items (classes of elements) available: `$root`, `$container`, `$block`, `$blockObject`,
1184
- * `$inlineObject`, and `$text`. They are defined as follows:
1185
- *
1186
- * schema.register( '$root', {
1187
- * isLimit: true
1188
- * } );
1189
- *
1190
- * schema.register( '$container', {
1191
- * allowIn: [ '$root', '$container' ]
1192
- * } );
1193
- *
1194
- * schema.register( '$block', {
1195
- * allowIn: [ '$root', '$container' ],
1196
- * isBlock: true
1197
- * } );
1198
- *
1199
- * schema.register( '$blockObject', {
1200
- * allowWhere: '$block',
1201
- * isBlock: true,
1202
- * isObject: true
1203
- * } );
1204
- *
1205
- * schema.register( '$inlineObject', {
1206
- * allowWhere: '$text',
1207
- * allowAttributesOf: '$text',
1208
- * isInline: true,
1209
- * isObject: true
1210
- * } );
1211
- *
1212
- * schema.register( '$text', {
1213
- * allowIn: '$block',
1214
- * isInline: true,
1215
- * isContent: true
1216
- * } );
1217
- *
1218
- * They reflect typical editor content that is contained within one root, consists of several blocks
1219
- * (paragraphs, lists items, headings, images) which, in turn, may contain text inside.
1220
- *
1221
- * By inheriting from the generic items you can define new items which will get extended by other editor features.
1222
- * Read more about generic types in the {@glink framework/guides/deep-dive/schema Schema deep dive} guide.
1223
- *
1224
- * # Example definitions
1225
- *
1226
- * Allow `paragraph` in roots and block quotes:
1227
- *
1228
- * schema.register( 'paragraph', {
1229
- * allowIn: [ '$root', 'blockQuote' ],
1230
- * isBlock: true
1231
- * } );
1232
- *
1233
- * Allow `paragraph` everywhere where `$block` is allowed (i.e. in `$root`):
1234
- *
1235
- * schema.register( 'paragraph', {
1236
- * allowWhere: '$block',
1237
- * isBlock: true
1238
- * } );
1239
- *
1240
- * Allow `paragraph` inside a `$root` and allow `$text` as a `paragraph` child:
1241
- *
1242
- * schema.register( 'paragraph', {
1243
- * allowIn: '$root',
1244
- * allowChildren: '$text',
1245
- * isBlock: true
1246
- * } );
1247
- *
1248
- * The previous rule can be written in a shorter form using inheritance:
1249
- *
1250
- * schema.register( 'paragraph', {
1251
- * inheritAllFrom: '$block'
1252
- * } );
1253
- *
1254
- * Make `imageBlock` a block object, which is allowed everywhere where `$block` is.
1255
- * Also, allow `src` and `alt` attributes in it:
1256
- *
1257
- * schema.register( 'imageBlock', {
1258
- * inheritAllFrom: '$blockObject',
1259
- * allowAttributes: [ 'src', 'alt' ],
1260
- * } );
1261
- *
1262
- * Make `caption` allowed in `imageBlock` and make it allow all the content of `$block`s (usually, `$text`).
1263
- * Also, mark it as a limit element so it cannot be split:
1264
- *
1265
- * schema.register( 'caption', {
1266
- * allowIn: 'imageBlock',
1267
- * allowContentOf: '$block',
1268
- * isLimit: true
1269
- * } );
1270
- *
1271
- * Make `listItem` inherit all from `$block` but also allow additional attributes:
1272
- *
1273
- * schema.register( 'listItem', {
1274
- * inheritAllFrom: '$block',
1275
- * allowAttributes: [ 'listType', 'listIndent' ]
1276
- * } );
1277
- *
1278
- * Which translates to:
1279
- *
1280
- * schema.register( 'listItem', {
1281
- * allowWhere: '$block',
1282
- * allowContentOf: '$block',
1283
- * allowAttributesOf: '$block',
1284
- * inheritTypesFrom: '$block',
1285
- * allowAttributes: [ 'listType', 'listIndent' ]
1286
- * } );
1287
- *
1288
- * # Tips
1289
- *
1290
- * * Check schema definitions of existing features to see how they are defined.
1291
- * * If you want to publish your feature so other developers can use it, try to use
1292
- * generic items as much as possible.
1293
- * * Keep your model clean. Limit it to the actual data and store information in a normalized way.
1294
- * * Remember about defining the `is*` properties. They do not affect the allowed structures, but they can
1295
- * affect how the editor features treat your elements.
1296
- *
1297
- * @typedef {Object} module:engine/model/schema~SchemaItemDefinition
1298
- *
1299
- * @property {String|Array.<String>} allowIn Defines in which other items this item will be allowed.
1300
- * @property {String|Array.<String>} allowChildren Defines which other items are allowed inside this item.
1301
- * @property {String|Array.<String>} allowAttributes Defines allowed attributes of the given item.
1302
- * @property {String|Array.<String>} allowContentOf Inherits "allowed children" from other items.
1303
- * @property {String|Array.<String>} allowWhere Inherits "allowed in" from other items.
1304
- * @property {String|Array.<String>} allowAttributesOf Inherits attributes from other items.
1305
- * @property {String|Array.<String>} inheritTypesFrom Inherits `is*` properties of other items.
1306
- * @property {String} inheritAllFrom A shorthand for `allowContentOf`, `allowWhere`, `allowAttributesOf`, `inheritTypesFrom`.
1307
- *
1308
- * @property {Boolean} isBlock
1309
- * Whether this item is paragraph-like. Generally speaking, content is usually made out of blocks
1310
- * like paragraphs, list items, images, headings, etc. All these elements are marked as blocks. A block
1311
- * should not allow another block inside. Note: There is also the `$block` generic item which has `isBlock` set to `true`.
1312
- * Most block type items will inherit from `$block` (through `inheritAllFrom`).
1313
- *
1314
- * Read more about the block elements in the
1315
- * {@glink framework/guides/deep-dive/schema#block-elements Block elements section} of
1316
- * the {@glink framework/guides/deep-dive/schema Schema deep dive}.
1317
- *
1318
- * @property {Boolean} isInline
1319
- * Whether an item is "text-like" and should be treated as an inline node. Examples of inline elements:
1320
- * `$text`, `softBreak` (`<br>`), etc.
1321
- *
1322
- * Read more about the inline elements in the
1323
- * {@glink framework/guides/deep-dive/schema#inline-elements Inline elements section} of the Schema deep dive guide.
1324
- *
1325
- * @property {Boolean} isLimit
1326
- * It can be understood as whether this element should not be split by <kbd>Enter</kbd>.
1327
- * Examples of limit elements: `$root`, table cell, image caption, etc. In other words, all actions that happen inside
1328
- * a limit element are limited to its content.
1329
- *
1330
- * Read more about the limit elements in the
1331
- * {@glink framework/guides/deep-dive/schema#limit-elements Limit elements section} of
1332
- * the {@glink framework/guides/deep-dive/schema Schema deep dive} guide.
1333
- *
1334
- * @property {Boolean} isObject
1335
- * Whether an item is "self-contained" and should be treated as a whole. Examples of object elements:
1336
- * `imageBlock`, `table`, `video`, etc.
1337
- *
1338
- * **Note:** An object is also a limit, so
1339
- * {@link module:engine/model/schema~Schema#isLimit `isLimit()`} returns `true` for object elements automatically.
1340
- *
1341
- * Read more about the object elements in the
1342
- * {@glink framework/guides/deep-dive/schema#object-elements Object elements section} of the Schema deep dive guide.
1343
- *
1344
- * @property {Boolean} isSelectable
1345
- * `true` when an element should be selectable as a whole by the user. Examples of selectable elements: `imageBlock`, `table`, `tableCell`,
1346
- * etc.
1347
- *
1348
- * **Note:** An object is also a selectable element, so
1349
- * {@link module:engine/model/schema~Schema#isSelectable `isSelectable()`} returns `true` for object elements automatically.
1350
- *
1351
- * Read more about selectable elements in the
1352
- * {@glink framework/guides/deep-dive/schema#selectable-elements Selectable elements section} of
1353
- * the {@glink framework/guides/deep-dive/schema Schema deep dive} guide.
1354
- *
1355
- * @property {Boolean} isContent
1356
- * An item is a content when it always finds its way to the editor data output regardless of the number and type of its descendants.
1357
- * Examples of content elements: `$text`, `imageBlock`, `table`, etc. (but not `paragraph`, `heading1` or `tableCell`).
1358
- *
1359
- * **Note:** An object is also a content element, so
1360
- * {@link module:engine/model/schema~Schema#isContent `isContent()`} returns `true` for object elements automatically.
1361
- *
1362
- * Read more about content elements in the
1363
- * {@glink framework/guides/deep-dive/schema#content-elements Content elements section} of
1364
- * the {@glink framework/guides/deep-dive/schema Schema deep dive} guide.
1365
- */
1366
-
1367
- /**
1368
- * A simplified version of {@link module:engine/model/schema~SchemaItemDefinition} after
1369
- * compilation by the {@link module:engine/model/schema~Schema schema}.
1370
- * Rules fed to the schema by {@link module:engine/model/schema~Schema#register}
1371
- * and {@link module:engine/model/schema~Schema#extend} methods are defined in the
1372
- * {@link module:engine/model/schema~SchemaItemDefinition} format.
1373
- * Later on, they are compiled to `SchemaCompiledItemDefinition` so when you use e.g.
1374
- * the {@link module:engine/model/schema~Schema#getDefinition} method you get the compiled version.
1375
- *
1376
- * The compiled version contains only the following properties:
1377
- *
1378
- * * The `name` property,
1379
- * * The `is*` properties,
1380
- * * The `allowIn` array,
1381
- * * The `allowChildren` array,
1382
- * * The `allowAttributes` array.
1383
- *
1384
- * @typedef {Object} module:engine/model/schema~SchemaCompiledItemDefinition
1385
- */
1386
-
1387
911
  /**
1388
912
  * A schema context &mdash; a list of ancestors of a given position in the document.
1389
913
  *
@@ -1409,458 +933,295 @@ mix( Schema, ObservableMixin );
1409
933
  * using these methods you need to use {@link module:engine/model/schema~SchemaContextDefinition}s.
1410
934
  */
1411
935
  export class SchemaContext {
1412
- /**
1413
- * Creates an instance of the context.
1414
- *
1415
- * @param {module:engine/model/schema~SchemaContextDefinition} context
1416
- */
1417
- constructor( context ) {
1418
- if ( context instanceof SchemaContext ) {
1419
- return context;
1420
- }
1421
-
1422
- if ( typeof context == 'string' ) {
1423
- context = [ context ];
1424
- } else if ( !Array.isArray( context ) ) {
1425
- // `context` is item or position.
1426
- // Position#getAncestors() doesn't accept any parameters but it works just fine here.
1427
- context = context.getAncestors( { includeSelf: true } );
1428
- }
1429
-
1430
- this._items = context.map( mapContextItem );
1431
- }
1432
-
1433
- /**
1434
- * The number of items.
1435
- *
1436
- * @type {Number}
1437
- */
1438
- get length() {
1439
- return this._items.length;
1440
- }
1441
-
1442
- /**
1443
- * The last item (the lowest node).
1444
- *
1445
- * @type {module:engine/model/schema~SchemaContextItem}
1446
- */
1447
- get last() {
1448
- return this._items[ this._items.length - 1 ];
1449
- }
1450
-
1451
- /**
1452
- * Iterable interface.
1453
- *
1454
- * Iterates over all context items.
1455
- *
1456
- * @returns {Iterable.<module:engine/model/schema~SchemaContextItem>}
1457
- */
1458
- [ Symbol.iterator ]() {
1459
- return this._items[ Symbol.iterator ]();
1460
- }
1461
-
1462
- /**
1463
- * Returns a new schema context instance with an additional item.
1464
- *
1465
- * Item can be added as:
1466
- *
1467
- * const context = new SchemaContext( [ '$root' ] );
1468
- *
1469
- * // An element.
1470
- * const fooElement = writer.createElement( 'fooElement' );
1471
- * const newContext = context.push( fooElement ); // [ '$root', 'fooElement' ]
1472
- *
1473
- * // A text node.
1474
- * const text = writer.createText( 'foobar' );
1475
- * const newContext = context.push( text ); // [ '$root', '$text' ]
1476
- *
1477
- * // A string (element name).
1478
- * const newContext = context.push( 'barElement' ); // [ '$root', 'barElement' ]
1479
- *
1480
- * **Note** {@link module:engine/model/node~Node} that is already in the model tree will be added as the only item
1481
- * (without ancestors).
1482
- *
1483
- * @param {String|module:engine/model/node~Node|Array<String|module:engine/model/node~Node>} item An item that will be added
1484
- * to the current context.
1485
- * @returns {module:engine/model/schema~SchemaContext} A new schema context instance with an additional item.
1486
- */
1487
- push( item ) {
1488
- const ctx = new SchemaContext( [ item ] );
1489
-
1490
- ctx._items = [ ...this._items, ...ctx._items ];
1491
-
1492
- return ctx;
1493
- }
1494
-
1495
- /**
1496
- * Gets an item on the given index.
1497
- *
1498
- * @returns {module:engine/model/schema~SchemaContextItem}
1499
- */
1500
- getItem( index ) {
1501
- return this._items[ index ];
1502
- }
1503
-
1504
- /**
1505
- * Returns the names of items.
1506
- *
1507
- * @returns {Iterable.<String>}
1508
- */
1509
- * getNames() {
1510
- yield* this._items.map( item => item.name );
1511
- }
1512
-
1513
- /**
1514
- * Checks whether the context ends with the given nodes.
1515
- *
1516
- * const ctx = new SchemaContext( [ rootElement, paragraphElement, textNode ] );
1517
- *
1518
- * ctx.endsWith( '$text' ); // -> true
1519
- * ctx.endsWith( 'paragraph $text' ); // -> true
1520
- * ctx.endsWith( '$root' ); // -> false
1521
- * ctx.endsWith( 'paragraph' ); // -> false
1522
- *
1523
- * @param {String} query
1524
- * @returns {Boolean}
1525
- */
1526
- endsWith( query ) {
1527
- return Array.from( this.getNames() ).join( ' ' ).endsWith( query );
1528
- }
1529
-
1530
- /**
1531
- * Checks whether the context starts with the given nodes.
1532
- *
1533
- * const ctx = new SchemaContext( [ rootElement, paragraphElement, textNode ] );
1534
- *
1535
- * ctx.endsWith( '$root' ); // -> true
1536
- * ctx.endsWith( '$root paragraph' ); // -> true
1537
- * ctx.endsWith( '$text' ); // -> false
1538
- * ctx.endsWith( 'paragraph' ); // -> false
1539
- *
1540
- * @param {String} query
1541
- * @returns {Boolean}
1542
- */
1543
- startsWith( query ) {
1544
- return Array.from( this.getNames() ).join( ' ' ).startsWith( query );
1545
- }
936
+ /**
937
+ * Creates an instance of the context.
938
+ *
939
+ * @param {module:engine/model/schema~SchemaContextDefinition} context
940
+ */
941
+ constructor(context) {
942
+ if (context instanceof SchemaContext) {
943
+ return context;
944
+ }
945
+ let items;
946
+ if (typeof context == 'string') {
947
+ items = [context];
948
+ }
949
+ else if (!Array.isArray(context)) {
950
+ // `context` is item or position.
951
+ // Position#getAncestors() doesn't accept any parameters but it works just fine here.
952
+ items = context.getAncestors({ includeSelf: true });
953
+ }
954
+ else {
955
+ items = context;
956
+ }
957
+ this._items = items.map(mapContextItem);
958
+ }
959
+ /**
960
+ * The number of items.
961
+ *
962
+ * @type {Number}
963
+ */
964
+ get length() {
965
+ return this._items.length;
966
+ }
967
+ /**
968
+ * The last item (the lowest node).
969
+ *
970
+ * @type {module:engine/model/schema~SchemaContextItem}
971
+ */
972
+ get last() {
973
+ return this._items[this._items.length - 1];
974
+ }
975
+ /**
976
+ * Iterable interface.
977
+ *
978
+ * Iterates over all context items.
979
+ *
980
+ * @returns {Iterable.<module:engine/model/schema~SchemaContextItem>}
981
+ */
982
+ [Symbol.iterator]() {
983
+ return this._items[Symbol.iterator]();
984
+ }
985
+ /**
986
+ * Returns a new schema context instance with an additional item.
987
+ *
988
+ * Item can be added as:
989
+ *
990
+ * const context = new SchemaContext( [ '$root' ] );
991
+ *
992
+ * // An element.
993
+ * const fooElement = writer.createElement( 'fooElement' );
994
+ * const newContext = context.push( fooElement ); // [ '$root', 'fooElement' ]
995
+ *
996
+ * // A text node.
997
+ * const text = writer.createText( 'foobar' );
998
+ * const newContext = context.push( text ); // [ '$root', '$text' ]
999
+ *
1000
+ * // A string (element name).
1001
+ * const newContext = context.push( 'barElement' ); // [ '$root', 'barElement' ]
1002
+ *
1003
+ * **Note** {@link module:engine/model/node~Node} that is already in the model tree will be added as the only item
1004
+ * (without ancestors).
1005
+ *
1006
+ * @param {String|module:engine/model/node~Node} item An item that will be added
1007
+ * to the current context.
1008
+ * @returns {module:engine/model/schema~SchemaContext} A new schema context instance with an additional item.
1009
+ */
1010
+ push(item) {
1011
+ const ctx = new SchemaContext([item]);
1012
+ ctx._items = [...this._items, ...ctx._items];
1013
+ return ctx;
1014
+ }
1015
+ /**
1016
+ * Gets an item on the given index.
1017
+ *
1018
+ * @returns {module:engine/model/schema~SchemaContextItem}
1019
+ */
1020
+ getItem(index) {
1021
+ return this._items[index];
1022
+ }
1023
+ /**
1024
+ * Returns the names of items.
1025
+ *
1026
+ * @returns {Iterable.<String>}
1027
+ */
1028
+ *getNames() {
1029
+ yield* this._items.map(item => item.name);
1030
+ }
1031
+ /**
1032
+ * Checks whether the context ends with the given nodes.
1033
+ *
1034
+ * const ctx = new SchemaContext( [ rootElement, paragraphElement, textNode ] );
1035
+ *
1036
+ * ctx.endsWith( '$text' ); // -> true
1037
+ * ctx.endsWith( 'paragraph $text' ); // -> true
1038
+ * ctx.endsWith( '$root' ); // -> false
1039
+ * ctx.endsWith( 'paragraph' ); // -> false
1040
+ *
1041
+ * @param {String} query
1042
+ * @returns {Boolean}
1043
+ */
1044
+ endsWith(query) {
1045
+ return Array.from(this.getNames()).join(' ').endsWith(query);
1046
+ }
1047
+ /**
1048
+ * Checks whether the context starts with the given nodes.
1049
+ *
1050
+ * const ctx = new SchemaContext( [ rootElement, paragraphElement, textNode ] );
1051
+ *
1052
+ * ctx.endsWith( '$root' ); // -> true
1053
+ * ctx.endsWith( '$root paragraph' ); // -> true
1054
+ * ctx.endsWith( '$text' ); // -> false
1055
+ * ctx.endsWith( 'paragraph' ); // -> false
1056
+ *
1057
+ * @param {String} query
1058
+ * @returns {Boolean}
1059
+ */
1060
+ startsWith(query) {
1061
+ return Array.from(this.getNames()).join(' ').startsWith(query);
1062
+ }
1546
1063
  }
1547
-
1548
- /**
1549
- * The definition of a {@link module:engine/model/schema~SchemaContext schema context}.
1550
- *
1551
- * Contexts can be created in multiple ways:
1552
- *
1553
- * * By defining a **node** – in this cases this node and all its ancestors will be used.
1554
- * * By defining a **position** in the document – in this case all its ancestors will be used.
1555
- * * By defining an **array of nodes** – in this case this array defines the entire context.
1556
- * * By defining a **name of node** - in this case node will be "mocked". It is not recommended because context
1557
- * will be unrealistic (e.g. attributes of these nodes are not specified). However, at times this may be the only
1558
- * way to define the context (e.g. when checking some hypothetical situation).
1559
- * * By defining an **array of node names** (potentially, mixed with real nodes) – The same as **name of node**
1560
- * but it is possible to create a path.
1561
- * * By defining a {@link module:engine/model/schema~SchemaContext} instance - in this case the same instance as provided
1562
- * will be return.
1563
- *
1564
- * Examples of context definitions passed to the {@link module:engine/model/schema~Schema#checkChild `Schema#checkChild()`}
1565
- * method:
1566
- *
1567
- * // Assuming that we have a $root > blockQuote > paragraph structure, the following code
1568
- * // will check node 'foo' in the following context:
1569
- * // [ rootElement, blockQuoteElement, paragraphElement ]
1570
- * const contextDefinition = paragraphElement;
1571
- * const childToCheck = 'foo';
1572
- * schema.checkChild( contextDefinition, childToCheck );
1573
- *
1574
- * // Also check in [ rootElement, blockQuoteElement, paragraphElement ].
1575
- * schema.checkChild( model.createPositionAt( paragraphElement, 0 ), 'foo' );
1576
- *
1577
- * // Check in [ rootElement, paragraphElement ].
1578
- * schema.checkChild( [ rootElement, paragraphElement ], 'foo' );
1579
- *
1580
- * // Check only fakeParagraphElement.
1581
- * schema.checkChild( 'paragraph', 'foo' );
1582
- *
1583
- * // Check in [ fakeRootElement, fakeBarElement, paragraphElement ].
1584
- * schema.checkChild( [ '$root', 'bar', paragraphElement ], 'foo' );
1585
- *
1586
- * All these `checkChild()` calls will fire {@link module:engine/model/schema~Schema#event:checkChild `Schema#checkChild`}
1587
- * events in which `args[ 0 ]` is an instance of the context. Therefore, you can write a listener like this:
1588
- *
1589
- * schema.on( 'checkChild', ( evt, args ) => {
1590
- * const ctx = args[ 0 ];
1591
- *
1592
- * console.log( Array.from( ctx.getNames() ) );
1593
- * } );
1594
- *
1595
- * Which will log the following:
1596
- *
1597
- * [ '$root', 'blockQuote', 'paragraph' ]
1598
- * [ '$root', 'paragraph' ]
1599
- * [ '$root', 'bar', 'paragraph' ]
1600
- *
1601
- * Note: When using the {@link module:engine/model/schema~Schema#checkAttribute `Schema#checkAttribute()`} method
1602
- * you may want to check whether a text node may have an attribute. A {@link module:engine/model/text~Text} is a
1603
- * correct way to define a context so you can do this:
1604
- *
1605
- * schema.checkAttribute( textNode, 'bold' );
1606
- *
1607
- * But sometimes you want to check whether a text at a given position might've had some attribute,
1608
- * in which case you can create a context by mixing in an array of elements with a `'$text'` string:
1609
- *
1610
- * // Check in [ rootElement, paragraphElement, textNode ].
1611
- * schema.checkChild( [ ...positionInParagraph.getAncestors(), '$text' ], 'bold' );
1612
- *
1613
- * @typedef {module:engine/model/node~Node|module:engine/model/position~Position|module:engine/model/schema~SchemaContext|
1614
- * String|Array.<String|module:engine/model/node~Node>} module:engine/model/schema~SchemaContextDefinition
1615
- */
1616
-
1617
- /**
1618
- * An item of the {@link module:engine/model/schema~SchemaContext schema context}.
1619
- *
1620
- * It contains 3 properties:
1621
- *
1622
- * * `name` – the name of this item,
1623
- * * `* getAttributeKeys()` – a generator of keys of item attributes,
1624
- * * `getAttribute( keyName )` – a method to get attribute values.
1625
- *
1626
- * The context item interface is a highly simplified version of {@link module:engine/model/node~Node} and its role
1627
- * is to expose only the information which schema checks are able to provide (which is the name of the node and
1628
- * node's attributes).
1629
- *
1630
- * schema.on( 'checkChild', ( evt, args ) => {
1631
- * const ctx = args[ 0 ];
1632
- * const firstItem = ctx.getItem( 0 );
1633
- *
1634
- * console.log( firstItem.name ); // -> '$root'
1635
- * console.log( firstItem.getAttribute( 'foo' ) ); // -> 'bar'
1636
- * console.log( Array.from( firstItem.getAttributeKeys() ) ); // -> [ 'foo', 'faa' ]
1637
- * } );
1638
- *
1639
- * @typedef {Object} module:engine/model/schema~SchemaContextItem
1640
- */
1641
-
1642
- /**
1643
- * A structure containing additional metadata describing the attribute.
1644
- *
1645
- * See {@link module:engine/model/schema~Schema#setAttributeProperties `Schema#setAttributeProperties()`} for usage examples.
1646
- *
1647
- * @typedef {Object} module:engine/model/schema~AttributeProperties
1648
- * @property {Boolean} [isFormatting] Indicates that the attribute should be considered as a visual formatting, like `bold`, `italic` or
1649
- * `fontSize` rather than semantic attribute (such as `src`, `listType`, etc.). For example, it is used by the "Remove format" feature.
1650
- * @property {Boolean} [copyOnEnter] Indicates that given text attribute should be copied to the next block when enter is pressed.
1651
- */
1652
-
1653
- function compileBaseItemRule( sourceItemRules, itemName ) {
1654
- const itemRule = {
1655
- name: itemName,
1656
-
1657
- allowIn: [],
1658
- allowContentOf: [],
1659
- allowWhere: [],
1660
-
1661
- allowAttributes: [],
1662
- allowAttributesOf: [],
1663
-
1664
- allowChildren: [],
1665
-
1666
- inheritTypesFrom: []
1667
- };
1668
-
1669
- copyTypes( sourceItemRules, itemRule );
1670
-
1671
- copyProperty( sourceItemRules, itemRule, 'allowIn' );
1672
- copyProperty( sourceItemRules, itemRule, 'allowContentOf' );
1673
- copyProperty( sourceItemRules, itemRule, 'allowWhere' );
1674
-
1675
- copyProperty( sourceItemRules, itemRule, 'allowAttributes' );
1676
- copyProperty( sourceItemRules, itemRule, 'allowAttributesOf' );
1677
-
1678
- copyProperty( sourceItemRules, itemRule, 'allowChildren' );
1679
-
1680
- copyProperty( sourceItemRules, itemRule, 'inheritTypesFrom' );
1681
-
1682
- makeInheritAllWork( sourceItemRules, itemRule );
1683
-
1684
- return itemRule;
1064
+ function compileBaseItemRule(sourceItemRules, itemName) {
1065
+ const itemRule = {
1066
+ name: itemName,
1067
+ allowIn: [],
1068
+ allowContentOf: [],
1069
+ allowWhere: [],
1070
+ allowAttributes: [],
1071
+ allowAttributesOf: [],
1072
+ allowChildren: [],
1073
+ inheritTypesFrom: []
1074
+ };
1075
+ copyTypes(sourceItemRules, itemRule);
1076
+ copyProperty(sourceItemRules, itemRule, 'allowIn');
1077
+ copyProperty(sourceItemRules, itemRule, 'allowContentOf');
1078
+ copyProperty(sourceItemRules, itemRule, 'allowWhere');
1079
+ copyProperty(sourceItemRules, itemRule, 'allowAttributes');
1080
+ copyProperty(sourceItemRules, itemRule, 'allowAttributesOf');
1081
+ copyProperty(sourceItemRules, itemRule, 'allowChildren');
1082
+ copyProperty(sourceItemRules, itemRule, 'inheritTypesFrom');
1083
+ makeInheritAllWork(sourceItemRules, itemRule);
1084
+ return itemRule;
1685
1085
  }
1686
-
1687
- function compileAllowChildren( compiledDefinitions, itemName ) {
1688
- const item = compiledDefinitions[ itemName ];
1689
-
1690
- for ( const allowChildrenItem of item.allowChildren ) {
1691
- const allowedChildren = compiledDefinitions[ allowChildrenItem ];
1692
-
1693
- // The allowChildren property may point to an unregistered element.
1694
- if ( !allowedChildren ) {
1695
- continue;
1696
- }
1697
-
1698
- allowedChildren.allowIn.push( itemName );
1699
- }
1700
-
1701
- // The allowIn property already includes correct items, reset the allowChildren property
1702
- // to avoid duplicates later when setting up compilation results.
1703
- item.allowChildren.length = 0;
1086
+ function compileAllowChildren(compiledDefinitions, itemName) {
1087
+ const item = compiledDefinitions[itemName];
1088
+ for (const allowChildrenItem of item.allowChildren) {
1089
+ const allowedChildren = compiledDefinitions[allowChildrenItem];
1090
+ // The allowChildren property may point to an unregistered element.
1091
+ if (!allowedChildren) {
1092
+ continue;
1093
+ }
1094
+ allowedChildren.allowIn.push(itemName);
1095
+ }
1096
+ // The allowIn property already includes correct items, reset the allowChildren property
1097
+ // to avoid duplicates later when setting up compilation results.
1098
+ item.allowChildren.length = 0;
1704
1099
  }
1705
-
1706
- function compileAllowContentOf( compiledDefinitions, itemName ) {
1707
- for ( const allowContentOfItemName of compiledDefinitions[ itemName ].allowContentOf ) {
1708
- // The allowContentOf property may point to an unregistered element.
1709
- if ( compiledDefinitions[ allowContentOfItemName ] ) {
1710
- const allowedChildren = getAllowedChildren( compiledDefinitions, allowContentOfItemName );
1711
-
1712
- allowedChildren.forEach( allowedItem => {
1713
- allowedItem.allowIn.push( itemName );
1714
- } );
1715
- }
1716
- }
1717
-
1718
- delete compiledDefinitions[ itemName ].allowContentOf;
1100
+ function compileAllowContentOf(compiledDefinitions, itemName) {
1101
+ for (const allowContentOfItemName of compiledDefinitions[itemName].allowContentOf) {
1102
+ // The allowContentOf property may point to an unregistered element.
1103
+ if (compiledDefinitions[allowContentOfItemName]) {
1104
+ const allowedChildren = getAllowedChildren(compiledDefinitions, allowContentOfItemName);
1105
+ allowedChildren.forEach(allowedItem => {
1106
+ allowedItem.allowIn.push(itemName);
1107
+ });
1108
+ }
1109
+ }
1110
+ delete compiledDefinitions[itemName].allowContentOf;
1719
1111
  }
1720
-
1721
- function compileAllowWhere( compiledDefinitions, itemName ) {
1722
- for ( const allowWhereItemName of compiledDefinitions[ itemName ].allowWhere ) {
1723
- const inheritFrom = compiledDefinitions[ allowWhereItemName ];
1724
-
1725
- // The allowWhere property may point to an unregistered element.
1726
- if ( inheritFrom ) {
1727
- const allowedIn = inheritFrom.allowIn;
1728
-
1729
- compiledDefinitions[ itemName ].allowIn.push( ...allowedIn );
1730
- }
1731
- }
1732
-
1733
- delete compiledDefinitions[ itemName ].allowWhere;
1112
+ function compileAllowWhere(compiledDefinitions, itemName) {
1113
+ for (const allowWhereItemName of compiledDefinitions[itemName].allowWhere) {
1114
+ const inheritFrom = compiledDefinitions[allowWhereItemName];
1115
+ // The allowWhere property may point to an unregistered element.
1116
+ if (inheritFrom) {
1117
+ const allowedIn = inheritFrom.allowIn;
1118
+ compiledDefinitions[itemName].allowIn.push(...allowedIn);
1119
+ }
1120
+ }
1121
+ delete compiledDefinitions[itemName].allowWhere;
1734
1122
  }
1735
-
1736
- function compileAllowAttributesOf( compiledDefinitions, itemName ) {
1737
- for ( const allowAttributeOfItem of compiledDefinitions[ itemName ].allowAttributesOf ) {
1738
- const inheritFrom = compiledDefinitions[ allowAttributeOfItem ];
1739
-
1740
- if ( inheritFrom ) {
1741
- const inheritAttributes = inheritFrom.allowAttributes;
1742
-
1743
- compiledDefinitions[ itemName ].allowAttributes.push( ...inheritAttributes );
1744
- }
1745
- }
1746
-
1747
- delete compiledDefinitions[ itemName ].allowAttributesOf;
1123
+ function compileAllowAttributesOf(compiledDefinitions, itemName) {
1124
+ for (const allowAttributeOfItem of compiledDefinitions[itemName].allowAttributesOf) {
1125
+ const inheritFrom = compiledDefinitions[allowAttributeOfItem];
1126
+ if (inheritFrom) {
1127
+ const inheritAttributes = inheritFrom.allowAttributes;
1128
+ compiledDefinitions[itemName].allowAttributes.push(...inheritAttributes);
1129
+ }
1130
+ }
1131
+ delete compiledDefinitions[itemName].allowAttributesOf;
1748
1132
  }
1749
-
1750
- function compileInheritPropertiesFrom( compiledDefinitions, itemName ) {
1751
- const item = compiledDefinitions[ itemName ];
1752
-
1753
- for ( const inheritPropertiesOfItem of item.inheritTypesFrom ) {
1754
- const inheritFrom = compiledDefinitions[ inheritPropertiesOfItem ];
1755
-
1756
- if ( inheritFrom ) {
1757
- const typeNames = Object.keys( inheritFrom ).filter( name => name.startsWith( 'is' ) );
1758
-
1759
- for ( const name of typeNames ) {
1760
- if ( !( name in item ) ) {
1761
- item[ name ] = inheritFrom[ name ];
1762
- }
1763
- }
1764
- }
1765
- }
1766
-
1767
- delete item.inheritTypesFrom;
1133
+ function compileInheritPropertiesFrom(compiledDefinitions, itemName) {
1134
+ const item = compiledDefinitions[itemName];
1135
+ for (const inheritPropertiesOfItem of item.inheritTypesFrom) {
1136
+ const inheritFrom = compiledDefinitions[inheritPropertiesOfItem];
1137
+ if (inheritFrom) {
1138
+ const typeNames = Object.keys(inheritFrom).filter(name => name.startsWith('is'));
1139
+ for (const name of typeNames) {
1140
+ if (!(name in item)) {
1141
+ item[name] = inheritFrom[name];
1142
+ }
1143
+ }
1144
+ }
1145
+ }
1146
+ delete item.inheritTypesFrom;
1768
1147
  }
1769
-
1770
1148
  // Remove items which weren't registered (because it may break some checks or we'd need to complicate them).
1771
1149
  // Make sure allowIn doesn't contain repeated values.
1772
- function cleanUpAllowIn( compiledDefinitions, itemName ) {
1773
- const itemRule = compiledDefinitions[ itemName ];
1774
- const existingItems = itemRule.allowIn.filter( itemToCheck => compiledDefinitions[ itemToCheck ] );
1775
-
1776
- itemRule.allowIn = Array.from( new Set( existingItems ) );
1150
+ function cleanUpAllowIn(compiledDefinitions, itemName) {
1151
+ const itemRule = compiledDefinitions[itemName];
1152
+ const existingItems = itemRule.allowIn.filter(itemToCheck => compiledDefinitions[itemToCheck]);
1153
+ itemRule.allowIn = Array.from(new Set(existingItems));
1777
1154
  }
1778
-
1779
1155
  // Setup allowChildren items based on allowIn.
1780
- function setupAllowChildren( compiledDefinitions, itemName ) {
1781
- const itemRule = compiledDefinitions[ itemName ];
1782
-
1783
- for ( const allowedParentItemName of itemRule.allowIn ) {
1784
- const allowedParentItem = compiledDefinitions[ allowedParentItemName ];
1785
-
1786
- allowedParentItem.allowChildren.push( itemName );
1787
- }
1156
+ function setupAllowChildren(compiledDefinitions, itemName) {
1157
+ const itemRule = compiledDefinitions[itemName];
1158
+ for (const allowedParentItemName of itemRule.allowIn) {
1159
+ const allowedParentItem = compiledDefinitions[allowedParentItemName];
1160
+ allowedParentItem.allowChildren.push(itemName);
1161
+ }
1788
1162
  }
1789
-
1790
- function cleanUpAllowAttributes( compiledDefinitions, itemName ) {
1791
- const itemRule = compiledDefinitions[ itemName ];
1792
-
1793
- itemRule.allowAttributes = Array.from( new Set( itemRule.allowAttributes ) );
1163
+ function cleanUpAllowAttributes(compiledDefinitions, itemName) {
1164
+ const itemRule = compiledDefinitions[itemName];
1165
+ itemRule.allowAttributes = Array.from(new Set(itemRule.allowAttributes));
1794
1166
  }
1795
-
1796
- function copyTypes( sourceItemRules, itemRule ) {
1797
- for ( const sourceItemRule of sourceItemRules ) {
1798
- const typeNames = Object.keys( sourceItemRule ).filter( name => name.startsWith( 'is' ) );
1799
-
1800
- for ( const name of typeNames ) {
1801
- itemRule[ name ] = sourceItemRule[ name ];
1802
- }
1803
- }
1167
+ function copyTypes(sourceItemRules, itemRule) {
1168
+ for (const sourceItemRule of sourceItemRules) {
1169
+ const typeNames = Object.keys(sourceItemRule).filter(name => name.startsWith('is'));
1170
+ for (const name of typeNames) {
1171
+ itemRule[name] = !!sourceItemRule[name];
1172
+ }
1173
+ }
1804
1174
  }
1805
-
1806
- function copyProperty( sourceItemRules, itemRule, propertyName ) {
1807
- for ( const sourceItemRule of sourceItemRules ) {
1808
- if ( typeof sourceItemRule[ propertyName ] == 'string' ) {
1809
- itemRule[ propertyName ].push( sourceItemRule[ propertyName ] );
1810
- } else if ( Array.isArray( sourceItemRule[ propertyName ] ) ) {
1811
- itemRule[ propertyName ].push( ...sourceItemRule[ propertyName ] );
1812
- }
1813
- }
1175
+ function copyProperty(sourceItemRules, itemRule, propertyName) {
1176
+ for (const sourceItemRule of sourceItemRules) {
1177
+ const value = sourceItemRule[propertyName];
1178
+ if (typeof value == 'string') {
1179
+ itemRule[propertyName].push(value);
1180
+ }
1181
+ else if (Array.isArray(value)) {
1182
+ itemRule[propertyName].push(...value);
1183
+ }
1184
+ }
1814
1185
  }
1815
-
1816
- function makeInheritAllWork( sourceItemRules, itemRule ) {
1817
- for ( const sourceItemRule of sourceItemRules ) {
1818
- const inheritFrom = sourceItemRule.inheritAllFrom;
1819
-
1820
- if ( inheritFrom ) {
1821
- itemRule.allowContentOf.push( inheritFrom );
1822
- itemRule.allowWhere.push( inheritFrom );
1823
- itemRule.allowAttributesOf.push( inheritFrom );
1824
- itemRule.inheritTypesFrom.push( inheritFrom );
1825
- }
1826
- }
1186
+ function makeInheritAllWork(sourceItemRules, itemRule) {
1187
+ for (const sourceItemRule of sourceItemRules) {
1188
+ const inheritFrom = sourceItemRule.inheritAllFrom;
1189
+ if (inheritFrom) {
1190
+ itemRule.allowContentOf.push(inheritFrom);
1191
+ itemRule.allowWhere.push(inheritFrom);
1192
+ itemRule.allowAttributesOf.push(inheritFrom);
1193
+ itemRule.inheritTypesFrom.push(inheritFrom);
1194
+ }
1195
+ }
1827
1196
  }
1828
-
1829
- function getAllowedChildren( compiledDefinitions, itemName ) {
1830
- const itemRule = compiledDefinitions[ itemName ];
1831
-
1832
- return getValues( compiledDefinitions ).filter( def => def.allowIn.includes( itemRule.name ) );
1197
+ function getAllowedChildren(compiledDefinitions, itemName) {
1198
+ const itemRule = compiledDefinitions[itemName];
1199
+ return getValues(compiledDefinitions).filter(def => def.allowIn.includes(itemRule.name));
1833
1200
  }
1834
-
1835
- function getValues( obj ) {
1836
- return Object.keys( obj ).map( key => obj[ key ] );
1201
+ function getValues(obj) {
1202
+ return Object.keys(obj).map(key => obj[key]);
1837
1203
  }
1838
-
1839
- function mapContextItem( ctxItem ) {
1840
- if ( typeof ctxItem == 'string' || ctxItem.is( 'documentFragment' ) ) {
1841
- return {
1842
- name: typeof ctxItem == 'string' ? ctxItem : '$documentFragment',
1843
-
1844
- * getAttributeKeys() {},
1845
-
1846
- getAttribute() {}
1847
- };
1848
- } else {
1849
- return {
1850
- // '$text' means text nodes and text proxies.
1851
- name: ctxItem.is( 'element' ) ? ctxItem.name : '$text',
1852
-
1853
- * getAttributeKeys() {
1854
- yield* ctxItem.getAttributeKeys();
1855
- },
1856
-
1857
- getAttribute( key ) {
1858
- return ctxItem.getAttribute( key );
1859
- }
1860
- };
1861
- }
1204
+ function mapContextItem(ctxItem) {
1205
+ if (typeof ctxItem == 'string' || ctxItem.is('documentFragment')) {
1206
+ return {
1207
+ name: typeof ctxItem == 'string' ? ctxItem : '$documentFragment',
1208
+ *getAttributeKeys() { },
1209
+ getAttribute() { }
1210
+ };
1211
+ }
1212
+ else {
1213
+ return {
1214
+ // '$text' means text nodes and text proxies.
1215
+ name: ctxItem.is('element') ? ctxItem.name : '$text',
1216
+ *getAttributeKeys() {
1217
+ yield* ctxItem.getAttributeKeys();
1218
+ },
1219
+ getAttribute(key) {
1220
+ return ctxItem.getAttribute(key);
1221
+ }
1222
+ };
1223
+ }
1862
1224
  }
1863
-
1864
1225
  // Generator function returning values from provided walkers, switching between them at each iteration. If only one walker
1865
1226
  // is provided it will return data only from that walker.
1866
1227
  //
@@ -1868,53 +1229,46 @@ function mapContextItem( ctxItem ) {
1868
1229
  // @param {module:engine/module/treewalker~TreeWalker} [forward] Walker iterating in forward direction.
1869
1230
  // @returns {Iterable.<Object>} Object returned at each iteration contains `value` and `walker` (informing which walker returned
1870
1231
  // given value) fields.
1871
- function* combineWalkers( backward, forward ) {
1872
- let done = false;
1873
-
1874
- while ( !done ) {
1875
- done = true;
1876
-
1877
- if ( backward ) {
1878
- const step = backward.next();
1879
-
1880
- if ( !step.done ) {
1881
- done = false;
1882
- yield {
1883
- walker: backward,
1884
- value: step.value
1885
- };
1886
- }
1887
- }
1888
-
1889
- if ( forward ) {
1890
- const step = forward.next();
1891
-
1892
- if ( !step.done ) {
1893
- done = false;
1894
- yield {
1895
- walker: forward,
1896
- value: step.value
1897
- };
1898
- }
1899
- }
1900
- }
1232
+ function* combineWalkers(backward, forward) {
1233
+ let done = false;
1234
+ while (!done) {
1235
+ done = true;
1236
+ if (backward) {
1237
+ const step = backward.next();
1238
+ if (!step.done) {
1239
+ done = false;
1240
+ yield {
1241
+ walker: backward,
1242
+ value: step.value
1243
+ };
1244
+ }
1245
+ }
1246
+ if (forward) {
1247
+ const step = forward.next();
1248
+ if (!step.done) {
1249
+ done = false;
1250
+ yield {
1251
+ walker: forward,
1252
+ value: step.value
1253
+ };
1254
+ }
1255
+ }
1256
+ }
1901
1257
  }
1902
-
1903
1258
  // Takes an array of non-intersecting ranges. For each of them gets minimal flat ranges covering that range and returns
1904
1259
  // all those minimal flat ranges.
1905
1260
  //
1906
1261
  // @param {Array.<module:engine/model/range~Range>} ranges Ranges to process.
1907
1262
  // @returns {Iterable.<module:engine/model/range~Range>} Minimal flat ranges of given `ranges`.
1908
- function* convertToMinimalFlatRanges( ranges ) {
1909
- for ( const range of ranges ) {
1910
- yield* range.getMinimalFlatRanges();
1911
- }
1263
+ function* convertToMinimalFlatRanges(ranges) {
1264
+ for (const range of ranges) {
1265
+ yield* range.getMinimalFlatRanges();
1266
+ }
1912
1267
  }
1913
-
1914
- function removeDisallowedAttributeFromNode( schema, node, writer ) {
1915
- for ( const attribute of node.getAttributeKeys() ) {
1916
- if ( !schema.checkAttribute( node, attribute ) ) {
1917
- writer.removeAttribute( attribute, node );
1918
- }
1919
- }
1268
+ function removeDisallowedAttributeFromNode(schema, node, writer) {
1269
+ for (const attribute of node.getAttributeKeys()) {
1270
+ if (!schema.checkAttribute(node, attribute)) {
1271
+ writer.removeAttribute(attribute, node);
1272
+ }
1273
+ }
1920
1274
  }