schema.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  1. /**
  2. * @license Copyright (c) 2003-2017, 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 their attributes.
  14. * The schema rules are usually defined by features and based on them the editing framework and features
  15. * make decisions how to 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 rules
  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 registered 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 occur:
  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. * node types defined by the editing framework. By default, the editor names the main root element a `<$root>`,
  36. * so the above rule 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 node types
  47. *
  48. * There are three basic generic node types: `$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. * Those rules can then be reused by features to define their rules in a more extensible way.
  63. * For example, the {@link module:paragraph/paragraph~Paragraph} feature will define its rules 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 rules are inherited from `<$block>` other features can use the `<$block>`
  86. * type to indirectly extend `<paragraph>`'s rules. 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.
  98. *
  99. * The side effect of such a rule 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. * ## Defining advanced rules in `checkChild()`'s callbacks
  103. *
  104. * The {@link ~Schema#checkChild} method which is the base method used to check whether some element is allowed in a given structure
  105. * is {@link module:utils/observablemixin~ObservableMixin#decorate decorated} with the {@link ~Schema#event:checkChild} event.
  106. * It means that you can add listeners to implement your specific rules which are not limited by the declarative
  107. * {@link module:engine/model/schema~SchemaItemDefinition} API.
  108. *
  109. * The block quote feature defines such a listener to disallow nested `<blockQuote>` structures:
  110. *
  111. * schema.on( 'checkChild', ( evt, args ) => {
  112. * // The checkChild()'s params.
  113. * // Note that context is automatically normalized to SchemaContext instance by a highest-priority listener.
  114. * const context = args[ 0 ];
  115. * const child = args[ 1 ];
  116. *
  117. * // Pass the child through getRule() to normalize it (child can be passed in multiple formats).
  118. * const childRule = schema.getRule( child );
  119. *
  120. * // If checkChild() is called with a context that ends with blockQuote and blockQuote as a child
  121. * // to check, make the method return false and stop the event so no other listener will override your decision.
  122. * if ( childRule && childRule.name == 'blockQuote' && context.matchEnd( 'blockQuote' ) ) {
  123. * evt.stop();
  124. * evt.return = false;
  125. * }
  126. * }, { priority: 'high' } );
  127. *
  128. * ## Defining attributes
  129. *
  130. * TODO
  131. *
  132. * ## Implementing additional constraints
  133. *
  134. * Schema's capabilities were limited to simple (and atomic) {@link ~Schema#checkChild} and
  135. * {@link ~Schema#checkAttribute} on purpose.
  136. * One may imagine that schema should support defining more complex rules such as
  137. * "element `<x>` must be always followed by `<y>`".
  138. * While it is feasible to create an API which would enable feeding the schema with such definitions,
  139. * it is unrealistic to then expect that every editing feature will consider them when processing the model.
  140. * It is also unrealistic to expect that it will be done automatically by the schema and the editing engine themselves.
  141. *
  142. * For instance, let's get back to the "element `<x>` must be always followed by `<y>`" rule and this initial content:
  143. *
  144. * <$root>
  145. * <x>foo</x>
  146. * <y>bar[bom</y>
  147. * <z>bom]bar</z>
  148. * </$root>
  149. *
  150. * Now, imagine the user presses the "block quote" button. Usually it would wrap the two selected blocks (`<y>` and `<z>`)
  151. * with a `<blockQuote>` element:
  152. *
  153. * <$root>
  154. * <x>foo</x>
  155. * <blockQuote>
  156. * <y>bar[bom</y>
  157. * <z>bom]bar</z>
  158. * </blockQuote>
  159. * </$root>
  160. *
  161. * But it turns out that this creates an incorrect structure – `<x>` is not followed by `<y>` anymore.
  162. *
  163. * What should happen instead? There are at least 4 possible solutions: the block quote feature should not be
  164. * applicable in such a context, someone should create a new `<y>` right after `<x>`, `<x>` should be moved
  165. * inside `<blockQuote>` together with `<y>` or vice versa.
  166. *
  167. * While this is a relatively simple scenario (unlike most real-time collaboration scenarios),
  168. * it turns out that it's already hard to say what should happen and who should react to fix this content.
  169. *
  170. * Therefore, if your editor needs to implement such rules, it should do that through model's post-fixers
  171. * fixing incorrect content or actively prevent such situations (e.g. by disabling certain features).
  172. * It means that those constraints will be defined specifically for your scenario by your code which
  173. * makes their implementation much easier.
  174. *
  175. * So the answer for who and how should implement additional constraints is your features or your editor
  176. * through CKEditor 5's rich and open API.
  177. *
  178. * @mixes module:utils/observablemixin~ObservableMixin
  179. */
  180. export default class Schema {
  181. /**
  182. * Creates schema instance.
  183. */
  184. constructor() {
  185. this._sourceRules = {};
  186. this.decorate( 'checkChild' );
  187. this.decorate( 'checkAttribute' );
  188. this.on( 'checkAttribute', ( evt, args ) => {
  189. args[ 0 ] = new SchemaContext( args[ 0 ] );
  190. }, { priority: 'highest' } );
  191. this.on( 'checkChild', ( evt, args ) => {
  192. args[ 0 ] = new SchemaContext( args[ 0 ] );
  193. }, { priority: 'highest' } );
  194. }
  195. /**
  196. * Registers schema item. Can only be called once for every item name.
  197. *
  198. * @param {String} itemName
  199. * @param {module:engine/model/schema~SchemaItemDefinition} rules
  200. */
  201. register( itemName, rules ) {
  202. if ( this._sourceRules[ itemName ] ) {
  203. // TODO docs
  204. throw new CKEditorError( 'schema-cannot-register-item-twice: A single item cannot be registered twice in the schema.', {
  205. itemName
  206. } );
  207. }
  208. this._sourceRules[ itemName ] = [
  209. Object.assign( {}, rules )
  210. ];
  211. this._clearCache();
  212. }
  213. /**
  214. * Extends a {@link #register registered} item's rules.
  215. *
  216. * Extending properties such as `allowIn` will add more items to the existing properties,
  217. * while redefining properties such as `isBlock` will override the previously defined ones.
  218. *
  219. * schema.register( 'foo', {
  220. * allowIn: '$root',
  221. * isBlock: true;
  222. * } );
  223. * schema.extend( 'foo', {
  224. * allowIn: 'blockQuote',
  225. * isBlock: false
  226. * } );
  227. *
  228. * schema.getRule( 'foo' );
  229. * // {
  230. * // allowIn: [ '$root', 'blockQuote' ],
  231. * // isBlock: false
  232. * // }
  233. *
  234. * @param {String} itemName
  235. * @param {module:engine/model/schema~SchemaItemDefinition} rules
  236. */
  237. extend( itemName, rules ) {
  238. if ( !this._sourceRules[ itemName ] ) {
  239. // TODO docs
  240. throw new CKEditorError( 'schema-cannot-extend-missing-item: Cannot extend an item which was not registered yet.', {
  241. itemName
  242. } );
  243. }
  244. this._sourceRules[ itemName ].push( Object.assign( {}, rules ) );
  245. this._clearCache();
  246. }
  247. /**
  248. * Returns all registered items.
  249. *
  250. * @returns {Object.<String,module:engine/model/schema~SchemaCompiledItemDefinition>}
  251. */
  252. getRules() {
  253. if ( !this._compiledRules ) {
  254. this._compile();
  255. }
  256. return this._compiledRules;
  257. }
  258. /**
  259. * Returns a definition of the given item or `undefined` if item is not registered.
  260. *
  261. * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
  262. * @returns {module:engine/model/schema~SchemaCompiledItemDefinition}
  263. */
  264. getRule( item ) {
  265. let itemName;
  266. if ( typeof item == 'string' ) {
  267. itemName = item;
  268. } else if ( item.is && ( item.is( 'text' ) || item.is( 'textProxy' ) ) ) {
  269. itemName = '$text';
  270. }
  271. // Element or module:engine/model/schema~SchemaContextItem.
  272. else {
  273. itemName = item.name;
  274. }
  275. return this.getRules()[ itemName ];
  276. }
  277. /**
  278. * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
  279. */
  280. isRegistered( item ) {
  281. return !!this.getRule( item );
  282. }
  283. /**
  284. * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
  285. */
  286. isBlock( item ) {
  287. const rule = this.getRule( item );
  288. return !!( rule && rule.isBlock );
  289. }
  290. /**
  291. * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
  292. */
  293. isLimit( item ) {
  294. const rule = this.getRule( item );
  295. return !!( rule && rule.isLimit );
  296. }
  297. /**
  298. * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
  299. */
  300. isObject( item ) {
  301. const rule = this.getRule( item );
  302. return !!( rule && rule.isObject );
  303. }
  304. /**
  305. * Checks whether the given node (`child`) can be a child of the given context.
  306. *
  307. * schema.checkChild( model.document.getRoot(), paragraph ); // -> false
  308. *
  309. * schema.register( 'paragraph', {
  310. * allowIn: '$root'
  311. * } );
  312. * schema.checkChild( model.document.getRoot(), paragraph ); // -> true
  313. *
  314. * @fires checkChild
  315. * @param {module:engine/model/schema~SchemaContextDefinition} context Context in which the child will be checked.
  316. * @param {module:engine/model/node~Node|String} child The child to check.
  317. */
  318. checkChild( context, child ) {
  319. const rule = this.getRule( child );
  320. if ( !rule ) {
  321. return false;
  322. }
  323. return this._checkContextMatch( rule, context );
  324. }
  325. /**
  326. * Checks whether the given attribute can be applied in the given context (on the last
  327. * item of the context).
  328. *
  329. * schema.checkAttribute( textNode, 'bold' ); // -> false
  330. *
  331. * schema.extend( '$text', {
  332. * allowAttributes: 'bold'
  333. * } );
  334. * schema.checkAttribute( textNode, 'bold' ); // -> true
  335. *
  336. * @fires checkAttribute
  337. * @param {module:engine/model/schema~SchemaContextDefinition} context
  338. * @param {String} attributeName
  339. */
  340. checkAttribute( context, attributeName ) {
  341. const rule = this.getRule( context.last );
  342. if ( !rule ) {
  343. return false;
  344. }
  345. return rule.allowAttributes.includes( attributeName );
  346. }
  347. /**
  348. * Returns the lowest {@link module:engine/model/schema~Schema#isLimit limit element} containing the entire
  349. * selection or the root otherwise.
  350. *
  351. * @param {module:engine/model/selection~Selection} selection Selection which returns the common ancestor.
  352. * @returns {module:engine/model/element~Element}
  353. */
  354. getLimitElement( selection ) {
  355. // Find the common ancestor for all selection's ranges.
  356. let element = Array.from( selection.getRanges() )
  357. .reduce( ( node, range ) => {
  358. if ( !node ) {
  359. return range.getCommonAncestor();
  360. }
  361. return node.getCommonAncestor( range.getCommonAncestor() );
  362. }, null );
  363. while ( !this.isLimit( element ) ) {
  364. if ( element.parent ) {
  365. element = element.parent;
  366. } else {
  367. break;
  368. }
  369. }
  370. return element;
  371. }
  372. /**
  373. * Checks whether the attribute is allowed in selection:
  374. *
  375. * * if the selection is not collapsed, then checks if the attribute is allowed on any of nodes in that range,
  376. * * if the selection is collapsed, then checks if on the selection position there's a text with the
  377. * specified attribute allowed.
  378. *
  379. * @param {module:engine/model/selection~Selection} selection Selection which will be checked.
  380. * @param {String} attribute The name of the attribute to check.
  381. * @returns {Boolean}
  382. */
  383. checkAttributeInSelection( selection, attribute ) {
  384. if ( selection.isCollapsed ) {
  385. // Check whether schema allows for a text with the attribute in the selection.
  386. return this.checkAttribute( [ ...selection.getFirstPosition().getAncestors(), '$text' ], attribute );
  387. } else {
  388. const ranges = selection.getRanges();
  389. // For all ranges, check nodes in them until you find a node that is allowed to have the attribute.
  390. for ( const range of ranges ) {
  391. for ( const value of range ) {
  392. if ( this.checkAttribute( value.item, attribute ) ) {
  393. // If we found a node that is allowed to have the attribute, return true.
  394. return true;
  395. }
  396. }
  397. }
  398. }
  399. // If we haven't found such node, return false.
  400. return false;
  401. }
  402. /**
  403. * Transforms the given set of ranges into a set of ranges where the given attribute is allowed (and can be applied).
  404. *
  405. * @param {Array.<module:engine/model/range~Range>} ranges Ranges to be validated.
  406. * @param {String} attribute The name of the attribute to check.
  407. * @returns {Array.<module:engine/model/range~Range>} Ranges in which the attribute is allowed.
  408. */
  409. getValidRanges( ranges, attribute ) {
  410. const validRanges = [];
  411. for ( const range of ranges ) {
  412. let last = range.start;
  413. let from = range.start;
  414. const to = range.end;
  415. for ( const value of range.getWalker() ) {
  416. if ( !this.checkAttribute( value.item, attribute ) ) {
  417. if ( !from.isEqual( last ) ) {
  418. validRanges.push( new Range( from, last ) );
  419. }
  420. from = value.nextPosition;
  421. }
  422. last = value.nextPosition;
  423. }
  424. if ( from && !from.isEqual( to ) ) {
  425. validRanges.push( new Range( from, to ) );
  426. }
  427. }
  428. return validRanges;
  429. }
  430. /**
  431. * Removes attributes disallowed by the schema.
  432. *
  433. * @param {Iterable.<module:engine/model/node~Node>} nodes Nodes that will be filtered.
  434. * @param {module:engine/model/writer~Writer} writer
  435. */
  436. removeDisallowedAttributes( nodes, writer ) {
  437. for ( const node of nodes ) {
  438. for ( const attribute of node.getAttributeKeys() ) {
  439. if ( !this.checkAttribute( node, attribute ) ) {
  440. writer.removeAttribute( attribute, node );
  441. }
  442. }
  443. if ( node.is( 'element' ) ) {
  444. this.removeDisallowedAttributes( node.getChildren(), writer );
  445. }
  446. }
  447. }
  448. /**
  449. * @private
  450. */
  451. _clearCache() {
  452. this._compiledRules = null;
  453. }
  454. /**
  455. * @private
  456. */
  457. _compile() {
  458. const compiledRules = {};
  459. const sourceRules = this._sourceRules;
  460. const itemNames = Object.keys( sourceRules );
  461. for ( const itemName of itemNames ) {
  462. compiledRules[ itemName ] = compileBaseItemRule( sourceRules[ itemName ], itemName );
  463. }
  464. for ( const itemName of itemNames ) {
  465. compileAllowContentOf( compiledRules, itemName );
  466. }
  467. for ( const itemName of itemNames ) {
  468. compileAllowWhere( compiledRules, itemName );
  469. }
  470. for ( const itemName of itemNames ) {
  471. compileAllowAttributesOf( compiledRules, itemName );
  472. compileInheritPropertiesFrom( compiledRules, itemName );
  473. }
  474. for ( const itemName of itemNames ) {
  475. cleanUpAllowIn( compiledRules, itemName );
  476. cleanUpAllowAttributes( compiledRules, itemName );
  477. }
  478. this._compiledRules = compiledRules;
  479. }
  480. /**
  481. * @private
  482. * @param {module:engine/model/schema~SchemaCompiledItemDefinition} rule
  483. * @param {module:engine/model/schema~SchemaContext} context
  484. * @param {Number} contextItemIndex
  485. */
  486. _checkContextMatch( rule, context, contextItemIndex = context.length - 1 ) {
  487. const contextItem = context.getItem( contextItemIndex );
  488. if ( rule.allowIn.includes( contextItem.name ) ) {
  489. if ( contextItemIndex == 0 ) {
  490. return true;
  491. } else {
  492. const parentRule = this.getRule( contextItem );
  493. return this._checkContextMatch( parentRule, context, contextItemIndex - 1 );
  494. }
  495. } else {
  496. return false;
  497. }
  498. }
  499. }
  500. mix( Schema, ObservableMixin );
  501. /**
  502. * TODO
  503. *
  504. * @event checkChild
  505. */
  506. /**
  507. * TODO
  508. *
  509. * @event checkAttribute
  510. */
  511. /**
  512. * TODO
  513. *
  514. * @typedef {Object} module:engine/model/schema~SchemaItemDefinition
  515. */
  516. /**
  517. * TODO
  518. *
  519. * @typedef {Object} module:engine/model/schema~SchemaCompiledItemDefinition
  520. */
  521. /**
  522. * TODO
  523. */
  524. export class SchemaContext {
  525. /**
  526. * TODO
  527. *
  528. * @param {module:engine/model/schema~SchemaContextDefinition} context
  529. */
  530. constructor( context ) {
  531. if ( Array.isArray( context ) ) {
  532. this._items = context.map( mapContextItem );
  533. }
  534. // Item or position (PS. It's ok that Position#getAncestors() doesn't accept params).
  535. else {
  536. this._items = context.getAncestors( { includeSelf: true } ).map( mapContextItem );
  537. }
  538. }
  539. get length() {
  540. return this._items.length;
  541. }
  542. get last() {
  543. return this._items[ this._items.length - 1 ];
  544. }
  545. /**
  546. * Returns an iterator that iterates over all context items.
  547. *
  548. * @returns {Iterator.<module:engine/model/schema~SchemaContextItem>}
  549. */
  550. [ Symbol.iterator ]() {
  551. return this._items[ Symbol.iterator ]();
  552. }
  553. getItem( index ) {
  554. return this._items[ index ];
  555. }
  556. * getNames() {
  557. yield* this._items.map( item => item.name );
  558. }
  559. matchEnd( query ) {
  560. return Array.from( this.getNames() ).join( ' ' ).endsWith( query );
  561. }
  562. }
  563. /**
  564. * TODO
  565. *
  566. * @typedef {module:engine/model/node~Node|module:engine/model/position~Position|
  567. * Array.<String|module:engine/model/node~Node>} module:engine/model/schema~SchemaContextDefinition
  568. */
  569. /**
  570. * TODO
  571. *
  572. * @typedef {Object} module:engine/model/schema~SchemaContextItem
  573. */
  574. function compileBaseItemRule( sourceItemRules, itemName ) {
  575. const itemRule = {
  576. name: itemName,
  577. allowIn: [],
  578. allowContentOf: [],
  579. allowWhere: [],
  580. allowAttributes: [],
  581. allowAttributesOf: [],
  582. inheritTypesFrom: []
  583. };
  584. copyTypes( sourceItemRules, itemRule );
  585. copyProperty( sourceItemRules, itemRule, 'allowIn' );
  586. copyProperty( sourceItemRules, itemRule, 'allowContentOf' );
  587. copyProperty( sourceItemRules, itemRule, 'allowWhere' );
  588. copyProperty( sourceItemRules, itemRule, 'allowAttributes' );
  589. copyProperty( sourceItemRules, itemRule, 'allowAttributesOf' );
  590. copyProperty( sourceItemRules, itemRule, 'inheritTypesFrom' );
  591. makeInheritAllWork( sourceItemRules, itemRule );
  592. return itemRule;
  593. }
  594. function compileAllowContentOf( compiledRules, itemName ) {
  595. for ( const allowContentOfItemName of compiledRules[ itemName ].allowContentOf ) {
  596. // The allowContentOf property may point to an unregistered element.
  597. if ( compiledRules[ allowContentOfItemName ] ) {
  598. const allowedChildren = getAllowedChildren( compiledRules, allowContentOfItemName );
  599. allowedChildren.forEach( allowedItem => {
  600. allowedItem.allowIn.push( itemName );
  601. } );
  602. }
  603. }
  604. delete compiledRules[ itemName ].allowContentOf;
  605. }
  606. function compileAllowWhere( compiledRules, itemName ) {
  607. for ( const allowWhereItemName of compiledRules[ itemName ].allowWhere ) {
  608. const inheritFrom = compiledRules[ allowWhereItemName ];
  609. // The allowWhere property may point to an unregistered element.
  610. if ( inheritFrom ) {
  611. const allowedIn = inheritFrom.allowIn;
  612. compiledRules[ itemName ].allowIn.push( ...allowedIn );
  613. }
  614. }
  615. delete compiledRules[ itemName ].allowWhere;
  616. }
  617. function compileAllowAttributesOf( compiledRules, itemName ) {
  618. for ( const allowAttributeOfItem of compiledRules[ itemName ].allowAttributesOf ) {
  619. const inheritFrom = compiledRules[ allowAttributeOfItem ];
  620. if ( inheritFrom ) {
  621. const inheritAttributes = inheritFrom.allowAttributes;
  622. compiledRules[ itemName ].allowAttributes.push( ...inheritAttributes );
  623. }
  624. }
  625. delete compiledRules[ itemName ].allowAttributesOf;
  626. }
  627. function compileInheritPropertiesFrom( compiledRules, itemName ) {
  628. const item = compiledRules[ itemName ];
  629. for ( const inheritPropertiesOfItem of item.inheritTypesFrom ) {
  630. const inheritFrom = compiledRules[ inheritPropertiesOfItem ];
  631. if ( inheritFrom ) {
  632. const typeNames = Object.keys( inheritFrom ).filter( name => name.startsWith( 'is' ) );
  633. for ( const name of typeNames ) {
  634. if ( !( name in item ) ) {
  635. item[ name ] = inheritFrom[ name ];
  636. }
  637. }
  638. }
  639. }
  640. delete item.inheritTypesFrom;
  641. }
  642. // Remove items which weren't registered (because it may break some checks or we'd need to complicate them).
  643. // Make sure allowIn doesn't contain repeated values.
  644. function cleanUpAllowIn( compiledRules, itemName ) {
  645. const itemRule = compiledRules[ itemName ];
  646. const existingItems = itemRule.allowIn.filter( itemToCheck => compiledRules[ itemToCheck ] );
  647. itemRule.allowIn = Array.from( new Set( existingItems ) );
  648. }
  649. function cleanUpAllowAttributes( compiledRules, itemName ) {
  650. const itemRule = compiledRules[ itemName ];
  651. itemRule.allowAttributes = Array.from( new Set( itemRule.allowAttributes ) );
  652. }
  653. function copyTypes( sourceItemRules, itemRule ) {
  654. for ( const sourceItemRule of sourceItemRules ) {
  655. const typeNames = Object.keys( sourceItemRule ).filter( name => name.startsWith( 'is' ) );
  656. for ( const name of typeNames ) {
  657. itemRule[ name ] = sourceItemRule[ name ];
  658. }
  659. }
  660. }
  661. function copyProperty( sourceItemRules, itemRule, propertyName ) {
  662. for ( const sourceItemRule of sourceItemRules ) {
  663. if ( typeof sourceItemRule[ propertyName ] == 'string' ) {
  664. itemRule[ propertyName ].push( sourceItemRule[ propertyName ] );
  665. } else if ( Array.isArray( sourceItemRule[ propertyName ] ) ) {
  666. itemRule[ propertyName ].push( ...sourceItemRule[ propertyName ] );
  667. }
  668. }
  669. }
  670. function makeInheritAllWork( sourceItemRules, itemRule ) {
  671. for ( const sourceItemRule of sourceItemRules ) {
  672. const inheritFrom = sourceItemRule.inheritAllFrom;
  673. if ( inheritFrom ) {
  674. itemRule.allowContentOf.push( inheritFrom );
  675. itemRule.allowWhere.push( inheritFrom );
  676. itemRule.allowAttributesOf.push( inheritFrom );
  677. itemRule.inheritTypesFrom.push( inheritFrom );
  678. }
  679. }
  680. }
  681. function getAllowedChildren( compiledRules, itemName ) {
  682. const itemRule = compiledRules[ itemName ];
  683. return getValues( compiledRules ).filter( rule => rule.allowIn.includes( itemRule.name ) );
  684. }
  685. function getValues( obj ) {
  686. return Object.keys( obj ).map( key => obj[ key ] );
  687. }
  688. function mapContextItem( ctxItem ) {
  689. if ( typeof ctxItem == 'string' ) {
  690. return {
  691. name: ctxItem,
  692. * getAttributeKeys() {},
  693. getAttribute() {}
  694. };
  695. } else {
  696. return {
  697. // '$text' means text nodes and text proxies.
  698. name: ctxItem.is( 'element' ) ? ctxItem.name : '$text',
  699. * getAttributeKeys() {
  700. yield* ctxItem.getAttributeKeys();
  701. },
  702. getAttribute( key ) {
  703. return ctxItem.getAttribute( key );
  704. }
  705. };
  706. }
  707. }