8
0

schema.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  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 clone from '@ckeditor/ckeditor5-utils/src/lib/lodash/clone';
  11. import isArray from '@ckeditor/ckeditor5-utils/src/lib/lodash/isArray';
  12. import isString from '@ckeditor/ckeditor5-utils/src/lib/lodash/isString';
  13. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  14. import Range from './range';
  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. if ( this.check( { name, inside: value.previousPosition, attributes: attribute } ) ) {
  301. // If we found a node that is allowed to have the attribute, return true.
  302. return true;
  303. }
  304. }
  305. }
  306. }
  307. // If we haven't found such node, return false.
  308. return false;
  309. }
  310. /**
  311. * Transforms the given set ranges into a set of ranges where the given attribute is allowed (and can be applied).
  312. *
  313. * @param {Array.<module:engine/model/range~Range>} ranges Ranges to be validated.
  314. * @param {String} attribute The name of the attribute to check.
  315. * @returns {Array.<module:engine/model/range~Range>} Ranges in which the attribute is allowed.
  316. */
  317. getValidRanges( ranges, attribute ) {
  318. const validRanges = [];
  319. for ( const range of ranges ) {
  320. let last = range.start;
  321. let from = range.start;
  322. const to = range.end;
  323. for ( const value of range.getWalker() ) {
  324. const name = value.item.name || '$text';
  325. const itemPosition = Position.createBefore( value.item );
  326. if ( !this.check( { name, inside: itemPosition, attributes: attribute } ) ) {
  327. if ( !from.isEqual( last ) ) {
  328. validRanges.push( new Range( from, last ) );
  329. }
  330. from = value.nextPosition;
  331. }
  332. last = value.nextPosition;
  333. }
  334. if ( from && !from.isEqual( to ) ) {
  335. validRanges.push( new Range( from, to ) );
  336. }
  337. }
  338. return validRanges;
  339. }
  340. /**
  341. * Returns the lowest limit element defined in {@link module:engine/model/schema~Schema#limits} for passed selection.
  342. *
  343. * @param {module:engine/model/selection~Selection} selection Selection which will be checked.
  344. * @returns {module:engine/model/element~Element}
  345. */
  346. getLimitElement( selection ) {
  347. let element = selection.getFirstRange().getCommonAncestor();
  348. while ( !this.limits.has( element.name ) ) {
  349. if ( element.parent ) {
  350. element = element.parent;
  351. } else {
  352. break;
  353. }
  354. }
  355. return element;
  356. }
  357. /**
  358. * Returns {@link module:engine/model/schema~SchemaItem schema item} that was registered in the schema under given name.
  359. * If item has not been found, throws error.
  360. *
  361. * @private
  362. * @param {String} itemName Name to look for in schema.
  363. * @returns {module:engine/model/schema~SchemaItem} Schema item registered under given name.
  364. */
  365. _getItem( itemName ) {
  366. if ( !this.hasItem( itemName ) ) {
  367. /**
  368. * Item with specified name does not exist in schema.
  369. *
  370. * @error model-schema-no-item
  371. */
  372. throw new CKEditorError( 'model-schema-no-item: Item with specified name does not exist in schema.' );
  373. }
  374. return this._items.get( itemName );
  375. }
  376. /**
  377. * Normalizes a path to an entity by converting it from {@link module:engine/model/schema~SchemaPath} to an array of strings.
  378. *
  379. * @protected
  380. * @param {module:engine/model/schema~SchemaPath} path Path to normalize.
  381. * @returns {Array.<String>} Normalized path.
  382. */
  383. static _normalizeQueryPath( path ) {
  384. let normalized = [];
  385. if ( isArray( path ) ) {
  386. for ( const pathItem of path ) {
  387. if ( pathItem instanceof Element ) {
  388. normalized.push( pathItem.name );
  389. } else if ( isString( pathItem ) ) {
  390. normalized.push( pathItem );
  391. }
  392. }
  393. } else if ( path instanceof Position ) {
  394. let parent = path.parent;
  395. while ( parent !== null ) {
  396. normalized.push( parent.name );
  397. parent = parent.parent;
  398. }
  399. normalized.reverse();
  400. } else if ( isString( path ) ) {
  401. normalized = path.split( ' ' );
  402. }
  403. return normalized;
  404. }
  405. }
  406. /**
  407. * SchemaItem is a singular registry item in {@link module:engine/model/schema~Schema} that groups and holds allow/disallow rules for
  408. * one entity. This class is used internally in {@link module:engine/model/schema~Schema} and should not be used outside it.
  409. *
  410. * @see module:engine/model/schema~Schema
  411. * @protected
  412. */
  413. export class SchemaItem {
  414. /**
  415. * Creates SchemaItem instance.
  416. *
  417. * @param {module:engine/model/schema~Schema} schema Schema instance that owns this item.
  418. */
  419. constructor( schema ) {
  420. /**
  421. * Schema instance that owns this item.
  422. *
  423. * @private
  424. * @member {module:engine/model/schema~Schema} module:engine/model/schema~SchemaItem#_schema
  425. */
  426. this._schema = schema;
  427. /**
  428. * Paths in which the entity, represented by this item, is allowed.
  429. *
  430. * @private
  431. * @member {Array} module:engine/model/schema~SchemaItem#_allowed
  432. */
  433. this._allowed = [];
  434. /**
  435. * Paths in which the entity, represented by this item, is disallowed.
  436. *
  437. * @private
  438. * @member {Array} module:engine/model/schema~SchemaItem#_disallowed
  439. */
  440. this._disallowed = [];
  441. /**
  442. * Attributes that are required by the entity represented by this item.
  443. *
  444. * @protected
  445. * @member {Array} module:engine/model/schema~SchemaItem#_requiredAttributes
  446. */
  447. this._requiredAttributes = [];
  448. }
  449. /**
  450. * Allows entity, represented by this item, to be in given path.
  451. *
  452. * @param {Array.<String>} path Path in which entity is allowed.
  453. * @param {Array.<String>|String} [attributes] If set, this path will be used only for entities that have attribute(s) with this key.
  454. */
  455. allow( path, attributes ) {
  456. this._addPath( '_allowed', path, attributes );
  457. }
  458. /**
  459. * Disallows entity, represented by this item, to be in given path.
  460. *
  461. * @param {Array.<String>} path Path in which entity is disallowed.
  462. * @param {Array.<String>|String} [attributes] If set, this path will be used only for entities that have an attribute(s) with this key.
  463. */
  464. disallow( path, attributes ) {
  465. this._addPath( '_disallowed', path, attributes );
  466. }
  467. /**
  468. * Specifies that the entity, to be valid, requires given attributes set. It is possible to register multiple
  469. * different attributes set. If there are more than one attributes set required, the entity will be valid if
  470. * at least one of them is fulfilled.
  471. *
  472. * @param {Array.<String>} attributes Attributes that has to be set on the entity to make it valid.
  473. */
  474. requireAttributes( attributes ) {
  475. this._requiredAttributes.push( attributes );
  476. }
  477. /**
  478. * Custom toJSON method to solve child-parent circular dependencies.
  479. *
  480. * @returns {Object} Clone of this object with the parent property replaced with its name.
  481. */
  482. toJSON() {
  483. const json = clone( this );
  484. // Due to circular references we need to remove parent reference.
  485. json._schema = '[model.Schema]';
  486. return json;
  487. }
  488. /**
  489. * Adds path to the SchemaItem instance.
  490. *
  491. * @private
  492. * @param {String} member Name of the array member into which the path will be added. Possible values are `_allowed` or `_disallowed`.
  493. * @param {Array.<String>} path Path to add.
  494. * @param {Array.<String>|String} [attributes] If set, this path will be used only for entities that have attribute(s) with this key.
  495. */
  496. _addPath( member, path, attributes ) {
  497. path = path.slice();
  498. if ( !isArray( attributes ) ) {
  499. attributes = [ attributes ];
  500. }
  501. for ( const attribute of attributes ) {
  502. this[ member ].push( { path, attribute } );
  503. }
  504. }
  505. /**
  506. * Returns all paths of given type that were previously registered in the item.
  507. *
  508. * @private
  509. * @param {String} type Paths' type. Possible values are `allow` or `disallow`.
  510. * @param {String} [attribute] If set, only paths registered for given attribute will be returned.
  511. * @returns {Array} Paths registered in the item.
  512. */
  513. _getPaths( type, attribute ) {
  514. const source = type === 'allow' ? this._allowed : this._disallowed;
  515. const paths = [];
  516. for ( const item of source ) {
  517. if ( item.attribute === attribute ) {
  518. paths.push( item.path );
  519. }
  520. }
  521. return paths;
  522. }
  523. /**
  524. * Checks whether given set of attributes fulfills required attributes of this item.
  525. *
  526. * @protected
  527. * @see module:engine/model/schema~SchemaItem#requireAttributes
  528. * @param {Array.<String>} attributesToCheck Attributes to check.
  529. * @returns {Boolean} `true` if given set or attributes fulfills required attributes, `false` otherwise.
  530. */
  531. _checkRequiredAttributes( attributesToCheck ) {
  532. let found = true;
  533. for ( const attributeSet of this._requiredAttributes ) {
  534. found = true;
  535. for ( const attribute of attributeSet ) {
  536. if ( attributesToCheck.indexOf( attribute ) == -1 ) {
  537. found = false;
  538. break;
  539. }
  540. }
  541. if ( found ) {
  542. break;
  543. }
  544. }
  545. return found;
  546. }
  547. /**
  548. * Checks whether this item has any registered path of given type that matches the provided path.
  549. *
  550. * @protected
  551. * @param {String} type Paths' type. Possible values are `allow` or `disallow`.
  552. * @param {Array.<String>} pathToCheck Path to check.
  553. * @param {String} [attribute] If set, only paths registered for given attribute will be checked.
  554. * @returns {Boolean} `true` if item has any registered matching path, `false` otherwise.
  555. */
  556. _hasMatchingPath( type, pathToCheck, attribute ) {
  557. const registeredPaths = this._getPaths( type, attribute );
  558. for ( const registeredPathPath of registeredPaths ) {
  559. if ( matchPaths( this._schema, pathToCheck, registeredPathPath ) ) {
  560. return true;
  561. }
  562. }
  563. return false;
  564. }
  565. }
  566. /**
  567. * Object with query used by {@link module:engine/model/schema~Schema} to query schema or add allow/disallow rules to schema.
  568. *
  569. * @typedef {Object} module:engine/model/schema~SchemaQuery
  570. * @property {String} name Entity name.
  571. * @property {module:engine/model/schema~SchemaPath} inside Path inside which the entity is placed.
  572. * @property {Array.<String>|String} [attributes] If set, the query applies only to entities that has attribute(s) with given key.
  573. */
  574. /**
  575. * Path to an entity, begins from the top-most ancestor. Can be passed in multiple formats. Internally, normalized to
  576. * an array of strings. If string is passed, entities from the path should be divided by ` ` (space character). If
  577. * an array is passed, unrecognized items are skipped. If position is passed, it is assumed that the entity is at given position.
  578. *
  579. * @typedef {String|Array.<String|module:engine/model/element~Element>|module:engine/model/position~Position}
  580. * module:engine/model/schema~SchemaPath
  581. */
  582. // Checks whether the given pathToCheck and registeredPath right ends match.
  583. //
  584. // pathToCheck: C, D
  585. // registeredPath: A, B, C, D
  586. // result: OK
  587. //
  588. // pathToCheck: A, B, C
  589. // registeredPath: A, B, C, D
  590. // result: NOK
  591. //
  592. // Note – when matching paths, element extension chains (inheritance) are taken into consideration.
  593. //
  594. // @param {Schema} schema
  595. // @param {Array.<String>} pathToCheck
  596. // @param {Array.<String>} registeredPath
  597. function matchPaths( schema, pathToCheck, registeredPath ) {
  598. // Start checking from the right end of both tables.
  599. let registeredPathIndex = registeredPath.length - 1;
  600. let pathToCheckIndex = pathToCheck.length - 1;
  601. // And finish once reaching an end of the shorter table.
  602. while ( registeredPathIndex >= 0 && pathToCheckIndex >= 0 ) {
  603. const checkName = pathToCheck[ pathToCheckIndex ];
  604. // Fail when checking a path which contains element which aren't even registered to the schema.
  605. if ( !schema.hasItem( checkName ) ) {
  606. return false;
  607. }
  608. const extChain = schema._extensionChains.get( checkName );
  609. if ( extChain.includes( registeredPath[ registeredPathIndex ] ) ) {
  610. registeredPathIndex--;
  611. pathToCheckIndex--;
  612. } else {
  613. return false;
  614. }
  615. }
  616. return true;
  617. }