@ckeditor/ckeditor5-html-support 39.0.1 → 40.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/LICENSE.md +1 -1
  2. package/README.md +3 -3
  3. package/build/html-support.js +1 -1
  4. package/build/html-support.js.map +1 -0
  5. package/lang/translations/ar.po +1 -0
  6. package/lang/translations/bg.po +1 -0
  7. package/lang/translations/bn.po +1 -0
  8. package/lang/translations/ca.po +1 -0
  9. package/lang/translations/cs.po +1 -0
  10. package/lang/translations/da.po +1 -0
  11. package/lang/translations/de.po +1 -0
  12. package/lang/translations/el.po +1 -0
  13. package/lang/translations/en-au.po +1 -0
  14. package/lang/translations/en.po +1 -0
  15. package/lang/translations/es.po +1 -0
  16. package/lang/translations/et.po +1 -0
  17. package/lang/translations/fi.po +1 -0
  18. package/lang/translations/fr.po +1 -0
  19. package/lang/translations/gl.po +1 -0
  20. package/lang/translations/he.po +1 -0
  21. package/lang/translations/hi.po +1 -0
  22. package/lang/translations/hr.po +1 -0
  23. package/lang/translations/hu.po +1 -0
  24. package/lang/translations/id.po +1 -0
  25. package/lang/translations/it.po +1 -0
  26. package/lang/translations/ja.po +1 -0
  27. package/lang/translations/jv.po +1 -0
  28. package/lang/translations/ko.po +1 -0
  29. package/lang/translations/lt.po +1 -0
  30. package/lang/translations/lv.po +1 -0
  31. package/lang/translations/ms.po +1 -0
  32. package/lang/translations/nl.po +1 -0
  33. package/lang/translations/no.po +1 -0
  34. package/lang/translations/pl.po +1 -0
  35. package/lang/translations/pt-br.po +1 -0
  36. package/lang/translations/pt.po +1 -0
  37. package/lang/translations/ro.po +1 -0
  38. package/lang/translations/ru.po +1 -0
  39. package/lang/translations/sk.po +1 -0
  40. package/lang/translations/sr-latn.po +1 -0
  41. package/lang/translations/sr.po +1 -0
  42. package/lang/translations/sv.po +1 -0
  43. package/lang/translations/th.po +1 -0
  44. package/lang/translations/tr.po +1 -0
  45. package/lang/translations/ug.po +1 -0
  46. package/lang/translations/uk.po +1 -0
  47. package/lang/translations/ur.po +1 -0
  48. package/lang/translations/vi.po +1 -0
  49. package/lang/translations/zh-cn.po +1 -0
  50. package/lang/translations/zh.po +1 -0
  51. package/package.json +2 -6
  52. package/src/augmentation.d.ts +33 -33
  53. package/src/augmentation.js +5 -5
  54. package/src/converters.d.ts +60 -60
  55. package/src/converters.js +180 -180
  56. package/src/datafilter.d.ts +304 -304
  57. package/src/datafilter.js +720 -720
  58. package/src/dataschema.d.ts +183 -183
  59. package/src/dataschema.js +196 -196
  60. package/src/fullpage.d.ts +21 -21
  61. package/src/fullpage.js +80 -80
  62. package/src/generalhtmlsupport.d.ts +98 -98
  63. package/src/generalhtmlsupport.js +240 -240
  64. package/src/generalhtmlsupportconfig.d.ts +77 -77
  65. package/src/generalhtmlsupportconfig.js +5 -5
  66. package/src/htmlcomment.d.ts +71 -71
  67. package/src/htmlcomment.js +218 -218
  68. package/src/htmlpagedataprocessor.d.ts +22 -22
  69. package/src/htmlpagedataprocessor.js +67 -67
  70. package/src/index.d.ts +25 -25
  71. package/src/index.js +14 -14
  72. package/src/integrations/codeblock.d.ts +23 -23
  73. package/src/integrations/codeblock.js +101 -101
  74. package/src/integrations/customelement.d.ts +27 -27
  75. package/src/integrations/customelement.js +146 -146
  76. package/src/integrations/documentlist.d.ts +27 -27
  77. package/src/integrations/documentlist.js +178 -203
  78. package/src/integrations/dualcontent.d.ts +45 -45
  79. package/src/integrations/dualcontent.js +119 -119
  80. package/src/integrations/heading.d.ts +31 -31
  81. package/src/integrations/heading.js +60 -60
  82. package/src/integrations/image.d.ts +26 -26
  83. package/src/integrations/image.js +189 -189
  84. package/src/integrations/integrationutils.d.ts +15 -15
  85. package/src/integrations/integrationutils.js +21 -21
  86. package/src/integrations/mediaembed.d.ts +26 -26
  87. package/src/integrations/mediaembed.js +119 -119
  88. package/src/integrations/script.d.ts +26 -26
  89. package/src/integrations/script.js +59 -59
  90. package/src/integrations/style.d.ts +26 -26
  91. package/src/integrations/style.js +59 -59
  92. package/src/integrations/table.d.ts +23 -23
  93. package/src/integrations/table.js +163 -163
  94. package/src/schemadefinitions.d.ts +13 -13
  95. package/src/schemadefinitions.js +956 -956
  96. package/src/utils.d.ts +72 -72
  97. package/src/utils.js +139 -139
