@ckeditor/ckeditor5-engine 30.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/LICENSE.md +17 -0
  2. package/README.md +30 -0
  3. package/package.json +70 -0
  4. package/src/controller/datacontroller.js +563 -0
  5. package/src/controller/editingcontroller.js +149 -0
  6. package/src/conversion/conversion.js +644 -0
  7. package/src/conversion/conversionhelpers.js +40 -0
  8. package/src/conversion/downcastdispatcher.js +914 -0
  9. package/src/conversion/downcasthelpers.js +1706 -0
  10. package/src/conversion/mapper.js +696 -0
  11. package/src/conversion/modelconsumable.js +329 -0
  12. package/src/conversion/upcastdispatcher.js +807 -0
  13. package/src/conversion/upcasthelpers.js +997 -0
  14. package/src/conversion/viewconsumable.js +623 -0
  15. package/src/dataprocessor/basichtmlwriter.js +32 -0
  16. package/src/dataprocessor/dataprocessor.jsdoc +64 -0
  17. package/src/dataprocessor/htmldataprocessor.js +159 -0
  18. package/src/dataprocessor/htmlwriter.js +22 -0
  19. package/src/dataprocessor/xmldataprocessor.js +161 -0
  20. package/src/dev-utils/model.js +482 -0
  21. package/src/dev-utils/operationreplayer.js +140 -0
  22. package/src/dev-utils/utils.js +103 -0
  23. package/src/dev-utils/view.js +1091 -0
  24. package/src/index.js +52 -0
  25. package/src/model/batch.js +82 -0
  26. package/src/model/differ.js +1282 -0
  27. package/src/model/document.js +483 -0
  28. package/src/model/documentfragment.js +390 -0
  29. package/src/model/documentselection.js +1261 -0
  30. package/src/model/element.js +438 -0
  31. package/src/model/history.js +138 -0
  32. package/src/model/item.jsdoc +14 -0
  33. package/src/model/liveposition.js +182 -0
  34. package/src/model/liverange.js +221 -0
  35. package/src/model/markercollection.js +553 -0
  36. package/src/model/model.js +934 -0
  37. package/src/model/node.js +507 -0
  38. package/src/model/nodelist.js +217 -0
  39. package/src/model/operation/attributeoperation.js +202 -0
  40. package/src/model/operation/detachoperation.js +103 -0
  41. package/src/model/operation/insertoperation.js +188 -0
  42. package/src/model/operation/markeroperation.js +154 -0
  43. package/src/model/operation/mergeoperation.js +216 -0
  44. package/src/model/operation/moveoperation.js +209 -0
  45. package/src/model/operation/nooperation.js +58 -0
  46. package/src/model/operation/operation.js +139 -0
  47. package/src/model/operation/operationfactory.js +49 -0
  48. package/src/model/operation/renameoperation.js +155 -0
  49. package/src/model/operation/rootattributeoperation.js +211 -0
  50. package/src/model/operation/splitoperation.js +254 -0
  51. package/src/model/operation/transform.js +2389 -0
  52. package/src/model/operation/utils.js +292 -0
  53. package/src/model/position.js +1164 -0
  54. package/src/model/range.js +1049 -0
  55. package/src/model/rootelement.js +111 -0
  56. package/src/model/schema.js +1851 -0
  57. package/src/model/selection.js +902 -0
  58. package/src/model/text.js +138 -0
  59. package/src/model/textproxy.js +279 -0
  60. package/src/model/treewalker.js +414 -0
  61. package/src/model/utils/autoparagraphing.js +77 -0
  62. package/src/model/utils/deletecontent.js +528 -0
  63. package/src/model/utils/getselectedcontent.js +150 -0
  64. package/src/model/utils/insertcontent.js +824 -0
  65. package/src/model/utils/modifyselection.js +229 -0
  66. package/src/model/utils/selection-post-fixer.js +297 -0
  67. package/src/model/writer.js +1574 -0
  68. package/src/view/attributeelement.js +274 -0
  69. package/src/view/containerelement.js +123 -0
  70. package/src/view/document.js +221 -0
  71. package/src/view/documentfragment.js +273 -0
  72. package/src/view/documentselection.js +387 -0
  73. package/src/view/domconverter.js +1437 -0
  74. package/src/view/downcastwriter.js +2121 -0
  75. package/src/view/editableelement.js +118 -0
  76. package/src/view/element.js +945 -0
  77. package/src/view/elementdefinition.jsdoc +59 -0
  78. package/src/view/emptyelement.js +119 -0
  79. package/src/view/filler.js +161 -0
  80. package/src/view/item.jsdoc +14 -0
  81. package/src/view/matcher.js +776 -0
  82. package/src/view/node.js +391 -0
  83. package/src/view/observer/arrowkeysobserver.js +58 -0
  84. package/src/view/observer/bubblingemittermixin.js +307 -0
  85. package/src/view/observer/bubblingeventinfo.js +71 -0
  86. package/src/view/observer/clickobserver.js +46 -0
  87. package/src/view/observer/compositionobserver.js +79 -0
  88. package/src/view/observer/domeventdata.js +82 -0
  89. package/src/view/observer/domeventobserver.js +99 -0
  90. package/src/view/observer/fakeselectionobserver.js +118 -0
  91. package/src/view/observer/focusobserver.js +106 -0
  92. package/src/view/observer/inputobserver.js +44 -0
  93. package/src/view/observer/keyobserver.js +83 -0
  94. package/src/view/observer/mouseobserver.js +56 -0
  95. package/src/view/observer/mutationobserver.js +345 -0
  96. package/src/view/observer/observer.js +118 -0
  97. package/src/view/observer/selectionobserver.js +242 -0
  98. package/src/view/placeholder.js +285 -0
  99. package/src/view/position.js +426 -0
  100. package/src/view/range.js +533 -0
  101. package/src/view/rawelement.js +148 -0
  102. package/src/view/renderer.js +1037 -0
  103. package/src/view/rooteditableelement.js +107 -0
  104. package/src/view/selection.js +718 -0
  105. package/src/view/styles/background.js +73 -0
  106. package/src/view/styles/border.js +362 -0
  107. package/src/view/styles/margin.js +41 -0
  108. package/src/view/styles/padding.js +40 -0
  109. package/src/view/styles/utils.js +277 -0
  110. package/src/view/stylesmap.js +938 -0
  111. package/src/view/text.js +147 -0
  112. package/src/view/textproxy.js +199 -0
  113. package/src/view/treewalker.js +496 -0
  114. package/src/view/uielement.js +238 -0
  115. package/src/view/upcastwriter.js +484 -0
  116. package/src/view/view.js +721 -0
  117. package/theme/placeholder.css +27 -0
