@ckeditor/ckeditor5-engine 38.1.0 → 38.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (241) hide show
  1. package/package.json +2 -2
  2. package/src/controller/datacontroller.d.ts +334 -334
  3. package/src/controller/datacontroller.js +481 -481
  4. package/src/controller/editingcontroller.d.ts +98 -98
  5. package/src/controller/editingcontroller.js +191 -191
  6. package/src/conversion/conversion.d.ts +478 -478
  7. package/src/conversion/conversion.js +601 -601
  8. package/src/conversion/conversionhelpers.d.ts +26 -26
  9. package/src/conversion/conversionhelpers.js +32 -32
  10. package/src/conversion/downcastdispatcher.d.ts +547 -547
  11. package/src/conversion/downcastdispatcher.js +538 -538
  12. package/src/conversion/downcasthelpers.d.ts +1226 -1226
  13. package/src/conversion/downcasthelpers.js +2183 -2183
  14. package/src/conversion/mapper.d.ts +503 -503
  15. package/src/conversion/mapper.js +536 -536
  16. package/src/conversion/modelconsumable.d.ts +201 -201
  17. package/src/conversion/modelconsumable.js +333 -333
  18. package/src/conversion/upcastdispatcher.d.ts +492 -492
  19. package/src/conversion/upcastdispatcher.js +460 -460
  20. package/src/conversion/upcasthelpers.d.ts +499 -499
  21. package/src/conversion/upcasthelpers.js +950 -950
  22. package/src/conversion/viewconsumable.d.ts +369 -369
  23. package/src/conversion/viewconsumable.js +532 -532
  24. package/src/dataprocessor/basichtmlwriter.d.ts +18 -18
  25. package/src/dataprocessor/basichtmlwriter.js +19 -19
  26. package/src/dataprocessor/dataprocessor.d.ts +61 -61
  27. package/src/dataprocessor/dataprocessor.js +5 -5
  28. package/src/dataprocessor/htmldataprocessor.d.ts +76 -76
  29. package/src/dataprocessor/htmldataprocessor.js +96 -96
  30. package/src/dataprocessor/htmlwriter.d.ts +16 -16
  31. package/src/dataprocessor/htmlwriter.js +5 -5
  32. package/src/dataprocessor/xmldataprocessor.d.ts +90 -90
  33. package/src/dataprocessor/xmldataprocessor.js +108 -108
  34. package/src/dev-utils/model.d.ts +124 -124
  35. package/src/dev-utils/model.js +395 -395
  36. package/src/dev-utils/operationreplayer.d.ts +51 -51
  37. package/src/dev-utils/operationreplayer.js +112 -112
  38. package/src/dev-utils/utils.d.ts +37 -37
  39. package/src/dev-utils/utils.js +73 -73
  40. package/src/dev-utils/view.d.ts +319 -319
  41. package/src/dev-utils/view.js +967 -967
  42. package/src/index.d.ts +113 -113
  43. package/src/index.js +77 -77
  44. package/src/model/batch.d.ts +106 -106
  45. package/src/model/batch.js +96 -96
  46. package/src/model/differ.d.ts +373 -373
  47. package/src/model/differ.js +1090 -1090
  48. package/src/model/document.d.ts +264 -264
  49. package/src/model/document.js +356 -356
  50. package/src/model/documentfragment.d.ts +200 -200
  51. package/src/model/documentfragment.js +306 -306
  52. package/src/model/documentselection.d.ts +420 -420
  53. package/src/model/documentselection.js +987 -987
  54. package/src/model/element.d.ts +165 -165
  55. package/src/model/element.js +281 -281
  56. package/src/model/history.d.ts +114 -114
  57. package/src/model/history.js +207 -207
  58. package/src/model/item.d.ts +14 -14
  59. package/src/model/item.js +5 -5
  60. package/src/model/liveposition.d.ts +77 -77
  61. package/src/model/liveposition.js +93 -93
  62. package/src/model/liverange.d.ts +102 -102
  63. package/src/model/liverange.js +120 -120
  64. package/src/model/markercollection.d.ts +335 -335
  65. package/src/model/markercollection.js +403 -403
  66. package/src/model/model.d.ts +920 -920
  67. package/src/model/model.js +843 -843
  68. package/src/model/node.d.ts +256 -256
  69. package/src/model/node.js +375 -375
  70. package/src/model/nodelist.d.ts +91 -91
  71. package/src/model/nodelist.js +163 -163
  72. package/src/model/operation/attributeoperation.d.ts +103 -103
  73. package/src/model/operation/attributeoperation.js +148 -148
  74. package/src/model/operation/detachoperation.d.ts +60 -60
  75. package/src/model/operation/detachoperation.js +77 -77
  76. package/src/model/operation/insertoperation.d.ts +90 -90
  77. package/src/model/operation/insertoperation.js +135 -135
  78. package/src/model/operation/markeroperation.d.ts +91 -91
  79. package/src/model/operation/markeroperation.js +107 -107
  80. package/src/model/operation/mergeoperation.d.ts +100 -100
  81. package/src/model/operation/mergeoperation.js +167 -167
  82. package/src/model/operation/moveoperation.d.ts +96 -96
  83. package/src/model/operation/moveoperation.js +164 -164
  84. package/src/model/operation/nooperation.d.ts +38 -38
  85. package/src/model/operation/nooperation.js +48 -48
  86. package/src/model/operation/operation.d.ts +96 -96
  87. package/src/model/operation/operation.js +62 -62
  88. package/src/model/operation/operationfactory.d.ts +18 -18
  89. package/src/model/operation/operationfactory.js +44 -44
  90. package/src/model/operation/renameoperation.d.ts +83 -83
  91. package/src/model/operation/renameoperation.js +115 -115
  92. package/src/model/operation/rootattributeoperation.d.ts +98 -98
  93. package/src/model/operation/rootattributeoperation.js +155 -155
  94. package/src/model/operation/rootoperation.d.ts +80 -80
  95. package/src/model/operation/rootoperation.js +114 -114
  96. package/src/model/operation/splitoperation.d.ts +109 -109
  97. package/src/model/operation/splitoperation.js +194 -194
  98. package/src/model/operation/transform.d.ts +100 -100
  99. package/src/model/operation/transform.js +1985 -1985
  100. package/src/model/operation/utils.d.ts +71 -71
  101. package/src/model/operation/utils.js +213 -213
  102. package/src/model/position.d.ts +539 -539
  103. package/src/model/position.js +979 -979
  104. package/src/model/range.d.ts +458 -458
  105. package/src/model/range.js +875 -875
  106. package/src/model/rootelement.d.ts +54 -54
  107. package/src/model/rootelement.js +68 -68
  108. package/src/model/schema.d.ts +1176 -1176
  109. package/src/model/schema.js +1237 -1237
  110. package/src/model/selection.d.ts +482 -482
  111. package/src/model/selection.js +789 -789
  112. package/src/model/text.d.ts +66 -66
  113. package/src/model/text.js +85 -85
  114. package/src/model/textproxy.d.ts +144 -144
  115. package/src/model/textproxy.js +189 -189
  116. package/src/model/treewalker.d.ts +186 -186
  117. package/src/model/treewalker.js +244 -244
  118. package/src/model/typecheckable.d.ts +285 -285
  119. package/src/model/typecheckable.js +16 -16
  120. package/src/model/utils/autoparagraphing.d.ts +37 -37
  121. package/src/model/utils/autoparagraphing.js +64 -64
  122. package/src/model/utils/deletecontent.d.ts +58 -58
  123. package/src/model/utils/deletecontent.js +488 -488
  124. package/src/model/utils/findoptimalinsertionrange.d.ts +32 -32
  125. package/src/model/utils/findoptimalinsertionrange.js +57 -57
  126. package/src/model/utils/getselectedcontent.d.ts +30 -30
  127. package/src/model/utils/getselectedcontent.js +125 -125
  128. package/src/model/utils/insertcontent.d.ts +46 -46
  129. package/src/model/utils/insertcontent.js +705 -705
  130. package/src/model/utils/insertobject.d.ts +44 -44
  131. package/src/model/utils/insertobject.js +139 -139
  132. package/src/model/utils/modifyselection.d.ts +48 -48
  133. package/src/model/utils/modifyselection.js +186 -186
  134. package/src/model/utils/selection-post-fixer.d.ts +74 -74
  135. package/src/model/utils/selection-post-fixer.js +260 -260
  136. package/src/model/writer.d.ts +851 -851
  137. package/src/model/writer.js +1306 -1306
  138. package/src/view/attributeelement.d.ts +108 -108
  139. package/src/view/attributeelement.js +184 -184
  140. package/src/view/containerelement.d.ts +49 -49
  141. package/src/view/containerelement.js +80 -80
  142. package/src/view/datatransfer.d.ts +79 -79
  143. package/src/view/datatransfer.js +98 -98
  144. package/src/view/document.d.ts +184 -184
  145. package/src/view/document.js +120 -120
  146. package/src/view/documentfragment.d.ts +149 -149
  147. package/src/view/documentfragment.js +228 -228
  148. package/src/view/documentselection.d.ts +306 -306
  149. package/src/view/documentselection.js +256 -256
  150. package/src/view/domconverter.d.ts +650 -650
  151. package/src/view/domconverter.js +1373 -1373
  152. package/src/view/downcastwriter.d.ts +996 -996
  153. package/src/view/downcastwriter.js +1696 -1696
  154. package/src/view/editableelement.d.ts +52 -52
  155. package/src/view/editableelement.js +61 -61
  156. package/src/view/element.d.ts +468 -468
  157. package/src/view/element.js +724 -724
  158. package/src/view/elementdefinition.d.ts +87 -87
  159. package/src/view/elementdefinition.js +5 -5
  160. package/src/view/emptyelement.d.ts +41 -41
  161. package/src/view/emptyelement.js +73 -73
  162. package/src/view/filler.d.ts +111 -111
  163. package/src/view/filler.js +148 -148
  164. package/src/view/item.d.ts +14 -14
  165. package/src/view/item.js +5 -5
  166. package/src/view/matcher.d.ts +486 -486
  167. package/src/view/matcher.js +507 -507
  168. package/src/view/node.d.ts +163 -163
  169. package/src/view/node.js +228 -228
  170. package/src/view/observer/arrowkeysobserver.d.ts +45 -45
  171. package/src/view/observer/arrowkeysobserver.js +40 -40
  172. package/src/view/observer/bubblingemittermixin.d.ts +166 -166
  173. package/src/view/observer/bubblingemittermixin.js +172 -172
  174. package/src/view/observer/bubblingeventinfo.d.ts +47 -47
  175. package/src/view/observer/bubblingeventinfo.js +37 -37
  176. package/src/view/observer/clickobserver.d.ts +43 -43
  177. package/src/view/observer/clickobserver.js +29 -29
  178. package/src/view/observer/compositionobserver.d.ts +82 -82
  179. package/src/view/observer/compositionobserver.js +60 -60
  180. package/src/view/observer/domeventdata.d.ts +50 -50
  181. package/src/view/observer/domeventdata.js +47 -47
  182. package/src/view/observer/domeventobserver.d.ts +73 -73
  183. package/src/view/observer/domeventobserver.js +79 -79
  184. package/src/view/observer/fakeselectionobserver.d.ts +47 -47
  185. package/src/view/observer/fakeselectionobserver.js +91 -91
  186. package/src/view/observer/focusobserver.d.ts +82 -82
  187. package/src/view/observer/focusobserver.js +86 -86
  188. package/src/view/observer/inputobserver.d.ts +86 -86
  189. package/src/view/observer/inputobserver.js +164 -164
  190. package/src/view/observer/keyobserver.d.ts +66 -66
  191. package/src/view/observer/keyobserver.js +39 -39
  192. package/src/view/observer/mouseobserver.d.ts +89 -89
  193. package/src/view/observer/mouseobserver.js +29 -29
  194. package/src/view/observer/mutationobserver.d.ts +86 -86
  195. package/src/view/observer/mutationobserver.js +206 -206
  196. package/src/view/observer/observer.d.ts +89 -89
  197. package/src/view/observer/observer.js +84 -84
  198. package/src/view/observer/selectionobserver.d.ts +148 -148
  199. package/src/view/observer/selectionobserver.js +202 -202
  200. package/src/view/observer/tabobserver.d.ts +46 -46
  201. package/src/view/observer/tabobserver.js +42 -42
  202. package/src/view/placeholder.d.ts +85 -85
  203. package/src/view/placeholder.js +230 -230
  204. package/src/view/position.d.ts +189 -189
  205. package/src/view/position.js +324 -324
  206. package/src/view/range.d.ts +279 -279
  207. package/src/view/range.js +430 -430
  208. package/src/view/rawelement.d.ts +73 -73
  209. package/src/view/rawelement.js +105 -105
  210. package/src/view/renderer.d.ts +265 -265
  211. package/src/view/renderer.js +1000 -1000
  212. package/src/view/rooteditableelement.d.ts +41 -41
  213. package/src/view/rooteditableelement.js +69 -69
  214. package/src/view/selection.d.ts +375 -375
  215. package/src/view/selection.js +559 -559
  216. package/src/view/styles/background.d.ts +33 -33
  217. package/src/view/styles/background.js +74 -74
  218. package/src/view/styles/border.d.ts +43 -43
  219. package/src/view/styles/border.js +316 -316
  220. package/src/view/styles/margin.d.ts +29 -29
  221. package/src/view/styles/margin.js +34 -34
  222. package/src/view/styles/padding.d.ts +29 -29
  223. package/src/view/styles/padding.js +34 -34
  224. package/src/view/styles/utils.d.ts +93 -93
  225. package/src/view/styles/utils.js +219 -219
  226. package/src/view/stylesmap.d.ts +675 -675
  227. package/src/view/stylesmap.js +766 -766
  228. package/src/view/text.d.ts +74 -74
  229. package/src/view/text.js +93 -93
  230. package/src/view/textproxy.d.ts +97 -97
  231. package/src/view/textproxy.js +124 -124
  232. package/src/view/treewalker.d.ts +195 -195
  233. package/src/view/treewalker.js +327 -327
  234. package/src/view/typecheckable.d.ts +448 -448
  235. package/src/view/typecheckable.js +19 -19
  236. package/src/view/uielement.d.ts +96 -96
  237. package/src/view/uielement.js +182 -182
  238. package/src/view/upcastwriter.d.ts +417 -417
  239. package/src/view/upcastwriter.js +359 -359
  240. package/src/view/view.d.ts +480 -480
  241. package/src/view/view.js +534 -534
