8
0

schema.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  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 Position from './position';
  9. import Element from './element';
  10. import Range from './range';
  11. import clone from '@ckeditor/ckeditor5-utils/src/lib/lodash/clone';
  12. import isArray from '@ckeditor/ckeditor5-utils/src/lib/lodash/isArray';
  13. import isString from '@ckeditor/ckeditor5-utils/src/lib/lodash/isString';
  14. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  15. /**
  16. * Schema is a definition of the structure of the document. It allows to define which tree model items (element, text, etc.)
  17. * can be nested within which ones and which attributes can be applied to them. It's created during the run-time of the application,
  18. * typically by features. Also, the features can query the schema to learn what structure is allowed and act accordingly.
  19. *
  20. * For instance, if a feature wants to define that an attribute bold is allowed on the text it needs to register this rule like this:
  21. *
  22. * editor.document.schema.allow( '$text', 'bold' );
  23. *
  24. * Note: items prefixed with `$` are special group of items. By default, `Schema` defines three special items:
  25. *
  26. * * `$inline` represents all inline elements,
  27. * * `$text` is a sub-group of `$inline` and represents text nodes,
  28. * * `$block` represents block elements,
  29. * * `$root` represents default editing roots (those that allow only `$block`s inside them).
  30. *
  31. * When registering an item it's possible to tell that this item should inherit from some other existing item.
  32. * E.g. `p` can inherit from `$block`, so whenever given attribute is allowed on the `$block` it will automatically be
  33. * also allowed on the `p` element. By default, `$text` item already inherits from `$inline`.
  34. */
  35. export default class Schema {
  36. /**
  37. * Creates Schema instance.
  38. */
  39. constructor() {
  40. /**
  41. * Names of elements which have "object" nature. This means that these
  42. * elements should be treated as whole, never merged, can be selected from outside, etc.
  43. * Just like images, placeholder widgets, etc.
  44. *
  45. * @member {Set.<String>} module:engine/model/schema~Schema#objects
  46. */
  47. this.objects = new Set();
  48. /**
  49. * Names of elements to which editing operations should be limited.
  50. * For example, the <kbd>Enter</kbd> should not split such elements and
  51. * <kbd>Backspace</kbd> should not be able to leave or modify such elements.
  52. *
  53. * @member {Set.<String>} module:engine/model/schema~Schema#limits
  54. */
  55. this.limits = new Set();
  56. /**
  57. * Schema items registered in the schema.
  58. *
  59. * @private
  60. * @member {Map} module:engine/model/schema~Schema#_items
  61. */
  62. this._items = new Map();
  63. /**
  64. * Description of what entities are a base for given entity.
  65. *
  66. * @private
  67. * @member {Map} module:engine/model/schema~Schema#_extensionChains
  68. */
  69. this._extensionChains = new Map();
  70. // Register some default abstract entities.
  71. this.registerItem( '$root' );
  72. this.registerItem( '$block' );
  73. this.registerItem( '$inline' );
  74. this.registerItem( '$text', '$inline' );
  75. this.allow( { name: '$block', inside: '$root' } );
  76. this.allow( { name: '$inline', inside: '$block' } );
  77. this.limits.add( '$root' );
  78. // TMP!
  79. // Create an "all allowed" context in the schema for processing the pasted content.
  80. // Read: https://github.com/ckeditor/ckeditor5-engine/issues/638#issuecomment-255086588
  81. this.registerItem( '$clipboardHolder', '$root' );
  82. this.allow( { name: '$inline', inside: '$clipboardHolder' } );
  83. }
  84. /**
  85. * Allows given query in the schema.
  86. *
  87. * // Allow text with bold attribute in all P elements.
  88. * schema.registerItem( 'p', '$block' );
  89. * schema.allow( { name: '$text', attributes: 'bold', inside: 'p' } );
  90. *
  91. * // Allow header in Ps that are in DIVs
  92. * schema.registerItem( 'header', '$block' );
  93. * schema.registerItem( 'div', '$block' );
  94. * schema.allow( { name: 'header', inside: 'div p' } ); // inside: [ 'div', 'p' ] would also work.
  95. *
  96. * @param {module:engine/model/schema~SchemaQuery} query Allowed query.
  97. */
  98. allow( query ) {
  99. this._getItem( query.name ).allow( Schema._normalizeQueryPath( query.inside ), query.attributes );
  100. }
  101. /**
  102. * Disallows given query in the schema.
  103. *
  104. * @see #allow
  105. * @param {module:engine/model/schema~SchemaQuery} query Disallowed query.
  106. */
  107. disallow( query ) {
  108. this._getItem( query.name ).disallow( Schema._normalizeQueryPath( query.inside ), query.attributes );
  109. }
  110. /**
  111. * Makes a requirement in schema that entity represented by given item has to have given set of attributes. Some
  112. * elements in the model might require some attributes to be set. If multiple sets of attributes are required it
  113. * is enough that the entity fulfills only one set.
  114. *
  115. * // "a" element must either have "href" attribute or "name" attribute
  116. * schema.requireAttributes( 'a', [ 'href' ] );
  117. * schema.requireAttributes( 'a', [ 'name' ] );
  118. * // "img" element must have both "src" and "alt" attributes
  119. * schema.requireAttributes( 'img', [ 'src', 'alt' ] );
  120. *
  121. * @param {String} name Entity name.
  122. * @param {Array.<String>} attributes Attributes that has to be set on the entity to make it valid.
  123. */
  124. requireAttributes( name, attributes ) {
  125. this._getItem( name ).requireAttributes( attributes );
  126. }
  127. /**
  128. * Checks whether given query is allowed in schema.
  129. *
  130. * // Check whether bold text is allowed in header element.
  131. * let query = {
  132. * name: '$text',
  133. * attributes: 'bold',
  134. * inside: 'header'
  135. * };
  136. * if ( schema.check( query ) ) { ... }
  137. *
  138. * // Check whether bold and italic text can be placed at caret position.
  139. * let caretPos = editor.document.selection.getFirstPosition();
  140. * let query = {
  141. * name: '$text',
  142. * attributes: [ 'bold', 'italic' ],
  143. * inside: caretPos
  144. * };
  145. * if ( schema.check( query ) ) { ... }
  146. *
  147. * // Check whether image with alt, src and title is allowed in given elements path.
  148. * let quoteElement = new Element( 'quote' );
  149. * let query = {
  150. * name: 'img',
  151. * attributes: [ 'alt', 'src', 'title' ],
  152. * // It is possible to mix strings with elements.
  153. * // Query will check whether "img" can be inside "quoteElement" that is inside a block element.
  154. * inside: [ '$block', quoteElement ]
  155. * };
  156. * if ( schema.check( query ) ) { ... }
  157. *
  158. * @param {module:engine/model/schema~SchemaQuery} query Query to check.
  159. * @returns {Boolean} `true` if given query is allowed in schema, `false` otherwise.
  160. */
  161. check( query ) {
  162. if ( !this.hasItem( query.name ) ) {
  163. return false;
  164. }
  165. // If attributes property is a string or undefined, wrap it in an array for easier processing.
  166. if ( !isArray( query.attributes ) ) {
  167. query.attributes = [ query.attributes ];
  168. } else if ( query.attributes.length === 0 ) {
  169. // To simplify algorithms, when a SchemaItem path is added "without" attribute, it is added with
  170. // attribute equal to undefined. This means that algorithms can work the same way for specified attributes
  171. // and no-atrtibutes, but we have to fill empty array with "fake" undefined value for algorithms reasons.
  172. query.attributes.push( undefined );
  173. }
  174. // Normalize the path to an array of strings.
  175. const path = Schema._normalizeQueryPath( query.inside );
  176. // Get extension chain of given item and retrieve all schema items that are extended by given item.
  177. const schemaItems = this._extensionChains.get( query.name ).map( name => {
  178. return this._getItem( name );
  179. } );
  180. // First check if the query meets at required attributes for this item.
  181. if ( !this._getItem( query.name )._checkRequiredAttributes( query.attributes ) ) {
  182. return false;
  183. }
  184. // If there is matching disallow path, this query is not valid with schema.
  185. for ( const attribute of query.attributes ) {
  186. for ( const schemaItem of schemaItems ) {
  187. if ( schemaItem._hasMatchingPath( 'disallow', path, attribute ) ) {
  188. return false;
  189. }
  190. }
  191. }
  192. // At this point, the query is not disallowed.
  193. // If there are correct allow paths that match the query, this query is valid with schema.
  194. // Since we are supporting multiple attributes, we have to make sure that if attributes are set,
  195. // we have allowed paths for all of them.
  196. // Keep in mind that if the query has no attributes, query.attribute was converted to an array
  197. // with a single `undefined` value. This fits the algorithm well.
  198. for ( const attribute of query.attributes ) {
  199. let matched = false;
  200. for ( const schemaItem of schemaItems ) {
  201. if ( schemaItem._hasMatchingPath( 'allow', path, attribute ) ) {
  202. matched = true;
  203. break;
  204. }
  205. }
  206. // The attribute has not been matched, so it is not allowed by any schema item.
  207. // The query is disallowed.
  208. if ( !matched ) {
  209. return false;
  210. }
  211. }
  212. return true;
  213. }
  214. /**
  215. * Checks whether there is an item registered under given name in schema.
  216. *
  217. * @param itemName
  218. * @returns {Boolean}
  219. */
  220. hasItem( itemName ) {
  221. return this._items.has( itemName );
  222. }
  223. /**
  224. * Registers given item name in schema.
  225. *
  226. * // Register P element that should be treated like all block elements.
  227. * schema.registerItem( 'p', '$block' );
  228. *
  229. * @param {String} itemName Name to register.
  230. * @param [isExtending] If set, new item will extend item with given name.
  231. */
  232. registerItem( itemName, isExtending ) {
  233. if ( this.hasItem( itemName ) ) {
  234. /**
  235. * Item with specified name already exists in schema.
  236. *
  237. * @error model-schema-item-exists
  238. */
  239. throw new CKEditorError( 'model-schema-item-exists: Item with specified name already exists in schema.' );
  240. }
  241. if ( !!isExtending && !this.hasItem( isExtending ) ) {
  242. /**
  243. * Item with specified name does not exist in schema.
  244. *
  245. * @error model-schema-no-item
  246. */
  247. throw new CKEditorError( 'model-schema-no-item: Item with specified name does not exist in schema.' );
  248. }
  249. // Create new SchemaItem and add it to the items store.
  250. this._items.set( itemName, new SchemaItem( this ) );
  251. // Create an extension chain.
  252. // Extension chain has all item names that should be checked when that item is on path to check.
  253. // This simply means, that if item is not extending anything, it should have only itself in it's extension chain.
  254. // Since extending is not dynamic, we can simply get extension chain of extended item and expand it with registered name,
  255. // if the registered item is extending something.
  256. const chain = this.hasItem( isExtending ) ? this._extensionChains.get( isExtending ).concat( itemName ) : [ itemName ];
  257. this._extensionChains.set( itemName, chain );
  258. }
  259. /**
  260. * Checks whether item of given name is extending item of another given name.
  261. *
  262. * @param {String} childItemName Name of the child item.
  263. * @param {String} parentItemName Name of the parent item.
  264. * @returns {Boolean} `true` if child item extends parent item, `false` otherwise.
  265. */
  266. itemExtends( childItemName, parentItemName ) {
  267. if ( !this.hasItem( childItemName ) || !this.hasItem( parentItemName ) ) {
  268. /**
  269. * Item with specified name does not exist in schema.
  270. *
  271. * @error model-schema-no-item
  272. */
  273. throw new CKEditorError( 'model-schema-no-item: Item with specified name does not exist in schema.' );
  274. }
  275. const chain = this._extensionChains.get( childItemName );
  276. return chain.some( itemName => itemName == parentItemName );
  277. }
  278. /**
  279. * Checks whether the attribute is allowed in selection:
  280. *
  281. * * if the selection is not collapsed, then checks if the attribute is allowed on any of nodes in that range,
  282. * * if the selection is collapsed, then checks if on the selection position there's a text with the
  283. * specified attribute allowed.
  284. *
  285. * @param {module:engine/model/selection~Selection} selection Selection which will be checked.
  286. * @param {String} attribute The name of the attribute to check.
  287. * @returns {Boolean}
  288. */
  289. checkAttributeInSelection( selection, attribute ) {
  290. if ( selection.isCollapsed ) {
  291. // Check whether schema allows for a text with the attribute in the selection.
  292. return this.check( { name: '$text', inside: selection.getFirstPosition(), attributes: attribute } );
  293. } else {
  294. const ranges = selection.getRanges();
  295. // For all ranges, check nodes in them until you find a node that is allowed to have the attribute.
  296. for ( const range of ranges ) {
  297. for ( const value of range ) {
  298. // If returned item does not have name property, it is a TextFragment.
  299. const name = value.item.name || '$text';
  300. // Attribute should be checked together with existing attributes.
  301. // See https://github.com/ckeditor/ckeditor5-engine/issues/1110.
  302. const attributes = Array.from( value.item.getAttributeKeys() ).concat( attribute );
  303. if ( this.check( { name, inside: value.previousPosition, attributes } ) ) {
  304. // If we found a node that is allowed to have the attribute, return true.
  305. return true;
  306. }
  307. }
  308. }
  309. }
  310. // If we haven't found such node, return false.
  311. return false;
  312. }
  313. /**
  314. * Transforms the given set ranges into a set of ranges where the given attribute is allowed (and can be applied).
  315. *
  316. * @param {Array.<module:engine/model/range~Range>} ranges Ranges to be validated.
  317. * @param {String} attribute The name of the attribute to check.
  318. * @returns {Array.<module:engine/model/range~Range>} Ranges in which the attribute is allowed.
  319. */
  320. getValidRanges( ranges, attribute ) {
  321. const validRanges = [];
  322. for ( const range of ranges ) {
  323. let last = range.start;
  324. let from = range.start;
  325. const to = range.end;
  326. for ( const value of range.getWalker() ) {
  327. const name = value.item.name || '$text';
  328. const itemPosition = Position.createBefore( value.item );
  329. if ( !this.check( { name, inside: itemPosition, attributes: attribute } ) ) {
  330. if ( !from.isEqual( last ) ) {
  331. validRanges.push( new Range( from, last ) );
  332. }
  333. from = value.nextPosition;
  334. }
  335. last = value.nextPosition;
  336. }
  337. if ( from && !from.isEqual( to ) ) {
  338. validRanges.push( new Range( from, to ) );
  339. }
  340. }
  341. return validRanges;
  342. }
  343. /**
  344. * Returns the lowest {@link module:engine/model/schema~Schema#limits limit element} containing the entire
  345. * selection or the root otherwise.
  346. *
  347. * @param {module:engine/model/selection~Selection} selection Selection which returns the common ancestor.
  348. * @returns {module:engine/model/element~Element}
  349. */
  350. getLimitElement( selection ) {
  351. // Find the common ancestor for all selection's ranges.
  352. let element = Array.from( selection.getRanges() )
  353. .reduce( ( node, range ) => {
  354. if ( !node ) {
  355. return range.getCommonAncestor();
  356. }
  357. return node.getCommonAncestor( range.getCommonAncestor() );
  358. }, null );
  359. while ( !this.limits.has( element.name ) ) {
  360. if ( element.parent ) {
  361. element = element.parent;
  362. } else {
  363. break;
  364. }
  365. }
  366. return element;
  367. }
  368. /**
  369. * Removes disallowed by {@link module:engine/model/schema~Schema schema} attributes from given nodes.
  370. * When {@link module:engine/model/batch~Batch batch} parameter is provided then attributes will be removed
  371. * by creating {@link module:engine/model/delta/attributedelta~AttributeDelta attributeDeltas} otherwise
  372. * attributes will be removed directly from provided nodes using {@link module:engine/model/node~Node node} API.
  373. *
  374. * @param {Iterable.<module:engine/model/node~Node>} nodes Nodes that will be filtered.
  375. * @param {module:engine/model/schema~SchemaPath} inside Path inside which schema will be checked.
  376. * @param {module:engine/model/batch~Batch} [batch] Batch to which the deltas will be added.
  377. */
  378. removeDisallowedAttributes( nodes, inside, batch ) {
  379. for ( const node of nodes ) {
  380. const name = node.is( 'text' ) ? '$text' : node.name;
  381. const attributes = Array.from( node.getAttributeKeys() );
  382. const normalizedQueryPath = Schema._normalizeQueryPath( inside );
  383. const queryPath = normalizedQueryPath.join( ' ' );
  384. // When node with attributes is not allowed in current position.
  385. if ( !this.check( { name, attributes, inside: queryPath } ) ) {
  386. // Let's remove attributes one by one.
  387. // This should be improved to check all combination of attributes.
  388. for ( const attribute of node.getAttributeKeys() ) {
  389. if ( !this.check( { name, attributes: attribute, inside: queryPath } ) ) {
  390. if ( batch ) {
  391. batch.removeAttribute( node, attribute );
  392. } else {
  393. node.removeAttribute( attribute );
  394. }
  395. }
  396. }
  397. }
  398. if ( node.is( 'element' ) ) {
  399. const newQueryPath = normalizedQueryPath.concat( [ node.name ] );
  400. this.removeDisallowedAttributes( node.getChildren(), newQueryPath, batch );
  401. }
  402. }
  403. }
  404. /**
  405. * Returns {@link module:engine/model/schema~SchemaItem schema item} that was registered in the schema under given name.
  406. * If item has not been found, throws error.
  407. *
  408. * @private
  409. * @param {String} itemName Name to look for in schema.
  410. * @returns {module:engine/model/schema~SchemaItem} Schema item registered under given name.
  411. */
  412. _getItem( itemName ) {
  413. if ( !this.hasItem( itemName ) ) {
  414. /**
  415. * Item with specified name does not exist in schema.
  416. *
  417. * @error model-schema-no-item
  418. */
  419. throw new CKEditorError( 'model-schema-no-item: Item with specified name does not exist in schema.' );
  420. }
  421. return this._items.get( itemName );
  422. }
  423. /**
  424. * Normalizes a path to an entity by converting it from {@link module:engine/model/schema~SchemaPath} to an array of strings.
  425. *
  426. * @protected
  427. * @param {module:engine/model/schema~SchemaPath} path Path to normalize.
  428. * @returns {Array.<String>} Normalized path.
  429. */
  430. static _normalizeQueryPath( path ) {
  431. let normalized = [];
  432. if ( isArray( path ) ) {
  433. for ( const pathItem of path ) {
  434. if ( pathItem instanceof Element ) {
  435. normalized.push( pathItem.name );
  436. } else if ( isString( pathItem ) ) {
  437. normalized.push( pathItem );
  438. }
  439. }
  440. } else if ( path instanceof Position ) {
  441. let parent = path.parent;
  442. while ( parent !== null ) {
  443. normalized.push( parent.name );
  444. parent = parent.parent;
  445. }
  446. normalized.reverse();
  447. } else if ( isString( path ) ) {
  448. normalized = path.split( ' ' );
  449. }
  450. return normalized;
  451. }
  452. }
  453. /**
  454. * SchemaItem is a singular registry item in {@link module:engine/model/schema~Schema} that groups and holds allow/disallow rules for
  455. * one entity. This class is used internally in {@link module:engine/model/schema~Schema} and should not be used outside it.
  456. *
  457. * @see module:engine/model/schema~Schema
  458. * @protected
  459. */
  460. export class SchemaItem {
  461. /**
  462. * Creates SchemaItem instance.
  463. *
  464. * @param {module:engine/model/schema~Schema} schema Schema instance that owns this item.
  465. */
  466. constructor( schema ) {
  467. /**
  468. * Schema instance that owns this item.
  469. *
  470. * @private
  471. * @member {module:engine/model/schema~Schema} module:engine/model/schema~SchemaItem#_schema
  472. */
  473. this._schema = schema;
  474. /**
  475. * Paths in which the entity, represented by this item, is allowed.
  476. *
  477. * @private
  478. * @member {Array} module:engine/model/schema~SchemaItem#_allowed
  479. */
  480. this._allowed = [];
  481. /**
  482. * Paths in which the entity, represented by this item, is disallowed.
  483. *
  484. * @private
  485. * @member {Array} module:engine/model/schema~SchemaItem#_disallowed
  486. */
  487. this._disallowed = [];
  488. /**
  489. * Attributes that are required by the entity represented by this item.
  490. *
  491. * @protected
  492. * @member {Array} module:engine/model/schema~SchemaItem#_requiredAttributes
  493. */
  494. this._requiredAttributes = [];
  495. }
  496. /**
  497. * Allows entity, represented by this item, to be in given path.
  498. *
  499. * @param {Array.<String>} path Path in which entity is allowed.
  500. * @param {Array.<String>|String} [attributes] If set, this path will be used only for entities that have attribute(s) with this key.
  501. */
  502. allow( path, attributes ) {
  503. this._addPath( '_allowed', path, attributes );
  504. }
  505. /**
  506. * Disallows entity, represented by this item, to be in given path.
  507. *
  508. * @param {Array.<String>} path Path in which entity is disallowed.
  509. * @param {Array.<String>|String} [attributes] If set, this path will be used only for entities that have an attribute(s) with this key.
  510. */
  511. disallow( path, attributes ) {
  512. this._addPath( '_disallowed', path, attributes );
  513. }
  514. /**
  515. * Specifies that the entity, to be valid, requires given attributes set. It is possible to register multiple
  516. * different attributes set. If there are more than one attributes set required, the entity will be valid if
  517. * at least one of them is fulfilled.
  518. *
  519. * @param {Array.<String>} attributes Attributes that has to be set on the entity to make it valid.
  520. */
  521. requireAttributes( attributes ) {
  522. this._requiredAttributes.push( attributes );
  523. }
  524. /**
  525. * Custom toJSON method to solve child-parent circular dependencies.
  526. *
  527. * @returns {Object} Clone of this object with the parent property replaced with its name.
  528. */
  529. toJSON() {
  530. const json = clone( this );
  531. // Due to circular references we need to remove parent reference.
  532. json._schema = '[model.Schema]';
  533. return json;
  534. }
  535. /**
  536. * Adds path to the SchemaItem instance.
  537. *
  538. * @private
  539. * @param {String} member Name of the array member into which the path will be added. Possible values are `_allowed` or `_disallowed`.
  540. * @param {Array.<String>} path Path to add.
  541. * @param {Array.<String>|String} [attributes] If set, this path will be used only for entities that have attribute(s) with this key.
  542. */
  543. _addPath( member, path, attributes ) {
  544. path = path.slice();
  545. if ( !isArray( attributes ) ) {
  546. attributes = [ attributes ];
  547. }
  548. for ( const attribute of attributes ) {
  549. this[ member ].push( { path, attribute } );
  550. }
  551. }
  552. /**
  553. * Returns all paths of given type that were previously registered in the item.
  554. *
  555. * @private
  556. * @param {String} type Paths' type. Possible values are `allow` or `disallow`.
  557. * @param {String} [attribute] If set, only paths registered for given attribute will be returned.
  558. * @returns {Array} Paths registered in the item.
  559. */
  560. _getPaths( type, attribute ) {
  561. const source = type === 'allow' ? this._allowed : this._disallowed;
  562. const paths = [];
  563. for ( const item of source ) {
  564. if ( item.attribute === attribute ) {
  565. paths.push( item.path );
  566. }
  567. }
  568. return paths;
  569. }
  570. /**
  571. * Checks whether given set of attributes fulfills required attributes of this item.
  572. *
  573. * @protected
  574. * @see module:engine/model/schema~SchemaItem#requireAttributes
  575. * @param {Array.<String>} attributesToCheck Attributes to check.
  576. * @returns {Boolean} `true` if given set or attributes fulfills required attributes, `false` otherwise.
  577. */
  578. _checkRequiredAttributes( attributesToCheck ) {
  579. let found = true;
  580. for ( const attributeSet of this._requiredAttributes ) {
  581. found = true;
  582. for ( const attribute of attributeSet ) {
  583. if ( attributesToCheck.indexOf( attribute ) == -1 ) {
  584. found = false;
  585. break;
  586. }
  587. }
  588. if ( found ) {
  589. break;
  590. }
  591. }
  592. return found;
  593. }
  594. /**
  595. * Checks whether this item has any registered path of given type that matches the provided path.
  596. *
  597. * @protected
  598. * @param {String} type Paths' type. Possible values are `allow` or `disallow`.
  599. * @param {Array.<String>} pathToCheck Path to check.
  600. * @param {String} [attribute] If set, only paths registered for given attribute will be checked.
  601. * @returns {Boolean} `true` if item has any registered matching path, `false` otherwise.
  602. */
  603. _hasMatchingPath( type, pathToCheck, attribute ) {
  604. const registeredPaths = this._getPaths( type, attribute );
  605. for ( const registeredPathPath of registeredPaths ) {
  606. if ( matchPaths( this._schema, pathToCheck, registeredPathPath ) ) {
  607. return true;
  608. }
  609. }
  610. return false;
  611. }
  612. }
  613. /**
  614. * Object with query used by {@link module:engine/model/schema~Schema} to query schema or add allow/disallow rules to schema.
  615. *
  616. * @typedef {Object} module:engine/model/schema~SchemaQuery
  617. * @property {String} name Entity name.
  618. * @property {module:engine/model/schema~SchemaPath} inside Path inside which the entity is placed.
  619. * @property {Array.<String>|String} [attributes] If set, the query applies only to entities that has attribute(s) with given key.
  620. */
  621. /**
  622. * Path to an entity, begins from the top-most ancestor. Can be passed in multiple formats. Internally, normalized to
  623. * an array of strings. If string is passed, entities from the path should be divided by ` ` (space character). If
  624. * an array is passed, unrecognized items are skipped. If position is passed, it is assumed that the entity is at given position.
  625. *
  626. * @typedef {String|Array.<String|module:engine/model/element~Element>|module:engine/model/position~Position}
  627. * module:engine/model/schema~SchemaPath
  628. */
  629. // Checks whether the given pathToCheck and registeredPath right ends match.
  630. //
  631. // pathToCheck: C, D
  632. // registeredPath: A, B, C, D
  633. // result: OK
  634. //
  635. // pathToCheck: A, B, C
  636. // registeredPath: A, B, C, D
  637. // result: NOK
  638. //
  639. // Note – when matching paths, element extension chains (inheritance) are taken into consideration.
  640. //
  641. // @param {Schema} schema
  642. // @param {Array.<String>} pathToCheck
  643. // @param {Array.<String>} registeredPath
  644. function matchPaths( schema, pathToCheck, registeredPath ) {
  645. // Start checking from the right end of both tables.
  646. let registeredPathIndex = registeredPath.length - 1;
  647. let pathToCheckIndex = pathToCheck.length - 1;
  648. // And finish once reaching an end of the shorter table.
  649. while ( registeredPathIndex >= 0 && pathToCheckIndex >= 0 ) {
  650. const checkName = pathToCheck[ pathToCheckIndex ];
  651. // Fail when checking a path which contains element which aren't even registered to the schema.
  652. if ( !schema.hasItem( checkName ) ) {
  653. return false;
  654. }
  655. const extChain = schema._extensionChains.get( checkName );
  656. if ( extChain.includes( registeredPath[ registeredPathIndex ] ) ) {
  657. registeredPathIndex--;
  658. pathToCheckIndex--;
  659. } else {
  660. return false;
  661. }
  662. }
  663. return true;
  664. }