@@ -0,0 +1,1851 @@
1
+ /**
2
+ * @license Copyright (c) 2003-2021, CKSource - Frederico Knabben. All rights reserved.
3
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4
+ */
5
+
6
+ /**
7
+ * @module engine/model/schema
8
+ */
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
+ import Element from './element';
17
+ import Text from './text';
18
+ import TreeWalker from './treewalker';
19
+
20
+ /**
21
+ * The model's schema. It defines the allowed and disallowed structures of nodes as well as nodes' attributes.
22
+ * The schema is usually defined by the features and based on them, the editing framework and features
23
+ * make decisions on how to change and process the model.
24
+ *
25
+ * The instance of schema is available in {@link module:engine/model/model~Model#schema `editor.model.schema`}.
26
+ *
27
+ * Read more about the schema in:
28
+ *
29
+ * * The {@glink framework/guides/architecture/editing-engine#schema schema section} of the
30
+ * {@glink framework/guides/architecture/editing-engine Introduction to the Editing engine architecture} guide.
31
+ * * The {@glink framework/guides/deep-dive/schema Schema deep dive} guide.
32
+ *
33
+ * @mixes module:utils/observablemixin~ObservableMixin
34
+ */
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
+ * Removes attributes disallowed by the schema.
839
+ *
840
+ * @param {Iterable.<module:engine/model/node~Node>} nodes Nodes that will be filtered.
841
+ * @param {module:engine/model/writer~Writer} writer
842
+ */
843
+ removeDisallowedAttributes( nodes, writer ) {
844
+ for ( const node of nodes ) {
845
+ // When node is a `Text` it has no children, so just filter it out.
846
+ if ( node.is( '$text' ) ) {
847
+ removeDisallowedAttributeFromNode( this, node, writer );
848
+ }
849
+ // In a case of `Element` iterates through positions between nodes inside this element
850
+ // and filter out node before the current position, or position parent when position
851
+ // is at start of an element. Using positions prevent from omitting merged nodes
852
+ // see https://github.com/ckeditor/ckeditor5-engine/issues/1789.
853
+ else {
854
+ const rangeInNode = Range._createIn( node );
855
+ const positionsInRange = rangeInNode.getPositions();
856
+
857
+ for ( const position of positionsInRange ) {
858
+ const item = position.nodeBefore || position.parent;
859
+
860
+ removeDisallowedAttributeFromNode( this, item, writer );
861
+ }
862
+ }
863
+ }
864
+ }
865
+
866
+ /**
867
+ * Creates an instance of the schema context.
868
+ *
869
+ * @param {module:engine/model/schema~SchemaContextDefinition} context
870
+ * @returns {module:engine/model/schema~SchemaContext}
871
+ */
872
+ createContext( context ) {
873
+ return new SchemaContext( context );
874
+ }
875
+
876
+ /**
877
+ * @private
878
+ */
879
+ _clearCache() {
880
+ this._compiledDefinitions = null;
881
+ }
882
+
883
+ /**
884
+ * @private
885
+ */
886
+ _compile() {
887
+ const compiledDefinitions = {};
888
+ const sourceRules = this._sourceDefinitions;
889
+ const itemNames = Object.keys( sourceRules );
890
+
891
+ for ( const itemName of itemNames ) {
892
+ compiledDefinitions[ itemName ] = compileBaseItemRule( sourceRules[ itemName ], itemName );
893
+ }
894
+
895
+ for ( const itemName of itemNames ) {
896
+ compileAllowChildren( compiledDefinitions, itemName );
897
+ }
898
+
899
+ for ( const itemName of itemNames ) {
900
+ compileAllowContentOf( compiledDefinitions, itemName );
901
+ }
902
+
903
+ for ( const itemName of itemNames ) {
904
+ compileAllowWhere( compiledDefinitions, itemName );
905
+ }
906
+
907
+ for ( const itemName of itemNames ) {
908
+ compileAllowAttributesOf( compiledDefinitions, itemName );
909
+ compileInheritPropertiesFrom( compiledDefinitions, itemName );
910
+ }
911
+
912
+ for ( const itemName of itemNames ) {
913
+ cleanUpAllowIn( compiledDefinitions, itemName );
914
+ setupAllowChildren( compiledDefinitions, itemName );
915
+ cleanUpAllowAttributes( compiledDefinitions, itemName );
916
+ }
917
+
918
+ this._compiledDefinitions = compiledDefinitions;
919
+ }
920
+
921
+ /**
922
+ * @private
923
+ * @param {module:engine/model/schema~SchemaCompiledItemDefinition} def
924
+ * @param {module:engine/model/schema~SchemaContext} context
925
+ * @param {Number} contextItemIndex
926
+ */
927
+ _checkContextMatch( def, context, contextItemIndex = context.length - 1 ) {
928
+ const contextItem = context.getItem( contextItemIndex );
929
+
930
+ if ( def.allowIn.includes( contextItem.name ) ) {
931
+ if ( contextItemIndex == 0 ) {
932
+ return true;
933
+ } else {
934
+ const parentRule = this.getDefinition( contextItem );
935
+
936
+ return this._checkContextMatch( parentRule, context, contextItemIndex - 1 );
937
+ }
938
+ } else {
939
+ return false;
940
+ }
941
+ }
942
+
943
+ /**
944
+ * Takes a flat range and an attribute name. Traverses the range recursively and deeply to find and return all ranges
945
+ * inside the given range on which the attribute can be applied.
946
+ *
947
+ * This is a helper function for {@link ~Schema#getValidRanges}.
948
+ *
949
+ * @private
950
+ * @param {module:engine/model/range~Range} range The range to process.
951
+ * @param {String} attribute The name of the attribute to check.
952
+ * @returns {Iterable.<module:engine/model/range~Range>} Ranges in which the attribute is allowed.
953
+ */
954
+ * _getValidRangesForRange( range, attribute ) {
955
+ let start = range.start;
956
+ let end = range.start;
957
+
958
+ for ( const item of range.getItems( { shallow: true } ) ) {
959
+ if ( item.is( 'element' ) ) {
960
+ yield* this._getValidRangesForRange( Range._createIn( item ), attribute );
961
+ }
962
+
963
+ if ( !this.checkAttribute( item, attribute ) ) {
964
+ if ( !start.isEqual( end ) ) {
965
+ yield new Range( start, end );
966
+ }
967
+
968
+ start = Position._createAfter( item );
969
+ }
970
+
971
+ end = Position._createAfter( item );
972
+ }
973
+
974
+ if ( !start.isEqual( end ) ) {
975
+ yield new Range( start, end );
976
+ }
977
+ }
978
+ }
979
+
980
+ mix( Schema, ObservableMixin );
981
+
982
+ /**
983
+ * Event fired when the {@link #checkChild} method is called. It allows plugging in
984
+ * additional behavior, for example implementing rules which cannot be defined using the declarative
985
+ * {@link module:engine/model/schema~SchemaItemDefinition} interface.
986
+ *
987
+ * **Note:** The {@link #addChildCheck} method is a more handy way to register callbacks. Internally,
988
+ * it registers a listener to this event but comes with a simpler API and it is the recommended choice
989
+ * in most of the cases.
990
+ *
991
+ * The {@link #checkChild} method fires an event because it is
992
+ * {@link module:utils/observablemixin~ObservableMixin#decorate decorated} with it. Thanks to that you can
993
+ * use this event in various ways, but the most important use case is overriding standard behavior of the
994
+ * `checkChild()` method. Let's see a typical listener template:
995
+ *
996
+ * schema.on( 'checkChild', ( evt, args ) => {
997
+ * const context = args[ 0 ];
998
+ * const childDefinition = args[ 1 ];
999
+ * }, { priority: 'high' } );
1000
+ *
1001
+ * The listener is added with a `high` priority to be executed before the default method is really called. The `args` callback
1002
+ * parameter contains arguments passed to `checkChild( context, child )`. However, the `context` parameter is already
1003
+ * normalized to a {@link module:engine/model/schema~SchemaContext} instance and `child` to a
1004
+ * {@link module:engine/model/schema~SchemaCompiledItemDefinition} instance, so you do not have to worry about
1005
+ * the various ways how `context` and `child` may be passed to `checkChild()`.
1006
+ *
1007
+ * **Note:** `childDefinition` may be `undefined` if `checkChild()` was called with a non-registered element.
1008
+ *
1009
+ * So, in order to implement a rule "disallow `heading1` in `blockQuote`", you can add such a listener:
1010
+ *
1011
+ * schema.on( 'checkChild', ( evt, args ) => {
1012
+ * const context = args[ 0 ];
1013
+ * const childDefinition = args[ 1 ];
1014
+ *
1015
+ * if ( context.endsWith( 'blockQuote' ) && childDefinition && childDefinition.name == 'heading1' ) {
1016
+ * // Prevent next listeners from being called.
1017
+ * evt.stop();
1018
+ * // Set the checkChild()'s return value.
1019
+ * evt.return = false;
1020
+ * }
1021
+ * }, { priority: 'high' } );
1022
+ *
1023
+ * Allowing elements in specific contexts will be a far less common use case, because it is normally handled by the
1024
+ * `allowIn` rule from {@link module:engine/model/schema~SchemaItemDefinition}. But if you have a complex scenario
1025
+ * where `listItem` should be allowed only in element `foo` which must be in element `bar`, then this would be the way:
1026
+ *
1027
+ * schema.on( 'checkChild', ( evt, args ) => {
1028
+ * const context = args[ 0 ];
1029
+ * const childDefinition = args[ 1 ];
1030
+ *
1031
+ * if ( context.endsWith( 'bar foo' ) && childDefinition.name == 'listItem' ) {
1032
+ * // Prevent next listeners from being called.
1033
+ * evt.stop();
1034
+ * // Set the checkChild()'s return value.
1035
+ * evt.return = true;
1036
+ * }
1037
+ * }, { priority: 'high' } );
1038
+ *
1039
+ * @event checkChild
1040
+ * @param {Array} args The `checkChild()`'s arguments.
1041
+ */
1042
+
1043
+ /**
1044
+ * Event fired when the {@link #checkAttribute} method is called. It allows plugging in
1045
+ * additional behavior, for example implementing rules which cannot be defined using the declarative
1046
+ * {@link module:engine/model/schema~SchemaItemDefinition} interface.
1047
+ *
1048
+ * **Note:** The {@link #addAttributeCheck} method is a more handy way to register callbacks. Internally,
1049
+ * it registers a listener to this event but comes with a simpler API and it is the recommended choice
1050
+ * in most of the cases.
1051
+ *
1052
+ * The {@link #checkAttribute} method fires an event because it is
1053
+ * {@link module:utils/observablemixin~ObservableMixin#decorate decorated} with it. Thanks to that you can
1054
+ * use this event in various ways, but the most important use case is overriding the standard behavior of the
1055
+ * `checkAttribute()` method. Let's see a typical listener template:
1056
+ *
1057
+ * schema.on( 'checkAttribute', ( evt, args ) => {
1058
+ * const context = args[ 0 ];
1059
+ * const attributeName = args[ 1 ];
1060
+ * }, { priority: 'high' } );
1061
+ *
1062
+ * The listener is added with a `high` priority to be executed before the default method is really called. The `args` callback
1063
+ * parameter contains arguments passed to `checkAttribute( context, attributeName )`. However, the `context` parameter is already
1064
+ * normalized to a {@link module:engine/model/schema~SchemaContext} instance, so you do not have to worry about
1065
+ * the various ways how `context` may be passed to `checkAttribute()`.
1066
+ *
1067
+ * So, in order to implement a rule "disallow `bold` in a text which is in a `heading1`, you can add such a listener:
1068
+ *
1069
+ * schema.on( 'checkAttribute', ( evt, args ) => {
1070
+ * const context = args[ 0 ];
1071
+ * const attributeName = args[ 1 ];
1072
+ *
1073
+ * if ( context.endsWith( 'heading1 $text' ) && attributeName == 'bold' ) {
1074
+ * // Prevent next listeners from being called.
1075
+ * evt.stop();
1076
+ * // Set the checkAttribute()'s return value.
1077
+ * evt.return = false;
1078
+ * }
1079
+ * }, { priority: 'high' } );
1080
+ *
1081
+ * Allowing attributes in specific contexts will be a far less common use case, because it is normally handled by the
1082
+ * `allowAttributes` rule from {@link module:engine/model/schema~SchemaItemDefinition}. But if you have a complex scenario
1083
+ * where `bold` should be allowed only in element `foo` which must be in element `bar`, then this would be the way:
1084
+ *
1085
+ * schema.on( 'checkAttribute', ( evt, args ) => {
1086
+ * const context = args[ 0 ];
1087
+ * const attributeName = args[ 1 ];
1088
+ *
1089
+ * if ( context.endsWith( 'bar foo $text' ) && attributeName == 'bold' ) {
1090
+ * // Prevent next listeners from being called.
1091
+ * evt.stop();
1092
+ * // Set the checkAttribute()'s return value.
1093
+ * evt.return = true;
1094
+ * }
1095
+ * }, { priority: 'high' } );
1096
+ *
1097
+ * @event checkAttribute
1098
+ * @param {Array} args The `checkAttribute()`'s arguments.
1099
+ */
1100
+
1101
+ /**
1102
+ * A definition of a {@link module:engine/model/schema~Schema schema} item.
1103
+ *
1104
+ * You can define the following rules:
1105
+ *
1106
+ * * {@link ~SchemaItemDefinition#allowIn `allowIn`} &ndash; Defines in which other items this item will be allowed.
1107
+ * * {@link ~SchemaItemDefinition#allowChildren `allowChildren`} &ndash; Defines which other items are allowed inside this item.
1108
+ * * {@link ~SchemaItemDefinition#allowAttributes `allowAttributes`} &ndash; Defines allowed attributes of the given item.
1109
+ * * {@link ~SchemaItemDefinition#allowContentOf `allowContentOf`} &ndash; Inherits "allowed children" from other items.
1110
+ * * {@link ~SchemaItemDefinition#allowWhere `allowWhere`} &ndash; Inherits "allowed in" from other items.
1111
+ * * {@link ~SchemaItemDefinition#allowAttributesOf `allowAttributesOf`} &ndash; Inherits attributes from other items.
1112
+ * * {@link ~SchemaItemDefinition#inheritTypesFrom `inheritTypesFrom`} &ndash; Inherits `is*` properties of other items.
1113
+ * * {@link ~SchemaItemDefinition#inheritAllFrom `inheritAllFrom`} &ndash;
1114
+ * A shorthand for `allowContentOf`, `allowWhere`, `allowAttributesOf`, `inheritTypesFrom`.
1115
+ *
1116
+ * # The `is*` properties
1117
+ *
1118
+ * There are a couple commonly used `is*` properties. Their role is to assign additional semantics to schema items.
1119
+ * You can define more properties but you will also need to implement support for them in the existing editor features.
1120
+ *
1121
+ * * {@link ~SchemaItemDefinition#isBlock `isBlock`} &ndash; Whether this item is paragraph-like.
1122
+ * Generally speaking, content is usually made out of blocks like paragraphs, list items, images, headings, etc.
1123
+ * * {@link ~SchemaItemDefinition#isInline `isInline`} &ndash; Whether an item is "text-like" and should be treated as an inline node.
1124
+ * Examples of inline elements: `$text`, `softBreak` (`<br>`), etc.
1125
+ * * {@link ~SchemaItemDefinition#isLimit `isLimit`} &ndash; It can be understood as whether this element
1126
+ * should not be split by <kbd>Enter</kbd>. Examples of limit elements: `$root`, table cell, image caption, etc.
1127
+ * In other words, all actions that happen inside a limit element are limited to its content.
1128
+ * All objects are treated as limit elements, too.
1129
+ * * {@link ~SchemaItemDefinition#isObject `isObject`} &ndash; Whether an item is "self-contained" and should be treated as a whole.
1130
+ * Examples of object elements: `imageBlock`, `table`, `video`, etc. An object is also a limit, so
1131
+ * {@link module:engine/model/schema~Schema#isLimit `isLimit()`} returns `true` for object elements automatically.
1132
+ *
1133
+ * Read more about the meaning of these types in the
1134
+ * {@glink framework/guides/deep-dive/schema#defining-additional-semantics dedicated section of the Schema deep dive} guide.
1135
+ *
1136
+ * # Generic items
1137
+ *
1138
+ * There are three basic generic items: `$root`, `$block` and `$text`.
1139
+ * They are defined as follows:
1140
+ *
1141
+ * this.schema.register( '$root', {
1142
+ * isLimit: true
1143
+ * } );
1144
+ * this.schema.register( '$block', {
1145
+ * allowIn: '$root',
1146
+ * isBlock: true
1147
+ * } );
1148
+ * this.schema.register( '$text', {
1149
+ * allowIn: '$block',
1150
+ * isInline: true
1151
+ * } );
1152
+ *
1153
+ * They reflect typical editor content that is contained within one root, consists of several blocks
1154
+ * (paragraphs, lists items, headings, images) which, in turn, may contain text inside.
1155
+ *
1156
+ * By inheriting from the generic items you can define new items which will get extended by other editor features.
1157
+ * Read more about generic types in the {@glink framework/guides/deep-dive/schema Schema deep dive} guide.
1158
+ *
1159
+ * # Example definitions
1160
+ *
1161
+ * Allow `paragraph` in roots and block quotes:
1162
+ *
1163
+ * schema.register( 'paragraph', {
1164
+ * allowIn: [ '$root', 'blockQuote' ],
1165
+ * isBlock: true
1166
+ * } );
1167
+ *
1168
+ * Allow `paragraph` everywhere where `$block` is allowed (i.e. in `$root`):
1169
+ *
1170
+ * schema.register( 'paragraph', {
1171
+ * allowWhere: '$block',
1172
+ * isBlock: true
1173
+ * } );
1174
+ *
1175
+ * Allow `paragraph` inside a `$root` and allow `$text` as a `paragraph` child:
1176
+ *
1177
+ * schema.register( 'paragraph', {
1178
+ * allowIn: '$root',
1179
+ * allowChildren: '$text',
1180
+ * isBlock: true
1181
+ * } );
1182
+ *
1183
+ * Make `imageBlock` a block object, which is allowed everywhere where `$block` is.
1184
+ * Also, allow `src` and `alt` attributes in it:
1185
+ *
1186
+ * schema.register( 'imageBlock', {
1187
+ * allowWhere: '$block',
1188
+ * allowAttributes: [ 'src', 'alt' ],
1189
+ * isBlock: true,
1190
+ * isObject: true
1191
+ * } );
1192
+ *
1193
+ * Make `caption` allowed in `imageBlock` and make it allow all the content of `$block`s (usually, `$text`).
1194
+ * Also, mark it as a limit element so it cannot be split:
1195
+ *
1196
+ * schema.register( 'caption', {
1197
+ * allowIn: 'imageBlock',
1198
+ * allowContentOf: '$block',
1199
+ * isLimit: true
1200
+ * } );
1201
+ *
1202
+ * Make `listItem` inherit all from `$block` but also allow additional attributes:
1203
+ *
1204
+ * schema.register( 'listItem', {
1205
+ * inheritAllFrom: '$block',
1206
+ * allowAttributes: [ 'listType', 'listIndent' ]
1207
+ * } );
1208
+ *
1209
+ * Which translates to:
1210
+ *
1211
+ * schema.register( 'listItem', {
1212
+ * allowWhere: '$block',
1213
+ * allowContentOf: '$block',
1214
+ * allowAttributesOf: '$block',
1215
+ * inheritTypesFrom: '$block',
1216
+ * allowAttributes: [ 'listType', 'listIndent' ]
1217
+ * } );
1218
+ *
1219
+ * # Tips
1220
+ *
1221
+ * * Check schema definitions of existing features to see how they are defined.
1222
+ * * If you want to publish your feature so other developers can use it, try to use
1223
+ * generic items as much as possible.
1224
+ * * Keep your model clean. Limit it to the actual data and store information in a normalized way.
1225
+ * * Remember about defining the `is*` properties. They do not affect the allowed structures, but they can
1226
+ * affect how the editor features treat your elements.
1227
+ *
1228
+ * @typedef {Object} module:engine/model/schema~SchemaItemDefinition
1229
+ *
1230
+ * @property {String|Array.<String>} allowIn Defines in which other items this item will be allowed.
1231
+ * @property {String|Array.<String>} allowChildren Defines which other items are allowed inside this item.
1232
+ * @property {String|Array.<String>} allowAttributes Defines allowed attributes of the given item.
1233
+ * @property {String|Array.<String>} allowContentOf Inherits "allowed children" from other items.
1234
+ * @property {String|Array.<String>} allowWhere Inherits "allowed in" from other items.
1235
+ * @property {String|Array.<String>} allowAttributesOf Inherits attributes from other items.
1236
+ * @property {String|Array.<String>} inheritTypesFrom Inherits `is*` properties of other items.
1237
+ * @property {String} inheritAllFrom A shorthand for `allowContentOf`, `allowWhere`, `allowAttributesOf`, `inheritTypesFrom`.
1238
+ *
1239
+ * @property {Boolean} isBlock
1240
+ * Whether this item is paragraph-like. Generally speaking, content is usually made out of blocks
1241
+ * like paragraphs, list items, images, headings, etc. All these elements are marked as blocks. A block
1242
+ * should not allow another block inside. Note: There is also the `$block` generic item which has `isBlock` set to `true`.
1243
+ * Most block type items will inherit from `$block` (through `inheritAllFrom`).
1244
+ *
1245
+ * Read more about the block elements in the
1246
+ * {@glink framework/guides/deep-dive/schema#block-elements Block elements section} of
1247
+ * the {@glink framework/guides/deep-dive/schema Schema deep dive}.
1248
+ *
1249
+ * @property {Boolean} isInline
1250
+ * Whether an item is "text-like" and should be treated as an inline node. Examples of inline elements:
1251
+ * `$text`, `softBreak` (`<br>`), etc.
1252
+ *
1253
+ * Read more about the inline elements in the
1254
+ * {@glink framework/guides/deep-dive/schema#inline-elements Inline elements section} of the Schema deep dive guide.
1255
+ *
1256
+ * @property {Boolean} isLimit
1257
+ * It can be understood as whether this element should not be split by <kbd>Enter</kbd>.
1258
+ * Examples of limit elements: `$root`, table cell, image caption, etc. In other words, all actions that happen inside
1259
+ * a limit element are limited to its content.
1260
+ *
1261
+ * Read more about the limit elements in the
1262
+ * {@glink framework/guides/deep-dive/schema#limit-elements Limit elements section} of
1263
+ * the {@glink framework/guides/deep-dive/schema Schema deep dive} guide.
1264
+ *
1265
+ * @property {Boolean} isObject
1266
+ * Whether an item is "self-contained" and should be treated as a whole. Examples of object elements:
1267
+ * `imageBlock`, `table`, `video`, etc.
1268
+ *
1269
+ * **Note:** An object is also a limit, so
1270
+ * {@link module:engine/model/schema~Schema#isLimit `isLimit()`} returns `true` for object elements automatically.
1271
+ *
1272
+ * Read more about the object elements in the
1273
+ * {@glink framework/guides/deep-dive/schema#object-elements Object elements section} of the Schema deep dive guide.
1274
+ *
1275
+ * @property {Boolean} isSelectable
1276
+ * `true` when an element should be selectable as a whole by the user. Examples of selectable elements: `imageBlock`, `table`, `tableCell`,
1277
+ * etc.
1278
+ *
1279
+ * **Note:** An object is also a selectable element, so
1280
+ * {@link module:engine/model/schema~Schema#isSelectable `isSelectable()`} returns `true` for object elements automatically.
1281
+ *
1282
+ * Read more about selectable elements in the
1283
+ * {@glink framework/guides/deep-dive/schema#selectable-elements Selectable elements section} of
1284
+ * the {@glink framework/guides/deep-dive/schema Schema deep dive} guide.
1285
+ *
1286
+ * @property {Boolean} isContent
1287
+ * 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.
1288
+ * Examples of content elements: `$text`, `imageBlock`, `table`, etc. (but not `paragraph`, `heading1` or `tableCell`).
1289
+ *
1290
+ * **Note:** An object is also a content element, so
1291
+ * {@link module:engine/model/schema~Schema#isContent `isContent()`} returns `true` for object elements automatically.
1292
+ *
1293
+ * Read more about content elements in the
1294
+ * {@glink framework/guides/deep-dive/schema#content-elements Content elements section} of
1295
+ * the {@glink framework/guides/deep-dive/schema Schema deep dive} guide.
1296
+ */
1297
+
1298
+ /**
1299
+ * A simplified version of {@link module:engine/model/schema~SchemaItemDefinition} after
1300
+ * compilation by the {@link module:engine/model/schema~Schema schema}.
1301
+ * Rules fed to the schema by {@link module:engine/model/schema~Schema#register}
1302
+ * and {@link module:engine/model/schema~Schema#extend} methods are defined in the
1303
+ * {@link module:engine/model/schema~SchemaItemDefinition} format.
1304
+ * Later on, they are compiled to `SchemaCompiledItemDefinition` so when you use e.g.
1305
+ * the {@link module:engine/model/schema~Schema#getDefinition} method you get the compiled version.
1306
+ *
1307
+ * The compiled version contains only the following properties:
1308
+ *
1309
+ * * The `name` property,
1310
+ * * The `is*` properties,
1311
+ * * The `allowIn` array,
1312
+ * * The `allowChildren` array,
1313
+ * * The `allowAttributes` array.
1314
+ *
1315
+ * @typedef {Object} module:engine/model/schema~SchemaCompiledItemDefinition
1316
+ */
1317
+
1318
+ /**
1319
+ * A schema context &mdash; a list of ancestors of a given position in the document.
1320
+ *
1321
+ * Considering such position:
1322
+ *
1323
+ * <$root>
1324
+ * <blockQuote>
1325
+ * <paragraph>
1326
+ * ^
1327
+ * </paragraph>
1328
+ * </blockQuote>
1329
+ * </$root>
1330
+ *
1331
+ * The context of this position is its {@link module:engine/model/position~Position#getAncestors lists of ancestors}:
1332
+ *
1333
+ * [ rootElement, blockQuoteElement, paragraphElement ]
1334
+ *
1335
+ * Contexts are used in the {@link module:engine/model/schema~Schema#event:checkChild `Schema#checkChild`} and
1336
+ * {@link module:engine/model/schema~Schema#event:checkAttribute `Schema#checkAttribute`} events as a definition
1337
+ * of a place in the document where the check occurs. The context instances are created based on the first arguments
1338
+ * of the {@link module:engine/model/schema~Schema#checkChild `Schema#checkChild()`} and
1339
+ * {@link module:engine/model/schema~Schema#checkAttribute `Schema#checkAttribute()`} methods so when
1340
+ * using these methods you need to use {@link module:engine/model/schema~SchemaContextDefinition}s.
1341
+ */
1342
+ export class SchemaContext {
1343
+ /**
1344
+ * Creates an instance of the context.
1345
+ *
1346
+ * @param {module:engine/model/schema~SchemaContextDefinition} context
1347
+ */
1348
+ constructor( context ) {
1349
+ if ( context instanceof SchemaContext ) {
1350
+ return context;
1351
+ }
1352
+
1353
+ if ( typeof context == 'string' ) {
1354
+ context = [ context ];
1355
+ } else if ( !Array.isArray( context ) ) {
1356
+ // `context` is item or position.
1357
+ // Position#getAncestors() doesn't accept any parameters but it works just fine here.
1358
+ context = context.getAncestors( { includeSelf: true } );
1359
+ }
1360
+
1361
+ this._items = context.map( mapContextItem );
1362
+ }
1363
+
1364
+ /**
1365
+ * The number of items.
1366
+ *
1367
+ * @type {Number}
1368
+ */
1369
+ get length() {
1370
+ return this._items.length;
1371
+ }
1372
+
1373
+ /**
1374
+ * The last item (the lowest node).
1375
+ *
1376
+ * @type {module:engine/model/schema~SchemaContextItem}
1377
+ */
1378
+ get last() {
1379
+ return this._items[ this._items.length - 1 ];
1380
+ }
1381
+
1382
+ /**
1383
+ * Iterable interface.
1384
+ *
1385
+ * Iterates over all context items.
1386
+ *
1387
+ * @returns {Iterable.<module:engine/model/schema~SchemaContextItem>}
1388
+ */
1389
+ [ Symbol.iterator ]() {
1390
+ return this._items[ Symbol.iterator ]();
1391
+ }
1392
+
1393
+ /**
1394
+ * Returns a new schema context instance with an additional item.
1395
+ *
1396
+ * Item can be added as:
1397
+ *
1398
+ * const context = new SchemaContext( [ '$root' ] );
1399
+ *
1400
+ * // An element.
1401
+ * const fooElement = writer.createElement( 'fooElement' );
1402
+ * const newContext = context.push( fooElement ); // [ '$root', 'fooElement' ]
1403
+ *
1404
+ * // A text node.
1405
+ * const text = writer.createText( 'foobar' );
1406
+ * const newContext = context.push( text ); // [ '$root', '$text' ]
1407
+ *
1408
+ * // A string (element name).
1409
+ * const newContext = context.push( 'barElement' ); // [ '$root', 'barElement' ]
1410
+ *
1411
+ * **Note** {@link module:engine/model/node~Node} that is already in the model tree will be added as the only item
1412
+ * (without ancestors).
1413
+ *
1414
+ * @param {String|module:engine/model/node~Node|Array<String|module:engine/model/node~Node>} item An item that will be added
1415
+ * to the current context.
1416
+ * @returns {module:engine/model/schema~SchemaContext} A new schema context instance with an additional item.
1417
+ */
1418
+ push( item ) {
1419
+ const ctx = new SchemaContext( [ item ] );
1420
+
1421
+ ctx._items = [ ...this._items, ...ctx._items ];
1422
+
1423
+ return ctx;
1424
+ }
1425
+
1426
+ /**
1427
+ * Gets an item on the given index.
1428
+ *
1429
+ * @returns {module:engine/model/schema~SchemaContextItem}
1430
+ */
1431
+ getItem( index ) {
1432
+ return this._items[ index ];
1433
+ }
1434
+
1435
+ /**
1436
+ * Returns the names of items.
1437
+ *
1438
+ * @returns {Iterable.<String>}
1439
+ */
1440
+ * getNames() {
1441
+ yield* this._items.map( item => item.name );
1442
+ }
1443
+
1444
+ /**
1445
+ * Checks whether the context ends with the given nodes.
1446
+ *
1447
+ * const ctx = new SchemaContext( [ rootElement, paragraphElement, textNode ] );
1448
+ *
1449
+ * ctx.endsWith( '$text' ); // -> true
1450
+ * ctx.endsWith( 'paragraph $text' ); // -> true
1451
+ * ctx.endsWith( '$root' ); // -> false
1452
+ * ctx.endsWith( 'paragraph' ); // -> false
1453
+ *
1454
+ * @param {String} query
1455
+ * @returns {Boolean}
1456
+ */
1457
+ endsWith( query ) {
1458
+ return Array.from( this.getNames() ).join( ' ' ).endsWith( query );
1459
+ }
1460
+
1461
+ /**
1462
+ * Checks whether the context starts with the given nodes.
1463
+ *
1464
+ * const ctx = new SchemaContext( [ rootElement, paragraphElement, textNode ] );
1465
+ *
1466
+ * ctx.endsWith( '$root' ); // -> true
1467
+ * ctx.endsWith( '$root paragraph' ); // -> true
1468
+ * ctx.endsWith( '$text' ); // -> false
1469
+ * ctx.endsWith( 'paragraph' ); // -> false
1470
+ *
1471
+ * @param {String} query
1472
+ * @returns {Boolean}
1473
+ */
1474
+ startsWith( query ) {
1475
+ return Array.from( this.getNames() ).join( ' ' ).startsWith( query );
1476
+ }
1477
+ }
1478
+
1479
+ /**
1480
+ * The definition of a {@link module:engine/model/schema~SchemaContext schema context}.
1481
+ *
1482
+ * Contexts can be created in multiple ways:
1483
+ *
1484
+ * * By defining a **node** – in this cases this node and all its ancestors will be used.
1485
+ * * By defining a **position** in the document – in this case all its ancestors will be used.
1486
+ * * By defining an **array of nodes** – in this case this array defines the entire context.
1487
+ * * By defining a **name of node** - in this case node will be "mocked". It is not recommended because context
1488
+ * will be unrealistic (e.g. attributes of these nodes are not specified). However, at times this may be the only
1489
+ * way to define the context (e.g. when checking some hypothetical situation).
1490
+ * * By defining an **array of node names** (potentially, mixed with real nodes) – The same as **name of node**
1491
+ * but it is possible to create a path.
1492
+ * * By defining a {@link module:engine/model/schema~SchemaContext} instance - in this case the same instance as provided
1493
+ * will be return.
1494
+ *
1495
+ * Examples of context definitions passed to the {@link module:engine/model/schema~Schema#checkChild `Schema#checkChild()`}
1496
+ * method:
1497
+ *
1498
+ * // Assuming that we have a $root > blockQuote > paragraph structure, the following code
1499
+ * // will check node 'foo' in the following context:
1500
+ * // [ rootElement, blockQuoteElement, paragraphElement ]
1501
+ * const contextDefinition = paragraphElement;
1502
+ * const childToCheck = 'foo';
1503
+ * schema.checkChild( contextDefinition, childToCheck );
1504
+ *
1505
+ * // Also check in [ rootElement, blockQuoteElement, paragraphElement ].
1506
+ * schema.checkChild( model.createPositionAt( paragraphElement, 0 ), 'foo' );
1507
+ *
1508
+ * // Check in [ rootElement, paragraphElement ].
1509
+ * schema.checkChild( [ rootElement, paragraphElement ], 'foo' );
1510
+ *
1511
+ * // Check only fakeParagraphElement.
1512
+ * schema.checkChild( 'paragraph', 'foo' );
1513
+ *
1514
+ * // Check in [ fakeRootElement, fakeBarElement, paragraphElement ].
1515
+ * schema.checkChild( [ '$root', 'bar', paragraphElement ], 'foo' );
1516
+ *
1517
+ * All these `checkChild()` calls will fire {@link module:engine/model/schema~Schema#event:checkChild `Schema#checkChild`}
1518
+ * events in which `args[ 0 ]` is an instance of the context. Therefore, you can write a listener like this:
1519
+ *
1520
+ * schema.on( 'checkChild', ( evt, args ) => {
1521
+ * const ctx = args[ 0 ];
1522
+ *
1523
+ * console.log( Array.from( ctx.getNames() ) );
1524
+ * } );
1525
+ *
1526
+ * Which will log the following:
1527
+ *
1528
+ * [ '$root', 'blockQuote', 'paragraph' ]
1529
+ * [ '$root', 'paragraph' ]
1530
+ * [ '$root', 'bar', 'paragraph' ]
1531
+ *
1532
+ * Note: When using the {@link module:engine/model/schema~Schema#checkAttribute `Schema#checkAttribute()`} method
1533
+ * you may want to check whether a text node may have an attribute. A {@link module:engine/model/text~Text} is a
1534
+ * correct way to define a context so you can do this:
1535
+ *
1536
+ * schema.checkAttribute( textNode, 'bold' );
1537
+ *
1538
+ * But sometimes you want to check whether a text at a given position might've had some attribute,
1539
+ * in which case you can create a context by mixing in an array of elements with a `'$text'` string:
1540
+ *
1541
+ * // Check in [ rootElement, paragraphElement, textNode ].
1542
+ * schema.checkChild( [ ...positionInParagraph.getAncestors(), '$text' ], 'bold' );
1543
+ *
1544
+ * @typedef {module:engine/model/node~Node|module:engine/model/position~Position|module:engine/model/schema~SchemaContext|
1545
+ * String|Array.<String|module:engine/model/node~Node>} module:engine/model/schema~SchemaContextDefinition
1546
+ */
1547
+
1548
+ /**
1549
+ * An item of the {@link module:engine/model/schema~SchemaContext schema context}.
1550
+ *
1551
+ * It contains 3 properties:
1552
+ *
1553
+ * * `name` – the name of this item,
1554
+ * * `* getAttributeKeys()` – a generator of keys of item attributes,
1555
+ * * `getAttribute( keyName )` – a method to get attribute values.
1556
+ *
1557
+ * The context item interface is a highly simplified version of {@link module:engine/model/node~Node} and its role
1558
+ * is to expose only the information which schema checks are able to provide (which is the name of the node and
1559
+ * node's attributes).
1560
+ *
1561
+ * schema.on( 'checkChild', ( evt, args ) => {
1562
+ * const ctx = args[ 0 ];
1563
+ * const firstItem = ctx.getItem( 0 );
1564
+ *
1565
+ * console.log( firstItem.name ); // -> '$root'
1566
+ * console.log( firstItem.getAttribute( 'foo' ) ); // -> 'bar'
1567
+ * console.log( Array.from( firstItem.getAttributeKeys() ) ); // -> [ 'foo', 'faa' ]
1568
+ * } );
1569
+ *
1570
+ * @typedef {Object} module:engine/model/schema~SchemaContextItem
1571
+ */
1572
+
1573
+ /**
1574
+ * A structure containing additional metadata describing the attribute.
1575
+ *
1576
+ * See {@link module:engine/model/schema~Schema#setAttributeProperties `Schema#setAttributeProperties()`} for usage examples.
1577
+ *
1578
+ * @typedef {Object} module:engine/model/schema~AttributeProperties
1579
+ * @property {Boolean} [isFormatting] Indicates that the attribute should be considered as a visual formatting, like `bold`, `italic` or
1580
+ * `fontSize` rather than semantic attribute (such as `src`, `listType`, etc.). For example, it is used by the "Remove format" feature.
1581
+ * @property {Boolean} [copyOnEnter] Indicates that given text attribute should be copied to the next block when enter is pressed.
1582
+ */
1583
+
1584
+ function compileBaseItemRule( sourceItemRules, itemName ) {
1585
+ const itemRule = {
1586
+ name: itemName,
1587
+
1588
+ allowIn: [],
1589
+ allowContentOf: [],
1590
+ allowWhere: [],
1591
+
1592
+ allowAttributes: [],
1593
+ allowAttributesOf: [],
1594
+
1595
+ allowChildren: [],
1596
+
1597
+ inheritTypesFrom: []
1598
+ };
1599
+
1600
+ copyTypes( sourceItemRules, itemRule );
1601
+
1602
+ copyProperty( sourceItemRules, itemRule, 'allowIn' );
1603
+ copyProperty( sourceItemRules, itemRule, 'allowContentOf' );
1604
+ copyProperty( sourceItemRules, itemRule, 'allowWhere' );
1605
+
1606
+ copyProperty( sourceItemRules, itemRule, 'allowAttributes' );
1607
+ copyProperty( sourceItemRules, itemRule, 'allowAttributesOf' );
1608
+
1609
+ copyProperty( sourceItemRules, itemRule, 'allowChildren' );
1610
+
1611
+ copyProperty( sourceItemRules, itemRule, 'inheritTypesFrom' );
1612
+
1613
+ makeInheritAllWork( sourceItemRules, itemRule );
1614
+
1615
+ return itemRule;
1616
+ }
1617
+
1618
+ function compileAllowChildren( compiledDefinitions, itemName ) {
1619
+ const item = compiledDefinitions[ itemName ];
1620
+
1621
+ for ( const allowChildrenItem of item.allowChildren ) {
1622
+ const allowedChildren = compiledDefinitions[ allowChildrenItem ];
1623
+
1624
+ // The allowChildren property may point to an unregistered element.
1625
+ if ( !allowedChildren ) {
1626
+ continue;
1627
+ }
1628
+
1629
+ allowedChildren.allowIn.push( itemName );
1630
+ }
1631
+
1632
+ // The allowIn property already includes correct items, reset the allowChildren property
1633
+ // to avoid duplicates later when setting up compilation results.
1634
+ item.allowChildren.length = 0;
1635
+ }
1636
+
1637
+ function compileAllowContentOf( compiledDefinitions, itemName ) {
1638
+ for ( const allowContentOfItemName of compiledDefinitions[ itemName ].allowContentOf ) {
1639
+ // The allowContentOf property may point to an unregistered element.
1640
+ if ( compiledDefinitions[ allowContentOfItemName ] ) {
1641
+ const allowedChildren = getAllowedChildren( compiledDefinitions, allowContentOfItemName );
1642
+
1643
+ allowedChildren.forEach( allowedItem => {
1644
+ allowedItem.allowIn.push( itemName );
1645
+ } );
1646
+ }
1647
+ }
1648
+
1649
+ delete compiledDefinitions[ itemName ].allowContentOf;
1650
+ }
1651
+
1652
+ function compileAllowWhere( compiledDefinitions, itemName ) {
1653
+ for ( const allowWhereItemName of compiledDefinitions[ itemName ].allowWhere ) {
1654
+ const inheritFrom = compiledDefinitions[ allowWhereItemName ];
1655
+
1656
+ // The allowWhere property may point to an unregistered element.
1657
+ if ( inheritFrom ) {
1658
+ const allowedIn = inheritFrom.allowIn;
1659
+
1660
+ compiledDefinitions[ itemName ].allowIn.push( ...allowedIn );
1661
+ }
1662
+ }
1663
+
1664
+ delete compiledDefinitions[ itemName ].allowWhere;
1665
+ }
1666
+
1667
+ function compileAllowAttributesOf( compiledDefinitions, itemName ) {
1668
+ for ( const allowAttributeOfItem of compiledDefinitions[ itemName ].allowAttributesOf ) {
1669
+ const inheritFrom = compiledDefinitions[ allowAttributeOfItem ];
1670
+
1671
+ if ( inheritFrom ) {
1672
+ const inheritAttributes = inheritFrom.allowAttributes;
1673
+
1674
+ compiledDefinitions[ itemName ].allowAttributes.push( ...inheritAttributes );
1675
+ }
1676
+ }
1677
+
1678
+ delete compiledDefinitions[ itemName ].allowAttributesOf;
1679
+ }
1680
+
1681
+ function compileInheritPropertiesFrom( compiledDefinitions, itemName ) {
1682
+ const item = compiledDefinitions[ itemName ];
1683
+
1684
+ for ( const inheritPropertiesOfItem of item.inheritTypesFrom ) {
1685
+ const inheritFrom = compiledDefinitions[ inheritPropertiesOfItem ];
1686
+
1687
+ if ( inheritFrom ) {
1688
+ const typeNames = Object.keys( inheritFrom ).filter( name => name.startsWith( 'is' ) );
1689
+
1690
+ for ( const name of typeNames ) {
1691
+ if ( !( name in item ) ) {
1692
+ item[ name ] = inheritFrom[ name ];
1693
+ }
1694
+ }
1695
+ }
1696
+ }
1697
+
1698
+ delete item.inheritTypesFrom;
1699
+ }
1700
+
1701
+ // Remove items which weren't registered (because it may break some checks or we'd need to complicate them).
1702
+ // Make sure allowIn doesn't contain repeated values.
1703
+ function cleanUpAllowIn( compiledDefinitions, itemName ) {
1704
+ const itemRule = compiledDefinitions[ itemName ];
1705
+ const existingItems = itemRule.allowIn.filter( itemToCheck => compiledDefinitions[ itemToCheck ] );
1706
+
1707
+ itemRule.allowIn = Array.from( new Set( existingItems ) );
1708
+ }
1709
+
1710
+ // Setup allowChildren items based on allowIn.
1711
+ function setupAllowChildren( compiledDefinitions, itemName ) {
1712
+ const itemRule = compiledDefinitions[ itemName ];
1713
+
1714
+ for ( const allowedParentItemName of itemRule.allowIn ) {
1715
+ const allowedParentItem = compiledDefinitions[ allowedParentItemName ];
1716
+
1717
+ allowedParentItem.allowChildren.push( itemName );
1718
+ }
1719
+ }
1720
+
1721
+ function cleanUpAllowAttributes( compiledDefinitions, itemName ) {
1722
+ const itemRule = compiledDefinitions[ itemName ];
1723
+
1724
+ itemRule.allowAttributes = Array.from( new Set( itemRule.allowAttributes ) );
1725
+ }
1726
+
1727
+ function copyTypes( sourceItemRules, itemRule ) {
1728
+ for ( const sourceItemRule of sourceItemRules ) {
1729
+ const typeNames = Object.keys( sourceItemRule ).filter( name => name.startsWith( 'is' ) );
1730
+
1731
+ for ( const name of typeNames ) {
1732
+ itemRule[ name ] = sourceItemRule[ name ];
1733
+ }
1734
+ }
1735
+ }
1736
+
1737
+ function copyProperty( sourceItemRules, itemRule, propertyName ) {
1738
+ for ( const sourceItemRule of sourceItemRules ) {
1739
+ if ( typeof sourceItemRule[ propertyName ] == 'string' ) {
1740
+ itemRule[ propertyName ].push( sourceItemRule[ propertyName ] );
1741
+ } else if ( Array.isArray( sourceItemRule[ propertyName ] ) ) {
1742
+ itemRule[ propertyName ].push( ...sourceItemRule[ propertyName ] );
1743
+ }
1744
+ }
1745
+ }
1746
+
1747
+ function makeInheritAllWork( sourceItemRules, itemRule ) {
1748
+ for ( const sourceItemRule of sourceItemRules ) {
1749
+ const inheritFrom = sourceItemRule.inheritAllFrom;
1750
+
1751
+ if ( inheritFrom ) {
1752
+ itemRule.allowContentOf.push( inheritFrom );
1753
+ itemRule.allowWhere.push( inheritFrom );
1754
+ itemRule.allowAttributesOf.push( inheritFrom );
1755
+ itemRule.inheritTypesFrom.push( inheritFrom );
1756
+ }
1757
+ }
1758
+ }
1759
+
1760
+ function getAllowedChildren( compiledDefinitions, itemName ) {
1761
+ const itemRule = compiledDefinitions[ itemName ];
1762
+
1763
+ return getValues( compiledDefinitions ).filter( def => def.allowIn.includes( itemRule.name ) );
1764
+ }
1765
+
1766
+ function getValues( obj ) {
1767
+ return Object.keys( obj ).map( key => obj[ key ] );
1768
+ }
1769
+
1770
+ function mapContextItem( ctxItem ) {
1771
+ if ( typeof ctxItem == 'string' || ctxItem.is( 'documentFragment' ) ) {
1772
+ return {
1773
+ name: typeof ctxItem == 'string' ? ctxItem : '$documentFragment',
1774
+
1775
+ * getAttributeKeys() {},
1776
+
1777
+ getAttribute() {}
1778
+ };
1779
+ } else {
1780
+ return {
1781
+ // '$text' means text nodes and text proxies.
1782
+ name: ctxItem.is( 'element' ) ? ctxItem.name : '$text',
1783
+
1784
+ * getAttributeKeys() {
1785
+ yield* ctxItem.getAttributeKeys();
1786
+ },
1787
+
1788
+ getAttribute( key ) {
1789
+ return ctxItem.getAttribute( key );
1790
+ }
1791
+ };
1792
+ }
1793
+ }
1794
+
1795
+ // Generator function returning values from provided walkers, switching between them at each iteration. If only one walker
1796
+ // is provided it will return data only from that walker.
1797
+ //
1798
+ // @param {module:engine/module/treewalker~TreeWalker} [backward] Walker iterating in backward direction.
1799
+ // @param {module:engine/module/treewalker~TreeWalker} [forward] Walker iterating in forward direction.
1800
+ // @returns {Iterable.<Object>} Object returned at each iteration contains `value` and `walker` (informing which walker returned
1801
+ // given value) fields.
1802
+ function* combineWalkers( backward, forward ) {
1803
+ let done = false;
1804
+
1805
+ while ( !done ) {
1806
+ done = true;
1807
+
1808
+ if ( backward ) {
1809
+ const step = backward.next();
1810
+
1811
+ if ( !step.done ) {
1812
+ done = false;
1813
+ yield {
1814
+ walker: backward,
1815
+ value: step.value
1816
+ };
1817
+ }
1818
+ }
1819
+
1820
+ if ( forward ) {
1821
+ const step = forward.next();
1822
+
1823
+ if ( !step.done ) {
1824
+ done = false;
1825
+ yield {
1826
+ walker: forward,
1827
+ value: step.value
1828
+ };
1829
+ }
1830
+ }
1831
+ }
1832
+ }
1833
+
1834
+ // Takes an array of non-intersecting ranges. For each of them gets minimal flat ranges covering that range and returns
1835
+ // all those minimal flat ranges.
1836
+ //
1837
+ // @param {Array.<module:engine/model/range~Range>} ranges Ranges to process.
1838
+ // @returns {Iterable.<module:engine/model/range~Range>} Minimal flat ranges of given `ranges`.
1839
+ function* convertToMinimalFlatRanges( ranges ) {
1840
+ for ( const range of ranges ) {
1841
+ yield* range.getMinimalFlatRanges();
1842
+ }
1843
+ }
1844
+
1845
+ function removeDisallowedAttributeFromNode( schema, node, writer ) {
1846
+ for ( const attribute of node.getAttributeKeys() ) {
1847
+ if ( !schema.checkAttribute( node, attribute ) ) {
1848
+ writer.removeAttribute( attribute, node );
1849
+ }
1850
+ }
1851
+ }