schema.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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 clone from '../lib/lodash/clone.js';
  7. import CKEditorError from '../ckeditorerror.js';
  8. /**
  9. * SchemaItem is a singular registry item in {@link core.treeModel.Schema} that groups and holds allow/disallow rules for
  10. * one entity. This class is used internally in {@link core.treeModel.Schema} and should not be used outside it.
  11. *
  12. * @see core.treeModel.Schema
  13. * @memberOf core.treeModel
  14. */
  15. export class SchemaItem {
  16. /**
  17. * Creates SchemaItem instance.
  18. *
  19. * @param {core.treeModel.Schema} schema Schema instance that owns this item.
  20. */
  21. constructor( schema ) {
  22. /**
  23. * Schema instance that owns this item.
  24. *
  25. * @member {core.treeModel.Schema} core.treeModel.SchemaItem#_schema
  26. * @private
  27. */
  28. this._schema = schema;
  29. /**
  30. * Paths in which the entity, represented by this item, is allowed.
  31. *
  32. * @member {Array} core.treeModel.SchemaItem#_allowed
  33. * @private
  34. */
  35. this._allowed = [];
  36. /**
  37. * Paths in which the entity, represented by this item, is disallowed.
  38. *
  39. * @member {Array} core.treeModel.SchemaItem#_disallowed
  40. * @private
  41. */
  42. this._disallowed = [];
  43. }
  44. /**
  45. * Allows entity, represented by this item, to be in given path.
  46. *
  47. * @param {Array.<String>|String} path Path in which entity is allowed. String with item names separated by spaces may be passed.
  48. * @param {String} [attribute] If set, this path will be used only for entities that have an attribute with this key.
  49. */
  50. addAllowed( path, attribute ) {
  51. this._addPath( '_allowed', path, attribute );
  52. }
  53. /**
  54. * Disallows entity, represented by this item, to be in given path.
  55. *
  56. * @param {Array.<String>|String} path Path in which entity is disallowed. String with item names separated by spaces may be passed.
  57. * @param {String} [attribute] If set, this path will be used only for entities that have an attribute with this key.
  58. */
  59. addDisallowed( path, attribute ) {
  60. this._addPath( '_disallowed', path, attribute );
  61. }
  62. /**
  63. * Adds path to the SchemaItem instance.
  64. *
  65. * @param {String} member Name of the array member into which the path will be added. Possible values are `_allowed` or `_disallowed`.
  66. * @param {Array.<String>|String} path Path to be added. String with item names separated by spaces may be passed.
  67. * @param {String} [attribute] If set, this path will be used only for entities that have an attribute with this key.
  68. * @private
  69. */
  70. _addPath( member, path, attribute ) {
  71. if ( typeof path === 'string' ) {
  72. path = path.split( ' ' );
  73. }
  74. path = path.slice();
  75. this[ member ].push( { path, attribute } );
  76. }
  77. /**
  78. * Returns all paths of given type that were previously registered in the item.
  79. *
  80. * @param {String} type Paths' type. Possible values are `ALLOW` or `DISALLOW`.
  81. * @param {String} [attribute] If set, only paths registered for given attribute will be returned.
  82. * @returns {Array} Paths registered in the item.
  83. * @private
  84. */
  85. _getPaths( type, attribute ) {
  86. let source = type === 'ALLOW' ? this._allowed : this._disallowed;
  87. let paths = [];
  88. for ( let item of source ) {
  89. if ( item.attribute === attribute ) {
  90. paths.push( item.path.slice() );
  91. }
  92. }
  93. return paths;
  94. }
  95. /**
  96. * Checks whether this item has any registered path of given type that matches provided path.
  97. *
  98. * @param {String} type Paths' type. Possible values are `ALLOW` or `DISALLOW`.
  99. * @param {Array.<String>} checkPath Path to check.
  100. * @param {String} [attribute] If set, only paths registered for given attribute will be returned.
  101. * @returns {Boolean} `true` if item has any registered matching path, `false` otherwise.
  102. * @private
  103. */
  104. _hasMatchingPath( type, checkPath, attribute ) {
  105. const itemPaths = this._getPaths( type, attribute );
  106. checkPath = checkPath.slice();
  107. // We check every path registered (possibly with given attribute) in the item.
  108. for ( let itemPath of itemPaths ) {
  109. // We have one of paths registered in the item.
  110. // Now we have to check every item name from the path to check.
  111. for ( let checkName of checkPath ) {
  112. // Every item name is expanded to all names of items that item is extending.
  113. // So, if on item path, there is an item that is extended by item from checked path, it will
  114. // also be treated as matching.
  115. let chain = this._schema._extensionChains.get( checkName );
  116. // Since our paths have to match in given order, we always check against first item from item path.
  117. // So, if item path is: B D E
  118. // And checked path is: A B C D E
  119. // It will be matching (A won't match, B will match, C won't match, D and E will match)
  120. if ( chain.indexOf( itemPath[ 0 ] ) > -1 ) {
  121. // Every time we have a match, we remove it from `itemPath` so we can still check against first item.
  122. itemPath.shift();
  123. }
  124. }
  125. // If `itemPath` has no items it means that we removed all of them, so we matched all of them.
  126. // This means that we found a matching path.
  127. if ( itemPath.length === 0 ) {
  128. return true;
  129. }
  130. }
  131. // No matching path found.
  132. return false;
  133. }
  134. /**
  135. * Custom toJSON method to solve child-parent circular dependencies.
  136. *
  137. * @returns {Object} Clone of this object with the parent property replaced with its name.
  138. */
  139. toJSON() {
  140. const json = clone( this );
  141. // Due to circular references we need to remove parent reference.
  142. json._schema = '[treeModel.Schema]';
  143. return json;
  144. }
  145. }
  146. /**
  147. * Schema is a run-time created and modified description of which entity in Tree Model is allowed to be inside another
  148. * entity. It is checked to verify whether given action can be preformed on Tree Model or whether Tree Model
  149. * is in correct state.
  150. *
  151. * Schema consist of {@link core.treeModel.SchemaItem schema items}, each describing different entity. Entity can be
  152. * either a Tree Model element or an abstract group for similar elements. Entities are represented by names. Names
  153. * of special/abstract entities should be prefixed by `$` sign.
  154. *
  155. * Each entity in Schema may have a set of allow/disallow rules. Every rule describes in which entities given entity
  156. * can or cannot be.
  157. *
  158. * Entities can extend other entities. This mechanism allows for grouping entities under abstract names. Whenever a rule
  159. * is applied to entity, it is also true for all other entities that extends that entity. For example, let's assume there is
  160. * entity named `$block` and entity `div` extends `$block`. If we add a rule, that entity `$text` with attribute `myAttr`
  161. * is allowed in `$block`, it will also be allowed in `div` (and all other entities extending `$block`). It would be
  162. * possible to disallow `$text` with `myAttr` in `div` by explicitly adding disallow rule for `$text` with `myAttr` in `$block`.
  163. *
  164. * @memberOf core.TreeModel
  165. */
  166. export default class Schema {
  167. /**
  168. * Creates Schema instance.
  169. */
  170. constructor() {
  171. /**
  172. * Schema items registered in the schema.
  173. *
  174. * @member {Map} core.treeModel.Schema#_items
  175. * @private
  176. */
  177. this._items = new Map();
  178. /**
  179. * Description of what entities are a base for given entity.
  180. *
  181. * @member {Map} core.treeModel.Schema#_extensionChains
  182. * @private
  183. */
  184. this._extensionChains = new Map();
  185. // Register some default abstract entities.
  186. this.registerItem( '$inline', null );
  187. this.registerItem( '$block', null );
  188. this.registerItem( '$text', '$inline' );
  189. // Allow inline elements inside block elements.
  190. this.allow( { name: '$inline', inside: '$block' } );
  191. }
  192. /**
  193. * Allows given query in the schema.
  194. *
  195. * // Allow text with bold attribute in all P elements.
  196. * schema.registerItem( 'p', '$block' );
  197. * schema.allow( { name: '$text', attribute: 'bold', inside: 'p' } );
  198. *
  199. * // Allow header in Ps that are in DIVs
  200. * schema.registerItem( 'header', '$block' );
  201. * schema.registerItem( 'div', '$block' );
  202. * schema.allow( { name: 'header', inside: 'div p' } ); // inside: [ 'div', 'p' ] would also work.
  203. *
  204. * @param {core.treeModel.SchemaQuery} query Allowed query.
  205. */
  206. allow( query ) {
  207. this._getItem( query.name ).addAllowed( query.inside, query.attribute );
  208. }
  209. /**
  210. * Disallows given query in the schema.
  211. *
  212. * @see {@link core.treeModel.Schema#allow}
  213. * @param {core.treeModel.SchemaQuery} query Disallowed query.
  214. */
  215. disallow( query ) {
  216. this._getItem( query.name ).addDisallowed( query.inside, query.attribute );
  217. }
  218. /**
  219. * Returns {@link core.treeModel.SchemaItem schema item} that was registered in the schema under given name.
  220. * If item has not been found, throws error.
  221. *
  222. * @param {String} itemName Name to look for in schema.
  223. * @returns {core.treeModel.SchemaItem} Schema item registered under given name.
  224. * @private
  225. */
  226. _getItem( itemName ) {
  227. if ( !this.hasItem( itemName ) ) {
  228. /**
  229. * Item with specified name does not exist in schema.
  230. *
  231. * @error schema-no-item
  232. */
  233. throw new CKEditorError( 'schema-no-item: Item with specified name does not exist in schema.' );
  234. }
  235. return this._items.get( itemName );
  236. }
  237. /**
  238. * Checks whether there is an item registered under given name in schema.
  239. *
  240. * @param itemName
  241. * @returns {boolean}
  242. */
  243. hasItem( itemName ) {
  244. return this._items.has( itemName );
  245. }
  246. /**
  247. * Registers given item name in schema.
  248. *
  249. * // Register P element that should be treated like all block elements.
  250. * schema.registerItem( 'p', '$block' );
  251. *
  252. * @param {String} itemName Name to register.
  253. * @param [isExtending] If set, new item will extend item with given name.
  254. */
  255. registerItem( itemName, isExtending ) {
  256. if ( this.hasItem( itemName ) ) {
  257. /**
  258. * Item with specified name already exists in schema.
  259. *
  260. * @error schema-item-exists
  261. */
  262. throw new CKEditorError( 'schema-item-exists: Item with specified name already exists in schema.' );
  263. }
  264. if ( !!isExtending && !this.hasItem( isExtending ) ) {
  265. /**
  266. * Item with specified name does not exist in schema.
  267. *
  268. * @error schema-no-item
  269. */
  270. throw new CKEditorError( 'schema-no-item: Item with specified name does not exist in schema.' );
  271. }
  272. // Create new SchemaItem and add it to the items store.
  273. this._items.set( itemName, new SchemaItem( this ) );
  274. // Create an extension chain.
  275. // Extension chain has all item names that should be checked when that item is on path to check.
  276. // This simply means, that if item is not extending anything, it should have only itself in it's extension chain.
  277. // Since extending is not dynamic, we can simply get extension chain of extended item and expand it with registered name,
  278. // if the registered item is extending something.
  279. const chain = this.hasItem( isExtending ) ? this._extensionChains.get( isExtending ).concat( itemName ) : [ itemName ];
  280. this._extensionChains.set( itemName, chain );
  281. }
  282. /**
  283. * Checks whether entity with given name (and optionally, with given attribute) is allowed at given position.
  284. *
  285. * // Check whether bold text can be placed at caret position.
  286. * let caretPos = editor.document.selection.getFirstPosition();
  287. * if ( schema.checkAtPosition( caretPos, '$text', 'bold' ) ) { ... }
  288. *
  289. * @param {core.treeModel.Position} position Position to check at.
  290. * @param {String} name Entity name to check.
  291. * @param {String} [attribute] If set, schema will check for entity with given attribute.
  292. * @returns {Boolean} `true` if entity is allowed, `false` otherwise
  293. */
  294. checkAtPosition( position, name, attribute ) {
  295. if ( !this.hasItem( name ) ) {
  296. return false;
  297. }
  298. return this.checkQuery( {
  299. name: name,
  300. inside: Schema._makeItemsPathFromPosition( position ),
  301. attribute: attribute
  302. } );
  303. }
  304. /**
  305. * Checks whether given query is allowed in schema.
  306. *
  307. * // Check whether bold text is allowed in header element.
  308. * let query = {
  309. * name: '$text',
  310. * attribute: 'bold',
  311. * inside: 'header'
  312. * };
  313. * if ( schema.checkQuery( query ) ) { ... }
  314. *
  315. * @param {core.treeModel.SchemaQuery} query Query to check.
  316. * @returns {Boolean} `true` if given query is allowed in schema, `false` otherwise.
  317. */
  318. checkQuery( query ) {
  319. if ( !this.hasItem( query.name ) ) {
  320. return false;
  321. }
  322. const path = ( typeof query.inside === 'string' ) ? query.inside.split( ' ' ) : query.inside;
  323. // Get extension chain of given item and retrieve all schema items that are extended by given item.
  324. const schemaItems = this._extensionChains.get( query.name ).map( ( name ) => {
  325. return this._getItem( name );
  326. } );
  327. // If there is matching disallow path, this query is not valid with schema.
  328. for ( let schemaItem of schemaItems ) {
  329. if ( schemaItem._hasMatchingPath( 'DISALLOW', path, query.attribute ) ) {
  330. return false;
  331. }
  332. }
  333. // At this point, the query is not disallowed.
  334. // If there is any allow path that matches query, this query is valid with schema.
  335. for ( let schemaItem of schemaItems ) {
  336. if ( schemaItem._hasMatchingPath( 'ALLOW', path, query.attribute ) ) {
  337. return true;
  338. }
  339. }
  340. // There are no allow paths that matches query. The query is not valid with schema.
  341. return false;
  342. }
  343. /**
  344. * Gets position and traverses through it's parents to get their names and returns them.
  345. *
  346. * @param {core.treeModel.Position} position Position to start building path from.
  347. * @returns {Array.<String>} Path containing elements names from top-most to the one containing given position.
  348. * @private
  349. */
  350. static _makeItemsPathFromPosition( position ) {
  351. let path = [];
  352. let parent = position.parent;
  353. while ( parent !== null ) {
  354. path.push( parent.name );
  355. parent = parent.parent;
  356. }
  357. path.reverse();
  358. return path;
  359. }
  360. }
  361. /**
  362. * Object with query used by {@link core.treeModel.Schema} to query schema or add allow/disallow rules to schema.
  363. *
  364. * @typedef {Object} core.treeModel.SchemaQuery
  365. * @property {String} name Entity name.
  366. * @property {Array.<String>|String} inside Path inside which the entity is placed.
  367. * @property {String} [attribute] If set, the query applies only to entities that has attribute with given key.
  368. */