schema.js 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/model/schema
  7. */
  8. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  9. import ObservableMixin from '@ckeditor/ckeditor5-utils/src/observablemixin';
  10. import mix from '@ckeditor/ckeditor5-utils/src/mix';
  11. import Range from './range';
  12. /**
  13. * The model's schema. It defines allowed and disallowed structures of nodes as well as nodes' attributes.
  14. * The schema is usually defined by features and based on them the editing framework and features
  15. * make decisions how to change and process the model.
  16. *
  17. * The instance of schema is available in {@link module:engine/model/model~Model#schema `editor.model.schema`}.
  18. *
  19. * # Schema definitions
  20. *
  21. * Schema defines allowed model structures and allowed attributes separately. They are also checked separately
  22. * by using the {@link ~Schema#checkChild} and {@link ~Schema#checkAttribute} methods.
  23. *
  24. * ## Defining allowed structures
  25. *
  26. * When a feature introduces a model element it should register it in the schema. Besides
  27. * defining that such an element may exist in the model, the feature also needs to define where
  28. * this element may be placed:
  29. *
  30. * schema.register( 'myElement', {
  31. * allowIn: '$root'
  32. * } );
  33. *
  34. * This lets the schema know that `<myElement>` may be a child of the `<$root>` element. `$root` is one of generic
  35. * nodes defined by the editing framework. By default, the editor names the main root element a `<$root>`,
  36. * so the above definition allows `<myElement>` in the main editor element.
  37. *
  38. * In other words, this would be correct:
  39. *
  40. * <$root><myElement></myElement></$root>
  41. *
  42. * While this would not be correct:
  43. *
  44. * <$root><foo><myElement></myElement></foo></$root>
  45. *
  46. * ## Generic items
  47. *
  48. * There are three basic generic items: `$root`, `$block` and `$text`.
  49. * They are defined as follows:
  50. *
  51. * this.schema.register( '$root', {
  52. * isLimit: true
  53. * } );
  54. * this.schema.register( '$block', {
  55. * allowIn: '$root',
  56. * isBlock: true
  57. * } );
  58. * this.schema.register( '$text', {
  59. * allowIn: '$block'
  60. * } );
  61. *
  62. * These definitions can then be reused by features to create their own definitions in a more extensible way.
  63. * For example, the {@link module:paragraph/paragraph~Paragraph} feature will define its item as:
  64. *
  65. * schema.register( 'paragraph', {
  66. * inheritAllFrom: '$block'
  67. * } );
  68. *
  69. * Which translates to:
  70. *
  71. * schema.register( 'paragraph', {
  72. * allowWhere: '$block',
  73. * allowContentOf: '$block',
  74. * allowAttributesOf: '$block',
  75. * inheritTypesFrom: '$block'
  76. * } );
  77. *
  78. * Which can be read as:
  79. *
  80. * * The `<paragraph>` element will be allowed in elements in which `<$block>` is allowed (e.g. in `<$root>`).
  81. * * The `<paragraph>` element will allow all nodes which are allowed in `<$block>` (e.g. `$text`).
  82. * * The `<paragraph>` element will allow all attributes allowed on `<$block>`.
  83. * * The `<paragraph>` element will inherit all `is*` properties of `<$block>` (e.g. `isBlock`).
  84. *
  85. * Thanks to the fact that `<paragraph>`'s definition is inherited from `<$block>` other features can use the `<$block>`
  86. * type to indirectly extend `<paragraph>`'s definition. For example, the {@link module:block-quote/blockquote~BlockQuote}
  87. * feature does this:
  88. *
  89. * schema.register( 'blockQuote', {
  90. * allowWhere: '$block',
  91. * allowContentOf: '$root'
  92. * } );
  93. *
  94. * Thanks to that, despite the fact that block quote and paragraph features know nothing about themselves, paragraphs
  95. * will be allowed in block quotes and block quotes will be allowed in all places where blocks are. So if anyone will
  96. * register a `<section>` element (with `allowContentOf: '$root'` rule), that `<section>` elements will allow
  97. * block quotes too.
  98. *
  99. * The side effect of such a definition inheritance is that now `<blockQuote>` is allowed in `<blockQuote>` which needs to be
  100. * resolved by a callback which will disallow this specific structure.
  101. *
  102. * You can read more about the format of an item definition in {@link module:engine/model/schema~SchemaItemDefinition}.
  103. *
  104. * ## Defining advanced rules in `checkChild()`'s callbacks
  105. *
  106. * The {@link ~Schema#checkChild} method which is the base method used to check whether some element is allowed in a given structure
  107. * is {@link module:utils/observablemixin~ObservableMixin#decorate a decorated method}.
  108. * It means that you can add listeners to implement your specific rules which are not limited by the declarative
  109. * {@link module:engine/model/schema~SchemaItemDefinition API}.
  110. *
  111. * Those listeners can be added either by listening directly to the {@link ~Schema#event:checkChild} event or
  112. * by using the handy {@link ~Schema#addChildCheck} method.
  113. *
  114. * For instance, the block quote feature defines such a listener to disallow nested `<blockQuote>` structures:
  115. *
  116. * schema.addChildCheck( context, childDefinition ) => {
  117. * // Note that context is automatically normalized to SchemaContext instance and
  118. * // child to its definition (SchemaCompiledItemDefinition).
  119. *
  120. * // If checkChild() is called with a context that ends with blockQuote and blockQuote as a child
  121. * // to check, make the checkChild() method return false.
  122. * if ( context.endsWith( 'blockQuote' ) && childDefinition.name == 'blockQuote' ) {
  123. * return false;
  124. * }
  125. * } );
  126. *
  127. * ## Defining attributes
  128. *
  129. * TODO
  130. *
  131. * ## Implementing additional constraints
  132. *
  133. * Schema's capabilities were limited to simple (and atomic) {@link ~Schema#checkChild} and
  134. * {@link ~Schema#checkAttribute} checks on purpose.
  135. * One may imagine that schema should support defining more complex rules such as
  136. * "element `<x>` must be always followed by `<y>`".
  137. * While it is feasible to create an API which would enable feeding the schema with such definitions,
  138. * it is unfortunately unrealistic to then expect that every editing feature will consider those rules when processing the model.
  139. * It is also unrealistic to expect that it will be done automatically by the schema and the editing engine themselves.
  140. *
  141. * For instance, let's get back to the "element `<x>` must be always followed by `<y>`" rule and this initial content:
  142. *
  143. * <$root>
  144. * <x>foo</x>
  145. * <y>bar[bom</y>
  146. * <z>bom]bar</z>
  147. * </$root>
  148. *
  149. * Now, imagine that the user presses the "block quote" button. Usually it would wrap the two selected blocks
  150. * (`<y>` and `<z>`) with a `<blockQuote>` element:
  151. *
  152. * <$root>
  153. * <x>foo</x>
  154. * <blockQuote>
  155. * <y>bar[bom</y>
  156. * <z>bom]bar</z>
  157. * </blockQuote>
  158. * </$root>
  159. *
  160. * But it turns out that this creates an incorrect structure – `<x>` is not followed by `<y>` anymore.
  161. *
  162. * What should happen instead? There are at least 4 possible solutions: the block quote feature should not be
  163. * applicable in such a context, someone should create a new `<y>` right after `<x>`, `<x>` should be moved
  164. * inside `<blockQuote>` together with `<y>` or vice versa.
  165. *
  166. * While this is a relatively simple scenario (unlike most real-time collaboration scenarios),
  167. * it turns out that it's already hard to say what should happen and who should react to fix this content.
  168. *
  169. * Therefore, if your editor needs to implement such rules, you should do that through model's post-fixers
  170. * fixing incorrect content or actively prevent such situations (e.g. by disabling certain features).
  171. * It means that those constraints will be defined specifically for your scenario by your code which
  172. * makes their implementation much easier.
  173. *
  174. * So the answer for who and how should implement additional constraints is your features or your editor
  175. * through CKEditor 5's rich and open API.
  176. *
  177. * @mixes module:utils/observablemixin~ObservableMixin
  178. */
  179. export default class Schema {
  180. /**
  181. * Creates schema instance.
  182. */
  183. constructor() {
  184. this._sourceDefinitions = {};
  185. this.decorate( 'checkChild' );
  186. this.decorate( 'checkAttribute' );
  187. this.on( 'checkAttribute', ( evt, args ) => {
  188. args[ 0 ] = new SchemaContext( args[ 0 ] );
  189. }, { priority: 'highest' } );
  190. this.on( 'checkChild', ( evt, args ) => {
  191. args[ 0 ] = new SchemaContext( args[ 0 ] );
  192. args[ 1 ] = this.getDefinition( args[ 1 ] );
  193. }, { priority: 'highest' } );
  194. }
  195. /**
  196. * Registers schema item. Can only be called once for every item name.
  197. *
  198. * schema.register( 'paragraph', {
  199. * inheritAllFrom: '$block'
  200. * } );
  201. *
  202. * @param {String} itemName
  203. * @param {module:engine/model/schema~SchemaItemDefinition} definition
  204. */
  205. register( itemName, definition ) {
  206. if ( this._sourceDefinitions[ itemName ] ) {
  207. // TODO docs
  208. throw new CKEditorError( 'schema-cannot-register-item-twice: A single item cannot be registered twice in the schema.', {
  209. itemName
  210. } );
  211. }
  212. this._sourceDefinitions[ itemName ] = [
  213. Object.assign( {}, definition )
  214. ];
  215. this._clearCache();
  216. }
  217. /**
  218. * Extends a {@link #register registered} item's definition.
  219. *
  220. * Extending properties such as `allowIn` will add more items to the existing properties,
  221. * while redefining properties such as `isBlock` will override the previously defined ones.
  222. *
  223. * schema.register( 'foo', {
  224. * allowIn: '$root',
  225. * isBlock: true;
  226. * } );
  227. * schema.extend( 'foo', {
  228. * allowIn: 'blockQuote',
  229. * isBlock: false
  230. * } );
  231. *
  232. * schema.getDefinition( 'foo' );
  233. * // {
  234. * // allowIn: [ '$root', 'blockQuote' ],
  235. * // isBlock: false
  236. * // }
  237. *
  238. * @param {String} itemName
  239. * @param {module:engine/model/schema~SchemaItemDefinition} definition
  240. */
  241. extend( itemName, definition ) {
  242. if ( !this._sourceDefinitions[ itemName ] ) {
  243. // TODO docs
  244. throw new CKEditorError( 'schema-cannot-extend-missing-item: Cannot extend an item which was not registered yet.', {
  245. itemName
  246. } );
  247. }
  248. this._sourceDefinitions[ itemName ].push( Object.assign( {}, definition ) );
  249. this._clearCache();
  250. }
  251. /**
  252. * Returns all registered items.
  253. *
  254. * @returns {Object.<String,module:engine/model/schema~SchemaCompiledItemDefinition>}
  255. */
  256. getDefinitions() {
  257. if ( !this._compiledDefinitions ) {
  258. this._compile();
  259. }
  260. return this._compiledDefinitions;
  261. }
  262. /**
  263. * Returns a definition of the given item or `undefined` if item is not registered.
  264. *
  265. * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
  266. * @returns {module:engine/model/schema~SchemaCompiledItemDefinition}
  267. */
  268. getDefinition( item ) {
  269. let itemName;
  270. if ( typeof item == 'string' ) {
  271. itemName = item;
  272. } else if ( item.is && ( item.is( 'text' ) || item.is( 'textProxy' ) ) ) {
  273. itemName = '$text';
  274. }
  275. // Element or module:engine/model/schema~SchemaContextItem.
  276. else {
  277. itemName = item.name;
  278. }
  279. return this.getDefinitions()[ itemName ];
  280. }
  281. /**
  282. * Returns `true` if the given item is registered in the schema.
  283. *
  284. * schema.isRegistered( 'paragraph' ); // -> true
  285. * schema.isRegistered( editor.model.document.getRoot() ); // -> true
  286. * schema.isRegistered( 'foo' ); // -> false
  287. *
  288. * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
  289. */
  290. isRegistered( item ) {
  291. return !!this.getDefinition( item );
  292. }
  293. /**
  294. * Returns `true` if the given item is defined to be
  295. * a block by {@link module:engine/model/schema~SchemaItemDefinition}'s `isBlock` property.
  296. *
  297. * schema.isBlock( 'paragraph' ); // -> true
  298. * schema.isBlock( '$root' ); // -> false
  299. *
  300. * const paragraphElement = writer.createElement( 'paragraph' );
  301. * schema.isBlock( paragraphElement ); // -> true
  302. *
  303. * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
  304. */
  305. isBlock( item ) {
  306. const def = this.getDefinition( item );
  307. return !!( def && def.isBlock );
  308. }
  309. /**
  310. * Returns `true` if the given item is defined to be
  311. * a limit element by {@link module:engine/model/schema~SchemaItemDefinition}'s `isLimit` property.
  312. *
  313. * schema.isLimit( 'paragraph' ); // -> false
  314. * schema.isLimit( '$root' ); // -> true
  315. * schema.isLimit( editor.model.document.getRoot() ); // -> true
  316. *
  317. * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
  318. */
  319. isLimit( item ) {
  320. const def = this.getDefinition( item );
  321. return !!( def && def.isLimit );
  322. }
  323. /**
  324. * Returns `true` if the given item is defined to be
  325. * a object element by {@link module:engine/model/schema~SchemaItemDefinition}'s `isObject` property.
  326. *
  327. * schema.isObject( 'paragraph' ); // -> false
  328. * schema.isObject( 'image' ); // -> true
  329. *
  330. * const imageElement = writer.createElement( 'image' );
  331. * schema.isObject( imageElement ); // -> true
  332. *
  333. * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
  334. */
  335. isObject( item ) {
  336. const def = this.getDefinition( item );
  337. return !!( def && def.isObject );
  338. }
  339. /**
  340. * Checks whether the given node (`child`) can be a child of the given context.
  341. *
  342. * schema.checkChild( model.document.getRoot(), paragraph ); // -> false
  343. *
  344. * schema.register( 'paragraph', {
  345. * allowIn: '$root'
  346. * } );
  347. * schema.checkChild( model.document.getRoot(), paragraph ); // -> true
  348. *
  349. * @fires checkChild
  350. * @param {module:engine/model/schema~SchemaContextDefinition} context Context in which the child will be checked.
  351. * @param {module:engine/model/node~Node|String} child The child to check.
  352. */
  353. checkChild( context, def ) {
  354. // Note: context and child are already normalized here to a SchemaContext and SchemaCompiledItemDefinition.
  355. if ( !def ) {
  356. return false;
  357. }
  358. return this._checkContextMatch( def, context );
  359. }
  360. /**
  361. * Checks whether the given attribute can be applied in the given context (on the last
  362. * item of the context).
  363. *
  364. * schema.checkAttribute( textNode, 'bold' ); // -> false
  365. *
  366. * schema.extend( '$text', {
  367. * allowAttributes: 'bold'
  368. * } );
  369. * schema.checkAttribute( textNode, 'bold' ); // -> true
  370. *
  371. * @fires checkAttribute
  372. * @param {module:engine/model/schema~SchemaContextDefinition} context
  373. * @param {String} attributeName
  374. */
  375. checkAttribute( context, attributeName ) {
  376. const def = this.getDefinition( context.last );
  377. if ( !def ) {
  378. return false;
  379. }
  380. return def.allowAttributes.includes( attributeName );
  381. }
  382. /**
  383. * Allows registering a callback to the {@link #checkChild} method calls.
  384. *
  385. * Callbacks allow you to implement rules which are not otherwise possible to achieve
  386. * by using the declarative API of {@link module:engine/model/schema~SchemaItemDefinition}.
  387. * For example, by using this method you can disallow elements in specific contexts.
  388. *
  389. * This method is a shorthand for using the {@link #event:checkChild} event. For even better control,
  390. * you can use that event instead.
  391. *
  392. * Example:
  393. *
  394. * // Disallow heading1 directly inside a blockQuote.
  395. * schema.addChildCheck( ( ctx, childDefinition ) => {
  396. * if ( ctx.endsWith( 'blockQuote' ) && childDefinition.name == 'heading1' ) {
  397. * return false;
  398. * }
  399. * } );
  400. *
  401. * Which translates to:
  402. *
  403. * schema.on( 'checkChild', ( evt, args ) => {
  404. * const context = args[ 0 ];
  405. * const childDefinition = args[ 1 ];
  406. *
  407. * if ( context.endsWith( 'blockQuote' ) && childDefinition && childDefinition.name == 'heading1' ) {
  408. * // Prevent next listeners from being called.
  409. * evt.stop();
  410. * // Set the checkChild()'s return value.
  411. * evt.return = false;
  412. * }
  413. * }, { priority: 'high' } );
  414. *
  415. * @param {Function} callback The callback to be called. It is called with two parameters:
  416. * {@link module:engine/model/schema~SchemaContext} (context) instance and
  417. * {@link module:engine/model/schema~SchemaCompiledItemDefinition} (child-to-check definition).
  418. * The callback may return `true/false` to override `checkChild()`'s return value. If it does not return
  419. * a boolean value, the default algorithm (or other callbacks) will define `checkChild()`'s return value.
  420. */
  421. addChildCheck( callback ) {
  422. this.on( 'checkChild', ( evt, [ ctx, childDef ] ) => {
  423. // checkChild() was called with a non-registered child.
  424. // In 99% cases such check should return false, so not to overcomplicate all callbacks
  425. // don't even execute them.
  426. if ( !childDef ) {
  427. return;
  428. }
  429. const retValue = callback( ctx, childDef );
  430. if ( typeof retValue == 'boolean' ) {
  431. evt.stop();
  432. evt.return = retValue;
  433. }
  434. }, { priority: 'high' } );
  435. }
  436. /**
  437. * Returns the lowest {@link module:engine/model/schema~Schema#isLimit limit element} containing the entire
  438. * selection or the root otherwise.
  439. *
  440. * @param {module:engine/model/selection~Selection} selection Selection which returns the common ancestor.
  441. * @returns {module:engine/model/element~Element}
  442. */
  443. getLimitElement( selection ) {
  444. // Find the common ancestor for all selection's ranges.
  445. let element = Array.from( selection.getRanges() )
  446. .reduce( ( node, range ) => {
  447. if ( !node ) {
  448. return range.getCommonAncestor();
  449. }
  450. return node.getCommonAncestor( range.getCommonAncestor() );
  451. }, null );
  452. while ( !this.isLimit( element ) ) {
  453. if ( element.parent ) {
  454. element = element.parent;
  455. } else {
  456. break;
  457. }
  458. }
  459. return element;
  460. }
  461. /**
  462. * Checks whether the attribute is allowed in selection:
  463. *
  464. * * if the selection is not collapsed, then checks if the attribute is allowed on any of nodes in that range,
  465. * * if the selection is collapsed, then checks if on the selection position there's a text with the
  466. * specified attribute allowed.
  467. *
  468. * @param {module:engine/model/selection~Selection} selection Selection which will be checked.
  469. * @param {String} attribute The name of the attribute to check.
  470. * @returns {Boolean}
  471. */
  472. checkAttributeInSelection( selection, attribute ) {
  473. if ( selection.isCollapsed ) {
  474. // Check whether schema allows for a text with the attribute in the selection.
  475. return this.checkAttribute( [ ...selection.getFirstPosition().getAncestors(), '$text' ], attribute );
  476. } else {
  477. const ranges = selection.getRanges();
  478. // For all ranges, check nodes in them until you find a node that is allowed to have the attribute.
  479. for ( const range of ranges ) {
  480. for ( const value of range ) {
  481. if ( this.checkAttribute( value.item, attribute ) ) {
  482. // If we found a node that is allowed to have the attribute, return true.
  483. return true;
  484. }
  485. }
  486. }
  487. }
  488. // If we haven't found such node, return false.
  489. return false;
  490. }
  491. /**
  492. * Transforms the given set of ranges into a set of ranges where the given attribute is allowed (and can be applied).
  493. *
  494. * @param {Array.<module:engine/model/range~Range>} ranges Ranges to be validated.
  495. * @param {String} attribute The name of the attribute to check.
  496. * @returns {Array.<module:engine/model/range~Range>} Ranges in which the attribute is allowed.
  497. */
  498. getValidRanges( ranges, attribute ) {
  499. const validRanges = [];
  500. for ( const range of ranges ) {
  501. let last = range.start;
  502. let from = range.start;
  503. const to = range.end;
  504. for ( const value of range.getWalker() ) {
  505. if ( !this.checkAttribute( value.item, attribute ) ) {
  506. if ( !from.isEqual( last ) ) {
  507. validRanges.push( new Range( from, last ) );
  508. }
  509. from = value.nextPosition;
  510. }
  511. last = value.nextPosition;
  512. }
  513. if ( from && !from.isEqual( to ) ) {
  514. validRanges.push( new Range( from, to ) );
  515. }
  516. }
  517. return validRanges;
  518. }
  519. /**
  520. * Removes attributes disallowed by the schema.
  521. *
  522. * @param {Iterable.<module:engine/model/node~Node>} nodes Nodes that will be filtered.
  523. * @param {module:engine/model/writer~Writer} writer
  524. */
  525. removeDisallowedAttributes( nodes, writer ) {
  526. for ( const node of nodes ) {
  527. for ( const attribute of node.getAttributeKeys() ) {
  528. if ( !this.checkAttribute( node, attribute ) ) {
  529. writer.removeAttribute( attribute, node );
  530. }
  531. }
  532. if ( node.is( 'element' ) ) {
  533. this.removeDisallowedAttributes( node.getChildren(), writer );
  534. }
  535. }
  536. }
  537. /**
  538. * @private
  539. */
  540. _clearCache() {
  541. this._compiledDefinitions = null;
  542. }
  543. /**
  544. * @private
  545. */
  546. _compile() {
  547. const compiledDefinitions = {};
  548. const sourceRules = this._sourceDefinitions;
  549. const itemNames = Object.keys( sourceRules );
  550. for ( const itemName of itemNames ) {
  551. compiledDefinitions[ itemName ] = compileBaseItemRule( sourceRules[ itemName ], itemName );
  552. }
  553. for ( const itemName of itemNames ) {
  554. compileAllowContentOf( compiledDefinitions, itemName );
  555. }
  556. for ( const itemName of itemNames ) {
  557. compileAllowWhere( compiledDefinitions, itemName );
  558. }
  559. for ( const itemName of itemNames ) {
  560. compileAllowAttributesOf( compiledDefinitions, itemName );
  561. compileInheritPropertiesFrom( compiledDefinitions, itemName );
  562. }
  563. for ( const itemName of itemNames ) {
  564. cleanUpAllowIn( compiledDefinitions, itemName );
  565. cleanUpAllowAttributes( compiledDefinitions, itemName );
  566. }
  567. this._compiledDefinitions = compiledDefinitions;
  568. }
  569. /**
  570. * @private
  571. * @param {module:engine/model/schema~SchemaCompiledItemDefinition} def
  572. * @param {module:engine/model/schema~SchemaContext} context
  573. * @param {Number} contextItemIndex
  574. */
  575. _checkContextMatch( def, context, contextItemIndex = context.length - 1 ) {
  576. const contextItem = context.getItem( contextItemIndex );
  577. if ( def.allowIn.includes( contextItem.name ) ) {
  578. if ( contextItemIndex == 0 ) {
  579. return true;
  580. } else {
  581. const parentRule = this.getDefinition( contextItem );
  582. return this._checkContextMatch( parentRule, context, contextItemIndex - 1 );
  583. }
  584. } else {
  585. return false;
  586. }
  587. }
  588. }
  589. mix( Schema, ObservableMixin );
  590. /**
  591. * Event fired when the {@link #checkChild} method is called. It allows plugging in
  592. * additional behavior – e.g. implementing rules which cannot be defined using the declarative
  593. * {@link module:engine/model/schema~SchemaItemDefinition} interface.
  594. *
  595. * **Note:** The {@link #addChildCheck} method is a more handy way to register callbacks. Internally,
  596. * it registers a listener to this event but comes with a simpler API and it is the recommended choice
  597. * in most of the cases.
  598. *
  599. * The {@link #checkChild} method fires an event because it is
  600. * {@link module:utils/observablemixin~ObservableMixin#decorate decorated} with it. Thanks to that you can
  601. * use this event in a various way, but the most important use case is overriding standard behaviour of the
  602. * `checkChild()` method. Let's see a typical listener template:
  603. *
  604. * schema.on( 'checkChild', ( evt, args ) => {
  605. * const context = args[ 0 ];
  606. * const childDefinition = args[ 1 ];
  607. * }, { priority: 'high' } );
  608. *
  609. * The listener is added with a `high` priority to be executed before the default method is really called. The `args` callback
  610. * parameter contains arguments passed to `checkChild( context, child )`. However, the `context` parameter is already
  611. * normalized to a {@link module:engine/model/schema~SchemaContext} instance and `child` to a
  612. * {@link module:engine/model/schema~SchemaCompiledItemDefinition} instance, so you don't have to worry about
  613. * the various ways how `context` and `child` may be passed to `checkChild()`.
  614. *
  615. * **Note:** `childDefinition` may be `undefined` if `checkChild()` was called with a non-registered element.
  616. *
  617. * So, in order to implement a rule "disallow `heading1` in `blockQuote`" you can add such a listener:
  618. *
  619. * schema.on( 'checkChild', ( evt, args ) => {
  620. * const context = args[ 0 ];
  621. * const childDefinition = args[ 1 ];
  622. *
  623. * if ( context.endsWith( 'blockQuote' ) && childDefinition && childDefinition.name == 'heading1' ) {
  624. * // Prevent next listeners from being called.
  625. * evt.stop();
  626. * // Set the checkChild()'s return value.
  627. * evt.return = false;
  628. * }
  629. * }, { priority: 'high' } );
  630. *
  631. * Allowing elements in specific contexts will be a far less common use case, because it's normally handled by
  632. * `allowIn` rule from {@link module:engine/model/schema~SchemaItemDefinition} but if you have a complex scenario
  633. * where `listItem` should be allowed only in element `foo` which must be in element `bar`, then this would be the way:
  634. *
  635. * schema.on( 'checkChild', ( evt, args ) => {
  636. * const context = args[ 0 ];
  637. * const childDefinition = args[ 1 ];
  638. *
  639. * if ( context.endsWith( 'bar foo' ) && childDefinition.name == 'listItem' ) {
  640. * // Prevent next listeners from being called.
  641. * evt.stop();
  642. * // Set the checkChild()'s return value.
  643. * evt.return = true;
  644. * }
  645. * }, { priority: 'high' } );
  646. *
  647. * @event checkChild
  648. * @param {Array} args The `checkChild()`'s arguments.
  649. */
  650. /**
  651. * Event fired when the {@link #checkAttribute} method is called. It allows plugging in
  652. * additional behavior – e.g. implementing rules which cannot be defined using the declarative
  653. * {@link module:engine/model/schema~SchemaItemDefinition} interface.
  654. *
  655. * The {@link #checkAttribute} method fires an event because it's
  656. * {@link module:utils/observablemixin~ObservableMixin#decorate decorated} with it. Thanks to that you can
  657. * use this event in a various way, but the most important use case is overriding standard behaviour of the
  658. * `checkAttribute()` method. Let's see a typical listener template:
  659. *
  660. * schema.on( 'checkAttribute', ( evt, args ) => {
  661. * const context = args[ 0 ];
  662. * const attributeName = args[ 1 ];
  663. * }, { priority: 'high' } );
  664. *
  665. * The listener is added with a `high` priority to be executed before the default method is really called. The `args` callback
  666. * parameter contains arguments passed to `checkAttribute( context, attributeName )`. However, the `context` parameter is already
  667. * normalized to a {@link module:engine/model/schema~SchemaContext} instance, so you don't have to worry about
  668. * the various ways how `context` may be passed to `checkAttribute()`.
  669. *
  670. * So, in order to implement a rule "disallow `bold` in a text which is in a `heading1` you can add such a listener:
  671. *
  672. * schema.on( 'checkAttribute', ( evt, args ) => {
  673. * const context = args[ 0 ];
  674. * const atributeName = args[ 1 ];
  675. *
  676. * if ( context.endsWith( 'heading1 $text' ) && attributeName == 'bold' ) {
  677. * // Prevent next listeners from being called.
  678. * evt.stop();
  679. * // Set the checkAttribute()'s return value.
  680. * evt.return = false;
  681. * }
  682. * }, { priority: 'high' } );
  683. *
  684. * Allowing attributes in specific contexts will be a far less common use case, because it's normally handled by
  685. * `allowAttributes` rule from {@link module:engine/model/schema~SchemaItemDefinition} but if you have a complex scenario
  686. * where `bold` should be allowed only in element `foo` which must be in element `bar`, then this would be the way:
  687. *
  688. * schema.on( 'checkAttribute', ( evt, args ) => {
  689. * const context = args[ 0 ];
  690. * const atributeName = args[ 1 ];
  691. *
  692. * if ( context.endsWith( 'bar foo $text' ) && attributeName == 'bold' ) {
  693. * // Prevent next listeners from being called.
  694. * evt.stop();
  695. * // Set the checkAttribute()'s return value.
  696. * evt.return = true;
  697. * }
  698. * }, { priority: 'high' } );
  699. *
  700. * @event checkAttribute
  701. * @param {Array} args The `checkAttribute()`'s arguments.
  702. */
  703. /**
  704. * A definition of a {@link module:engine/model/schema~Schema schema} item.
  705. *
  706. * You can define the following rules:
  707. *
  708. * * `allowIn` – a string or an array of strings. Defines in which other items this item will be allowed.
  709. * * `allowAttributes` – a string or an array of strings. Defines allowed attributes of the given item.
  710. * * `allowContentOf` – a string or an array of strings. Inherit "allowed children" from other items.
  711. * * `allowWhere` – a string or an array of strings. Inherit "allowed in" from other items.
  712. * * `allowAttributesOf` – a string or an array of strings. Inherit attributes from other items.
  713. * * `inheritTypesFrom` – a string or an array of strings. Inherit `is*` properties of other items.
  714. * * `inheritAllFrom` – a string. A shorthand for `allowContentOf`, `allowWhere`, `allowAttributesOf`, `inheritTypesFrom`.
  715. * * additionall, you can define the following `is*` properties: `isBlock`, `isLimit`, `isObject`. Read about them below.
  716. *
  717. * # The is* properties
  718. *
  719. * There are 3 commonly used `is*` properties. Their role is to assign additional semantics to schema items.
  720. * You can define more properties but you will also need to implement support for them in the existing editor features.
  721. *
  722. * * `isBlock` – whether this item is paragraph-like. Generally speaking, a content is usually made out of blocks
  723. * like paragraphs, list items, images, headings, etc. All these elements are marked as blocks. A block
  724. * should not allow another block inside. Note: there's also the `$block` generic item which has `isBlock` set to `true`.
  725. * Most block type items will inherit from `$block` (through `inheritAllFrom`).
  726. * * `isLimit` – can be understood as whether this element should not be split by <kbd>Enter</kbd>.
  727. * Examples of limit elements – `$root`, table cell, image caption, etc. In other words, all actions which happen inside
  728. * a limit element are limitted to its content.
  729. * * `isObject` – whether item is "self-contained" and should be treated as a whole. Examples of object elements –
  730. * `image`, `table`, `video`, etc.
  731. *
  732. * # Generic items
  733. *
  734. * There are three basic generic items: `$root`, `$block` and `$text`.
  735. * They are defined as follows:
  736. *
  737. * this.schema.register( '$root', {
  738. * isLimit: true
  739. * } );
  740. * this.schema.register( '$block', {
  741. * allowIn: '$root',
  742. * isBlock: true
  743. * } );
  744. * this.schema.register( '$text', {
  745. * allowIn: '$block'
  746. * } );
  747. *
  748. * They reflect a typical editor content which is contained within one root, consists of several blocks
  749. * (paragraphs, lists items, headings, images) which, in turn, may contain text inside.
  750. *
  751. * By inheriting from the generic items you can define new items which will get extended by other editor features.
  752. * Read more about generic types in the {@linkTODO Defining schema} guide.
  753. *
  754. * # Example definitions
  755. *
  756. * Allow `paragraph` in roots and block quotes:
  757. *
  758. * schema.register( 'paragraph', {
  759. * allowIn: [ '$root', 'blockQuote' ],
  760. * isBlock: true
  761. * } );
  762. *
  763. * Allow `paragraph` everywhere where `$block` is allowed (i.e. in `$root`):
  764. *
  765. * schema.register( 'paragraph', {
  766. * allowWhere: '$block',
  767. * isBlock: true
  768. * } );
  769. *
  770. * Make `image` a block object, which is allowed everywhere where `$block` is.
  771. * Also, allow `src` and `alt` attributes on it:
  772. *
  773. * schema.register( 'image', {
  774. * allowWhere: '$block',
  775. * allowAttributes: [ 'src', 'alt' ],
  776. * isBlock: true,
  777. * isObject: true
  778. * } );
  779. *
  780. * Make `caption` allowed in `image` and make it allow all the content of `$block`s (usually, `$text`).
  781. * Also, mark it as a limit element so it can't be split:
  782. *
  783. * schema.register( 'caption', {
  784. * allowIn: 'image',
  785. * allowContentOf: '$block',
  786. * isLimit: true
  787. * } );
  788. *
  789. * Make `listItem` inherit all from `$block` but also allow additional attributes:
  790. *
  791. * schema.register( 'listItem', {
  792. * inheritAllFrom: '$block',
  793. * allowAttributes: [ 'type', 'indent' ]
  794. * } );
  795. *
  796. * Which translates to:
  797. *
  798. * schema.register( 'listItem', {
  799. * allowWhere: '$block',
  800. * allowContentOf: '$block',
  801. * allowAttributesOf: '$block',
  802. * inheritTypesFrom: '$block',
  803. * allowAttributes: [ 'type', 'indent' ]
  804. * } );
  805. *
  806. * # Tips
  807. *
  808. * * Check schema definitions of existing features to see how they are defined.
  809. * * If you want to publish your feature so other developers can use it, try to use
  810. * generic items as much as possible.
  811. * * Keep your model clean – limit it to the actual data and store information in an normalized way.
  812. * * Remember about definining the `is*` properties. They don't affect the allowed structures, but they can
  813. * affect how editor features treat your elements.
  814. *
  815. * @typedef {Object} module:engine/model/schema~SchemaItemDefinition
  816. */
  817. /**
  818. * A simplified version of {@link module:engine/model/schema~SchemaItemDefinition} after
  819. * compilation by the {@link module:engine/model/schema~Schema schema}.
  820. * Rules feed to the schema by {@link module:engine/model/schema~Schema#register}
  821. * and {@link module:engine/model/schema~Schema#extend} are defined in the
  822. * {@link module:engine/model/schema~SchemaItemDefinition} format.
  823. * Later on, they are compiled to `SchemaCompiledItemDefition` so when you use e.g.
  824. * the {@link module:engine/model/schema~Schema#getDefinition} method you get the compiled version.
  825. *
  826. * The compiled version contains only the following properties:
  827. *
  828. * * `name` property,
  829. * * `is*` properties,
  830. * * `allowIn` array,
  831. * * `allowAttributes` array.
  832. *
  833. * @typedef {Object} module:engine/model/schema~SchemaCompiledItemDefinition
  834. */
  835. /**
  836. * A schema context – a list of ancestors of a given position in the document.
  837. *
  838. * Considering such a position:
  839. *
  840. * <$root>
  841. * <blockQuote>
  842. * <paragraph>
  843. * ^
  844. * </paragraph>
  845. * </blockQuote>
  846. * </$root>
  847. *
  848. * The context of this position is its {@link module:engine/model/position~Position#getAncestors lists of ancestors}:
  849. *
  850. * [ rootElement, blockQuoteElement, paragraphElement ]
  851. *
  852. * Contexts are used in the {@link module:engine/model/schema~Schema#event:checkChild `Schema#checkChild`} and
  853. * {@link module:engine/model/schema~Schema#event:checkAttribute `Schema#checkAttribute`} events as a definition
  854. * of a place in the document where the check occurs. The context instances are created based on the first arguments
  855. * of the {@link module:engine/model/schema~Schema#checkChild `Schema#checkChild()`} and
  856. * {@link module:engine/model/schema~Schema#checkAttribute `Schema#checkAttribute()`} methods so when
  857. * using these methods you need to use {@link module:engine/model/schema~SchemaContextDefinition}s.
  858. */
  859. export class SchemaContext {
  860. /**
  861. * Creates an instance of the context.
  862. *
  863. * @param {module:engine/model/schema~SchemaContextDefinition} context
  864. */
  865. constructor( context ) {
  866. if ( Array.isArray( context ) ) {
  867. if ( context[ 0 ] && typeof context[ 0 ] != 'string' && context[ 0 ].is( 'documentFragment' ) ) {
  868. context.shift();
  869. }
  870. }
  871. else {
  872. // `context` is item or position.
  873. // Position#getAncestors() doesn't accept any parameters but it works just fine here.
  874. context = context.getAncestors( { includeSelf: true } );
  875. if ( context[ 0 ].is( 'documentFragment' ) ) {
  876. context.shift();
  877. }
  878. }
  879. this._items = context.map( mapContextItem );
  880. }
  881. /**
  882. * Number of items.
  883. *
  884. * @type {Number}
  885. */
  886. get length() {
  887. return this._items.length;
  888. }
  889. /**
  890. * The last item (the lowest node).
  891. *
  892. * @type {module:engine/model/schema~SchemaContextItem}
  893. */
  894. get last() {
  895. return this._items[ this._items.length - 1 ];
  896. }
  897. /**
  898. * Iterable interface.
  899. *
  900. * Iterates over all context items.
  901. *
  902. * @returns {Iterable.<module:engine/model/schema~SchemaContextItem>}
  903. */
  904. [ Symbol.iterator ]() {
  905. return this._items[ Symbol.iterator ]();
  906. }
  907. /**
  908. * Gets an item on the given index.
  909. *
  910. * @returns {module:engine/model/schema~SchemaContextItem}
  911. */
  912. getItem( index ) {
  913. return this._items[ index ];
  914. }
  915. /**
  916. * Returns the names of items.
  917. *
  918. * @returns {Iterable.<String>}
  919. */
  920. * getNames() {
  921. yield* this._items.map( item => item.name );
  922. }
  923. /**
  924. * Checks whether the context ends with the given nodes.
  925. *
  926. * const ctx = new SchemaContext( [ rootElement, paragraphElement, textNode ] );
  927. *
  928. * ctx.endsWith( '$text' ); // -> true
  929. * ctx.endsWith( 'paragraph $text' ); // -> true
  930. * ctx.endsWith( '$root' ); // -> false
  931. * ctx.endsWith( 'paragraph' ); // -> false
  932. *
  933. * @param {String} query
  934. * @returns {Boolean}
  935. */
  936. endsWith( query ) {
  937. return Array.from( this.getNames() ).join( ' ' ).endsWith( query );
  938. }
  939. }
  940. /**
  941. * The definition of a {@link module:engine/model/schema~SchemaContext schema context}.
  942. *
  943. * Contexts can be created in multiple ways:
  944. *
  945. * * By defining a **node** – in this cases this node and all its ancestors will be used.
  946. * * By defining a **position** in the document – in this case all its ancestors will be used.
  947. * * By defining an **array of nodes** – in this case this array defines the entire context.
  948. * * By defining an **array of node names** (potentially, mixed with real nodes) – in this case
  949. * nodes definied by strings will be "mocked". Using strings is not recommended as it
  950. * means that the context will be unrealistic (e.g. attributes of these nodes are not specified).
  951. * However, at times this may be the only way to define the context (e.g. when checking some
  952. * hypothetical situation).
  953. *
  954. * Examples of context definitions passed to the {@link module:engine/model/schema~Schema#checkChild `Schema#checkChild()`}
  955. * method:
  956. *
  957. * // Assuming that we have a $root > blockQuote > paragraph structure, the following code
  958. * // will check node 'foo' in the following context:
  959. * // [ rootElement, blockQuoteElement, paragraphElement ]
  960. * const contextDefinition = paragraphElement;
  961. * const childToCheck = 'foo';
  962. * schema.checkChild( contextDefinition, childToCheck );
  963. *
  964. * // Also check in [ rootElement, blockQuoteElement, paragraphElement ].
  965. * schema.checkChild( Position.createAt( paragraphElement ), 'foo' );
  966. *
  967. * // Check in [ rootElement, paragraphElement ].
  968. * schema.checkChild( [ rootElement, paragraphElement ], 'foo' );
  969. *
  970. * // Check in [ fakeRootElement, fakeBarElement, paragraphElement ].
  971. * schema.checkChild( [ '$root', 'bar', paragraphElement ], 'foo' );
  972. *
  973. * All these `checkChild()` calls will fire {@link module:engine/model/schema~Schema#event:checkChild `Schema#checkChild`}
  974. * events in which `args[ 0 ]` is an instance of the context. Therefore, you can write a listener like this:
  975. *
  976. * schema.on( 'checkChild', ( evt, args ) => {
  977. * const ctx = args[ 0 ];
  978. *
  979. * console.log( Array.from( ctx.getNames() ) );
  980. * } );
  981. *
  982. * Which will log the following:
  983. *
  984. * [ '$root', 'blockQuote', 'paragraph' ]
  985. * [ '$root', 'paragraph' ]
  986. * [ '$root', 'bar', 'paragraph' ]
  987. *
  988. * Note: When using the {@link module:engine/model/schema~Schema#checkAttribute `Schema#checkAttribute()`} method
  989. * you may want to check whether a text node may have an attribute. A {@link module:engine/model/text~Text} is a
  990. * correct way to define a context so you can do this:
  991. *
  992. * schema.checkAttribute( textNode, 'bold' );
  993. *
  994. * But sometimes you want to check whether a text at a given position might've had some attribute,
  995. * in which case you can create a context by mising an array of elements with a `'$text'` string:
  996. *
  997. * // Check in [ rootElement, paragraphElement, textNode ].
  998. * schema.checkChild( [ ...positionInParagraph.getAncestors(), '$text' ], 'bold' );
  999. *
  1000. * @typedef {module:engine/model/node~Node|module:engine/model/position~Position|
  1001. * Array.<String|module:engine/model/node~Node>} module:engine/model/schema~SchemaContextDefinition
  1002. */
  1003. /**
  1004. * An item of the {@link module:engine/model/schema~SchemaContext schema context}.
  1005. *
  1006. * It contains 3 properties:
  1007. *
  1008. * * `name` – the name of this item,
  1009. * * `* getAttributeKeys()` – a generator of keys of item attributes,
  1010. * * `getAttribute( keyName )` – a method to get attribute values.
  1011. *
  1012. * The context item interface is a highly simplified version of {@link module:engine/model/node~Node} and its role
  1013. * is to expose only the information which schema checks are able to provide (which is the name of the node and
  1014. * node's attributes).
  1015. *
  1016. * schema.on( 'checkChild', ( evt, args ) => {
  1017. * const ctx = args[ 0 ];
  1018. * const firstItem = ctx.getItem( 0 );
  1019. *
  1020. * console.log( firstItem.name ); // -> '$root'
  1021. * console.log( firstItem.getAttribute( 'foo' ) ); // -> 'bar'
  1022. * console.log( Array.from( firstItem.getAttributeKeys() ) ); // -> [ 'foo', 'faa' ]
  1023. * } );
  1024. *
  1025. * @typedef {Object} module:engine/model/schema~SchemaContextItem
  1026. */
  1027. function compileBaseItemRule( sourceItemRules, itemName ) {
  1028. const itemRule = {
  1029. name: itemName,
  1030. allowIn: [],
  1031. allowContentOf: [],
  1032. allowWhere: [],
  1033. allowAttributes: [],
  1034. allowAttributesOf: [],
  1035. inheritTypesFrom: []
  1036. };
  1037. copyTypes( sourceItemRules, itemRule );
  1038. copyProperty( sourceItemRules, itemRule, 'allowIn' );
  1039. copyProperty( sourceItemRules, itemRule, 'allowContentOf' );
  1040. copyProperty( sourceItemRules, itemRule, 'allowWhere' );
  1041. copyProperty( sourceItemRules, itemRule, 'allowAttributes' );
  1042. copyProperty( sourceItemRules, itemRule, 'allowAttributesOf' );
  1043. copyProperty( sourceItemRules, itemRule, 'inheritTypesFrom' );
  1044. makeInheritAllWork( sourceItemRules, itemRule );
  1045. return itemRule;
  1046. }
  1047. function compileAllowContentOf( compiledDefinitions, itemName ) {
  1048. for ( const allowContentOfItemName of compiledDefinitions[ itemName ].allowContentOf ) {
  1049. // The allowContentOf property may point to an unregistered element.
  1050. if ( compiledDefinitions[ allowContentOfItemName ] ) {
  1051. const allowedChildren = getAllowedChildren( compiledDefinitions, allowContentOfItemName );
  1052. allowedChildren.forEach( allowedItem => {
  1053. allowedItem.allowIn.push( itemName );
  1054. } );
  1055. }
  1056. }
  1057. delete compiledDefinitions[ itemName ].allowContentOf;
  1058. }
  1059. function compileAllowWhere( compiledDefinitions, itemName ) {
  1060. for ( const allowWhereItemName of compiledDefinitions[ itemName ].allowWhere ) {
  1061. const inheritFrom = compiledDefinitions[ allowWhereItemName ];
  1062. // The allowWhere property may point to an unregistered element.
  1063. if ( inheritFrom ) {
  1064. const allowedIn = inheritFrom.allowIn;
  1065. compiledDefinitions[ itemName ].allowIn.push( ...allowedIn );
  1066. }
  1067. }
  1068. delete compiledDefinitions[ itemName ].allowWhere;
  1069. }
  1070. function compileAllowAttributesOf( compiledDefinitions, itemName ) {
  1071. for ( const allowAttributeOfItem of compiledDefinitions[ itemName ].allowAttributesOf ) {
  1072. const inheritFrom = compiledDefinitions[ allowAttributeOfItem ];
  1073. if ( inheritFrom ) {
  1074. const inheritAttributes = inheritFrom.allowAttributes;
  1075. compiledDefinitions[ itemName ].allowAttributes.push( ...inheritAttributes );
  1076. }
  1077. }
  1078. delete compiledDefinitions[ itemName ].allowAttributesOf;
  1079. }
  1080. function compileInheritPropertiesFrom( compiledDefinitions, itemName ) {
  1081. const item = compiledDefinitions[ itemName ];
  1082. for ( const inheritPropertiesOfItem of item.inheritTypesFrom ) {
  1083. const inheritFrom = compiledDefinitions[ inheritPropertiesOfItem ];
  1084. if ( inheritFrom ) {
  1085. const typeNames = Object.keys( inheritFrom ).filter( name => name.startsWith( 'is' ) );
  1086. for ( const name of typeNames ) {
  1087. if ( !( name in item ) ) {
  1088. item[ name ] = inheritFrom[ name ];
  1089. }
  1090. }
  1091. }
  1092. }
  1093. delete item.inheritTypesFrom;
  1094. }
  1095. // Remove items which weren't registered (because it may break some checks or we'd need to complicate them).
  1096. // Make sure allowIn doesn't contain repeated values.
  1097. function cleanUpAllowIn( compiledDefinitions, itemName ) {
  1098. const itemRule = compiledDefinitions[ itemName ];
  1099. const existingItems = itemRule.allowIn.filter( itemToCheck => compiledDefinitions[ itemToCheck ] );
  1100. itemRule.allowIn = Array.from( new Set( existingItems ) );
  1101. }
  1102. function cleanUpAllowAttributes( compiledDefinitions, itemName ) {
  1103. const itemRule = compiledDefinitions[ itemName ];
  1104. itemRule.allowAttributes = Array.from( new Set( itemRule.allowAttributes ) );
  1105. }
  1106. function copyTypes( sourceItemRules, itemRule ) {
  1107. for ( const sourceItemRule of sourceItemRules ) {
  1108. const typeNames = Object.keys( sourceItemRule ).filter( name => name.startsWith( 'is' ) );
  1109. for ( const name of typeNames ) {
  1110. itemRule[ name ] = sourceItemRule[ name ];
  1111. }
  1112. }
  1113. }
  1114. function copyProperty( sourceItemRules, itemRule, propertyName ) {
  1115. for ( const sourceItemRule of sourceItemRules ) {
  1116. if ( typeof sourceItemRule[ propertyName ] == 'string' ) {
  1117. itemRule[ propertyName ].push( sourceItemRule[ propertyName ] );
  1118. } else if ( Array.isArray( sourceItemRule[ propertyName ] ) ) {
  1119. itemRule[ propertyName ].push( ...sourceItemRule[ propertyName ] );
  1120. }
  1121. }
  1122. }
  1123. function makeInheritAllWork( sourceItemRules, itemRule ) {
  1124. for ( const sourceItemRule of sourceItemRules ) {
  1125. const inheritFrom = sourceItemRule.inheritAllFrom;
  1126. if ( inheritFrom ) {
  1127. itemRule.allowContentOf.push( inheritFrom );
  1128. itemRule.allowWhere.push( inheritFrom );
  1129. itemRule.allowAttributesOf.push( inheritFrom );
  1130. itemRule.inheritTypesFrom.push( inheritFrom );
  1131. }
  1132. }
  1133. }
  1134. function getAllowedChildren( compiledDefinitions, itemName ) {
  1135. const itemRule = compiledDefinitions[ itemName ];
  1136. return getValues( compiledDefinitions ).filter( def => def.allowIn.includes( itemRule.name ) );
  1137. }
  1138. function getValues( obj ) {
  1139. return Object.keys( obj ).map( key => obj[ key ] );
  1140. }
  1141. function mapContextItem( ctxItem ) {
  1142. if ( typeof ctxItem == 'string' ) {
  1143. return {
  1144. name: ctxItem,
  1145. * getAttributeKeys() {},
  1146. getAttribute() {}
  1147. };
  1148. } else {
  1149. return {
  1150. // '$text' means text nodes and text proxies.
  1151. name: ctxItem.is( 'element' ) ? ctxItem.name : '$text',
  1152. * getAttributeKeys() {
  1153. yield* ctxItem.getAttributeKeys();
  1154. },
  1155. getAttribute( key ) {
  1156. return ctxItem.getAttribute( key );
  1157. }
  1158. };
  1159. }
  1160. }