schema.js 18 KB

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