8
0

schema.js 20 KB

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