schema.js 14 KB

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