@@ -1,1237 +1,1237 @@
1
- /**
2
- * @license Copyright (c) 2003-2023, CKSource Holding sp. z o.o. All rights reserved.
3
- * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4
- */
5
- /**
6
- * @module engine/model/schema
7
- */
8
- import Element from './element';
9
- import Position from './position';
10
- import Range from './range';
11
- import Text from './text';
12
- import TreeWalker from './treewalker';
13
- import { CKEditorError, ObservableMixin } from '@ckeditor/ckeditor5-utils';
14
- /**
15
- * The model's schema. It defines the allowed and disallowed structures of nodes as well as nodes' attributes.
16
- * The schema is usually defined by the features and based on them, the editing framework and features
17
- * make decisions on how to change and process the model.
18
- *
19
- * The instance of schema is available in {@link module:engine/model/model~Model#schema `editor.model.schema`}.
20
- *
21
- * Read more about the schema in:
22
- *
23
- * * The {@glink framework/architecture/editing-engine#schema schema section} of the
24
- * {@glink framework/architecture/editing-engine Introduction to the Editing engine architecture} guide.
25
- * * The {@glink framework/deep-dive/schema Schema deep-dive} guide.
26
- */
27
- export default class Schema extends ObservableMixin() {
28
- /**
29
- * Creates a schema instance.
30
- */
31
- constructor() {
32
- super();
33
- this._sourceDefinitions = {};
34
- /**
35
- * A dictionary containing attribute properties.
36
- */
37
- this._attributeProperties = {};
38
- this.decorate('checkChild');
39
- this.decorate('checkAttribute');
40
- this.on('checkAttribute', (evt, args) => {
41
- args[0] = new SchemaContext(args[0]);
42
- }, { priority: 'highest' });
43
- this.on('checkChild', (evt, args) => {
44
- args[0] = new SchemaContext(args[0]);
45
- args[1] = this.getDefinition(args[1]);
46
- }, { priority: 'highest' });
47
- }
48
- /**
49
- * Registers a schema item. Can only be called once for every item name.
50
- *
51
- * ```ts
52
- * schema.register( 'paragraph', {
53
- * inheritAllFrom: '$block'
54
- * } );
55
- * ```
56
- */
57
- register(itemName, definition) {
58
- if (this._sourceDefinitions[itemName]) {
59
- /**
60
- * A single item cannot be registered twice in the schema.
61
- *
62
- * This situation may happen when:
63
- *
64
- * * Two or more plugins called {@link module:engine/model/schema~Schema#register `register()`} with the same name.
65
- * This will usually mean that there is a collision between plugins which try to use the same element in the model.
66
- * Unfortunately, the only way to solve this is by modifying one of these plugins to use a unique model element name.
67
- * * A single plugin was loaded twice. This happens when it is installed by npm/yarn in two versions
68
- * and usually means one or more of the following issues:
69
- * * a version mismatch (two of your dependencies require two different versions of this plugin),
70
- * * incorrect imports (this plugin is somehow imported twice in a way which confuses webpack),
71
- * * mess in `node_modules/` (`rm -rf node_modules/` may help).
72
- *
73
- * **Note:** Check the logged `itemName` to better understand which plugin was duplicated/conflicting.
74
- *
75
- * @param itemName The name of the model element that is being registered twice.
76
- * @error schema-cannot-register-item-twice
77
- */
78
- throw new CKEditorError('schema-cannot-register-item-twice', this, {
79
- itemName
80
- });
81
- }
82
- this._sourceDefinitions[itemName] = [
83
- Object.assign({}, definition)
84
- ];
85
- this._clearCache();
86
- }
87
- /**
88
- * Extends a {@link #register registered} item's definition.
89
- *
90
- * Extending properties such as `allowIn` will add more items to the existing properties,
91
- * while redefining properties such as `isBlock` will override the previously defined ones.
92
- *
93
- * ```ts
94
- * schema.register( 'foo', {
95
- * allowIn: '$root',
96
- * isBlock: true;
97
- * } );
98
- * schema.extend( 'foo', {
99
- * allowIn: 'blockQuote',
100
- * isBlock: false
101
- * } );
102
- *
103
- * schema.getDefinition( 'foo' );
104
- * // {
105
- * // allowIn: [ '$root', 'blockQuote' ],
106
- * // isBlock: false
107
- * // }
108
- * ```
109
- */
110
- extend(itemName, definition) {
111
- if (!this._sourceDefinitions[itemName]) {
112
- /**
113
- * Cannot extend an item which was not registered yet.
114
- *
115
- * This error happens when a plugin tries to extend the schema definition of an item which was not
116
- * {@link module:engine/model/schema~Schema#register registered} yet.
117
- *
118
- * @param itemName The name of the model element which is being extended.
119
- * @error schema-cannot-extend-missing-item
120
- */
121
- throw new CKEditorError('schema-cannot-extend-missing-item', this, {
122
- itemName
123
- });
124
- }
125
- this._sourceDefinitions[itemName].push(Object.assign({}, definition));
126
- this._clearCache();
127
- }
128
- /**
129
- * Returns data of all registered items.
130
- *
131
- * This method should normally be used for reflection purposes (e.g. defining a clone of a certain element,
132
- * checking a list of all block elements, etc).
133
- * Use specific methods (such as {@link #checkChild `checkChild()`} or {@link #isLimit `isLimit()`})
134
- * in other cases.
135
- */
136
- getDefinitions() {
137
- if (!this._compiledDefinitions) {
138
- this._compile();
139
- }
140
- return this._compiledDefinitions;
141
- }
142
- /**
143
- * Returns a definition of the given item or `undefined` if an item is not registered.
144
- *
145
- * This method should normally be used for reflection purposes (e.g. defining a clone of a certain element,
146
- * checking a list of all block elements, etc).
147
- * Use specific methods (such as {@link #checkChild `checkChild()`} or {@link #isLimit `isLimit()`})
148
- * in other cases.
149
- */
150
- getDefinition(item) {
151
- let itemName;
152
- if (typeof item == 'string') {
153
- itemName = item;
154
- }
155
- else if ('is' in item && (item.is('$text') || item.is('$textProxy'))) {
156
- itemName = '$text';
157
- }
158
- // Element or module:engine/model/schema~SchemaContextItem.
159
- else {
160
- itemName = item.name;
161
- }
162
- return this.getDefinitions()[itemName];
163
- }
164
- /**
165
- * Returns `true` if the given item is registered in the schema.
166
- *
167
- * ```ts
168
- * schema.isRegistered( 'paragraph' ); // -> true
169
- * schema.isRegistered( editor.model.document.getRoot() ); // -> true
170
- * schema.isRegistered( 'foo' ); // -> false
171
- * ```
172
- */
173
- isRegistered(item) {
174
- return !!this.getDefinition(item);
175
- }
176
- /**
177
- * Returns `true` if the given item is defined to be
178
- * a block by the {@link module:engine/model/schema~SchemaItemDefinition}'s `isBlock` property.
179
- *
180
- * ```ts
181
- * schema.isBlock( 'paragraph' ); // -> true
182
- * schema.isBlock( '$root' ); // -> false
183
- *
184
- * const paragraphElement = writer.createElement( 'paragraph' );
185
- * schema.isBlock( paragraphElement ); // -> true
186
- * ```
187
- *
188
- * See the {@glink framework/deep-dive/schema#block-elements Block elements} section of
189
- * the {@glink framework/deep-dive/schema Schema deep-dive} guide for more details.
190
- */
191
- isBlock(item) {
192
- const def = this.getDefinition(item);
193
- return !!(def && def.isBlock);
194
- }
195
- /**
196
- * Returns `true` if the given item should be treated as a limit element.
197
- *
198
- * It considers an item to be a limit element if its
199
- * {@link module:engine/model/schema~SchemaItemDefinition}'s
200
- * {@link module:engine/model/schema~SchemaItemDefinition#isLimit `isLimit`} or
201
- * {@link module:engine/model/schema~SchemaItemDefinition#isObject `isObject`} property
202
- * was set to `true`.
203
- *
204
- * ```ts
205
- * schema.isLimit( 'paragraph' ); // -> false
206
- * schema.isLimit( '$root' ); // -> true
207
- * schema.isLimit( editor.model.document.getRoot() ); // -> true
208
- * schema.isLimit( 'imageBlock' ); // -> true
209
- * ```
210
- *
211
- * See the {@glink framework/deep-dive/schema#limit-elements Limit elements} section of
212
- * the {@glink framework/deep-dive/schema Schema deep-dive} guide for more details.
213
- */
214
- isLimit(item) {
215
- const def = this.getDefinition(item);
216
- if (!def) {
217
- return false;
218
- }
219
- return !!(def.isLimit || def.isObject);
220
- }
221
- /**
222
- * Returns `true` if the given item should be treated as an object element.
223
- *
224
- * It considers an item to be an object element if its
225
- * {@link module:engine/model/schema~SchemaItemDefinition}'s
226
- * {@link module:engine/model/schema~SchemaItemDefinition#isObject `isObject`} property
227
- * was set to `true`.
228
- *
229
- * ```ts
230
- * schema.isObject( 'paragraph' ); // -> false
231
- * schema.isObject( 'imageBlock' ); // -> true
232
- *
233
- * const imageElement = writer.createElement( 'imageBlock' );
234
- * schema.isObject( imageElement ); // -> true
235
- * ```
236
- *
237
- * See the {@glink framework/deep-dive/schema#object-elements Object elements} section of
238
- * the {@glink framework/deep-dive/schema Schema deep-dive} guide for more details.
239
- */
240
- isObject(item) {
241
- const def = this.getDefinition(item);
242
- if (!def) {
243
- return false;
244
- }
245
- // Note: Check out the implementation of #isLimit(), #isSelectable(), and #isContent()
246
- // to understand why these three constitute an object.
247
- return !!(def.isObject || (def.isLimit && def.isSelectable && def.isContent));
248
- }
249
- /**
250
- * Returns `true` if the given item is defined to be
251
- * an inline element by the {@link module:engine/model/schema~SchemaItemDefinition}'s `isInline` property.
252
- *
253
- * ```ts
254
- * schema.isInline( 'paragraph' ); // -> false
255
- * schema.isInline( 'softBreak' ); // -> true
256
- *
257
- * const text = writer.createText( 'foo' );
258
- * schema.isInline( text ); // -> true
259
- * ```
260
- *
261
- * See the {@glink framework/deep-dive/schema#inline-elements Inline elements} section of
262
- * the {@glink framework/deep-dive/schema Schema deep-dive} guide for more details.
263
- */
264
- isInline(item) {
265
- const def = this.getDefinition(item);
266
- return !!(def && def.isInline);
267
- }
268
- /**
269
- * Returns `true` if the given item is defined to be
270
- * a selectable element by the {@link module:engine/model/schema~SchemaItemDefinition}'s `isSelectable` property.
271
- *
272
- * ```ts
273
- * schema.isSelectable( 'paragraph' ); // -> false
274
- * schema.isSelectable( 'heading1' ); // -> false
275
- * schema.isSelectable( 'imageBlock' ); // -> true
276
- * schema.isSelectable( 'tableCell' ); // -> true
277
- *
278
- * const text = writer.createText( 'foo' );
279
- * schema.isSelectable( text ); // -> false
280
- * ```
281
- *
282
- * See the {@glink framework/deep-dive/schema#selectable-elements Selectable elements section} of
283
- * the {@glink framework/deep-dive/schema Schema deep-dive} guide for more details.
284
- */
285
- isSelectable(item) {
286
- const def = this.getDefinition(item);
287
- if (!def) {
288
- return false;
289
- }
290
- return !!(def.isSelectable || def.isObject);
291
- }
292
- /**
293
- * Returns `true` if the given item is defined to be
294
- * a content by the {@link module:engine/model/schema~SchemaItemDefinition}'s `isContent` property.
295
- *
296
- * ```ts
297
- * schema.isContent( 'paragraph' ); // -> false
298
- * schema.isContent( 'heading1' ); // -> false
299
- * schema.isContent( 'imageBlock' ); // -> true
300
- * schema.isContent( 'horizontalLine' ); // -> true
301
- *
302
- * const text = writer.createText( 'foo' );
303
- * schema.isContent( text ); // -> true
304
- * ```
305
- *
306
- * See the {@glink framework/deep-dive/schema#content-elements Content elements section} of
307
- * the {@glink framework/deep-dive/schema Schema deep-dive} guide for more details.
308
- */
309
- isContent(item) {
310
- const def = this.getDefinition(item);
311
- if (!def) {
312
- return false;
313
- }
314
- return !!(def.isContent || def.isObject);
315
- }
316
- /**
317
- * Checks whether the given node (`child`) can be a child of the given context.
318
- *
319
- * ```ts
320
- * schema.checkChild( model.document.getRoot(), paragraph ); // -> false
321
- *
322
- * schema.register( 'paragraph', {
323
- * allowIn: '$root'
324
- * } );
325
- * schema.checkChild( model.document.getRoot(), paragraph ); // -> true
326
- * ```
327
- *
328
- * Note: When verifying whether the given node can be a child of the given context, the
329
- * schema also verifies the entire context — from its root to its last element. Therefore, it is possible
330
- * for `checkChild()` to return `false` even though the context's last element can contain the checked child.
331
- * It happens if one of the context's elements does not allow its child.
332
- *
333
- * @fires checkChild
334
- * @param context The context in which the child will be checked.
335
- * @param def The child to check.
336
- */
337
- checkChild(context, def) {
338
- // Note: context and child are already normalized here to a SchemaContext and SchemaCompiledItemDefinition.
339
- if (!def) {
340
- return false;
341
- }
342
- return this._checkContextMatch(def, context);
343
- }
344
- /**
345
- * Checks whether the given attribute can be applied in the given context (on the last
346
- * item of the context).
347
- *
348
- * ```ts
349
- * schema.checkAttribute( textNode, 'bold' ); // -> false
350
- *
351
- * schema.extend( '$text', {
352
- * allowAttributes: 'bold'
353
- * } );
354
- * schema.checkAttribute( textNode, 'bold' ); // -> true
355
- * ```
356
- *
357
- * @fires checkAttribute
358
- * @param context The context in which the attribute will be checked.
359
- */
360
- checkAttribute(context, attributeName) {
361
- const def = this.getDefinition(context.last);
362
- if (!def) {
363
- return false;
364
- }
365
- return def.allowAttributes.includes(attributeName);
366
- }
367
- /**
368
- * Checks whether the given element (`elementToMerge`) can be merged with the specified base element (`positionOrBaseElement`).
369
- *
370
- * In other words — whether `elementToMerge`'s children {@link #checkChild are allowed} in the `positionOrBaseElement`.
371
- *
372
- * This check ensures that elements merged with {@link module:engine/model/writer~Writer#merge `Writer#merge()`}
373
- * will be valid.
374
- *
375
- * Instead of elements, you can pass the instance of the {@link module:engine/model/position~Position} class as the
376
- * `positionOrBaseElement`. It means that the elements before and after the position will be checked whether they can be merged.
377
- *
378
- * @param positionOrBaseElement The position or base element to which the `elementToMerge` will be merged.
379
- * @param elementToMerge The element to merge. Required if `positionOrBaseElement` is an element.
380
- */
381
- checkMerge(positionOrBaseElement, elementToMerge) {
382
- if (positionOrBaseElement instanceof Position) {
383
- const nodeBefore = positionOrBaseElement.nodeBefore;
384
- const nodeAfter = positionOrBaseElement.nodeAfter;
385
- if (!(nodeBefore instanceof Element)) {
386
- /**
387
- * The node before the merge position must be an element.
388
- *
389
- * @error schema-check-merge-no-element-before
390
- */
391
- throw new CKEditorError('schema-check-merge-no-element-before', this);
392
- }
393
- if (!(nodeAfter instanceof Element)) {
394
- /**
395
- * The node after the merge position must be an element.
396
- *
397
- * @error schema-check-merge-no-element-after
398
- */
399
- throw new CKEditorError('schema-check-merge-no-element-after', this);
400
- }
401
- return this.checkMerge(nodeBefore, nodeAfter);
402
- }
403
- for (const child of elementToMerge.getChildren()) {
404
- if (!this.checkChild(positionOrBaseElement, child)) {
405
- return false;
406
- }
407
- }
408
- return true;
409
- }
410
- /**
411
- * Allows registering a callback to the {@link #checkChild} method calls.
412
- *
413
- * Callbacks allow you to implement rules which are not otherwise possible to achieve
414
- * by using the declarative API of {@link module:engine/model/schema~SchemaItemDefinition}.
415
- * For example, by using this method you can disallow elements in specific contexts.
416
- *
417
- * This method is a shorthand for using the {@link #event:checkChild} event. For even better control,
418
- * you can use that event instead.
419
- *
420
- * Example:
421
- *
422
- * ```ts
423
- * // Disallow heading1 directly inside a blockQuote.
424
- * schema.addChildCheck( ( context, childDefinition ) => {
425
- * if ( context.endsWith( 'blockQuote' ) && childDefinition.name == 'heading1' ) {
426
- * return false;
427
- * }
428
- * } );
429
- * ```
430
- *
431
- * Which translates to:
432
- *
433
- * ```ts
434
- * schema.on( 'checkChild', ( evt, args ) => {
435
- * const context = args[ 0 ];
436
- * const childDefinition = args[ 1 ];
437
- *
438
- * if ( context.endsWith( 'blockQuote' ) && childDefinition && childDefinition.name == 'heading1' ) {
439
- * // Prevent next listeners from being called.
440
- * evt.stop();
441
- * // Set the checkChild()'s return value.
442
- * evt.return = false;
443
- * }
444
- * }, { priority: 'high' } );
445
- * ```
446
- *
447
- * @param callback The callback to be called. It is called with two parameters:
448
- * {@link module:engine/model/schema~SchemaContext} (context) instance and
449
- * {@link module:engine/model/schema~SchemaCompiledItemDefinition} (child-to-check definition).
450
- * The callback may return `true/false` to override `checkChild()`'s return value. If it does not return
451
- * a boolean value, the default algorithm (or other callbacks) will define `checkChild()`'s return value.
452
- */
453
- addChildCheck(callback) {
454
- this.on('checkChild', (evt, [ctx, childDef]) => {
455
- // checkChild() was called with a non-registered child.
456
- // In 99% cases such check should return false, so not to overcomplicate all callbacks
457
- // don't even execute them.
458
- if (!childDef) {
459
- return;
460
- }
461
- const retValue = callback(ctx, childDef);
462
- if (typeof retValue == 'boolean') {
463
- evt.stop();
464
- evt.return = retValue;
465
- }
466
- }, { priority: 'high' });
467
- }
468
- /**
469
- * Allows registering a callback to the {@link #checkAttribute} method calls.
470
- *
471
- * Callbacks allow you to implement rules which are not otherwise possible to achieve
472
- * by using the declarative API of {@link module:engine/model/schema~SchemaItemDefinition}.
473
- * For example, by using this method you can disallow attribute if node to which it is applied
474
- * is contained within some other element (e.g. you want to disallow `bold` on `$text` within `heading1`).
475
- *
476
- * This method is a shorthand for using the {@link #event:checkAttribute} event. For even better control,
477
- * you can use that event instead.
478
- *
479
- * Example:
480
- *
481
- * ```ts
482
- * // Disallow bold on $text inside heading1.
483
- * schema.addAttributeCheck( ( context, attributeName ) => {
484
- * if ( context.endsWith( 'heading1 $text' ) && attributeName == 'bold' ) {
485
- * return false;
486
- * }
487
- * } );
488
- * ```
489
- *
490
- * Which translates to:
491
- *
492
- * ```ts
493
- * schema.on( 'checkAttribute', ( evt, args ) => {
494
- * const context = args[ 0 ];
495
- * const attributeName = args[ 1 ];
496
- *
497
- * if ( context.endsWith( 'heading1 $text' ) && attributeName == 'bold' ) {
498
- * // Prevent next listeners from being called.
499
- * evt.stop();
500
- * // Set the checkAttribute()'s return value.
501
- * evt.return = false;
502
- * }
503
- * }, { priority: 'high' } );
504
- * ```
505
- *
506
- * @param callback The callback to be called. It is called with two parameters:
507
- * {@link module:engine/model/schema~SchemaContext} (context) instance and attribute name.
508
- * The callback may return `true/false` to override `checkAttribute()`'s return value. If it does not return
509
- * a boolean value, the default algorithm (or other callbacks) will define `checkAttribute()`'s return value.
510
- */
511
- addAttributeCheck(callback) {
512
- this.on('checkAttribute', (evt, [ctx, attributeName]) => {
513
- const retValue = callback(ctx, attributeName);
514
- if (typeof retValue == 'boolean') {
515
- evt.stop();
516
- evt.return = retValue;
517
- }
518
- }, { priority: 'high' });
519
- }
520
- /**
521
- * This method allows assigning additional metadata to the model attributes. For example,
522
- * {@link module:engine/model/schema~AttributeProperties `AttributeProperties#isFormatting` property} is
523
- * used to mark formatting attributes (like `bold` or `italic`).
524
- *
525
- * ```ts
526
- * // Mark bold as a formatting attribute.
527
- * schema.setAttributeProperties( 'bold', {
528
- * isFormatting: true
529
- * } );
530
- *
531
- * // Override code not to be considered a formatting markup.
532
- * schema.setAttributeProperties( 'code', {
533
- * isFormatting: false
534
- * } );
535
- * ```
536
- *
537
- * Properties are not limited to members defined in the
538
- * {@link module:engine/model/schema~AttributeProperties `AttributeProperties` type} and you can also use custom properties:
539
- *
540
- * ```ts
541
- * schema.setAttributeProperties( 'blockQuote', {
542
- * customProperty: 'value'
543
- * } );
544
- * ```
545
- *
546
- * Subsequent calls with the same attribute will extend its custom properties:
547
- *
548
- * ```ts
549
- * schema.setAttributeProperties( 'blockQuote', {
550
- * one: 1
551
- * } );
552
- *
553
- * schema.setAttributeProperties( 'blockQuote', {
554
- * two: 2
555
- * } );
556
- *
557
- * console.log( schema.getAttributeProperties( 'blockQuote' ) );
558
- * // Logs: { one: 1, two: 2 }
559
- * ```
560
- *
561
- * @param attributeName A name of the attribute to receive the properties.
562
- * @param properties A dictionary of properties.
563
- */
564
- setAttributeProperties(attributeName, properties) {
565
- this._attributeProperties[attributeName] = Object.assign(this.getAttributeProperties(attributeName), properties);
566
- }
567
- /**
568
- * Returns properties associated with a given model attribute. See {@link #setAttributeProperties `setAttributeProperties()`}.
569
- *
570
- * @param attributeName A name of the attribute.
571
- */
572
- getAttributeProperties(attributeName) {
573
- return this._attributeProperties[attributeName] || {};
574
- }
575
- /**
576
- * Returns the lowest {@link module:engine/model/schema~Schema#isLimit limit element} containing the entire
577
- * selection/range/position or the root otherwise.
578
- *
579
- * @param selectionOrRangeOrPosition The selection/range/position to check.
580
- * @returns The lowest limit element containing the entire `selectionOrRangeOrPosition`.
581
- */
582
- getLimitElement(selectionOrRangeOrPosition) {
583
- let element;
584
- if (selectionOrRangeOrPosition instanceof Position) {
585
- element = selectionOrRangeOrPosition.parent;
586
- }
587
- else {
588
- const ranges = selectionOrRangeOrPosition instanceof Range ?
589
- [selectionOrRangeOrPosition] :
590
- Array.from(selectionOrRangeOrPosition.getRanges());
591
- // Find the common ancestor for all selection's ranges.
592
- element = ranges
593
- .reduce((element, range) => {
594
- const rangeCommonAncestor = range.getCommonAncestor();
595
- if (!element) {
596
- return rangeCommonAncestor;
597
- }
598
- return element.getCommonAncestor(rangeCommonAncestor, { includeSelf: true });
599
- }, null);
600
- }
601
- while (!this.isLimit(element)) {
602
- if (element.parent) {
603
- element = element.parent;
604
- }
605
- else {
606
- break;
607
- }
608
- }
609
- return element;
610
- }
611
- /**
612
- * Checks whether the attribute is allowed in selection:
613
- *
614
- * * if the selection is not collapsed, then checks if the attribute is allowed on any of nodes in that range,
615
- * * if the selection is collapsed, then checks if on the selection position there's a text with the
616
- * specified attribute allowed.
617
- *
618
- * @param selection Selection which will be checked.
619
- * @param attribute The name of the attribute to check.
620
- */
621
- checkAttributeInSelection(selection, attribute) {
622
- if (selection.isCollapsed) {
623
- const firstPosition = selection.getFirstPosition();
624
- const context = [
625
- ...firstPosition.getAncestors(),
626
- new Text('', selection.getAttributes())
627
- ];
628
- // Check whether schema allows for a text with the attribute in the selection.
629
- return this.checkAttribute(context, attribute);
630
- }
631
- else {
632
- const ranges = selection.getRanges();
633
- // For all ranges, check nodes in them until you find a node that is allowed to have the attribute.
634
- for (const range of ranges) {
635
- for (const value of range) {
636
- if (this.checkAttribute(value.item, attribute)) {
637
- // If we found a node that is allowed to have the attribute, return true.
638
- return true;
639
- }
640
- }
641
- }
642
- }
643
- // If we haven't found such node, return false.
644
- return false;
645
- }
646
- /**
647
- * Transforms the given set of ranges into a set of ranges where the given attribute is allowed (and can be applied).
648
- *
649
- * @param ranges Ranges to be validated.
650
- * @param attribute The name of the attribute to check.
651
- * @returns Ranges in which the attribute is allowed.
652
- */
653
- *getValidRanges(ranges, attribute) {
654
- ranges = convertToMinimalFlatRanges(ranges);
655
- for (const range of ranges) {
656
- yield* this._getValidRangesForRange(range, attribute);
657
- }
658
- }
659
- /**
660
- * Basing on given `position`, finds and returns a {@link module:engine/model/range~Range range} which is
661
- * nearest to that `position` and is a correct range for selection.
662
- *
663
- * The correct selection range might be collapsed when it is located in a position where the text node can be placed.
664
- * Non-collapsed range is returned when selection can be placed around element marked as an "object" in
665
- * the {@link module:engine/model/schema~Schema schema}.
666
- *
667
- * Direction of searching for the nearest correct selection range can be specified as:
668
- *
669
- * * `both` - searching will be performed in both ways,
670
- * * `forward` - searching will be performed only forward,
671
- * * `backward` - searching will be performed only backward.
672
- *
673
- * When valid selection range cannot be found, `null` is returned.
674
- *
675
- * @param position Reference position where new selection range should be looked for.
676
- * @param direction Search direction.
677
- * @returns Nearest selection range or `null` if one cannot be found.
678
- */
679
- getNearestSelectionRange(position, direction = 'both') {
680
- // Return collapsed range if provided position is valid.
681
- if (this.checkChild(position, '$text')) {
682
- return new Range(position);
683
- }
684
- let backwardWalker, forwardWalker;
685
- // Never leave a limit element.
686
- const limitElement = position.getAncestors().reverse().find(item => this.isLimit(item)) ||
687
- position.root;
688
- if (direction == 'both' || direction == 'backward') {
689
- backwardWalker = new TreeWalker({
690
- boundaries: Range._createIn(limitElement),
691
- startPosition: position,
692
- direction: 'backward'
693
- });
694
- }
695
- if (direction == 'both' || direction == 'forward') {
696
- forwardWalker = new TreeWalker({
697
- boundaries: Range._createIn(limitElement),
698
- startPosition: position
699
- });
700
- }
701
- for (const data of combineWalkers(backwardWalker, forwardWalker)) {
702
- const type = (data.walker == backwardWalker ? 'elementEnd' : 'elementStart');
703
- const value = data.value;
704
- if (value.type == type && this.isObject(value.item)) {
705
- return Range._createOn(value.item);
706
- }
707
- if (this.checkChild(value.nextPosition, '$text')) {
708
- return new Range(value.nextPosition);
709
- }
710
- }
711
- return null;
712
- }
713
- /**
714
- * Tries to find position ancestors that allow to insert a given node.
715
- * It starts searching from the given position and goes node by node to the top of the model tree
716
- * as long as a {@link module:engine/model/schema~Schema#isLimit limit element}, an
717
- * {@link module:engine/model/schema~Schema#isObject object element} or a topmost ancestor is not reached.
718
- *
719
- * @param position The position that the search will start from.
720
- * @param node The node for which an allowed parent should be found or its name.
721
- * @returns Allowed parent or null if nothing was found.
722
- */
723
- findAllowedParent(position, node) {
724
- let parent = position.parent;
725
- while (parent) {
726
- if (this.checkChild(parent, node)) {
727
- return parent;
728
- }
729
- // Do not split limit elements.
730
- if (this.isLimit(parent)) {
731
- return null;
732
- }
733
- parent = parent.parent;
734
- }
735
- return null;
736
- }
737
- /**
738
- * Sets attributes allowed by the schema on a given node.
739
- *
740
- * @param node A node to set attributes on.
741
- * @param attributes Attributes keys and values.
742
- * @param writer An instance of the model writer.
743
- */
744
- setAllowedAttributes(node, attributes, writer) {
745
- const model = writer.model;
746
- for (const [attributeName, attributeValue] of Object.entries(attributes)) {
747
- if (model.schema.checkAttribute(node, attributeName)) {
748
- writer.setAttribute(attributeName, attributeValue, node);
749
- }
750
- }
751
- }
752
- /**
753
- * Removes attributes disallowed by the schema.
754
- *
755
- * @param nodes Nodes that will be filtered.
756
- */
757
- removeDisallowedAttributes(nodes, writer) {
758
- for (const node of nodes) {
759
- // When node is a `Text` it has no children, so just filter it out.
760
- if (node.is('$text')) {
761
- removeDisallowedAttributeFromNode(this, node, writer);
762
- }
763
- // In a case of `Element` iterates through positions between nodes inside this element
764
- // and filter out node before the current position, or position parent when position
765
- // is at start of an element. Using positions prevent from omitting merged nodes
766
- // see https://github.com/ckeditor/ckeditor5-engine/issues/1789.
767
- else {
768
- const rangeInNode = Range._createIn(node);
769
- const positionsInRange = rangeInNode.getPositions();
770
- for (const position of positionsInRange) {
771
- const item = position.nodeBefore || position.parent;
772
- removeDisallowedAttributeFromNode(this, item, writer);
773
- }
774
- }
775
- }
776
- }
777
- /**
778
- * Gets attributes of a node that have a given property.
779
- *
780
- * @param node Node to get attributes from.
781
- * @param propertyName Name of the property that attribute must have to return it.
782
- * @param propertyValue Desired value of the property that we want to check.
783
- * When `undefined` attributes will be returned if they have set a given property no matter what the value is. If specified it will
784
- * return attributes which given property's value is equal to this parameter.
785
- * @returns Object with attributes' names as key and attributes' values as value.
786
- */
787
- getAttributesWithProperty(node, propertyName, propertyValue) {
788
- const attributes = {};
789
- for (const [attributeName, attributeValue] of node.getAttributes()) {
790
- const attributeProperties = this.getAttributeProperties(attributeName);
791
- if (attributeProperties[propertyName] === undefined) {
792
- continue;
793
- }
794
- if (propertyValue === undefined || propertyValue === attributeProperties[propertyName]) {
795
- attributes[attributeName] = attributeValue;
796
- }
797
- }
798
- return attributes;
799
- }
800
- /**
801
- * Creates an instance of the schema context.
802
- */
803
- createContext(context) {
804
- return new SchemaContext(context);
805
- }
806
- _clearCache() {
807
- this._compiledDefinitions = null;
808
- }
809
- _compile() {
810
- const compiledDefinitions = {};
811
- const sourceRules = this._sourceDefinitions;
812
- const itemNames = Object.keys(sourceRules);
813
- for (const itemName of itemNames) {
814
- compiledDefinitions[itemName] = compileBaseItemRule(sourceRules[itemName], itemName);
815
- }
816
- for (const itemName of itemNames) {
817
- compileAllowChildren(compiledDefinitions, itemName);
818
- }
819
- for (const itemName of itemNames) {
820
- compileAllowContentOf(compiledDefinitions, itemName);
821
- }
822
- for (const itemName of itemNames) {
823
- compileAllowWhere(compiledDefinitions, itemName);
824
- }
825
- for (const itemName of itemNames) {
826
- compileAllowAttributesOf(compiledDefinitions, itemName);
827
- compileInheritPropertiesFrom(compiledDefinitions, itemName);
828
- }
829
- for (const itemName of itemNames) {
830
- cleanUpAllowIn(compiledDefinitions, itemName);
831
- setupAllowChildren(compiledDefinitions, itemName);
832
- cleanUpAllowAttributes(compiledDefinitions, itemName);
833
- }
834
- this._compiledDefinitions = compiledDefinitions;
835
- }
836
- _checkContextMatch(def, context, contextItemIndex = context.length - 1) {
837
- const contextItem = context.getItem(contextItemIndex);
838
- if (def.allowIn.includes(contextItem.name)) {
839
- if (contextItemIndex == 0) {
840
- return true;
841
- }
842
- else {
843
- const parentRule = this.getDefinition(contextItem);
844
- return this._checkContextMatch(parentRule, context, contextItemIndex - 1);
845
- }
846
- }
847
- else {
848
- return false;
849
- }
850
- }
851
- /**
852
- * Takes a flat range and an attribute name. Traverses the range recursively and deeply to find and return all ranges
853
- * inside the given range on which the attribute can be applied.
854
- *
855
- * This is a helper function for {@link ~Schema#getValidRanges}.
856
- *
857
- * @param range The range to process.
858
- * @param attribute The name of the attribute to check.
859
- * @returns Ranges in which the attribute is allowed.
860
- */
861
- *_getValidRangesForRange(range, attribute) {
862
- let start = range.start;
863
- let end = range.start;
864
- for (const item of range.getItems({ shallow: true })) {
865
- if (item.is('element')) {
866
- yield* this._getValidRangesForRange(Range._createIn(item), attribute);
867
- }
868
- if (!this.checkAttribute(item, attribute)) {
869
- if (!start.isEqual(end)) {
870
- yield new Range(start, end);
871
- }
872
- start = Position._createAfter(item);
873
- }
874
- end = Position._createAfter(item);
875
- }
876
- if (!start.isEqual(end)) {
877
- yield new Range(start, end);
878
- }
879
- }
880
- }
881
- /**
882
- * A schema context — a list of ancestors of a given position in the document.
883
- *
884
- * Considering such position:
885
- *
886
- * ```xml
887
- * <$root>
888
- * <blockQuote>
889
- * <paragraph>
890
- * ^
891
- * </paragraph>
892
- * </blockQuote>
893
- * </$root>
894
- * ```
895
- *
896
- * The context of this position is its {@link module:engine/model/position~Position#getAncestors lists of ancestors}:
897
- *
898
- * [ rootElement, blockQuoteElement, paragraphElement ]
899
- *
900
- * Contexts are used in the {@link module:engine/model/schema~Schema#event:checkChild `Schema#checkChild`} and
901
- * {@link module:engine/model/schema~Schema#event:checkAttribute `Schema#checkAttribute`} events as a definition
902
- * of a place in the document where the check occurs. The context instances are created based on the first arguments
903
- * of the {@link module:engine/model/schema~Schema#checkChild `Schema#checkChild()`} and
904
- * {@link module:engine/model/schema~Schema#checkAttribute `Schema#checkAttribute()`} methods so when
905
- * using these methods you need to use {@link module:engine/model/schema~SchemaContextDefinition}s.
906
- */
907
- export class SchemaContext {
908
- /**
909
- * Creates an instance of the context.
910
- */
911
- constructor(context) {
912
- if (context instanceof SchemaContext) {
913
- return context;
914
- }
915
- let items;
916
- if (typeof context == 'string') {
917
- items = [context];
918
- }
919
- else if (!Array.isArray(context)) {
920
- // `context` is item or position.
921
- // Position#getAncestors() doesn't accept any parameters but it works just fine here.
922
- items = context.getAncestors({ includeSelf: true });
923
- }
924
- else {
925
- items = context;
926
- }
927
- this._items = items.map(mapContextItem);
928
- }
929
- /**
930
- * The number of items.
931
- */
932
- get length() {
933
- return this._items.length;
934
- }
935
- /**
936
- * The last item (the lowest node).
937
- */
938
- get last() {
939
- return this._items[this._items.length - 1];
940
- }
941
- /**
942
- * Iterable interface.
943
- *
944
- * Iterates over all context items.
945
- */
946
- [Symbol.iterator]() {
947
- return this._items[Symbol.iterator]();
948
- }
949
- /**
950
- * Returns a new schema context instance with an additional item.
951
- *
952
- * Item can be added as:
953
- *
954
- * ```ts
955
- * const context = new SchemaContext( [ '$root' ] );
956
- *
957
- * // An element.
958
- * const fooElement = writer.createElement( 'fooElement' );
959
- * const newContext = context.push( fooElement ); // [ '$root', 'fooElement' ]
960
- *
961
- * // A text node.
962
- * const text = writer.createText( 'foobar' );
963
- * const newContext = context.push( text ); // [ '$root', '$text' ]
964
- *
965
- * // A string (element name).
966
- * const newContext = context.push( 'barElement' ); // [ '$root', 'barElement' ]
967
- * ```
968
- *
969
- * **Note** {@link module:engine/model/node~Node} that is already in the model tree will be added as the only item
970
- * (without ancestors).
971
- *
972
- * @param item An item that will be added to the current context.
973
- * @returns A new schema context instance with an additional item.
974
- */
975
- push(item) {
976
- const ctx = new SchemaContext([item]);
977
- ctx._items = [...this._items, ...ctx._items];
978
- return ctx;
979
- }
980
- /**
981
- * Gets an item on the given index.
982
- */
983
- getItem(index) {
984
- return this._items[index];
985
- }
986
- /**
987
- * Returns the names of items.
988
- */
989
- *getNames() {
990
- yield* this._items.map(item => item.name);
991
- }
992
- /**
993
- * Checks whether the context ends with the given nodes.
994
- *
995
- * ```ts
996
- * const ctx = new SchemaContext( [ rootElement, paragraphElement, textNode ] );
997
- *
998
- * ctx.endsWith( '$text' ); // -> true
999
- * ctx.endsWith( 'paragraph $text' ); // -> true
1000
- * ctx.endsWith( '$root' ); // -> false
1001
- * ctx.endsWith( 'paragraph' ); // -> false
1002
- * ```
1003
- */
1004
- endsWith(query) {
1005
- return Array.from(this.getNames()).join(' ').endsWith(query);
1006
- }
1007
- /**
1008
- * Checks whether the context starts with the given nodes.
1009
- *
1010
- * ```ts
1011
- * const ctx = new SchemaContext( [ rootElement, paragraphElement, textNode ] );
1012
- *
1013
- * ctx.endsWith( '$root' ); // -> true
1014
- * ctx.endsWith( '$root paragraph' ); // -> true
1015
- * ctx.endsWith( '$text' ); // -> false
1016
- * ctx.endsWith( 'paragraph' ); // -> false
1017
- * ```
1018
- */
1019
- startsWith(query) {
1020
- return Array.from(this.getNames()).join(' ').startsWith(query);
1021
- }
1022
- }
1023
- function compileBaseItemRule(sourceItemRules, itemName) {
1024
- const itemRule = {
1025
- name: itemName,
1026
- allowIn: [],
1027
- allowContentOf: [],
1028
- allowWhere: [],
1029
- allowAttributes: [],
1030
- allowAttributesOf: [],
1031
- allowChildren: [],
1032
- inheritTypesFrom: []
1033
- };
1034
- copyTypes(sourceItemRules, itemRule);
1035
- copyProperty(sourceItemRules, itemRule, 'allowIn');
1036
- copyProperty(sourceItemRules, itemRule, 'allowContentOf');
1037
- copyProperty(sourceItemRules, itemRule, 'allowWhere');
1038
- copyProperty(sourceItemRules, itemRule, 'allowAttributes');
1039
- copyProperty(sourceItemRules, itemRule, 'allowAttributesOf');
1040
- copyProperty(sourceItemRules, itemRule, 'allowChildren');
1041
- copyProperty(sourceItemRules, itemRule, 'inheritTypesFrom');
1042
- makeInheritAllWork(sourceItemRules, itemRule);
1043
- return itemRule;
1044
- }
1045
- function compileAllowChildren(compiledDefinitions, itemName) {
1046
- const item = compiledDefinitions[itemName];
1047
- for (const allowChildrenItem of item.allowChildren) {
1048
- const allowedChildren = compiledDefinitions[allowChildrenItem];
1049
- // The allowChildren property may point to an unregistered element.
1050
- if (!allowedChildren) {
1051
- continue;
1052
- }
1053
- allowedChildren.allowIn.push(itemName);
1054
- }
1055
- // The allowIn property already includes correct items, reset the allowChildren property
1056
- // to avoid duplicates later when setting up compilation results.
1057
- item.allowChildren.length = 0;
1058
- }
1059
- function compileAllowContentOf(compiledDefinitions, itemName) {
1060
- for (const allowContentOfItemName of compiledDefinitions[itemName].allowContentOf) {
1061
- // The allowContentOf property may point to an unregistered element.
1062
- if (compiledDefinitions[allowContentOfItemName]) {
1063
- const allowedChildren = getAllowedChildren(compiledDefinitions, allowContentOfItemName);
1064
- allowedChildren.forEach(allowedItem => {
1065
- allowedItem.allowIn.push(itemName);
1066
- });
1067
- }
1068
- }
1069
- delete compiledDefinitions[itemName].allowContentOf;
1070
- }
1071
- function compileAllowWhere(compiledDefinitions, itemName) {
1072
- for (const allowWhereItemName of compiledDefinitions[itemName].allowWhere) {
1073
- const inheritFrom = compiledDefinitions[allowWhereItemName];
1074
- // The allowWhere property may point to an unregistered element.
1075
- if (inheritFrom) {
1076
- const allowedIn = inheritFrom.allowIn;
1077
- compiledDefinitions[itemName].allowIn.push(...allowedIn);
1078
- }
1079
- }
1080
- delete compiledDefinitions[itemName].allowWhere;
1081
- }
1082
- function compileAllowAttributesOf(compiledDefinitions, itemName) {
1083
- for (const allowAttributeOfItem of compiledDefinitions[itemName].allowAttributesOf) {
1084
- const inheritFrom = compiledDefinitions[allowAttributeOfItem];
1085
- if (inheritFrom) {
1086
- const inheritAttributes = inheritFrom.allowAttributes;
1087
- compiledDefinitions[itemName].allowAttributes.push(...inheritAttributes);
1088
- }
1089
- }
1090
- delete compiledDefinitions[itemName].allowAttributesOf;
1091
- }
1092
- function compileInheritPropertiesFrom(compiledDefinitions, itemName) {
1093
- const item = compiledDefinitions[itemName];
1094
- for (const inheritPropertiesOfItem of item.inheritTypesFrom) {
1095
- const inheritFrom = compiledDefinitions[inheritPropertiesOfItem];
1096
- if (inheritFrom) {
1097
- const typeNames = Object.keys(inheritFrom).filter(name => name.startsWith('is'));
1098
- for (const name of typeNames) {
1099
- if (!(name in item)) {
1100
- item[name] = inheritFrom[name];
1101
- }
1102
- }
1103
- }
1104
- }
1105
- delete item.inheritTypesFrom;
1106
- }
1107
- // Remove items which weren't registered (because it may break some checks or we'd need to complicate them).
1108
- // Make sure allowIn doesn't contain repeated values.
1109
- function cleanUpAllowIn(compiledDefinitions, itemName) {
1110
- const itemRule = compiledDefinitions[itemName];
1111
- const existingItems = itemRule.allowIn.filter(itemToCheck => compiledDefinitions[itemToCheck]);
1112
- itemRule.allowIn = Array.from(new Set(existingItems));
1113
- }
1114
- // Setup allowChildren items based on allowIn.
1115
- function setupAllowChildren(compiledDefinitions, itemName) {
1116
- const itemRule = compiledDefinitions[itemName];
1117
- for (const allowedParentItemName of itemRule.allowIn) {
1118
- const allowedParentItem = compiledDefinitions[allowedParentItemName];
1119
- allowedParentItem.allowChildren.push(itemName);
1120
- }
1121
- }
1122
- function cleanUpAllowAttributes(compiledDefinitions, itemName) {
1123
- const itemRule = compiledDefinitions[itemName];
1124
- itemRule.allowAttributes = Array.from(new Set(itemRule.allowAttributes));
1125
- }
1126
- function copyTypes(sourceItemRules, itemRule) {
1127
- for (const sourceItemRule of sourceItemRules) {
1128
- const typeNames = Object.keys(sourceItemRule).filter(name => name.startsWith('is'));
1129
- for (const name of typeNames) {
1130
- itemRule[name] = !!sourceItemRule[name];
1131
- }
1132
- }
1133
- }
1134
- function copyProperty(sourceItemRules, itemRule, propertyName) {
1135
- for (const sourceItemRule of sourceItemRules) {
1136
- const value = sourceItemRule[propertyName];
1137
- if (typeof value == 'string') {
1138
- itemRule[propertyName].push(value);
1139
- }
1140
- else if (Array.isArray(value)) {
1141
- itemRule[propertyName].push(...value);
1142
- }
1143
- }
1144
- }
1145
- function makeInheritAllWork(sourceItemRules, itemRule) {
1146
- for (const sourceItemRule of sourceItemRules) {
1147
- const inheritFrom = sourceItemRule.inheritAllFrom;
1148
- if (inheritFrom) {
1149
- itemRule.allowContentOf.push(inheritFrom);
1150
- itemRule.allowWhere.push(inheritFrom);
1151
- itemRule.allowAttributesOf.push(inheritFrom);
1152
- itemRule.inheritTypesFrom.push(inheritFrom);
1153
- }
1154
- }
1155
- }
1156
- function getAllowedChildren(compiledDefinitions, itemName) {
1157
- const itemRule = compiledDefinitions[itemName];
1158
- return getValues(compiledDefinitions).filter(def => def.allowIn.includes(itemRule.name));
1159
- }
1160
- function getValues(obj) {
1161
- return Object.keys(obj).map(key => obj[key]);
1162
- }
1163
- function mapContextItem(ctxItem) {
1164
- if (typeof ctxItem == 'string' || ctxItem.is('documentFragment')) {
1165
- return {
1166
- name: typeof ctxItem == 'string' ? ctxItem : '$documentFragment',
1167
- *getAttributeKeys() { },
1168
- getAttribute() { }
1169
- };
1170
- }
1171
- else {
1172
- return {
1173
- // '$text' means text nodes and text proxies.
1174
- name: ctxItem.is('element') ? ctxItem.name : '$text',
1175
- *getAttributeKeys() {
1176
- yield* ctxItem.getAttributeKeys();
1177
- },
1178
- getAttribute(key) {
1179
- return ctxItem.getAttribute(key);
1180
- }
1181
- };
1182
- }
1183
- }
1184
- /**
1185
- * Generator function returning values from provided walkers, switching between them at each iteration. If only one walker
1186
- * is provided it will return data only from that walker.
1187
- *
1188
- * @param backward Walker iterating in backward direction.
1189
- * @param forward Walker iterating in forward direction.
1190
- * @returns Object returned at each iteration contains `value` and `walker` (informing which walker returned
1191
- * given value) fields.
1192
- */
1193
- function* combineWalkers(backward, forward) {
1194
- let done = false;
1195
- while (!done) {
1196
- done = true;
1197
- if (backward) {
1198
- const step = backward.next();
1199
- if (!step.done) {
1200
- done = false;
1201
- yield {
1202
- walker: backward,
1203
- value: step.value
1204
- };
1205
- }
1206
- }
1207
- if (forward) {
1208
- const step = forward.next();
1209
- if (!step.done) {
1210
- done = false;
1211
- yield {
1212
- walker: forward,
1213
- value: step.value
1214
- };
1215
- }
1216
- }
1217
- }
1218
- }
1219
- /**
1220
- * Takes an array of non-intersecting ranges. For each of them gets minimal flat ranges covering that range and returns
1221
- * all those minimal flat ranges.
1222
- *
1223
- * @param ranges Ranges to process.
1224
- * @returns Minimal flat ranges of given `ranges`.
1225
- */
1226
- function* convertToMinimalFlatRanges(ranges) {
1227
- for (const range of ranges) {
1228
- yield* range.getMinimalFlatRanges();
1229
- }
1230
- }
1231
- function removeDisallowedAttributeFromNode(schema, node, writer) {
1232
- for (const attribute of node.getAttributeKeys()) {
1233
- if (!schema.checkAttribute(node, attribute)) {
1234
- writer.removeAttribute(attribute, node);
1235
- }
1236
- }
1237
- }
1
+ /**
2
+ * @license Copyright (c) 2003-2023, CKSource Holding sp. z o.o. All rights reserved.
3
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4
+ */
5
+ /**
6
+ * @module engine/model/schema
7
+ */
8
+ import Element from './element';
9
+ import Position from './position';
10
+ import Range from './range';
11
+ import Text from './text';
12
+ import TreeWalker from './treewalker';
13
+ import { CKEditorError, ObservableMixin } from '@ckeditor/ckeditor5-utils';
14
+ /**
15
+ * The model's schema. It defines the allowed and disallowed structures of nodes as well as nodes' attributes.
16
+ * The schema is usually defined by the features and based on them, the editing framework and features
17
+ * make decisions on how to change and process the model.
18
+ *
19
+ * The instance of schema is available in {@link module:engine/model/model~Model#schema `editor.model.schema`}.
20
+ *
21
+ * Read more about the schema in:
22
+ *
23
+ * * The {@glink framework/architecture/editing-engine#schema schema section} of the
24
+ * {@glink framework/architecture/editing-engine Introduction to the Editing engine architecture} guide.
25
+ * * The {@glink framework/deep-dive/schema Schema deep-dive} guide.
26
+ */
27
+ export default class Schema extends ObservableMixin() {
28
+ /**
29
+ * Creates a schema instance.
30
+ */
31
+ constructor() {
32
+ super();
33
+ this._sourceDefinitions = {};
34
+ /**
35
+ * A dictionary containing attribute properties.
36
+ */
37
+ this._attributeProperties = {};
38
+ this.decorate('checkChild');
39
+ this.decorate('checkAttribute');
40
+ this.on('checkAttribute', (evt, args) => {
41
+ args[0] = new SchemaContext(args[0]);
42
+ }, { priority: 'highest' });
43
+ this.on('checkChild', (evt, args) => {
44
+ args[0] = new SchemaContext(args[0]);
45
+ args[1] = this.getDefinition(args[1]);
46
+ }, { priority: 'highest' });
47
+ }
48
+ /**
49
+ * Registers a schema item. Can only be called once for every item name.
50
+ *
51
+ * ```ts
52
+ * schema.register( 'paragraph', {
53
+ * inheritAllFrom: '$block'
54
+ * } );
55
+ * ```
56
+ */
57
+ register(itemName, definition) {
58
+ if (this._sourceDefinitions[itemName]) {
59
+ /**
60
+ * A single item cannot be registered twice in the schema.
61
+ *
62
+ * This situation may happen when:
63
+ *
64
+ * * Two or more plugins called {@link module:engine/model/schema~Schema#register `register()`} with the same name.
65
+ * This will usually mean that there is a collision between plugins which try to use the same element in the model.
66
+ * Unfortunately, the only way to solve this is by modifying one of these plugins to use a unique model element name.
67
+ * * A single plugin was loaded twice. This happens when it is installed by npm/yarn in two versions
68
+ * and usually means one or more of the following issues:
69
+ * * a version mismatch (two of your dependencies require two different versions of this plugin),
70
+ * * incorrect imports (this plugin is somehow imported twice in a way which confuses webpack),
71
+ * * mess in `node_modules/` (`rm -rf node_modules/` may help).
72
+ *
73
+ * **Note:** Check the logged `itemName` to better understand which plugin was duplicated/conflicting.
74
+ *
75
+ * @param itemName The name of the model element that is being registered twice.
76
+ * @error schema-cannot-register-item-twice
77
+ */
78
+ throw new CKEditorError('schema-cannot-register-item-twice', this, {
79
+ itemName
80
+ });
81
+ }
82
+ this._sourceDefinitions[itemName] = [
83
+ Object.assign({}, definition)
84
+ ];
85
+ this._clearCache();
86
+ }
87
+ /**
88
+ * Extends a {@link #register registered} item's definition.
89
+ *
90
+ * Extending properties such as `allowIn` will add more items to the existing properties,
91
+ * while redefining properties such as `isBlock` will override the previously defined ones.
92
+ *
93
+ * ```ts
94
+ * schema.register( 'foo', {
95
+ * allowIn: '$root',
96
+ * isBlock: true;
97
+ * } );
98
+ * schema.extend( 'foo', {
99
+ * allowIn: 'blockQuote',
100
+ * isBlock: false
101
+ * } );
102
+ *
103
+ * schema.getDefinition( 'foo' );
104
+ * // {
105
+ * // allowIn: [ '$root', 'blockQuote' ],
106
+ * // isBlock: false
107
+ * // }
108
+ * ```
109
+ */
110
+ extend(itemName, definition) {
111
+ if (!this._sourceDefinitions[itemName]) {
112
+ /**
113
+ * Cannot extend an item which was not registered yet.
114
+ *
115
+ * This error happens when a plugin tries to extend the schema definition of an item which was not
116
+ * {@link module:engine/model/schema~Schema#register registered} yet.
117
+ *
118
+ * @param itemName The name of the model element which is being extended.
119
+ * @error schema-cannot-extend-missing-item
120
+ */
121
+ throw new CKEditorError('schema-cannot-extend-missing-item', this, {
122
+ itemName
123
+ });
124
+ }
125
+ this._sourceDefinitions[itemName].push(Object.assign({}, definition));
126
+ this._clearCache();
127
+ }
128
+ /**
129
+ * Returns data of all registered items.
130
+ *
131
+ * This method should normally be used for reflection purposes (e.g. defining a clone of a certain element,
132
+ * checking a list of all block elements, etc).
133
+ * Use specific methods (such as {@link #checkChild `checkChild()`} or {@link #isLimit `isLimit()`})
134
+ * in other cases.
135
+ */
136
+ getDefinitions() {
137
+ if (!this._compiledDefinitions) {
138
+ this._compile();
139
+ }
140
+ return this._compiledDefinitions;
141
+ }
142
+ /**
143
+ * Returns a definition of the given item or `undefined` if an item is not registered.
144
+ *
145
+ * This method should normally be used for reflection purposes (e.g. defining a clone of a certain element,
146
+ * checking a list of all block elements, etc).
147
+ * Use specific methods (such as {@link #checkChild `checkChild()`} or {@link #isLimit `isLimit()`})
148
+ * in other cases.
149
+ */
150
+ getDefinition(item) {
151
+ let itemName;
152
+ if (typeof item == 'string') {
153
+ itemName = item;
154
+ }
155
+ else if ('is' in item && (item.is('$text') || item.is('$textProxy'))) {
156
+ itemName = '$text';
157
+ }
158
+ // Element or module:engine/model/schema~SchemaContextItem.
159
+ else {
160
+ itemName = item.name;
161
+ }
162
+ return this.getDefinitions()[itemName];
163
+ }
164
+ /**
165
+ * Returns `true` if the given item is registered in the schema.
166
+ *
167
+ * ```ts
168
+ * schema.isRegistered( 'paragraph' ); // -> true
169
+ * schema.isRegistered( editor.model.document.getRoot() ); // -> true
170
+ * schema.isRegistered( 'foo' ); // -> false
171
+ * ```
172
+ */
173
+ isRegistered(item) {
174
+ return !!this.getDefinition(item);
175
+ }
176
+ /**
177
+ * Returns `true` if the given item is defined to be
178
+ * a block by the {@link module:engine/model/schema~SchemaItemDefinition}'s `isBlock` property.
179
+ *
180
+ * ```ts
181
+ * schema.isBlock( 'paragraph' ); // -> true
182
+ * schema.isBlock( '$root' ); // -> false
183
+ *
184
+ * const paragraphElement = writer.createElement( 'paragraph' );
185
+ * schema.isBlock( paragraphElement ); // -> true
186
+ * ```
187
+ *
188
+ * See the {@glink framework/deep-dive/schema#block-elements Block elements} section of
189
+ * the {@glink framework/deep-dive/schema Schema deep-dive} guide for more details.
190
+ */
191
+ isBlock(item) {
192
+ const def = this.getDefinition(item);
193
+ return !!(def && def.isBlock);
194
+ }
195
+ /**
196
+ * Returns `true` if the given item should be treated as a limit element.
197
+ *
198
+ * It considers an item to be a limit element if its
199
+ * {@link module:engine/model/schema~SchemaItemDefinition}'s
200
+ * {@link module:engine/model/schema~SchemaItemDefinition#isLimit `isLimit`} or
201
+ * {@link module:engine/model/schema~SchemaItemDefinition#isObject `isObject`} property
202
+ * was set to `true`.
203
+ *
204
+ * ```ts
205
+ * schema.isLimit( 'paragraph' ); // -> false
206
+ * schema.isLimit( '$root' ); // -> true
207
+ * schema.isLimit( editor.model.document.getRoot() ); // -> true
208
+ * schema.isLimit( 'imageBlock' ); // -> true
209
+ * ```
210
+ *
211
+ * See the {@glink framework/deep-dive/schema#limit-elements Limit elements} section of
212
+ * the {@glink framework/deep-dive/schema Schema deep-dive} guide for more details.
213
+ */
214
+ isLimit(item) {
215
+ const def = this.getDefinition(item);
216
+ if (!def) {
217
+ return false;
218
+ }
219
+ return !!(def.isLimit || def.isObject);
220
+ }
221
+ /**
222
+ * Returns `true` if the given item should be treated as an object element.
223
+ *
224
+ * It considers an item to be an object element if its
225
+ * {@link module:engine/model/schema~SchemaItemDefinition}'s
226
+ * {@link module:engine/model/schema~SchemaItemDefinition#isObject `isObject`} property
227
+ * was set to `true`.
228
+ *
229
+ * ```ts
230
+ * schema.isObject( 'paragraph' ); // -> false
231
+ * schema.isObject( 'imageBlock' ); // -> true
232
+ *
233
+ * const imageElement = writer.createElement( 'imageBlock' );
234
+ * schema.isObject( imageElement ); // -> true
235
+ * ```
236
+ *
237
+ * See the {@glink framework/deep-dive/schema#object-elements Object elements} section of
238
+ * the {@glink framework/deep-dive/schema Schema deep-dive} guide for more details.
239
+ */
240
+ isObject(item) {
241
+ const def = this.getDefinition(item);
242
+ if (!def) {
243
+ return false;
244
+ }
245
+ // Note: Check out the implementation of #isLimit(), #isSelectable(), and #isContent()
246
+ // to understand why these three constitute an object.
247
+ return !!(def.isObject || (def.isLimit && def.isSelectable && def.isContent));
248
+ }
249
+ /**
250
+ * Returns `true` if the given item is defined to be
251
+ * an inline element by the {@link module:engine/model/schema~SchemaItemDefinition}'s `isInline` property.
252
+ *
253
+ * ```ts
254
+ * schema.isInline( 'paragraph' ); // -> false
255
+ * schema.isInline( 'softBreak' ); // -> true
256
+ *
257
+ * const text = writer.createText( 'foo' );
258
+ * schema.isInline( text ); // -> true
259
+ * ```
260
+ *
261
+ * See the {@glink framework/deep-dive/schema#inline-elements Inline elements} section of
262
+ * the {@glink framework/deep-dive/schema Schema deep-dive} guide for more details.
263
+ */
264
+ isInline(item) {
265
+ const def = this.getDefinition(item);
266
+ return !!(def && def.isInline);
267
+ }
268
+ /**
269
+ * Returns `true` if the given item is defined to be
270
+ * a selectable element by the {@link module:engine/model/schema~SchemaItemDefinition}'s `isSelectable` property.
271
+ *
272
+ * ```ts
273
+ * schema.isSelectable( 'paragraph' ); // -> false
274
+ * schema.isSelectable( 'heading1' ); // -> false
275
+ * schema.isSelectable( 'imageBlock' ); // -> true
276
+ * schema.isSelectable( 'tableCell' ); // -> true
277
+ *
278
+ * const text = writer.createText( 'foo' );
279
+ * schema.isSelectable( text ); // -> false
280
+ * ```
281
+ *
282
+ * See the {@glink framework/deep-dive/schema#selectable-elements Selectable elements section} of
283
+ * the {@glink framework/deep-dive/schema Schema deep-dive} guide for more details.
284
+ */
285
+ isSelectable(item) {
286
+ const def = this.getDefinition(item);
287
+ if (!def) {
288
+ return false;
289
+ }
290
+ return !!(def.isSelectable || def.isObject);
291
+ }
292
+ /**
293
+ * Returns `true` if the given item is defined to be
294
+ * a content by the {@link module:engine/model/schema~SchemaItemDefinition}'s `isContent` property.
295
+ *
296
+ * ```ts
297
+ * schema.isContent( 'paragraph' ); // -> false
298
+ * schema.isContent( 'heading1' ); // -> false
299
+ * schema.isContent( 'imageBlock' ); // -> true
300
+ * schema.isContent( 'horizontalLine' ); // -> true
301
+ *
302
+ * const text = writer.createText( 'foo' );
303
+ * schema.isContent( text ); // -> true
304
+ * ```
305
+ *
306
+ * See the {@glink framework/deep-dive/schema#content-elements Content elements section} of
307
+ * the {@glink framework/deep-dive/schema Schema deep-dive} guide for more details.
308
+ */
309
+ isContent(item) {
310
+ const def = this.getDefinition(item);
311
+ if (!def) {
312
+ return false;
313
+ }
314
+ return !!(def.isContent || def.isObject);
315
+ }
316
+ /**
317
+ * Checks whether the given node (`child`) can be a child of the given context.
318
+ *
319
+ * ```ts
320
+ * schema.checkChild( model.document.getRoot(), paragraph ); // -> false
321
+ *
322
+ * schema.register( 'paragraph', {
323
+ * allowIn: '$root'
324
+ * } );
325
+ * schema.checkChild( model.document.getRoot(), paragraph ); // -> true
326
+ * ```
327
+ *
328
+ * Note: When verifying whether the given node can be a child of the given context, the
329
+ * schema also verifies the entire context &mdash; from its root to its last element. Therefore, it is possible
330
+ * for `checkChild()` to return `false` even though the context's last element can contain the checked child.
331
+ * It happens if one of the context's elements does not allow its child.
332
+ *
333
+ * @fires checkChild
334
+ * @param context The context in which the child will be checked.
335
+ * @param def The child to check.
336
+ */
337
+ checkChild(context, def) {
338
+ // Note: context and child are already normalized here to a SchemaContext and SchemaCompiledItemDefinition.
339
+ if (!def) {
340
+ return false;
341
+ }
342
+ return this._checkContextMatch(def, context);
343
+ }
344
+ /**
345
+ * Checks whether the given attribute can be applied in the given context (on the last
346
+ * item of the context).
347
+ *
348
+ * ```ts
349
+ * schema.checkAttribute( textNode, 'bold' ); // -> false
350
+ *
351
+ * schema.extend( '$text', {
352
+ * allowAttributes: 'bold'
353
+ * } );
354
+ * schema.checkAttribute( textNode, 'bold' ); // -> true
355
+ * ```
356
+ *
357
+ * @fires checkAttribute
358
+ * @param context The context in which the attribute will be checked.
359
+ */
360
+ checkAttribute(context, attributeName) {
361
+ const def = this.getDefinition(context.last);
362
+ if (!def) {
363
+ return false;
364
+ }
365
+ return def.allowAttributes.includes(attributeName);
366
+ }
367
+ /**
368
+ * Checks whether the given element (`elementToMerge`) can be merged with the specified base element (`positionOrBaseElement`).
369
+ *
370
+ * In other words &mdash; whether `elementToMerge`'s children {@link #checkChild are allowed} in the `positionOrBaseElement`.
371
+ *
372
+ * This check ensures that elements merged with {@link module:engine/model/writer~Writer#merge `Writer#merge()`}
373
+ * will be valid.
374
+ *
375
+ * Instead of elements, you can pass the instance of the {@link module:engine/model/position~Position} class as the
376
+ * `positionOrBaseElement`. It means that the elements before and after the position will be checked whether they can be merged.
377
+ *
378
+ * @param positionOrBaseElement The position or base element to which the `elementToMerge` will be merged.
379
+ * @param elementToMerge The element to merge. Required if `positionOrBaseElement` is an element.
380
+ */
381
+ checkMerge(positionOrBaseElement, elementToMerge) {
382
+ if (positionOrBaseElement instanceof Position) {
383
+ const nodeBefore = positionOrBaseElement.nodeBefore;
384
+ const nodeAfter = positionOrBaseElement.nodeAfter;
385
+ if (!(nodeBefore instanceof Element)) {
386
+ /**
387
+ * The node before the merge position must be an element.
388
+ *
389
+ * @error schema-check-merge-no-element-before
390
+ */
391
+ throw new CKEditorError('schema-check-merge-no-element-before', this);
392
+ }
393
+ if (!(nodeAfter instanceof Element)) {
394
+ /**
395
+ * The node after the merge position must be an element.
396
+ *
397
+ * @error schema-check-merge-no-element-after
398
+ */
399
+ throw new CKEditorError('schema-check-merge-no-element-after', this);
400
+ }
401
+ return this.checkMerge(nodeBefore, nodeAfter);
402
+ }
403
+ for (const child of elementToMerge.getChildren()) {
404
+ if (!this.checkChild(positionOrBaseElement, child)) {
405
+ return false;
406
+ }
407
+ }
408
+ return true;
409
+ }
410
+ /**
411
+ * Allows registering a callback to the {@link #checkChild} method calls.
412
+ *
413
+ * Callbacks allow you to implement rules which are not otherwise possible to achieve
414
+ * by using the declarative API of {@link module:engine/model/schema~SchemaItemDefinition}.
415
+ * For example, by using this method you can disallow elements in specific contexts.
416
+ *
417
+ * This method is a shorthand for using the {@link #event:checkChild} event. For even better control,
418
+ * you can use that event instead.
419
+ *
420
+ * Example:
421
+ *
422
+ * ```ts
423
+ * // Disallow heading1 directly inside a blockQuote.
424
+ * schema.addChildCheck( ( context, childDefinition ) => {
425
+ * if ( context.endsWith( 'blockQuote' ) && childDefinition.name == 'heading1' ) {
426
+ * return false;
427
+ * }
428
+ * } );
429
+ * ```
430
+ *
431
+ * Which translates to:
432
+ *
433
+ * ```ts
434
+ * schema.on( 'checkChild', ( evt, args ) => {
435
+ * const context = args[ 0 ];
436
+ * const childDefinition = args[ 1 ];
437
+ *
438
+ * if ( context.endsWith( 'blockQuote' ) && childDefinition && childDefinition.name == 'heading1' ) {
439
+ * // Prevent next listeners from being called.
440
+ * evt.stop();
441
+ * // Set the checkChild()'s return value.
442
+ * evt.return = false;
443
+ * }
444
+ * }, { priority: 'high' } );
445
+ * ```
446
+ *
447
+ * @param callback The callback to be called. It is called with two parameters:
448
+ * {@link module:engine/model/schema~SchemaContext} (context) instance and
449
+ * {@link module:engine/model/schema~SchemaCompiledItemDefinition} (child-to-check definition).
450
+ * The callback may return `true/false` to override `checkChild()`'s return value. If it does not return
451
+ * a boolean value, the default algorithm (or other callbacks) will define `checkChild()`'s return value.
452
+ */
453
+ addChildCheck(callback) {
454
+ this.on('checkChild', (evt, [ctx, childDef]) => {
455
+ // checkChild() was called with a non-registered child.
456
+ // In 99% cases such check should return false, so not to overcomplicate all callbacks
457
+ // don't even execute them.
458
+ if (!childDef) {
459
+ return;
460
+ }
461
+ const retValue = callback(ctx, childDef);
462
+ if (typeof retValue == 'boolean') {
463
+ evt.stop();
464
+ evt.return = retValue;
465
+ }
466
+ }, { priority: 'high' });
467
+ }
468
+ /**
469
+ * Allows registering a callback to the {@link #checkAttribute} method calls.
470
+ *
471
+ * Callbacks allow you to implement rules which are not otherwise possible to achieve
472
+ * by using the declarative API of {@link module:engine/model/schema~SchemaItemDefinition}.
473
+ * For example, by using this method you can disallow attribute if node to which it is applied
474
+ * is contained within some other element (e.g. you want to disallow `bold` on `$text` within `heading1`).
475
+ *
476
+ * This method is a shorthand for using the {@link #event:checkAttribute} event. For even better control,
477
+ * you can use that event instead.
478
+ *
479
+ * Example:
480
+ *
481
+ * ```ts
482
+ * // Disallow bold on $text inside heading1.
483
+ * schema.addAttributeCheck( ( context, attributeName ) => {
484
+ * if ( context.endsWith( 'heading1 $text' ) && attributeName == 'bold' ) {
485
+ * return false;
486
+ * }
487
+ * } );
488
+ * ```
489
+ *
490
+ * Which translates to:
491
+ *
492
+ * ```ts
493
+ * schema.on( 'checkAttribute', ( evt, args ) => {
494
+ * const context = args[ 0 ];
495
+ * const attributeName = args[ 1 ];
496
+ *
497
+ * if ( context.endsWith( 'heading1 $text' ) && attributeName == 'bold' ) {
498
+ * // Prevent next listeners from being called.
499
+ * evt.stop();
500
+ * // Set the checkAttribute()'s return value.
501
+ * evt.return = false;
502
+ * }
503
+ * }, { priority: 'high' } );
504
+ * ```
505
+ *
506
+ * @param callback The callback to be called. It is called with two parameters:
507
+ * {@link module:engine/model/schema~SchemaContext} (context) instance and attribute name.
508
+ * The callback may return `true/false` to override `checkAttribute()`'s return value. If it does not return
509
+ * a boolean value, the default algorithm (or other callbacks) will define `checkAttribute()`'s return value.
510
+ */
511
+ addAttributeCheck(callback) {
512
+ this.on('checkAttribute', (evt, [ctx, attributeName]) => {
513
+ const retValue = callback(ctx, attributeName);
514
+ if (typeof retValue == 'boolean') {
515
+ evt.stop();
516
+ evt.return = retValue;
517
+ }
518
+ }, { priority: 'high' });
519
+ }
520
+ /**
521
+ * This method allows assigning additional metadata to the model attributes. For example,
522
+ * {@link module:engine/model/schema~AttributeProperties `AttributeProperties#isFormatting` property} is
523
+ * used to mark formatting attributes (like `bold` or `italic`).
524
+ *
525
+ * ```ts
526
+ * // Mark bold as a formatting attribute.
527
+ * schema.setAttributeProperties( 'bold', {
528
+ * isFormatting: true
529
+ * } );
530
+ *
531
+ * // Override code not to be considered a formatting markup.
532
+ * schema.setAttributeProperties( 'code', {
533
+ * isFormatting: false
534
+ * } );
535
+ * ```
536
+ *
537
+ * Properties are not limited to members defined in the
538
+ * {@link module:engine/model/schema~AttributeProperties `AttributeProperties` type} and you can also use custom properties:
539
+ *
540
+ * ```ts
541
+ * schema.setAttributeProperties( 'blockQuote', {
542
+ * customProperty: 'value'
543
+ * } );
544
+ * ```
545
+ *
546
+ * Subsequent calls with the same attribute will extend its custom properties:
547
+ *
548
+ * ```ts
549
+ * schema.setAttributeProperties( 'blockQuote', {
550
+ * one: 1
551
+ * } );
552
+ *
553
+ * schema.setAttributeProperties( 'blockQuote', {
554
+ * two: 2
555
+ * } );
556
+ *
557
+ * console.log( schema.getAttributeProperties( 'blockQuote' ) );
558
+ * // Logs: { one: 1, two: 2 }
559
+ * ```
560
+ *
561
+ * @param attributeName A name of the attribute to receive the properties.
562
+ * @param properties A dictionary of properties.
563
+ */
564
+ setAttributeProperties(attributeName, properties) {
565
+ this._attributeProperties[attributeName] = Object.assign(this.getAttributeProperties(attributeName), properties);
566
+ }
567
+ /**
568
+ * Returns properties associated with a given model attribute. See {@link #setAttributeProperties `setAttributeProperties()`}.
569
+ *
570
+ * @param attributeName A name of the attribute.
571
+ */
572
+ getAttributeProperties(attributeName) {
573
+ return this._attributeProperties[attributeName] || {};
574
+ }
575
+ /**
576
+ * Returns the lowest {@link module:engine/model/schema~Schema#isLimit limit element} containing the entire
577
+ * selection/range/position or the root otherwise.
578
+ *
579
+ * @param selectionOrRangeOrPosition The selection/range/position to check.
580
+ * @returns The lowest limit element containing the entire `selectionOrRangeOrPosition`.
581
+ */
582
+ getLimitElement(selectionOrRangeOrPosition) {
583
+ let element;
584
+ if (selectionOrRangeOrPosition instanceof Position) {
585
+ element = selectionOrRangeOrPosition.parent;
586
+ }
587
+ else {
588
+ const ranges = selectionOrRangeOrPosition instanceof Range ?
589
+ [selectionOrRangeOrPosition] :
590
+ Array.from(selectionOrRangeOrPosition.getRanges());
591
+ // Find the common ancestor for all selection's ranges.
592
+ element = ranges
593
+ .reduce((element, range) => {
594
+ const rangeCommonAncestor = range.getCommonAncestor();
595
+ if (!element) {
596
+ return rangeCommonAncestor;
597
+ }
598
+ return element.getCommonAncestor(rangeCommonAncestor, { includeSelf: true });
599
+ }, null);
600
+ }
601
+ while (!this.isLimit(element)) {
602
+ if (element.parent) {
603
+ element = element.parent;
604
+ }
605
+ else {
606
+ break;
607
+ }
608
+ }
609
+ return element;
610
+ }
611
+ /**
612
+ * Checks whether the attribute is allowed in selection:
613
+ *
614
+ * * if the selection is not collapsed, then checks if the attribute is allowed on any of nodes in that range,
615
+ * * if the selection is collapsed, then checks if on the selection position there's a text with the
616
+ * specified attribute allowed.
617
+ *
618
+ * @param selection Selection which will be checked.
619
+ * @param attribute The name of the attribute to check.
620
+ */
621
+ checkAttributeInSelection(selection, attribute) {
622
+ if (selection.isCollapsed) {
623
+ const firstPosition = selection.getFirstPosition();
624
+ const context = [
625
+ ...firstPosition.getAncestors(),
626
+ new Text('', selection.getAttributes())
627
+ ];
628
+ // Check whether schema allows for a text with the attribute in the selection.
629
+ return this.checkAttribute(context, attribute);
630
+ }
631
+ else {
632
+ const ranges = selection.getRanges();
633
+ // For all ranges, check nodes in them until you find a node that is allowed to have the attribute.
634
+ for (const range of ranges) {
635
+ for (const value of range) {
636
+ if (this.checkAttribute(value.item, attribute)) {
637
+ // If we found a node that is allowed to have the attribute, return true.
638
+ return true;
639
+ }
640
+ }
641
+ }
642
+ }
643
+ // If we haven't found such node, return false.
644
+ return false;
645
+ }
646
+ /**
647
+ * Transforms the given set of ranges into a set of ranges where the given attribute is allowed (and can be applied).
648
+ *
649
+ * @param ranges Ranges to be validated.
650
+ * @param attribute The name of the attribute to check.
651
+ * @returns Ranges in which the attribute is allowed.
652
+ */
653
+ *getValidRanges(ranges, attribute) {
654
+ ranges = convertToMinimalFlatRanges(ranges);
655
+ for (const range of ranges) {
656
+ yield* this._getValidRangesForRange(range, attribute);
657
+ }
658
+ }
659
+ /**
660
+ * Basing on given `position`, finds and returns a {@link module:engine/model/range~Range range} which is
661
+ * nearest to that `position` and is a correct range for selection.
662
+ *
663
+ * The correct selection range might be collapsed when it is located in a position where the text node can be placed.
664
+ * Non-collapsed range is returned when selection can be placed around element marked as an "object" in
665
+ * the {@link module:engine/model/schema~Schema schema}.
666
+ *
667
+ * Direction of searching for the nearest correct selection range can be specified as:
668
+ *
669
+ * * `both` - searching will be performed in both ways,
670
+ * * `forward` - searching will be performed only forward,
671
+ * * `backward` - searching will be performed only backward.
672
+ *
673
+ * When valid selection range cannot be found, `null` is returned.
674
+ *
675
+ * @param position Reference position where new selection range should be looked for.
676
+ * @param direction Search direction.
677
+ * @returns Nearest selection range or `null` if one cannot be found.
678
+ */
679
+ getNearestSelectionRange(position, direction = 'both') {
680
+ // Return collapsed range if provided position is valid.
681
+ if (this.checkChild(position, '$text')) {
682
+ return new Range(position);
683
+ }
684
+ let backwardWalker, forwardWalker;
685
+ // Never leave a limit element.
686
+ const limitElement = position.getAncestors().reverse().find(item => this.isLimit(item)) ||
687
+ position.root;
688
+ if (direction == 'both' || direction == 'backward') {
689
+ backwardWalker = new TreeWalker({
690
+ boundaries: Range._createIn(limitElement),
691
+ startPosition: position,
692
+ direction: 'backward'
693
+ });
694
+ }
695
+ if (direction == 'both' || direction == 'forward') {
696
+ forwardWalker = new TreeWalker({
697
+ boundaries: Range._createIn(limitElement),
698
+ startPosition: position
699
+ });
700
+ }
701
+ for (const data of combineWalkers(backwardWalker, forwardWalker)) {
702
+ const type = (data.walker == backwardWalker ? 'elementEnd' : 'elementStart');
703
+ const value = data.value;
704
+ if (value.type == type && this.isObject(value.item)) {
705
+ return Range._createOn(value.item);
706
+ }
707
+ if (this.checkChild(value.nextPosition, '$text')) {
708
+ return new Range(value.nextPosition);
709
+ }
710
+ }
711
+ return null;
712
+ }
713
+ /**
714
+ * Tries to find position ancestors that allow to insert a given node.
715
+ * It starts searching from the given position and goes node by node to the top of the model tree
716
+ * as long as a {@link module:engine/model/schema~Schema#isLimit limit element}, an
717
+ * {@link module:engine/model/schema~Schema#isObject object element} or a topmost ancestor is not reached.
718
+ *
719
+ * @param position The position that the search will start from.
720
+ * @param node The node for which an allowed parent should be found or its name.
721
+ * @returns Allowed parent or null if nothing was found.
722
+ */
723
+ findAllowedParent(position, node) {
724
+ let parent = position.parent;
725
+ while (parent) {
726
+ if (this.checkChild(parent, node)) {
727
+ return parent;
728
+ }
729
+ // Do not split limit elements.
730
+ if (this.isLimit(parent)) {
731
+ return null;
732
+ }
733
+ parent = parent.parent;
734
+ }
735
+ return null;
736
+ }
737
+ /**
738
+ * Sets attributes allowed by the schema on a given node.
739
+ *
740
+ * @param node A node to set attributes on.
741
+ * @param attributes Attributes keys and values.
742
+ * @param writer An instance of the model writer.
743
+ */
744
+ setAllowedAttributes(node, attributes, writer) {
745
+ const model = writer.model;
746
+ for (const [attributeName, attributeValue] of Object.entries(attributes)) {
747
+ if (model.schema.checkAttribute(node, attributeName)) {
748
+ writer.setAttribute(attributeName, attributeValue, node);
749
+ }
750
+ }
751
+ }
752
+ /**
753
+ * Removes attributes disallowed by the schema.
754
+ *
755
+ * @param nodes Nodes that will be filtered.
756
+ */
757
+ removeDisallowedAttributes(nodes, writer) {
758
+ for (const node of nodes) {
759
+ // When node is a `Text` it has no children, so just filter it out.
760
+ if (node.is('$text')) {
761
+ removeDisallowedAttributeFromNode(this, node, writer);
762
+ }
763
+ // In a case of `Element` iterates through positions between nodes inside this element
764
+ // and filter out node before the current position, or position parent when position
765
+ // is at start of an element. Using positions prevent from omitting merged nodes
766
+ // see https://github.com/ckeditor/ckeditor5-engine/issues/1789.
767
+ else {
768
+ const rangeInNode = Range._createIn(node);
769
+ const positionsInRange = rangeInNode.getPositions();
770
+ for (const position of positionsInRange) {
771
+ const item = position.nodeBefore || position.parent;
772
+ removeDisallowedAttributeFromNode(this, item, writer);
773
+ }
774
+ }
775
+ }
776
+ }
777
+ /**
778
+ * Gets attributes of a node that have a given property.
779
+ *
780
+ * @param node Node to get attributes from.
781
+ * @param propertyName Name of the property that attribute must have to return it.
782
+ * @param propertyValue Desired value of the property that we want to check.
783
+ * When `undefined` attributes will be returned if they have set a given property no matter what the value is. If specified it will
784
+ * return attributes which given property's value is equal to this parameter.
785
+ * @returns Object with attributes' names as key and attributes' values as value.
786
+ */
787
+ getAttributesWithProperty(node, propertyName, propertyValue) {
788
+ const attributes = {};
789
+ for (const [attributeName, attributeValue] of node.getAttributes()) {
790
+ const attributeProperties = this.getAttributeProperties(attributeName);
791
+ if (attributeProperties[propertyName] === undefined) {
792
+ continue;
793
+ }
794
+ if (propertyValue === undefined || propertyValue === attributeProperties[propertyName]) {
795
+ attributes[attributeName] = attributeValue;
796
+ }
797
+ }
798
+ return attributes;
799
+ }
800
+ /**
801
+ * Creates an instance of the schema context.
802
+ */
803
+ createContext(context) {
804
+ return new SchemaContext(context);
805
+ }
806
+ _clearCache() {
807
+ this._compiledDefinitions = null;
808
+ }
809
+ _compile() {
810
+ const compiledDefinitions = {};
811
+ const sourceRules = this._sourceDefinitions;
812
+ const itemNames = Object.keys(sourceRules);
813
+ for (const itemName of itemNames) {
814
+ compiledDefinitions[itemName] = compileBaseItemRule(sourceRules[itemName], itemName);
815
+ }
816
+ for (const itemName of itemNames) {
817
+ compileAllowChildren(compiledDefinitions, itemName);
818
+ }
819
+ for (const itemName of itemNames) {
820
+ compileAllowContentOf(compiledDefinitions, itemName);
821
+ }
822
+ for (const itemName of itemNames) {
823
+ compileAllowWhere(compiledDefinitions, itemName);
824
+ }
825
+ for (const itemName of itemNames) {
826
+ compileAllowAttributesOf(compiledDefinitions, itemName);
827
+ compileInheritPropertiesFrom(compiledDefinitions, itemName);
828
+ }
829
+ for (const itemName of itemNames) {
830
+ cleanUpAllowIn(compiledDefinitions, itemName);
831
+ setupAllowChildren(compiledDefinitions, itemName);
832
+ cleanUpAllowAttributes(compiledDefinitions, itemName);
833
+ }
834
+ this._compiledDefinitions = compiledDefinitions;
835
+ }
836
+ _checkContextMatch(def, context, contextItemIndex = context.length - 1) {
837
+ const contextItem = context.getItem(contextItemIndex);
838
+ if (def.allowIn.includes(contextItem.name)) {
839
+ if (contextItemIndex == 0) {
840
+ return true;
841
+ }
842
+ else {
843
+ const parentRule = this.getDefinition(contextItem);
844
+ return this._checkContextMatch(parentRule, context, contextItemIndex - 1);
845
+ }
846
+ }
847
+ else {
848
+ return false;
849
+ }
850
+ }
851
+ /**
852
+ * Takes a flat range and an attribute name. Traverses the range recursively and deeply to find and return all ranges
853
+ * inside the given range on which the attribute can be applied.
854
+ *
855
+ * This is a helper function for {@link ~Schema#getValidRanges}.
856
+ *
857
+ * @param range The range to process.
858
+ * @param attribute The name of the attribute to check.
859
+ * @returns Ranges in which the attribute is allowed.
860
+ */
861
+ *_getValidRangesForRange(range, attribute) {
862
+ let start = range.start;
863
+ let end = range.start;
864
+ for (const item of range.getItems({ shallow: true })) {
865
+ if (item.is('element')) {
866
+ yield* this._getValidRangesForRange(Range._createIn(item), attribute);
867
+ }
868
+ if (!this.checkAttribute(item, attribute)) {
869
+ if (!start.isEqual(end)) {
870
+ yield new Range(start, end);
871
+ }
872
+ start = Position._createAfter(item);
873
+ }
874
+ end = Position._createAfter(item);
875
+ }
876
+ if (!start.isEqual(end)) {
877
+ yield new Range(start, end);
878
+ }
879
+ }
880
+ }
881
+ /**
882
+ * A schema context &mdash; a list of ancestors of a given position in the document.
883
+ *
884
+ * Considering such position:
885
+ *
886
+ * ```xml
887
+ * <$root>
888
+ * <blockQuote>
889
+ * <paragraph>
890
+ * ^
891
+ * </paragraph>
892
+ * </blockQuote>
893
+ * </$root>
894
+ * ```
895
+ *
896
+ * The context of this position is its {@link module:engine/model/position~Position#getAncestors lists of ancestors}:
897
+ *
898
+ * [ rootElement, blockQuoteElement, paragraphElement ]
899
+ *
900
+ * Contexts are used in the {@link module:engine/model/schema~Schema#event:checkChild `Schema#checkChild`} and
901
+ * {@link module:engine/model/schema~Schema#event:checkAttribute `Schema#checkAttribute`} events as a definition
902
+ * of a place in the document where the check occurs. The context instances are created based on the first arguments
903
+ * of the {@link module:engine/model/schema~Schema#checkChild `Schema#checkChild()`} and
904
+ * {@link module:engine/model/schema~Schema#checkAttribute `Schema#checkAttribute()`} methods so when
905
+ * using these methods you need to use {@link module:engine/model/schema~SchemaContextDefinition}s.
906
+ */
907
+ export class SchemaContext {
908
+ /**
909
+ * Creates an instance of the context.
910
+ */
911
+ constructor(context) {
912
+ if (context instanceof SchemaContext) {
913
+ return context;
914
+ }
915
+ let items;
916
+ if (typeof context == 'string') {
917
+ items = [context];
918
+ }
919
+ else if (!Array.isArray(context)) {
920
+ // `context` is item or position.
921
+ // Position#getAncestors() doesn't accept any parameters but it works just fine here.
922
+ items = context.getAncestors({ includeSelf: true });
923
+ }
924
+ else {
925
+ items = context;
926
+ }
927
+ this._items = items.map(mapContextItem);
928
+ }
929
+ /**
930
+ * The number of items.
931
+ */
932
+ get length() {
933
+ return this._items.length;
934
+ }
935
+ /**
936
+ * The last item (the lowest node).
937
+ */
938
+ get last() {
939
+ return this._items[this._items.length - 1];
940
+ }
941
+ /**
942
+ * Iterable interface.
943
+ *
944
+ * Iterates over all context items.
945
+ */
946
+ [Symbol.iterator]() {
947
+ return this._items[Symbol.iterator]();
948
+ }
949
+ /**
950
+ * Returns a new schema context instance with an additional item.
951
+ *
952
+ * Item can be added as:
953
+ *
954
+ * ```ts
955
+ * const context = new SchemaContext( [ '$root' ] );
956
+ *
957
+ * // An element.
958
+ * const fooElement = writer.createElement( 'fooElement' );
959
+ * const newContext = context.push( fooElement ); // [ '$root', 'fooElement' ]
960
+ *
961
+ * // A text node.
962
+ * const text = writer.createText( 'foobar' );
963
+ * const newContext = context.push( text ); // [ '$root', '$text' ]
964
+ *
965
+ * // A string (element name).
966
+ * const newContext = context.push( 'barElement' ); // [ '$root', 'barElement' ]
967
+ * ```
968
+ *
969
+ * **Note** {@link module:engine/model/node~Node} that is already in the model tree will be added as the only item
970
+ * (without ancestors).
971
+ *
972
+ * @param item An item that will be added to the current context.
973
+ * @returns A new schema context instance with an additional item.
974
+ */
975
+ push(item) {
976
+ const ctx = new SchemaContext([item]);
977
+ ctx._items = [...this._items, ...ctx._items];
978
+ return ctx;
979
+ }
980
+ /**
981
+ * Gets an item on the given index.
982
+ */
983
+ getItem(index) {
984
+ return this._items[index];
985
+ }
986
+ /**
987
+ * Returns the names of items.
988
+ */
989
+ *getNames() {
990
+ yield* this._items.map(item => item.name);
991
+ }
992
+ /**
993
+ * Checks whether the context ends with the given nodes.
994
+ *
995
+ * ```ts
996
+ * const ctx = new SchemaContext( [ rootElement, paragraphElement, textNode ] );
997
+ *
998
+ * ctx.endsWith( '$text' ); // -> true
999
+ * ctx.endsWith( 'paragraph $text' ); // -> true
1000
+ * ctx.endsWith( '$root' ); // -> false
1001
+ * ctx.endsWith( 'paragraph' ); // -> false
1002
+ * ```
1003
+ */
1004
+ endsWith(query) {
1005
+ return Array.from(this.getNames()).join(' ').endsWith(query);
1006
+ }
1007
+ /**
1008
+ * Checks whether the context starts with the given nodes.
1009
+ *
1010
+ * ```ts
1011
+ * const ctx = new SchemaContext( [ rootElement, paragraphElement, textNode ] );
1012
+ *
1013
+ * ctx.endsWith( '$root' ); // -> true
1014
+ * ctx.endsWith( '$root paragraph' ); // -> true
1015
+ * ctx.endsWith( '$text' ); // -> false
1016
+ * ctx.endsWith( 'paragraph' ); // -> false
1017
+ * ```
1018
+ */
1019
+ startsWith(query) {
1020
+ return Array.from(this.getNames()).join(' ').startsWith(query);
1021
+ }
1022
+ }
1023
+ function compileBaseItemRule(sourceItemRules, itemName) {
1024
+ const itemRule = {
1025
+ name: itemName,
1026
+ allowIn: [],
1027
+ allowContentOf: [],
1028
+ allowWhere: [],
1029
+ allowAttributes: [],
1030
+ allowAttributesOf: [],
1031
+ allowChildren: [],
1032
+ inheritTypesFrom: []
1033
+ };
1034
+ copyTypes(sourceItemRules, itemRule);
1035
+ copyProperty(sourceItemRules, itemRule, 'allowIn');
1036
+ copyProperty(sourceItemRules, itemRule, 'allowContentOf');
1037
+ copyProperty(sourceItemRules, itemRule, 'allowWhere');
1038
+ copyProperty(sourceItemRules, itemRule, 'allowAttributes');
1039
+ copyProperty(sourceItemRules, itemRule, 'allowAttributesOf');
1040
+ copyProperty(sourceItemRules, itemRule, 'allowChildren');
1041
+ copyProperty(sourceItemRules, itemRule, 'inheritTypesFrom');
1042
+ makeInheritAllWork(sourceItemRules, itemRule);
1043
+ return itemRule;
1044
+ }
1045
+ function compileAllowChildren(compiledDefinitions, itemName) {
1046
+ const item = compiledDefinitions[itemName];
1047
+ for (const allowChildrenItem of item.allowChildren) {
1048
+ const allowedChildren = compiledDefinitions[allowChildrenItem];
1049
+ // The allowChildren property may point to an unregistered element.
1050
+ if (!allowedChildren) {
1051
+ continue;
1052
+ }
1053
+ allowedChildren.allowIn.push(itemName);
1054
+ }
1055
+ // The allowIn property already includes correct items, reset the allowChildren property
1056
+ // to avoid duplicates later when setting up compilation results.
1057
+ item.allowChildren.length = 0;
1058
+ }
1059
+ function compileAllowContentOf(compiledDefinitions, itemName) {
1060
+ for (const allowContentOfItemName of compiledDefinitions[itemName].allowContentOf) {
1061
+ // The allowContentOf property may point to an unregistered element.
1062
+ if (compiledDefinitions[allowContentOfItemName]) {
1063
+ const allowedChildren = getAllowedChildren(compiledDefinitions, allowContentOfItemName);
1064
+ allowedChildren.forEach(allowedItem => {
1065
+ allowedItem.allowIn.push(itemName);
1066
+ });
1067
+ }
1068
+ }
1069
+ delete compiledDefinitions[itemName].allowContentOf;
1070
+ }
1071
+ function compileAllowWhere(compiledDefinitions, itemName) {
1072
+ for (const allowWhereItemName of compiledDefinitions[itemName].allowWhere) {
1073
+ const inheritFrom = compiledDefinitions[allowWhereItemName];
1074
+ // The allowWhere property may point to an unregistered element.
1075
+ if (inheritFrom) {
1076
+ const allowedIn = inheritFrom.allowIn;
1077
+ compiledDefinitions[itemName].allowIn.push(...allowedIn);
1078
+ }
1079
+ }
1080
+ delete compiledDefinitions[itemName].allowWhere;
1081
+ }
1082
+ function compileAllowAttributesOf(compiledDefinitions, itemName) {
1083
+ for (const allowAttributeOfItem of compiledDefinitions[itemName].allowAttributesOf) {
1084
+ const inheritFrom = compiledDefinitions[allowAttributeOfItem];
1085
+ if (inheritFrom) {
1086
+ const inheritAttributes = inheritFrom.allowAttributes;
1087
+ compiledDefinitions[itemName].allowAttributes.push(...inheritAttributes);
1088
+ }
1089
+ }
1090
+ delete compiledDefinitions[itemName].allowAttributesOf;
1091
+ }
1092
+ function compileInheritPropertiesFrom(compiledDefinitions, itemName) {
1093
+ const item = compiledDefinitions[itemName];
1094
+ for (const inheritPropertiesOfItem of item.inheritTypesFrom) {
1095
+ const inheritFrom = compiledDefinitions[inheritPropertiesOfItem];
1096
+ if (inheritFrom) {
1097
+ const typeNames = Object.keys(inheritFrom).filter(name => name.startsWith('is'));
1098
+ for (const name of typeNames) {
1099
+ if (!(name in item)) {
1100
+ item[name] = inheritFrom[name];
1101
+ }
1102
+ }
1103
+ }
1104
+ }
1105
+ delete item.inheritTypesFrom;
1106
+ }
1107
+ // Remove items which weren't registered (because it may break some checks or we'd need to complicate them).
1108
+ // Make sure allowIn doesn't contain repeated values.
1109
+ function cleanUpAllowIn(compiledDefinitions, itemName) {
1110
+ const itemRule = compiledDefinitions[itemName];
1111
+ const existingItems = itemRule.allowIn.filter(itemToCheck => compiledDefinitions[itemToCheck]);
1112
+ itemRule.allowIn = Array.from(new Set(existingItems));
1113
+ }
1114
+ // Setup allowChildren items based on allowIn.
1115
+ function setupAllowChildren(compiledDefinitions, itemName) {
1116
+ const itemRule = compiledDefinitions[itemName];
1117
+ for (const allowedParentItemName of itemRule.allowIn) {
1118
+ const allowedParentItem = compiledDefinitions[allowedParentItemName];
1119
+ allowedParentItem.allowChildren.push(itemName);
1120
+ }
1121
+ }
1122
+ function cleanUpAllowAttributes(compiledDefinitions, itemName) {
1123
+ const itemRule = compiledDefinitions[itemName];
1124
+ itemRule.allowAttributes = Array.from(new Set(itemRule.allowAttributes));
1125
+ }
1126
+ function copyTypes(sourceItemRules, itemRule) {
1127
+ for (const sourceItemRule of sourceItemRules) {
1128
+ const typeNames = Object.keys(sourceItemRule).filter(name => name.startsWith('is'));
1129
+ for (const name of typeNames) {
1130
+ itemRule[name] = !!sourceItemRule[name];
1131
+ }
1132
+ }
1133
+ }
1134
+ function copyProperty(sourceItemRules, itemRule, propertyName) {
1135
+ for (const sourceItemRule of sourceItemRules) {
1136
+ const value = sourceItemRule[propertyName];
1137
+ if (typeof value == 'string') {
1138
+ itemRule[propertyName].push(value);
1139
+ }
1140
+ else if (Array.isArray(value)) {
1141
+ itemRule[propertyName].push(...value);
1142
+ }
1143
+ }
1144
+ }
1145
+ function makeInheritAllWork(sourceItemRules, itemRule) {
1146
+ for (const sourceItemRule of sourceItemRules) {
1147
+ const inheritFrom = sourceItemRule.inheritAllFrom;
1148
+ if (inheritFrom) {
1149
+ itemRule.allowContentOf.push(inheritFrom);
1150
+ itemRule.allowWhere.push(inheritFrom);
1151
+ itemRule.allowAttributesOf.push(inheritFrom);
1152
+ itemRule.inheritTypesFrom.push(inheritFrom);
1153
+ }
1154
+ }
1155
+ }
1156
+ function getAllowedChildren(compiledDefinitions, itemName) {
1157
+ const itemRule = compiledDefinitions[itemName];
1158
+ return getValues(compiledDefinitions).filter(def => def.allowIn.includes(itemRule.name));
1159
+ }
1160
+ function getValues(obj) {
1161
+ return Object.keys(obj).map(key => obj[key]);
1162
+ }
1163
+ function mapContextItem(ctxItem) {
1164
+ if (typeof ctxItem == 'string' || ctxItem.is('documentFragment')) {
1165
+ return {
1166
+ name: typeof ctxItem == 'string' ? ctxItem : '$documentFragment',
1167
+ *getAttributeKeys() { },
1168
+ getAttribute() { }
1169
+ };
1170
+ }
1171
+ else {
1172
+ return {
1173
+ // '$text' means text nodes and text proxies.
1174
+ name: ctxItem.is('element') ? ctxItem.name : '$text',
1175
+ *getAttributeKeys() {
1176
+ yield* ctxItem.getAttributeKeys();
1177
+ },
1178
+ getAttribute(key) {
1179
+ return ctxItem.getAttribute(key);
1180
+ }
1181
+ };
1182
+ }
1183
+ }
1184
+ /**
1185
+ * Generator function returning values from provided walkers, switching between them at each iteration. If only one walker
1186
+ * is provided it will return data only from that walker.
1187
+ *
1188
+ * @param backward Walker iterating in backward direction.
1189
+ * @param forward Walker iterating in forward direction.
1190
+ * @returns Object returned at each iteration contains `value` and `walker` (informing which walker returned
1191
+ * given value) fields.
1192
+ */
1193
+ function* combineWalkers(backward, forward) {
1194
+ let done = false;
1195
+ while (!done) {
1196
+ done = true;
1197
+ if (backward) {
1198
+ const step = backward.next();
1199
+ if (!step.done) {
1200
+ done = false;
1201
+ yield {
1202
+ walker: backward,
1203
+ value: step.value
1204
+ };
1205
+ }
1206
+ }
1207
+ if (forward) {
1208
+ const step = forward.next();
1209
+ if (!step.done) {
1210
+ done = false;
1211
+ yield {
1212
+ walker: forward,
1213
+ value: step.value
1214
+ };
1215
+ }
1216
+ }
1217
+ }
1218
+ }
1219
+ /**
1220
+ * Takes an array of non-intersecting ranges. For each of them gets minimal flat ranges covering that range and returns
1221
+ * all those minimal flat ranges.
1222
+ *
1223
+ * @param ranges Ranges to process.
1224
+ * @returns Minimal flat ranges of given `ranges`.
1225
+ */
1226
+ function* convertToMinimalFlatRanges(ranges) {
1227
+ for (const range of ranges) {
1228
+ yield* range.getMinimalFlatRanges();
1229
+ }
1230
+ }
1231
+ function removeDisallowedAttributeFromNode(schema, node, writer) {
1232
+ for (const attribute of node.getAttributeKeys()) {
1233
+ if (!schema.checkAttribute(node, attribute)) {
1234
+ writer.removeAttribute(attribute, node);
1235
+ }
1236
+ }
1237
+ }