package/src/datafilter.js CHANGED
@@ -1,720 +1,720 @@
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 html-support/datafilter
7
- */
8
- import { Plugin } from 'ckeditor5/src/core';
9
- import { Matcher } from 'ckeditor5/src/engine';
10
- import { CKEditorError, priorities, isValidAttributeName } from 'ckeditor5/src/utils';
11
- import { Widget } from 'ckeditor5/src/widget';
12
- import { viewToModelObjectConverter, toObjectWidgetConverter, createObjectView, viewToAttributeInlineConverter, attributeToViewInlineConverter, emptyInlineModelElementToViewConverter, viewToModelBlockAttributeConverter, modelToViewBlockAttributeConverter } from './converters';
13
- import { default as DataSchema } from './dataschema';
14
- import { getHtmlAttributeName } from './utils';
15
- import { isPlainObject, pull as removeItemFromArray } from 'lodash-es';
16
- import '../theme/datafilter.css';
17
- /**
18
- * Allows to validate elements and element attributes registered by {@link module:html-support/dataschema~DataSchema}.
19
- *
20
- * To enable registered element in the editor, use {@link module:html-support/datafilter~DataFilter#allowElement} method:
21
- *
22
- * ```ts
23
- * dataFilter.allowElement( 'section' );
24
- * ```
25
- *
26
- * You can also allow or disallow specific element attributes:
27
- *
28
- * ```ts
29
- * // Allow `data-foo` attribute on `section` element.
30
- * dataFilter.allowAttributes( {
31
- * name: 'section',
32
- * attributes: {
33
- * 'data-foo': true
34
- * }
35
- * } );
36
- *
37
- * // Disallow `color` style attribute on 'section' element.
38
- * dataFilter.disallowAttributes( {
39
- * name: 'section',
40
- * styles: {
41
- * color: /[\s\S]+/
42
- * }
43
- * } );
44
- * ```
45
- *
46
- * To apply the information about allowed and disallowed attributes in custom integration plugin,
47
- * use the {@link module:html-support/datafilter~DataFilter#processViewAttributes `processViewAttributes()`} method.
48
- */
49
- export default class DataFilter extends Plugin {
50
- constructor(editor) {
51
- super(editor);
52
- this._dataSchema = editor.plugins.get('DataSchema');
53
- this._allowedAttributes = new Matcher();
54
- this._disallowedAttributes = new Matcher();
55
- this._allowedElements = new Set();
56
- this._disallowedElements = new Set();
57
- this._dataInitialized = false;
58
- this._coupledAttributes = null;
59
- this._registerElementsAfterInit();
60
- this._registerElementHandlers();
61
- this._registerCoupledAttributesPostFixer();
62
- this._registerAssociatedHtmlAttributesPostFixer();
63
- }
64
- /**
65
- * @inheritDoc
66
- */
67
- static get pluginName() {
68
- return 'DataFilter';
69
- }
70
- /**
71
- * @inheritDoc
72
- */
73
- static get requires() {
74
- return [DataSchema, Widget];
75
- }
76
- /**
77
- * Load a configuration of one or many elements, where their attributes should be allowed.
78
- *
79
- * **Note**: Rules will be applied just before next data pipeline data init or set.
80
- *
81
- * @param config Configuration of elements that should have their attributes accepted in the editor.
82
- */
83
- loadAllowedConfig(config) {
84
- for (const pattern of config) {
85
- // MatcherPattern allows omitting `name` to widen the search of elements.
86
- // Let's keep it consistent and match every element if a `name` has not been provided.
87
- const elementName = pattern.name || /[\s\S]+/;
88
- const rules = splitRules(pattern);
89
- this.allowElement(elementName);
90
- rules.forEach(pattern => this.allowAttributes(pattern));
91
- }
92
- }
93
- /**
94
- * Load a configuration of one or many elements, where their attributes should be disallowed.
95
- *
96
- * **Note**: Rules will be applied just before next data pipeline data init or set.
97
- *
98
- * @param config Configuration of elements that should have their attributes rejected from the editor.
99
- */
100
- loadDisallowedConfig(config) {
101
- for (const pattern of config) {
102
- // MatcherPattern allows omitting `name` to widen the search of elements.
103
- // Let's keep it consistent and match every element if a `name` has not been provided.
104
- const elementName = pattern.name || /[\s\S]+/;
105
- const rules = splitRules(pattern);
106
- // Disallow element itself if there is no other rules.
107
- if (rules.length == 0) {
108
- this.disallowElement(elementName);
109
- }
110
- else {
111
- rules.forEach(pattern => this.disallowAttributes(pattern));
112
- }
113
- }
114
- }
115
- /**
116
- * Load a configuration of one or many elements, where when empty should be allowed.
117
- *
118
- * **Note**: It modifies DataSchema so must be loaded before registering filtering rules.
119
- *
120
- * @param config Configuration of elements that should be preserved even if empty.
121
- */
122
- loadAllowedEmptyElementsConfig(config) {
123
- for (const elementName of config) {
124
- this.allowEmptyElement(elementName);
125
- }
126
- }
127
- /**
128
- * Allow the given element in the editor context.
129
- *
130
- * This method will only allow elements described by the {@link module:html-support/dataschema~DataSchema} used
131
- * to create data filter.
132
- *
133
- * **Note**: Rules will be applied just before next data pipeline data init or set.
134
- *
135
- * @param viewName String or regular expression matching view name.
136
- */
137
- allowElement(viewName) {
138
- for (const definition of this._dataSchema.getDefinitionsForView(viewName, true)) {
139
- this._addAllowedElement(definition);
140
- // Reset cached map to recalculate it on the next usage.
141
- this._coupledAttributes = null;
142
- }
143
- }
144
- /**
145
- * Disallow the given element in the editor context.
146
- *
147
- * This method will only disallow elements described by the {@link module:html-support/dataschema~DataSchema} used
148
- * to create data filter.
149
- *
150
- * @param viewName String or regular expression matching view name.
151
- */
152
- disallowElement(viewName) {
153
- for (const definition of this._dataSchema.getDefinitionsForView(viewName, false)) {
154
- this._disallowedElements.add(definition.view);
155
- }
156
- }
157
- /**
158
- * Allow the given empty element in the editor context.
159
- *
160
- * This method will only allow elements described by the {@link module:html-support/dataschema~DataSchema} used
161
- * to create data filter.
162
- *
163
- * **Note**: It modifies DataSchema so must be called before registering filtering rules.
164
- *
165
- * @param viewName String or regular expression matching view name.
166
- */
167
- allowEmptyElement(viewName) {
168
- for (const definition of this._dataSchema.getDefinitionsForView(viewName, true)) {
169
- if (definition.isInline) {
170
- this._dataSchema.extendInlineElement({ ...definition, allowEmpty: true });
171
- }
172
- }
173
- }
174
- /**
175
- * Allow the given attributes for view element allowed by {@link #allowElement} method.
176
- *
177
- * @param config Pattern matching all attributes which should be allowed.
178
- */
179
- allowAttributes(config) {
180
- this._allowedAttributes.add(config);
181
- }
182
- /**
183
- * Disallow the given attributes for view element allowed by {@link #allowElement} method.
184
- *
185
- * @param config Pattern matching all attributes which should be disallowed.
186
- */
187
- disallowAttributes(config) {
188
- this._disallowedAttributes.add(config);
189
- }
190
- /**
191
- * Processes all allowed and disallowed attributes on the view element by consuming them and returning the allowed ones.
192
- *
193
- * This method applies the configuration set up by {@link #allowAttributes `allowAttributes()`}
194
- * and {@link #disallowAttributes `disallowAttributes()`} over the given view element by consuming relevant attributes.
195
- * It returns the allowed attributes that were found on the given view element for further processing by integration code.
196
- *
197
- * ```ts
198
- * dispatcher.on( 'element:myElement', ( evt, data, conversionApi ) => {
199
- * // Get rid of disallowed and extract all allowed attributes from a viewElement.
200
- * const viewAttributes = dataFilter.processViewAttributes( data.viewItem, conversionApi );
201
- * // Do something with them, i.e. store inside a model as a dictionary.
202
- * if ( viewAttributes ) {
203
- * conversionApi.writer.setAttribute( 'htmlAttributesOfMyElement', viewAttributes, data.modelRange );
204
- * }
205
- * } );
206
- * ```
207
- *
208
- * @see module:engine/conversion/viewconsumable~ViewConsumable#consume
209
- *
210
- * @returns Object with following properties:
211
- * - attributes Set with matched attribute names.
212
- * - styles Set with matched style names.
213
- * - classes Set with matched class names.
214
- */
215
- processViewAttributes(viewElement, conversionApi) {
216
- // Make sure that the disabled attributes are handled before the allowed attributes are called.
217
- // For example, for block images the <figure> converter triggers conversion for <img> first and then for other elements, i.e. <a>.
218
- consumeAttributes(viewElement, conversionApi, this._disallowedAttributes);
219
- return consumeAttributes(viewElement, conversionApi, this._allowedAttributes);
220
- }
221
- /**
222
- * Adds allowed element definition and fires registration event.
223
- */
224
- _addAllowedElement(definition) {
225
- if (this._allowedElements.has(definition)) {
226
- return;
227
- }
228
- this._allowedElements.add(definition);
229
- // For attribute based integrations (table figure, document lists, etc.) register related element definitions.
230
- if ('appliesToBlock' in definition && typeof definition.appliesToBlock == 'string') {
231
- for (const relatedDefinition of this._dataSchema.getDefinitionsForModel(definition.appliesToBlock)) {
232
- if (relatedDefinition.isBlock) {
233
- this._addAllowedElement(relatedDefinition);
234
- }
235
- }
236
- }
237
- // We need to wait for all features to be initialized before we can register
238
- // element, so we can access existing features model schemas.
239
- // If the data has not been initialized yet, _registerElementsAfterInit() method will take care of
240
- // registering elements.
241
- if (this._dataInitialized) {
242
- // Defer registration to the next data pipeline data set so any disallow rules could be applied
243
- // even if added after allow rule (disallowElement).
244
- this.editor.data.once('set', () => {
245
- this._fireRegisterEvent(definition);
246
- }, {
247
- // With the highest priority listener we are able to register elements right before
248
- // running data conversion.
249
- priority: priorities.highest + 1
250
- });
251
- }
252
- }
253
- /**
254
- * Registers elements allowed by {@link module:html-support/datafilter~DataFilter#allowElement} method
255
- * once {@link module:engine/controller/datacontroller~DataController editor's data controller} is initialized.
256
- */
257
- _registerElementsAfterInit() {
258
- this.editor.data.on('init', () => {
259
- this._dataInitialized = true;
260
- for (const definition of this._allowedElements) {
261
- this._fireRegisterEvent(definition);
262
- }
263
- }, {
264
- // With highest priority listener we are able to register elements right before
265
- // running data conversion. Also:
266
- // * Make sure that priority is higher than the one used by `RealTimeCollaborationClient`,
267
- // as RTC is stopping event propagation.
268
- // * Make sure no other features hook into this event before GHS because otherwise the
269
- // downcast conversion (for these features) could run before GHS registered its converters
270
- // (https://github.com/ckeditor/ckeditor5/issues/11356).
271
- priority: priorities.highest + 1
272
- });
273
- }
274
- /**
275
- * Registers default element handlers.
276
- */
277
- _registerElementHandlers() {
278
- this.on('register', (evt, definition) => {
279
- const schema = this.editor.model.schema;
280
- // Object element should be only registered for new features.
281
- // If the model schema is already registered, it should be handled by
282
- // #_registerBlockElement() or #_registerObjectElement() attribute handlers.
283
- if (definition.isObject && !schema.isRegistered(definition.model)) {
284
- this._registerObjectElement(definition);
285
- }
286
- else if (definition.isBlock) {
287
- this._registerBlockElement(definition);
288
- }
289
- else if (definition.isInline) {
290
- this._registerInlineElement(definition);
291
- }
292
- else {
293
- /**
294
- * The definition cannot be handled by the data filter.
295
- *
296
- * Make sure that the registered definition is correct.
297
- *
298
- * @error data-filter-invalid-definition
299
- */
300
- throw new CKEditorError('data-filter-invalid-definition', null, definition);
301
- }
302
- evt.stop();
303
- }, { priority: 'lowest' });
304
- }
305
- /**
306
- * Registers a model post-fixer that is removing coupled GHS attributes of inline elements. Those attributes
307
- * are removed if a coupled feature attribute is removed.
308
- *
309
- * For example, consider following HTML:
310
- *
311
- * ```html
312
- * <a href="foo.html" id="myId">bar</a>
313
- * ```
314
- *
315
- * Which would be upcasted to following text node in the model:
316
- *
317
- * ```html
318
- * <$text linkHref="foo.html" htmlA="{ attributes: { id: 'myId' } }">bar</$text>
319
- * ```
320
- *
321
- * When the user removes the link from that text (using UI), only `linkHref` attribute would be removed:
322
- *
323
- * ```html
324
- * <$text htmlA="{ attributes: { id: 'myId' } }">bar</$text>
325
- * ```
326
- *
327
- * The `htmlA` attribute would stay in the model and would cause GHS to generate an `<a>` element.
328
- * This is incorrect from UX point of view, as the user wanted to remove the whole link (not only `href`).
329
- */
330
- _registerCoupledAttributesPostFixer() {
331
- const model = this.editor.model;
332
- model.document.registerPostFixer(writer => {
333
- const changes = model.document.differ.getChanges();
334
- let changed = false;
335
- const coupledAttributes = this._getCoupledAttributesMap();
336
- for (const change of changes) {
337
- // Handle only attribute removals.
338
- if (change.type != 'attribute' || change.attributeNewValue !== null) {
339
- continue;
340
- }
341
- // Find a list of coupled GHS attributes.
342
- const attributeKeys = coupledAttributes.get(change.attributeKey);
343
- if (!attributeKeys) {
344
- continue;
345
- }
346
- // Remove the coupled GHS attributes on the same range as the feature attribute was removed.
347
- for (const { item } of change.range.getWalker({ shallow: true })) {
348
- for (const attributeKey of attributeKeys) {
349
- if (item.hasAttribute(attributeKey)) {
350
- writer.removeAttribute(attributeKey, item);
351
- changed = true;
352
- }
353
- }
354
- }
355
- }
356
- return changed;
357
- });
358
- }
359
- /**
360
- * Removes `html*Attributes` attributes from incompatible elements.
361
- *
362
- * For example, consider the following HTML:
363
- *
364
- * ```html
365
- * <heading2 htmlH2Attributes="...">foobar[]</heading2>
366
- * ```
367
- *
368
- * Pressing `enter` creates a new `paragraph` element that inherits
369
- * the `htmlH2Attributes` attribute from `heading2`.
370
- *
371
- * ```html
372
- * <heading2 htmlH2Attributes="...">foobar</heading2>
373
- * <paragraph htmlH2Attributes="...">[]</paragraph>
374
- * ```
375
- *
376
- * This postfixer ensures that this doesn't happen, and that elements can
377
- * only have `html*Attributes` associated with them,
378
- * e.g.: `htmlPAttributes` for `<p>`, `htmlDivAttributes` for `<div>`, etc.
379
- *
380
- * With it enabled, pressing `enter` at the end of `<heading2>` will create
381
- * a new paragraph without the `htmlH2Attributes` attribute.
382
- *
383
- * ```html
384
- * <heading2 htmlH2Attributes="...">foobar</heading2>
385
- * <paragraph>[]</paragraph>
386
- * ```
387
- */
388
- _registerAssociatedHtmlAttributesPostFixer() {
389
- const model = this.editor.model;
390
- model.document.registerPostFixer(writer => {
391
- const changes = model.document.differ.getChanges();
392
- let changed = false;
393
- for (const change of changes) {
394
- if (change.type !== 'insert' || change.name === '$text') {
395
- continue;
396
- }
397
- for (const attr of change.attributes.keys()) {
398
- if (!attr.startsWith('html') || !attr.endsWith('Attributes')) {
399
- continue;
400
- }
401
- if (!model.schema.checkAttribute(change.name, attr)) {
402
- writer.removeAttribute(attr, change.position.nodeAfter);
403
- changed = true;
404
- }
405
- }
406
- }
407
- return changed;
408
- });
409
- }
410
- /**
411
- * Collects the map of coupled attributes. The returned map is keyed by the feature attribute name
412
- * and coupled GHS attribute names are stored in the value array.
413
- */
414
- _getCoupledAttributesMap() {
415
- if (this._coupledAttributes) {
416
- return this._coupledAttributes;
417
- }
418
- this._coupledAttributes = new Map();
419
- for (const definition of this._allowedElements) {
420
- if (definition.coupledAttribute && definition.model) {
421
- const attributeNames = this._coupledAttributes.get(definition.coupledAttribute);
422
- if (attributeNames) {
423
- attributeNames.push(definition.model);
424
- }
425
- else {
426
- this._coupledAttributes.set(definition.coupledAttribute, [definition.model]);
427
- }
428
- }
429
- }
430
- return this._coupledAttributes;
431
- }
432
- /**
433
- * Fires `register` event for the given element definition.
434
- */
435
- _fireRegisterEvent(definition) {
436
- if (definition.view && this._disallowedElements.has(definition.view)) {
437
- return;
438
- }
439
- this.fire(definition.view ? `register:${definition.view}` : 'register', definition);
440
- }
441
- /**
442
- * Registers object element and attribute converters for the given data schema definition.
443
- */
444
- _registerObjectElement(definition) {
445
- const editor = this.editor;
446
- const schema = editor.model.schema;
447
- const conversion = editor.conversion;
448
- const { view: viewName, model: modelName } = definition;
449
- schema.register(modelName, definition.modelSchema);
450
- /* istanbul ignore next: paranoid check -- @preserve */
451
- if (!viewName) {
452
- return;
453
- }
454
- schema.extend(definition.model, {
455
- allowAttributes: [getHtmlAttributeName(viewName), 'htmlContent']
456
- });
457
- // Store element content in special `$rawContent` custom property to
458
- // avoid editor's data filtering mechanism.
459
- editor.data.registerRawContentMatcher({
460
- name: viewName
461
- });
462
- conversion.for('upcast').elementToElement({
463
- view: viewName,
464
- model: viewToModelObjectConverter(definition),
465
- // With a `low` priority, `paragraph` plugin auto-paragraphing mechanism is executed. Make sure
466
- // this listener is called before it. If not, some elements will be transformed into a paragraph.
467
- // `+ 2` is used to take priority over `_addDefaultH1Conversion` in the Heading plugin.
468
- converterPriority: priorities.low + 2
469
- });
470
- conversion.for('upcast').add(viewToModelBlockAttributeConverter(definition, this));
471
- conversion.for('editingDowncast').elementToStructure({
472
- model: {
473
- name: modelName,
474
- attributes: [getHtmlAttributeName(viewName)]
475
- },
476
- view: toObjectWidgetConverter(editor, definition)
477
- });
478
- conversion.for('dataDowncast').elementToElement({
479
- model: modelName,
480
- view: (modelElement, { writer }) => {
481
- return createObjectView(viewName, modelElement, writer);
482
- }
483
- });
484
- conversion.for('dataDowncast').add(modelToViewBlockAttributeConverter(definition));
485
- }
486
- /**
487
- * Registers block element and attribute converters for the given data schema definition.
488
- */
489
- _registerBlockElement(definition) {
490
- const editor = this.editor;
491
- const schema = editor.model.schema;
492
- const conversion = editor.conversion;
493
- const { view: viewName, model: modelName } = definition;
494
- if (!schema.isRegistered(definition.model)) {
495
- schema.register(definition.model, definition.modelSchema);
496
- if (!viewName) {
497
- return;
498
- }
499
- conversion.for('upcast').elementToElement({
500
- model: modelName,
501
- view: viewName,
502
- // With a `low` priority, `paragraph` plugin auto-paragraphing mechanism is executed. Make sure
503
- // this listener is called before it. If not, some elements will be transformed into a paragraph.
504
- // `+ 2` is used to take priority over `_addDefaultH1Conversion` in the Heading plugin.
505
- converterPriority: priorities.low + 2
506
- });
507
- conversion.for('downcast').elementToElement({
508
- model: modelName,
509
- view: viewName
510
- });
511
- }
512
- if (!viewName) {
513
- return;
514
- }
515
- schema.extend(definition.model, {
516
- allowAttributes: getHtmlAttributeName(viewName)
517
- });
518
- conversion.for('upcast').add(viewToModelBlockAttributeConverter(definition, this));
519
- conversion.for('downcast').add(modelToViewBlockAttributeConverter(definition));
520
- }
521
- /**
522
- * Registers inline element and attribute converters for the given data schema definition.
523
- *
524
- * Extends `$text` model schema to allow the given definition model attribute and its properties.
525
- */
526
- _registerInlineElement(definition) {
527
- const editor = this.editor;
528
- const schema = editor.model.schema;
529
- const conversion = editor.conversion;
530
- const attributeKey = definition.model;
531
- // This element is stored in the model as an attribute on a block element, for example DocumentLists.
532
- if (definition.appliesToBlock) {
533
- return;
534
- }
535
- schema.extend('$text', {
536
- allowAttributes: attributeKey
537
- });
538
- if (definition.attributeProperties) {
539
- schema.setAttributeProperties(attributeKey, definition.attributeProperties);
540
- }
541
- conversion.for('upcast').add(viewToAttributeInlineConverter(definition, this));
542
- conversion.for('downcast').attributeToElement({
543
- model: attributeKey,
544
- view: attributeToViewInlineConverter(definition)
545
- });
546
- if (!definition.allowEmpty) {
547
- return;
548
- }
549
- schema.setAttributeProperties(attributeKey, { copyFromObject: false });
550
- if (!schema.isRegistered('htmlEmptyElement')) {
551
- schema.register('htmlEmptyElement', {
552
- inheritAllFrom: '$inlineObject'
553
- });
554
- }
555
- editor.data.htmlProcessor.domConverter.registerInlineObjectMatcher(element => {
556
- // Element must be empty and have any attribute.
557
- if (element.name == definition.view &&
558
- element.isEmpty &&
559
- Array.from(element.getAttributeKeys()).length) {
560
- return {
561
- name: true
562
- };
563
- }
564
- return null;
565
- });
566
- conversion.for('editingDowncast')
567
- .elementToElement({
568
- model: 'htmlEmptyElement',
569
- view: emptyInlineModelElementToViewConverter(definition, true)
570
- });
571
- conversion.for('dataDowncast')
572
- .elementToElement({
573
- model: 'htmlEmptyElement',
574
- view: emptyInlineModelElementToViewConverter(definition)
575
- });
576
- }
577
- }
578
- /**
579
- * Matches and consumes the given view attributes.
580
- */
581
- function consumeAttributes(viewElement, conversionApi, matcher) {
582
- const matches = consumeAttributeMatches(viewElement, conversionApi, matcher);
583
- const { attributes, styles, classes } = mergeMatchResults(matches);
584
- const viewAttributes = {};
585
- // Remove invalid DOM element attributes.
586
- if (attributes.size) {
587
- for (const key of attributes) {
588
- if (!isValidAttributeName(key)) {
589
- attributes.delete(key);
590
- }
591
- }
592
- }
593
- if (attributes.size) {
594
- viewAttributes.attributes = iterableToObject(attributes, key => viewElement.getAttribute(key));
595
- }
596
- if (styles.size) {
597
- viewAttributes.styles = iterableToObject(styles, key => viewElement.getStyle(key));
598
- }
599
- if (classes.size) {
600
- viewAttributes.classes = Array.from(classes);
601
- }
602
- if (!Object.keys(viewAttributes).length) {
603
- return null;
604
- }
605
- return viewAttributes;
606
- }
607
- /**
608
- * Consumes matched attributes.
609
- *
610
- * @returns Array with match information about found attributes.
611
- */
612
- function consumeAttributeMatches(viewElement, { consumable }, matcher) {
613
- const matches = matcher.matchAll(viewElement) || [];
614
- const consumedMatches = [];
615
- for (const match of matches) {
616
- removeConsumedAttributes(consumable, viewElement, match);
617
- // We only want to consume attributes, so element can be still processed by other converters.
618
- delete match.match.name;
619
- consumable.consume(viewElement, match.match);
620
- consumedMatches.push(match);
621
- }
622
- return consumedMatches;
623
- }
624
- /**
625
- * Removes attributes from the given match that were already consumed by other converters.
626
- */
627
- function removeConsumedAttributes(consumable, viewElement, match) {
628
- for (const key of ['attributes', 'classes', 'styles']) {
629
- const attributes = match.match[key];
630
- if (!attributes) {
631
- continue;
632
- }
633
- // Iterating over a copy of an array so removing items doesn't influence iteration.
634
- for (const value of Array.from(attributes)) {
635
- if (!consumable.test(viewElement, ({ [key]: [value] }))) {
636
- removeItemFromArray(attributes, value);
637
- }
638
- }
639
- }
640
- }
641
- /**
642
- * Merges the result of {@link module:engine/view/matcher~Matcher#matchAll} method.
643
- *
644
- * @param matches
645
- * @returns Object with following properties:
646
- * - attributes Set with matched attribute names.
647
- * - styles Set with matched style names.
648
- * - classes Set with matched class names.
649
- */
650
- function mergeMatchResults(matches) {
651
- const matchResult = {
652
- attributes: new Set(),
653
- classes: new Set(),
654
- styles: new Set()
655
- };
656
- for (const match of matches) {
657
- for (const key in matchResult) {
658
- const values = match.match[key] || [];
659
- values.forEach(value => (matchResult[key]).add(value));
660
- }
661
- }
662
- return matchResult;
663
- }
664
- /**
665
- * Converts the given iterable object into an object.
666
- */
667
- function iterableToObject(iterable, getValue) {
668
- const attributesObject = {};
669
- for (const prop of iterable) {
670
- const value = getValue(prop);
671
- if (value !== undefined) {
672
- attributesObject[prop] = getValue(prop);
673
- }
674
- }
675
- return attributesObject;
676
- }
677
- /**
678
- * Matcher by default has to match **all** patterns to count it as an actual match. Splitting the pattern
679
- * into separate patterns means that any matched pattern will be count as a match.
680
- *
681
- * @param pattern Pattern to split.
682
- * @param attributeName Name of the attribute to split (e.g. 'attributes', 'classes', 'styles').
683
- */
684
- function splitPattern(pattern, attributeName) {
685
- const { name } = pattern;
686
- const attributeValue = pattern[attributeName];
687
- if (isPlainObject(attributeValue)) {
688
- return Object.entries(attributeValue).map(([key, value]) => ({
689
- name,
690
- [attributeName]: {
691
- [key]: value
692
- }
693
- }));
694
- }
695
- if (Array.isArray(attributeValue)) {
696
- return attributeValue.map(value => ({
697
- name,
698
- [attributeName]: [value]
699
- }));
700
- }
701
- return [pattern];
702
- }
703
- /**
704
- * Rules are matched in conjunction (AND operation), but we want to have a match if *any* of the rules is matched (OR operation).
705
- * By splitting the rules we force the latter effect.
706
- */
707
- function splitRules(rules) {
708
- const { name, attributes, classes, styles } = rules;
709
- const splitRules = [];
710
- if (attributes) {
711
- splitRules.push(...splitPattern({ name, attributes }, 'attributes'));
712
- }
713
- if (classes) {
714
- splitRules.push(...splitPattern({ name, classes }, 'classes'));
715
- }
716
- if (styles) {
717
- splitRules.push(...splitPattern({ name, styles }, 'styles'));
718
- }
719
- return splitRules;
720
- }
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 html-support/datafilter
7
+ */
8
+ import { Plugin } from 'ckeditor5/src/core';
9
+ import { Matcher } from 'ckeditor5/src/engine';
10
+ import { CKEditorError, priorities, isValidAttributeName } from 'ckeditor5/src/utils';
11
+ import { Widget } from 'ckeditor5/src/widget';
12
+ import { viewToModelObjectConverter, toObjectWidgetConverter, createObjectView, viewToAttributeInlineConverter, attributeToViewInlineConverter, emptyInlineModelElementToViewConverter, viewToModelBlockAttributeConverter, modelToViewBlockAttributeConverter } from './converters';
13
+ import { default as DataSchema } from './dataschema';
14
+ import { getHtmlAttributeName } from './utils';
15
+ import { isPlainObject, pull as removeItemFromArray } from 'lodash-es';
16
+ import '../theme/datafilter.css';
17
+ /**
18
+ * Allows to validate elements and element attributes registered by {@link module:html-support/dataschema~DataSchema}.
19
+ *
20
+ * To enable registered element in the editor, use {@link module:html-support/datafilter~DataFilter#allowElement} method:
21
+ *
22
+ * ```ts
23
+ * dataFilter.allowElement( 'section' );
24
+ * ```
25
+ *
26
+ * You can also allow or disallow specific element attributes:
27
+ *
28
+ * ```ts
29
+ * // Allow `data-foo` attribute on `section` element.
30
+ * dataFilter.allowAttributes( {
31
+ * name: 'section',
32
+ * attributes: {
33
+ * 'data-foo': true
34
+ * }
35
+ * } );
36
+ *
37
+ * // Disallow `color` style attribute on 'section' element.
38
+ * dataFilter.disallowAttributes( {
39
+ * name: 'section',
40
+ * styles: {
41
+ * color: /[\s\S]+/
42
+ * }
43
+ * } );
44
+ * ```
45
+ *
46
+ * To apply the information about allowed and disallowed attributes in custom integration plugin,
47
+ * use the {@link module:html-support/datafilter~DataFilter#processViewAttributes `processViewAttributes()`} method.
48
+ */
49
+ export default class DataFilter extends Plugin {
50
+ constructor(editor) {
51
+ super(editor);
52
+ this._dataSchema = editor.plugins.get('DataSchema');
53
+ this._allowedAttributes = new Matcher();
54
+ this._disallowedAttributes = new Matcher();
55
+ this._allowedElements = new Set();
56
+ this._disallowedElements = new Set();
57
+ this._dataInitialized = false;
58
+ this._coupledAttributes = null;
59
+ this._registerElementsAfterInit();
60
+ this._registerElementHandlers();
61
+ this._registerCoupledAttributesPostFixer();
62
+ this._registerAssociatedHtmlAttributesPostFixer();
63
+ }
64
+ /**
65
+ * @inheritDoc
66
+ */
67
+ static get pluginName() {
68
+ return 'DataFilter';
69
+ }
70
+ /**
71
+ * @inheritDoc
72
+ */
73
+ static get requires() {
74
+ return [DataSchema, Widget];
75
+ }
76
+ /**
77
+ * Load a configuration of one or many elements, where their attributes should be allowed.
78
+ *
79
+ * **Note**: Rules will be applied just before next data pipeline data init or set.
80
+ *
81
+ * @param config Configuration of elements that should have their attributes accepted in the editor.
82
+ */
83
+ loadAllowedConfig(config) {
84
+ for (const pattern of config) {
85
+ // MatcherPattern allows omitting `name` to widen the search of elements.
86
+ // Let's keep it consistent and match every element if a `name` has not been provided.
87
+ const elementName = pattern.name || /[\s\S]+/;
88
+ const rules = splitRules(pattern);
89
+ this.allowElement(elementName);
90
+ rules.forEach(pattern => this.allowAttributes(pattern));
91
+ }
92
+ }
93
+ /**
94
+ * Load a configuration of one or many elements, where their attributes should be disallowed.
95
+ *
96
+ * **Note**: Rules will be applied just before next data pipeline data init or set.
97
+ *
98
+ * @param config Configuration of elements that should have their attributes rejected from the editor.
99
+ */
100
+ loadDisallowedConfig(config) {
101
+ for (const pattern of config) {
102
+ // MatcherPattern allows omitting `name` to widen the search of elements.
103
+ // Let's keep it consistent and match every element if a `name` has not been provided.
104
+ const elementName = pattern.name || /[\s\S]+/;
105
+ const rules = splitRules(pattern);
106
+ // Disallow element itself if there is no other rules.
107
+ if (rules.length == 0) {
108
+ this.disallowElement(elementName);
109
+ }
110
+ else {
111
+ rules.forEach(pattern => this.disallowAttributes(pattern));
112
+ }
113
+ }
114
+ }
115
+ /**
116
+ * Load a configuration of one or many elements, where when empty should be allowed.
117
+ *
118
+ * **Note**: It modifies DataSchema so must be loaded before registering filtering rules.
119
+ *
120
+ * @param config Configuration of elements that should be preserved even if empty.
121
+ */
122
+ loadAllowedEmptyElementsConfig(config) {
123
+ for (const elementName of config) {
124
+ this.allowEmptyElement(elementName);
125
+ }
126
+ }
127
+ /**
128
+ * Allow the given element in the editor context.
129
+ *
130
+ * This method will only allow elements described by the {@link module:html-support/dataschema~DataSchema} used
131
+ * to create data filter.
132
+ *
133
+ * **Note**: Rules will be applied just before next data pipeline data init or set.
134
+ *
135
+ * @param viewName String or regular expression matching view name.
136
+ */
137
+ allowElement(viewName) {
138
+ for (const definition of this._dataSchema.getDefinitionsForView(viewName, true)) {
139
+ this._addAllowedElement(definition);
140
+ // Reset cached map to recalculate it on the next usage.
141
+ this._coupledAttributes = null;
142
+ }
143
+ }
144
+ /**
145
+ * Disallow the given element in the editor context.
146
+ *
147
+ * This method will only disallow elements described by the {@link module:html-support/dataschema~DataSchema} used
148
+ * to create data filter.
149
+ *
150
+ * @param viewName String or regular expression matching view name.
151
+ */
152
+ disallowElement(viewName) {
153
+ for (const definition of this._dataSchema.getDefinitionsForView(viewName, false)) {
154
+ this._disallowedElements.add(definition.view);
155
+ }
156
+ }
157
+ /**
158
+ * Allow the given empty element in the editor context.
159
+ *
160
+ * This method will only allow elements described by the {@link module:html-support/dataschema~DataSchema} used
161
+ * to create data filter.
162
+ *
163
+ * **Note**: It modifies DataSchema so must be called before registering filtering rules.
164
+ *
165
+ * @param viewName String or regular expression matching view name.
166
+ */
167
+ allowEmptyElement(viewName) {
168
+ for (const definition of this._dataSchema.getDefinitionsForView(viewName, true)) {
169
+ if (definition.isInline) {
170
+ this._dataSchema.extendInlineElement({ ...definition, allowEmpty: true });
171
+ }
172
+ }
173
+ }
174
+ /**
175
+ * Allow the given attributes for view element allowed by {@link #allowElement} method.
176
+ *
177
+ * @param config Pattern matching all attributes which should be allowed.
178
+ */
179
+ allowAttributes(config) {
180
+ this._allowedAttributes.add(config);
181
+ }
182
+ /**
183
+ * Disallow the given attributes for view element allowed by {@link #allowElement} method.
184
+ *
185
+ * @param config Pattern matching all attributes which should be disallowed.
186
+ */
187
+ disallowAttributes(config) {
188
+ this._disallowedAttributes.add(config);
189
+ }
190
+ /**
191
+ * Processes all allowed and disallowed attributes on the view element by consuming them and returning the allowed ones.
192
+ *
193
+ * This method applies the configuration set up by {@link #allowAttributes `allowAttributes()`}
194
+ * and {@link #disallowAttributes `disallowAttributes()`} over the given view element by consuming relevant attributes.
195
+ * It returns the allowed attributes that were found on the given view element for further processing by integration code.
196
+ *
197
+ * ```ts
198
+ * dispatcher.on( 'element:myElement', ( evt, data, conversionApi ) => {
199
+ * // Get rid of disallowed and extract all allowed attributes from a viewElement.
200
+ * const viewAttributes = dataFilter.processViewAttributes( data.viewItem, conversionApi );
201
+ * // Do something with them, i.e. store inside a model as a dictionary.
202
+ * if ( viewAttributes ) {
203
+ * conversionApi.writer.setAttribute( 'htmlAttributesOfMyElement', viewAttributes, data.modelRange );
204
+ * }
205
+ * } );
206
+ * ```
207
+ *
208
+ * @see module:engine/conversion/viewconsumable~ViewConsumable#consume
209
+ *
210
+ * @returns Object with following properties:
211
+ * - attributes Set with matched attribute names.
212
+ * - styles Set with matched style names.
213
+ * - classes Set with matched class names.
214
+ */
215
+ processViewAttributes(viewElement, conversionApi) {
216
+ // Make sure that the disabled attributes are handled before the allowed attributes are called.
217
+ // For example, for block images the <figure> converter triggers conversion for <img> first and then for other elements, i.e. <a>.
218
+ consumeAttributes(viewElement, conversionApi, this._disallowedAttributes);
219
+ return consumeAttributes(viewElement, conversionApi, this._allowedAttributes);
220
+ }
221
+ /**
222
+ * Adds allowed element definition and fires registration event.
223
+ */
224
+ _addAllowedElement(definition) {
225
+ if (this._allowedElements.has(definition)) {
226
+ return;
227
+ }
228
+ this._allowedElements.add(definition);
229
+ // For attribute based integrations (table figure, document lists, etc.) register related element definitions.
230
+ if ('appliesToBlock' in definition && typeof definition.appliesToBlock == 'string') {
231
+ for (const relatedDefinition of this._dataSchema.getDefinitionsForModel(definition.appliesToBlock)) {
232
+ if (relatedDefinition.isBlock) {
233
+ this._addAllowedElement(relatedDefinition);
234
+ }
235
+ }
236
+ }
237
+ // We need to wait for all features to be initialized before we can register
238
+ // element, so we can access existing features model schemas.
239
+ // If the data has not been initialized yet, _registerElementsAfterInit() method will take care of
240
+ // registering elements.
241
+ if (this._dataInitialized) {
242
+ // Defer registration to the next data pipeline data set so any disallow rules could be applied
243
+ // even if added after allow rule (disallowElement).
244
+ this.editor.data.once('set', () => {
245
+ this._fireRegisterEvent(definition);
246
+ }, {
247
+ // With the highest priority listener we are able to register elements right before
248
+ // running data conversion.
249
+ priority: priorities.highest + 1
250
+ });
251
+ }
252
+ }
253
+ /**
254
+ * Registers elements allowed by {@link module:html-support/datafilter~DataFilter#allowElement} method
255
+ * once {@link module:engine/controller/datacontroller~DataController editor's data controller} is initialized.
256
+ */
257
+ _registerElementsAfterInit() {
258
+ this.editor.data.on('init', () => {
259
+ this._dataInitialized = true;
260
+ for (const definition of this._allowedElements) {
261
+ this._fireRegisterEvent(definition);
262
+ }
263
+ }, {
264
+ // With highest priority listener we are able to register elements right before
265
+ // running data conversion. Also:
266
+ // * Make sure that priority is higher than the one used by `RealTimeCollaborationClient`,
267
+ // as RTC is stopping event propagation.
268
+ // * Make sure no other features hook into this event before GHS because otherwise the
269
+ // downcast conversion (for these features) could run before GHS registered its converters
270
+ // (https://github.com/ckeditor/ckeditor5/issues/11356).
271
+ priority: priorities.highest + 1
272
+ });
273
+ }
274
+ /**
275
+ * Registers default element handlers.
276
+ */
277
+ _registerElementHandlers() {
278
+ this.on('register', (evt, definition) => {
279
+ const schema = this.editor.model.schema;
280
+ // Object element should be only registered for new features.
281
+ // If the model schema is already registered, it should be handled by
282
+ // #_registerBlockElement() or #_registerObjectElement() attribute handlers.
283
+ if (definition.isObject && !schema.isRegistered(definition.model)) {
284
+ this._registerObjectElement(definition);
285
+ }
286
+ else if (definition.isBlock) {
287
+ this._registerBlockElement(definition);
288
+ }
289
+ else if (definition.isInline) {
290
+ this._registerInlineElement(definition);
291
+ }
292
+ else {
293
+ /**
294
+ * The definition cannot be handled by the data filter.
295
+ *
296
+ * Make sure that the registered definition is correct.
297
+ *
298
+ * @error data-filter-invalid-definition
299
+ */
300
+ throw new CKEditorError('data-filter-invalid-definition', null, definition);
301
+ }
302
+ evt.stop();
303
+ }, { priority: 'lowest' });
304
+ }
305
+ /**
306
+ * Registers a model post-fixer that is removing coupled GHS attributes of inline elements. Those attributes
307
+ * are removed if a coupled feature attribute is removed.
308
+ *
309
+ * For example, consider following HTML:
310
+ *
311
+ * ```html
312
+ * <a href="foo.html" id="myId">bar</a>
313
+ * ```
314
+ *
315
+ * Which would be upcasted to following text node in the model:
316
+ *
317
+ * ```html
318
+ * <$text linkHref="foo.html" htmlA="{ attributes: { id: 'myId' } }">bar</$text>
319
+ * ```
320
+ *
321
+ * When the user removes the link from that text (using UI), only `linkHref` attribute would be removed:
322
+ *
323
+ * ```html
324
+ * <$text htmlA="{ attributes: { id: 'myId' } }">bar</$text>
325
+ * ```
326
+ *
327
+ * The `htmlA` attribute would stay in the model and would cause GHS to generate an `<a>` element.
328
+ * This is incorrect from UX point of view, as the user wanted to remove the whole link (not only `href`).
329
+ */
330
+ _registerCoupledAttributesPostFixer() {
331
+ const model = this.editor.model;
332
+ model.document.registerPostFixer(writer => {
333
+ const changes = model.document.differ.getChanges();
334
+ let changed = false;
335
+ const coupledAttributes = this._getCoupledAttributesMap();
336
+ for (const change of changes) {
337
+ // Handle only attribute removals.
338
+ if (change.type != 'attribute' || change.attributeNewValue !== null) {
339
+ continue;
340
+ }
341
+ // Find a list of coupled GHS attributes.
342
+ const attributeKeys = coupledAttributes.get(change.attributeKey);
343
+ if (!attributeKeys) {
344
+ continue;
345
+ }
346
+ // Remove the coupled GHS attributes on the same range as the feature attribute was removed.
347
+ for (const { item } of change.range.getWalker({ shallow: true })) {
348
+ for (const attributeKey of attributeKeys) {
349
+ if (item.hasAttribute(attributeKey)) {
350
+ writer.removeAttribute(attributeKey, item);
351
+ changed = true;
352
+ }
353
+ }
354
+ }
355
+ }
356
+ return changed;
357
+ });
358
+ }
359
+ /**
360
+ * Removes `html*Attributes` attributes from incompatible elements.
361
+ *
362
+ * For example, consider the following HTML:
363
+ *
364
+ * ```html
365
+ * <heading2 htmlH2Attributes="...">foobar[]</heading2>
366
+ * ```
367
+ *
368
+ * Pressing `enter` creates a new `paragraph` element that inherits
369
+ * the `htmlH2Attributes` attribute from `heading2`.
370
+ *
371
+ * ```html
372
+ * <heading2 htmlH2Attributes="...">foobar</heading2>
373
+ * <paragraph htmlH2Attributes="...">[]</paragraph>
374
+ * ```
375
+ *
376
+ * This postfixer ensures that this doesn't happen, and that elements can
377
+ * only have `html*Attributes` associated with them,
378
+ * e.g.: `htmlPAttributes` for `<p>`, `htmlDivAttributes` for `<div>`, etc.
379
+ *
380
+ * With it enabled, pressing `enter` at the end of `<heading2>` will create
381
+ * a new paragraph without the `htmlH2Attributes` attribute.
382
+ *
383
+ * ```html
384
+ * <heading2 htmlH2Attributes="...">foobar</heading2>
385
+ * <paragraph>[]</paragraph>
386
+ * ```
387
+ */
388
+ _registerAssociatedHtmlAttributesPostFixer() {
389
+ const model = this.editor.model;
390
+ model.document.registerPostFixer(writer => {
391
+ const changes = model.document.differ.getChanges();
392
+ let changed = false;
393
+ for (const change of changes) {
394
+ if (change.type !== 'insert' || change.name === '$text') {
395
+ continue;
396
+ }
397
+ for (const attr of change.attributes.keys()) {
398
+ if (!attr.startsWith('html') || !attr.endsWith('Attributes')) {
399
+ continue;
400
+ }
401
+ if (!model.schema.checkAttribute(change.name, attr)) {
402
+ writer.removeAttribute(attr, change.position.nodeAfter);
403
+ changed = true;
404
+ }
405
+ }
406
+ }
407
+ return changed;
408
+ });
409
+ }
410
+ /**
411
+ * Collects the map of coupled attributes. The returned map is keyed by the feature attribute name
412
+ * and coupled GHS attribute names are stored in the value array.
413
+ */
414
+ _getCoupledAttributesMap() {
415
+ if (this._coupledAttributes) {
416
+ return this._coupledAttributes;
417
+ }
418
+ this._coupledAttributes = new Map();
419
+ for (const definition of this._allowedElements) {
420
+ if (definition.coupledAttribute && definition.model) {
421
+ const attributeNames = this._coupledAttributes.get(definition.coupledAttribute);
422
+ if (attributeNames) {
423
+ attributeNames.push(definition.model);
424
+ }
425
+ else {
426
+ this._coupledAttributes.set(definition.coupledAttribute, [definition.model]);
427
+ }
428
+ }
429
+ }
430
+ return this._coupledAttributes;
431
+ }
432
+ /**
433
+ * Fires `register` event for the given element definition.
434
+ */
435
+ _fireRegisterEvent(definition) {
436
+ if (definition.view && this._disallowedElements.has(definition.view)) {
437
+ return;
438
+ }
439
+ this.fire(definition.view ? `register:${definition.view}` : 'register', definition);
440
+ }
441
+ /**
442
+ * Registers object element and attribute converters for the given data schema definition.
443
+ */
444
+ _registerObjectElement(definition) {
445
+ const editor = this.editor;
446
+ const schema = editor.model.schema;
447
+ const conversion = editor.conversion;
448
+ const { view: viewName, model: modelName } = definition;
449
+ schema.register(modelName, definition.modelSchema);
450
+ /* istanbul ignore next: paranoid check -- @preserve */
451
+ if (!viewName) {
452
+ return;
453
+ }
454
+ schema.extend(definition.model, {
455
+ allowAttributes: [getHtmlAttributeName(viewName), 'htmlContent']
456
+ });
457
+ // Store element content in special `$rawContent` custom property to
458
+ // avoid editor's data filtering mechanism.
459
+ editor.data.registerRawContentMatcher({
460
+ name: viewName
461
+ });
462
+ conversion.for('upcast').elementToElement({
463
+ view: viewName,
464
+ model: viewToModelObjectConverter(definition),
465
+ // With a `low` priority, `paragraph` plugin auto-paragraphing mechanism is executed. Make sure
466
+ // this listener is called before it. If not, some elements will be transformed into a paragraph.
467
+ // `+ 2` is used to take priority over `_addDefaultH1Conversion` in the Heading plugin.
468
+ converterPriority: priorities.low + 2
469
+ });
470
+ conversion.for('upcast').add(viewToModelBlockAttributeConverter(definition, this));
471
+ conversion.for('editingDowncast').elementToStructure({
472
+ model: {
473
+ name: modelName,
474
+ attributes: [getHtmlAttributeName(viewName)]
475
+ },
476
+ view: toObjectWidgetConverter(editor, definition)
477
+ });
478
+ conversion.for('dataDowncast').elementToElement({
479
+ model: modelName,
480
+ view: (modelElement, { writer }) => {
481
+ return createObjectView(viewName, modelElement, writer);
482
+ }
483
+ });
484
+ conversion.for('dataDowncast').add(modelToViewBlockAttributeConverter(definition));
485
+ }
486
+ /**
487
+ * Registers block element and attribute converters for the given data schema definition.
488
+ */
489
+ _registerBlockElement(definition) {
490
+ const editor = this.editor;
491
+ const schema = editor.model.schema;
492
+ const conversion = editor.conversion;
493
+ const { view: viewName, model: modelName } = definition;
494
+ if (!schema.isRegistered(definition.model)) {
495
+ schema.register(definition.model, definition.modelSchema);
496
+ if (!viewName) {
497
+ return;
498
+ }
499
+ conversion.for('upcast').elementToElement({
500
+ model: modelName,
501
+ view: viewName,
502
+ // With a `low` priority, `paragraph` plugin auto-paragraphing mechanism is executed. Make sure
503
+ // this listener is called before it. If not, some elements will be transformed into a paragraph.
504
+ // `+ 2` is used to take priority over `_addDefaultH1Conversion` in the Heading plugin.
505
+ converterPriority: priorities.low + 2
506
+ });
507
+ conversion.for('downcast').elementToElement({
508
+ model: modelName,
509
+ view: viewName
510
+ });
511
+ }
512
+ if (!viewName) {
513
+ return;
514
+ }
515
+ schema.extend(definition.model, {
516
+ allowAttributes: getHtmlAttributeName(viewName)
517
+ });
518
+ conversion.for('upcast').add(viewToModelBlockAttributeConverter(definition, this));
519
+ conversion.for('downcast').add(modelToViewBlockAttributeConverter(definition));
520
+ }
521
+ /**
522
+ * Registers inline element and attribute converters for the given data schema definition.
523
+ *
524
+ * Extends `$text` model schema to allow the given definition model attribute and its properties.
525
+ */
526
+ _registerInlineElement(definition) {
527
+ const editor = this.editor;
528
+ const schema = editor.model.schema;
529
+ const conversion = editor.conversion;
530
+ const attributeKey = definition.model;
531
+ // This element is stored in the model as an attribute on a block element, for example DocumentLists.
532
+ if (definition.appliesToBlock) {
533
+ return;
534
+ }
535
+ schema.extend('$text', {
536
+ allowAttributes: attributeKey
537
+ });
538
+ if (definition.attributeProperties) {
539
+ schema.setAttributeProperties(attributeKey, definition.attributeProperties);
540
+ }
541
+ conversion.for('upcast').add(viewToAttributeInlineConverter(definition, this));
542
+ conversion.for('downcast').attributeToElement({
543
+ model: attributeKey,
544
+ view: attributeToViewInlineConverter(definition)
545
+ });
546
+ if (!definition.allowEmpty) {
547
+ return;
548
+ }
549
+ schema.setAttributeProperties(attributeKey, { copyFromObject: false });
550
+ if (!schema.isRegistered('htmlEmptyElement')) {
551
+ schema.register('htmlEmptyElement', {
552
+ inheritAllFrom: '$inlineObject'
553
+ });
554
+ }
555
+ editor.data.htmlProcessor.domConverter.registerInlineObjectMatcher(element => {
556
+ // Element must be empty and have any attribute.
557
+ if (element.name == definition.view &&
558
+ element.isEmpty &&
559
+ Array.from(element.getAttributeKeys()).length) {
560
+ return {
561
+ name: true
562
+ };
563
+ }
564
+ return null;
565
+ });
566
+ conversion.for('editingDowncast')
567
+ .elementToElement({
568
+ model: 'htmlEmptyElement',
569
+ view: emptyInlineModelElementToViewConverter(definition, true)
570
+ });
571
+ conversion.for('dataDowncast')
572
+ .elementToElement({
573
+ model: 'htmlEmptyElement',
574
+ view: emptyInlineModelElementToViewConverter(definition)
575
+ });
576
+ }
577
+ }
578
+ /**
579
+ * Matches and consumes the given view attributes.
580
+ */
581
+ function consumeAttributes(viewElement, conversionApi, matcher) {
582
+ const matches = consumeAttributeMatches(viewElement, conversionApi, matcher);
583
+ const { attributes, styles, classes } = mergeMatchResults(matches);
584
+ const viewAttributes = {};
585
+ // Remove invalid DOM element attributes.
586
+ if (attributes.size) {
587
+ for (const key of attributes) {
588
+ if (!isValidAttributeName(key)) {
589
+ attributes.delete(key);
590
+ }
591
+ }
592
+ }
593
+ if (attributes.size) {
594
+ viewAttributes.attributes = iterableToObject(attributes, key => viewElement.getAttribute(key));
595
+ }
596
+ if (styles.size) {
597
+ viewAttributes.styles = iterableToObject(styles, key => viewElement.getStyle(key));
598
+ }
599
+ if (classes.size) {
600
+ viewAttributes.classes = Array.from(classes);
601
+ }
602
+ if (!Object.keys(viewAttributes).length) {
603
+ return null;
604
+ }
605
+ return viewAttributes;
606
+ }
607
+ /**
608
+ * Consumes matched attributes.
609
+ *
610
+ * @returns Array with match information about found attributes.
611
+ */
612
+ function consumeAttributeMatches(viewElement, { consumable }, matcher) {
613
+ const matches = matcher.matchAll(viewElement) || [];
614
+ const consumedMatches = [];
615
+ for (const match of matches) {
616
+ removeConsumedAttributes(consumable, viewElement, match);
617
+ // We only want to consume attributes, so element can be still processed by other converters.
618
+ delete match.match.name;
619
+ consumable.consume(viewElement, match.match);
620
+ consumedMatches.push(match);
621
+ }
622
+ return consumedMatches;
623
+ }
624
+ /**
625
+ * Removes attributes from the given match that were already consumed by other converters.
626
+ */
627
+ function removeConsumedAttributes(consumable, viewElement, match) {
628
+ for (const key of ['attributes', 'classes', 'styles']) {
629
+ const attributes = match.match[key];
630
+ if (!attributes) {
631
+ continue;
632
+ }
633
+ // Iterating over a copy of an array so removing items doesn't influence iteration.
634
+ for (const value of Array.from(attributes)) {
635
+ if (!consumable.test(viewElement, ({ [key]: [value] }))) {
636
+ removeItemFromArray(attributes, value);
637
+ }
638
+ }
639
+ }
640
+ }
641
+ /**
642
+ * Merges the result of {@link module:engine/view/matcher~Matcher#matchAll} method.
643
+ *
644
+ * @param matches
645
+ * @returns Object with following properties:
646
+ * - attributes Set with matched attribute names.
647
+ * - styles Set with matched style names.
648
+ * - classes Set with matched class names.
649
+ */
650
+ function mergeMatchResults(matches) {
651
+ const matchResult = {
652
+ attributes: new Set(),
653
+ classes: new Set(),
654
+ styles: new Set()
655
+ };
656
+ for (const match of matches) {
657
+ for (const key in matchResult) {
658
+ const values = match.match[key] || [];
659
+ values.forEach(value => (matchResult[key]).add(value));
660
+ }
661
+ }
662
+ return matchResult;
663
+ }
664
+ /**
665
+ * Converts the given iterable object into an object.
666
+ */
667
+ function iterableToObject(iterable, getValue) {
668
+ const attributesObject = {};
669
+ for (const prop of iterable) {
670
+ const value = getValue(prop);
671
+ if (value !== undefined) {
672
+ attributesObject[prop] = getValue(prop);
673
+ }
674
+ }
675
+ return attributesObject;
676
+ }
677
+ /**
678
+ * Matcher by default has to match **all** patterns to count it as an actual match. Splitting the pattern
679
+ * into separate patterns means that any matched pattern will be count as a match.
680
+ *
681
+ * @param pattern Pattern to split.
682
+ * @param attributeName Name of the attribute to split (e.g. 'attributes', 'classes', 'styles').
683
+ */
684
+ function splitPattern(pattern, attributeName) {
685
+ const { name } = pattern;
686
+ const attributeValue = pattern[attributeName];
687
+ if (isPlainObject(attributeValue)) {
688
+ return Object.entries(attributeValue).map(([key, value]) => ({
689
+ name,
690
+ [attributeName]: {
691
+ [key]: value
692
+ }
693
+ }));
694
+ }
695
+ if (Array.isArray(attributeValue)) {
696
+ return attributeValue.map(value => ({
697
+ name,
698
+ [attributeName]: [value]
699
+ }));
700
+ }
701
+ return [pattern];
702
+ }
703
+ /**
704
+ * Rules are matched in conjunction (AND operation), but we want to have a match if *any* of the rules is matched (OR operation).
705
+ * By splitting the rules we force the latter effect.
706
+ */
707
+ function splitRules(rules) {
708
+ const { name, attributes, classes, styles } = rules;
709
+ const splitRules = [];
710
+ if (attributes) {
711
+ splitRules.push(...splitPattern({ name, attributes }, 'attributes'));
712
+ }
713
+ if (classes) {
714
+ splitRules.push(...splitPattern({ name, classes }, 'classes'));
715
+ }
716
+ if (styles) {
717
+ splitRules.push(...splitPattern({ name, styles }, 'styles'));
718
+ }
719
+ return splitRules;
720
+ }