8
0

schema.js 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428
  1. /**
  2. * @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/model/schema
  7. */
  8. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  9. import ObservableMixin from '@ckeditor/ckeditor5-utils/src/observablemixin';
  10. import mix from '@ckeditor/ckeditor5-utils/src/mix';
  11. import Range from './range';
  12. import Position from './position';
  13. import Element from './element';
  14. /**
  15. * The model's schema. It defines allowed and disallowed structures of nodes as well as nodes' attributes.
  16. * The schema is usually defined by features and based on them the editing framework and features
  17. * make decisions how to change and process the model.
  18. *
  19. * The instance of schema is available in {@link module:engine/model/model~Model#schema `editor.model.schema`}.
  20. *
  21. * # Schema definitions
  22. *
  23. * Schema defines allowed model structures and allowed attributes separately. They are also checked separately
  24. * by using the {@link ~Schema#checkChild} and {@link ~Schema#checkAttribute} methods.
  25. *
  26. * ## Defining allowed structures
  27. *
  28. * When a feature introduces a model element it should register it in the schema. Besides
  29. * defining that such an element may exist in the model, the feature also needs to define where
  30. * this element may be placed:
  31. *
  32. * schema.register( 'myElement', {
  33. * allowIn: '$root'
  34. * } );
  35. *
  36. * This lets the schema know that `<myElement>` may be a child of the `<$root>` element. `$root` is one of generic
  37. * nodes defined by the editing framework. By default, the editor names the main root element a `<$root>`,
  38. * so the above definition allows `<myElement>` in the main editor element.
  39. *
  40. * In other words, this would be correct:
  41. *
  42. * <$root><myElement></myElement></$root>
  43. *
  44. * While this would not be correct:
  45. *
  46. * <$root><foo><myElement></myElement></foo></$root>
  47. *
  48. * ## Generic items
  49. *
  50. * There are three basic generic items: `$root`, `$block` and `$text`.
  51. * They are defined as follows:
  52. *
  53. * this.schema.register( '$root', {
  54. * isLimit: true
  55. * } );
  56. * this.schema.register( '$block', {
  57. * allowIn: '$root',
  58. * isBlock: true
  59. * } );
  60. * this.schema.register( '$text', {
  61. * allowIn: '$block'
  62. * } );
  63. *
  64. * These definitions can then be reused by features to create their own definitions in a more extensible way.
  65. * For example, the {@link module:paragraph/paragraph~Paragraph} feature will define its item as:
  66. *
  67. * schema.register( 'paragraph', {
  68. * inheritAllFrom: '$block'
  69. * } );
  70. *
  71. * Which translates to:
  72. *
  73. * schema.register( 'paragraph', {
  74. * allowWhere: '$block',
  75. * allowContentOf: '$block',
  76. * allowAttributesOf: '$block',
  77. * inheritTypesFrom: '$block'
  78. * } );
  79. *
  80. * Which can be read as:
  81. *
  82. * * The `<paragraph>` element will be allowed in elements in which `<$block>` is allowed (e.g. in `<$root>`).
  83. * * The `<paragraph>` element will allow all nodes which are allowed in `<$block>` (e.g. `$text`).
  84. * * The `<paragraph>` element will allow all attributes allowed on `<$block>`.
  85. * * The `<paragraph>` element will inherit all `is*` properties of `<$block>` (e.g. `isBlock`).
  86. *
  87. * Thanks to the fact that `<paragraph>`'s definition is inherited from `<$block>` other features can use the `<$block>`
  88. * type to indirectly extend `<paragraph>`'s definition. For example, the {@link module:block-quote/blockquote~BlockQuote}
  89. * feature does this:
  90. *
  91. * schema.register( 'blockQuote', {
  92. * allowWhere: '$block',
  93. * allowContentOf: '$root'
  94. * } );
  95. *
  96. * Thanks to that, despite the fact that block quote and paragraph features know nothing about themselves, paragraphs
  97. * will be allowed in block quotes and block quotes will be allowed in all places where blocks are. So if anyone will
  98. * register a `<section>` element (with `allowContentOf: '$root'` rule), that `<section>` elements will allow
  99. * block quotes too.
  100. *
  101. * The side effect of such a definition inheritance is that now `<blockQuote>` is allowed in `<blockQuote>` which needs to be
  102. * resolved by a callback which will disallow this specific structure.
  103. *
  104. * You can read more about the format of an item definition in {@link module:engine/model/schema~SchemaItemDefinition}.
  105. *
  106. * ## Defining advanced rules in `checkChild()`'s callbacks
  107. *
  108. * The {@link ~Schema#checkChild} method which is the base method used to check whether some element is allowed in a given structure
  109. * is {@link module:utils/observablemixin~ObservableMixin#decorate a decorated method}.
  110. * It means that you can add listeners to implement your specific rules which are not limited by the declarative
  111. * {@link module:engine/model/schema~SchemaItemDefinition API}.
  112. *
  113. * Those listeners can be added either by listening directly to the {@link ~Schema#event:checkChild} event or
  114. * by using the handy {@link ~Schema#addChildCheck} method.
  115. *
  116. * For instance, the block quote feature defines such a listener to disallow nested `<blockQuote>` structures:
  117. *
  118. * schema.addChildCheck( context, childDefinition ) => {
  119. * // Note that context is automatically normalized to SchemaContext instance and
  120. * // child to its definition (SchemaCompiledItemDefinition).
  121. *
  122. * // If checkChild() is called with a context that ends with blockQuote and blockQuote as a child
  123. * // to check, make the checkChild() method return false.
  124. * if ( context.endsWith( 'blockQuote' ) && childDefinition.name == 'blockQuote' ) {
  125. * return false;
  126. * }
  127. * } );
  128. *
  129. * ## Defining attributes
  130. *
  131. * TODO
  132. *
  133. * ## Implementing additional constraints
  134. *
  135. * Schema's capabilities were limited to simple (and atomic) {@link ~Schema#checkChild} and
  136. * {@link ~Schema#checkAttribute} checks on purpose.
  137. * One may imagine that schema should support defining more complex rules such as
  138. * "element `<x>` must be always followed by `<y>`".
  139. * While it is feasible to create an API which would enable feeding the schema with such definitions,
  140. * it is unfortunately unrealistic to then expect that every editing feature will consider those rules when processing the model.
  141. * It is also unrealistic to expect that it will be done automatically by the schema and the editing engine themselves.
  142. *
  143. * For instance, let's get back to the "element `<x>` must be always followed by `<y>`" rule and this initial content:
  144. *
  145. * <$root>
  146. * <x>foo</x>
  147. * <y>bar[bom</y>
  148. * <z>bom]bar</z>
  149. * </$root>
  150. *
  151. * Now, imagine that the user presses the "block quote" button. Usually it would wrap the two selected blocks
  152. * (`<y>` and `<z>`) with a `<blockQuote>` element:
  153. *
  154. * <$root>
  155. * <x>foo</x>
  156. * <blockQuote>
  157. * <y>bar[bom</y>
  158. * <z>bom]bar</z>
  159. * </blockQuote>
  160. * </$root>
  161. *
  162. * But it turns out that this creates an incorrect structure – `<x>` is not followed by `<y>` anymore.
  163. *
  164. * What should happen instead? There are at least 4 possible solutions: the block quote feature should not be
  165. * applicable in such a context, someone should create a new `<y>` right after `<x>`, `<x>` should be moved
  166. * inside `<blockQuote>` together with `<y>` or vice versa.
  167. *
  168. * While this is a relatively simple scenario (unlike most real-time collaboration scenarios),
  169. * it turns out that it's already hard to say what should happen and who should react to fix this content.
  170. *
  171. * Therefore, if your editor needs to implement such rules, you should do that through model's post-fixers
  172. * fixing incorrect content or actively prevent such situations (e.g. by disabling certain features).
  173. * It means that those constraints will be defined specifically for your scenario by your code which
  174. * makes their implementation much easier.
  175. *
  176. * So the answer for who and how should implement additional constraints is your features or your editor
  177. * through CKEditor 5's rich and open API.
  178. *
  179. * @mixes module:utils/observablemixin~ObservableMixin
  180. */
  181. export default class Schema {
  182. /**
  183. * Creates schema instance.
  184. */
  185. constructor() {
  186. this._sourceDefinitions = {};
  187. this.decorate( 'checkChild' );
  188. this.decorate( 'checkAttribute' );
  189. this.on( 'checkAttribute', ( evt, args ) => {
  190. args[ 0 ] = new SchemaContext( args[ 0 ] );
  191. }, { priority: 'highest' } );
  192. this.on( 'checkChild', ( evt, args ) => {
  193. args[ 0 ] = new SchemaContext( args[ 0 ] );
  194. args[ 1 ] = this.getDefinition( args[ 1 ] );
  195. }, { priority: 'highest' } );
  196. }
  197. /**
  198. * Registers schema item. Can only be called once for every item name.
  199. *
  200. * schema.register( 'paragraph', {
  201. * inheritAllFrom: '$block'
  202. * } );
  203. *
  204. * @param {String} itemName
  205. * @param {module:engine/model/schema~SchemaItemDefinition} definition
  206. */
  207. register( itemName, definition ) {
  208. if ( this._sourceDefinitions[ itemName ] ) {
  209. // TODO docs
  210. throw new CKEditorError( 'schema-cannot-register-item-twice: A single item cannot be registered twice in the schema.', {
  211. itemName
  212. } );
  213. }
  214. this._sourceDefinitions[ itemName ] = [
  215. Object.assign( {}, definition )
  216. ];
  217. this._clearCache();
  218. }
  219. /**
  220. * Extends a {@link #register registered} item's definition.
  221. *
  222. * Extending properties such as `allowIn` will add more items to the existing properties,
  223. * while redefining properties such as `isBlock` will override the previously defined ones.
  224. *
  225. * schema.register( 'foo', {
  226. * allowIn: '$root',
  227. * isBlock: true;
  228. * } );
  229. * schema.extend( 'foo', {
  230. * allowIn: 'blockQuote',
  231. * isBlock: false
  232. * } );
  233. *
  234. * schema.getDefinition( 'foo' );
  235. * // {
  236. * // allowIn: [ '$root', 'blockQuote' ],
  237. * // isBlock: false
  238. * // }
  239. *
  240. * @param {String} itemName
  241. * @param {module:engine/model/schema~SchemaItemDefinition} definition
  242. */
  243. extend( itemName, definition ) {
  244. if ( !this._sourceDefinitions[ itemName ] ) {
  245. // TODO docs
  246. throw new CKEditorError( 'schema-cannot-extend-missing-item: Cannot extend an item which was not registered yet.', {
  247. itemName
  248. } );
  249. }
  250. this._sourceDefinitions[ itemName ].push( Object.assign( {}, definition ) );
  251. this._clearCache();
  252. }
  253. /**
  254. * Returns all registered items.
  255. *
  256. * @returns {Object.<String,module:engine/model/schema~SchemaCompiledItemDefinition>}
  257. */
  258. getDefinitions() {
  259. if ( !this._compiledDefinitions ) {
  260. this._compile();
  261. }
  262. return this._compiledDefinitions;
  263. }
  264. /**
  265. * Returns a definition of the given item or `undefined` if item is not registered.
  266. *
  267. * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
  268. * @returns {module:engine/model/schema~SchemaCompiledItemDefinition}
  269. */
  270. getDefinition( item ) {
  271. let itemName;
  272. if ( typeof item == 'string' ) {
  273. itemName = item;
  274. } else if ( item.is && ( item.is( 'text' ) || item.is( 'textProxy' ) ) ) {
  275. itemName = '$text';
  276. }
  277. // Element or module:engine/model/schema~SchemaContextItem.
  278. else {
  279. itemName = item.name;
  280. }
  281. return this.getDefinitions()[ itemName ];
  282. }
  283. /**
  284. * Returns `true` if the given item is registered in the schema.
  285. *
  286. * schema.isRegistered( 'paragraph' ); // -> true
  287. * schema.isRegistered( editor.model.document.getRoot() ); // -> true
  288. * schema.isRegistered( 'foo' ); // -> false
  289. *
  290. * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
  291. */
  292. isRegistered( item ) {
  293. return !!this.getDefinition( item );
  294. }
  295. /**
  296. * Returns `true` if the given item is defined to be
  297. * a block by {@link module:engine/model/schema~SchemaItemDefinition}'s `isBlock` property.
  298. *
  299. * schema.isBlock( 'paragraph' ); // -> true
  300. * schema.isBlock( '$root' ); // -> false
  301. *
  302. * const paragraphElement = writer.createElement( 'paragraph' );
  303. * schema.isBlock( paragraphElement ); // -> true
  304. *
  305. * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
  306. */
  307. isBlock( item ) {
  308. const def = this.getDefinition( item );
  309. return !!( def && def.isBlock );
  310. }
  311. /**
  312. * Returns `true` if the given item is defined to be
  313. * a limit element by {@link module:engine/model/schema~SchemaItemDefinition}'s `isLimit` property.
  314. *
  315. * schema.isLimit( 'paragraph' ); // -> false
  316. * schema.isLimit( '$root' ); // -> true
  317. * schema.isLimit( editor.model.document.getRoot() ); // -> true
  318. *
  319. * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
  320. */
  321. isLimit( item ) {
  322. const def = this.getDefinition( item );
  323. return !!( def && def.isLimit );
  324. }
  325. /**
  326. * Returns `true` if the given item is defined to be
  327. * a object element by {@link module:engine/model/schema~SchemaItemDefinition}'s `isObject` property.
  328. *
  329. * schema.isObject( 'paragraph' ); // -> false
  330. * schema.isObject( 'image' ); // -> true
  331. *
  332. * const imageElement = writer.createElement( 'image' );
  333. * schema.isObject( imageElement ); // -> true
  334. *
  335. * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
  336. */
  337. isObject( item ) {
  338. const def = this.getDefinition( item );
  339. return !!( def && def.isObject );
  340. }
  341. /**
  342. * Checks whether the given node (`child`) can be a child of the given context.
  343. *
  344. * schema.checkChild( model.document.getRoot(), paragraph ); // -> false
  345. *
  346. * schema.register( 'paragraph', {
  347. * allowIn: '$root'
  348. * } );
  349. * schema.checkChild( model.document.getRoot(), paragraph ); // -> true
  350. *
  351. * @fires checkChild
  352. * @param {module:engine/model/schema~SchemaContextDefinition|module:engine/model/schema~SchemaContext} context
  353. * Context in which the child will be checked.
  354. * @param {module:engine/model/node~Node|String} def The child to check.
  355. */
  356. checkChild( context, def ) {
  357. // Note: context and child are already normalized here to a SchemaContext and SchemaCompiledItemDefinition.
  358. if ( !def ) {
  359. return false;
  360. }
  361. return this._checkContextMatch( def, context );
  362. }
  363. /**
  364. * Checks whether the given attribute can be applied in the given context (on the last
  365. * item of the context).
  366. *
  367. * schema.checkAttribute( textNode, 'bold' ); // -> false
  368. *
  369. * schema.extend( '$text', {
  370. * allowAttributes: 'bold'
  371. * } );
  372. * schema.checkAttribute( textNode, 'bold' ); // -> true
  373. *
  374. * @fires checkAttribute
  375. * @param {module:engine/model/schema~SchemaContextDefinition|module:engine/model/schema~SchemaContext} context
  376. * Context in which the attribute will be checked.
  377. * @param {String} attributeName
  378. */
  379. checkAttribute( context, attributeName ) {
  380. const def = this.getDefinition( context.last );
  381. if ( !def ) {
  382. return false;
  383. }
  384. return def.allowAttributes.includes( attributeName );
  385. }
  386. /**
  387. * Checks whether the given element (`elementToMerge`) can be merged with the specified base element (`positionOrBaseElement`).
  388. *
  389. * In other words – whether `elementToMerge`'s children {@link #checkChild are allowed} in the `positionOrBaseElement`.
  390. *
  391. * This check ensures that elements merged with {@link module:engine/model/writer~Writer#merge `Writer#merge()`}
  392. * will be valid.
  393. *
  394. * Instead of elements, you can pass the instance of {@link module:engine/model/position~Position} class as the `positionOrBaseElement`.
  395. * It means that the elements before and after the position will be checked whether they can be merged.
  396. *
  397. * @param {module:engine/model/position~Position|module:engine/model/element~Element} positionOrBaseElement The position or base
  398. * element to which the `elementToMerge` will be merged.
  399. * @param {module:engine/model/element~Element} elementToMerge The element to merge. Required if `positionOrBaseElement` is a element.
  400. * @returns {Boolean}
  401. */
  402. checkMerge( positionOrBaseElement, elementToMerge = null ) {
  403. if ( positionOrBaseElement instanceof Position ) {
  404. const nodeBefore = positionOrBaseElement.nodeBefore;
  405. const nodeAfter = positionOrBaseElement.nodeAfter;
  406. if ( !( nodeBefore instanceof Element ) ) {
  407. /**
  408. * The node before the merge position must be an element.
  409. *
  410. * @error schema-check-merge-no-element-before
  411. */
  412. throw new CKEditorError( 'schema-check-merge-no-element-before: The node before the merge position must be an element.' );
  413. }
  414. if ( !( nodeAfter instanceof Element ) ) {
  415. /**
  416. * The node after the merge position must be an element.
  417. *
  418. * @error schema-check-merge-no-element-after
  419. */
  420. throw new CKEditorError( 'schema-check-merge-no-element-after: The node after the merge position must be an element.' );
  421. }
  422. return this.checkMerge( nodeBefore, nodeAfter );
  423. }
  424. for ( const child of elementToMerge.getChildren() ) {
  425. if ( !this.checkChild( positionOrBaseElement, child ) ) {
  426. return false;
  427. }
  428. }
  429. return true;
  430. }
  431. /**
  432. * Allows registering a callback to the {@link #checkChild} method calls.
  433. *
  434. * Callbacks allow you to implement rules which are not otherwise possible to achieve
  435. * by using the declarative API of {@link module:engine/model/schema~SchemaItemDefinition}.
  436. * For example, by using this method you can disallow elements in specific contexts.
  437. *
  438. * This method is a shorthand for using the {@link #event:checkChild} event. For even better control,
  439. * you can use that event instead.
  440. *
  441. * Example:
  442. *
  443. * // Disallow heading1 directly inside a blockQuote.
  444. * schema.addChildCheck( ( context, childDefinition ) => {
  445. * if ( context.endsWith( 'blockQuote' ) && childDefinition.name == 'heading1' ) {
  446. * return false;
  447. * }
  448. * } );
  449. *
  450. * Which translates to:
  451. *
  452. * schema.on( 'checkChild', ( evt, args ) => {
  453. * const context = args[ 0 ];
  454. * const childDefinition = args[ 1 ];
  455. *
  456. * if ( context.endsWith( 'blockQuote' ) && childDefinition && childDefinition.name == 'heading1' ) {
  457. * // Prevent next listeners from being called.
  458. * evt.stop();
  459. * // Set the checkChild()'s return value.
  460. * evt.return = false;
  461. * }
  462. * }, { priority: 'high' } );
  463. *
  464. * @param {Function} callback The callback to be called. It is called with two parameters:
  465. * {@link module:engine/model/schema~SchemaContext} (context) instance and
  466. * {@link module:engine/model/schema~SchemaCompiledItemDefinition} (child-to-check definition).
  467. * The callback may return `true/false` to override `checkChild()`'s return value. If it does not return
  468. * a boolean value, the default algorithm (or other callbacks) will define `checkChild()`'s return value.
  469. */
  470. addChildCheck( callback ) {
  471. this.on( 'checkChild', ( evt, [ ctx, childDef ] ) => {
  472. // checkChild() was called with a non-registered child.
  473. // In 99% cases such check should return false, so not to overcomplicate all callbacks
  474. // don't even execute them.
  475. if ( !childDef ) {
  476. return;
  477. }
  478. const retValue = callback( ctx, childDef );
  479. if ( typeof retValue == 'boolean' ) {
  480. evt.stop();
  481. evt.return = retValue;
  482. }
  483. }, { priority: 'high' } );
  484. }
  485. /**
  486. * Allows registering a callback to the {@link #checkAttribute} method calls.
  487. *
  488. * Callbacks allow you to implement rules which are not otherwise possible to achieve
  489. * by using the declarative API of {@link module:engine/model/schema~SchemaItemDefinition}.
  490. * For example, by using this method you can disallow attribute if node to which it is applied
  491. * is contained within some other element (e.g. you want to disallow `bold` on `$text` within `heading1`).
  492. *
  493. * This method is a shorthand for using the {@link #event:checkAttribute} event. For even better control,
  494. * you can use that event instead.
  495. *
  496. * Example:
  497. *
  498. * // Disallow bold on $text inside heading1.
  499. * schema.addChildCheck( ( context, attributeName ) => {
  500. * if ( context.endsWith( 'heading1 $text' ) && attributeName == 'bold' ) {
  501. * return false;
  502. * }
  503. * } );
  504. *
  505. * Which translates to:
  506. *
  507. * schema.on( 'checkAttribute', ( evt, args ) => {
  508. * const context = args[ 0 ];
  509. * const attributeName = args[ 1 ];
  510. *
  511. * if ( context.endsWith( 'heading1 $text' ) && attributeName == 'bold' ) {
  512. * // Prevent next listeners from being called.
  513. * evt.stop();
  514. * // Set the checkAttribute()'s return value.
  515. * evt.return = false;
  516. * }
  517. * }, { priority: 'high' } );
  518. *
  519. * @param {Function} callback The callback to be called. It is called with two parameters:
  520. * {@link module:engine/model/schema~SchemaContext} (context) instance and attribute name.
  521. * The callback may return `true/false` to override `checkAttribute()`'s return value. If it does not return
  522. * a boolean value, the default algorithm (or other callbacks) will define `checkAttribute()`'s return value.
  523. */
  524. addAttributeCheck( callback ) {
  525. this.on( 'checkAttribute', ( evt, [ ctx, attributeName ] ) => {
  526. const retValue = callback( ctx, attributeName );
  527. if ( typeof retValue == 'boolean' ) {
  528. evt.stop();
  529. evt.return = retValue;
  530. }
  531. }, { priority: 'high' } );
  532. }
  533. /**
  534. * Returns the lowest {@link module:engine/model/schema~Schema#isLimit limit element} containing the entire
  535. * selection or the root otherwise.
  536. *
  537. * @param {module:engine/model/selection~Selection} selection Selection which returns the common ancestor.
  538. * @returns {module:engine/model/element~Element}
  539. */
  540. getLimitElement( selection ) {
  541. // Find the common ancestor for all selection's ranges.
  542. let element = Array.from( selection.getRanges() )
  543. .reduce( ( node, range ) => {
  544. if ( !node ) {
  545. return range.getCommonAncestor();
  546. }
  547. return node.getCommonAncestor( range.getCommonAncestor() );
  548. }, null );
  549. while ( !this.isLimit( element ) ) {
  550. if ( element.parent ) {
  551. element = element.parent;
  552. } else {
  553. break;
  554. }
  555. }
  556. return element;
  557. }
  558. /**
  559. * Checks whether the attribute is allowed in selection:
  560. *
  561. * * if the selection is not collapsed, then checks if the attribute is allowed on any of nodes in that range,
  562. * * if the selection is collapsed, then checks if on the selection position there's a text with the
  563. * specified attribute allowed.
  564. *
  565. * @param {module:engine/model/selection~Selection} selection Selection which will be checked.
  566. * @param {String} attribute The name of the attribute to check.
  567. * @returns {Boolean}
  568. */
  569. checkAttributeInSelection( selection, attribute ) {
  570. if ( selection.isCollapsed ) {
  571. // Check whether schema allows for a text with the attribute in the selection.
  572. return this.checkAttribute( [ ...selection.getFirstPosition().getAncestors(), '$text' ], attribute );
  573. } else {
  574. const ranges = selection.getRanges();
  575. // For all ranges, check nodes in them until you find a node that is allowed to have the attribute.
  576. for ( const range of ranges ) {
  577. for ( const value of range ) {
  578. if ( this.checkAttribute( value.item, attribute ) ) {
  579. // If we found a node that is allowed to have the attribute, return true.
  580. return true;
  581. }
  582. }
  583. }
  584. }
  585. // If we haven't found such node, return false.
  586. return false;
  587. }
  588. /**
  589. * Transforms the given set of ranges into a set of ranges where the given attribute is allowed (and can be applied).
  590. *
  591. * @param {Array.<module:engine/model/range~Range>} ranges Ranges to be validated.
  592. * @param {String} attribute The name of the attribute to check.
  593. * @returns {Array.<module:engine/model/range~Range>} Ranges in which the attribute is allowed.
  594. */
  595. getValidRanges( ranges, attribute ) {
  596. const validRanges = [];
  597. for ( const range of ranges ) {
  598. let last = range.start;
  599. let from = range.start;
  600. const to = range.end;
  601. for ( const value of range.getWalker() ) {
  602. if ( !this.checkAttribute( value.item, attribute ) ) {
  603. if ( !from.isEqual( last ) ) {
  604. validRanges.push( new Range( from, last ) );
  605. }
  606. from = value.nextPosition;
  607. }
  608. last = value.nextPosition;
  609. }
  610. if ( from && !from.isEqual( to ) ) {
  611. validRanges.push( new Range( from, to ) );
  612. }
  613. }
  614. return validRanges;
  615. }
  616. /**
  617. * Tries to find position ancestors that allows to insert given node.
  618. * It starts searching from the given position and goes node by node to the top of the model tree
  619. * as long as {@link module:engine/model/schema~Schema#isLimit limit element} or top-most ancestor won't be reached.
  620. *
  621. * @params {module:engine/model/node~Node} node Node for which allowed parent should be found.
  622. * @params {module:engine/model/position~Position} position Position from searching will start.
  623. * @params {module:engine/model/element~Element} [limitElement] Custom limit element.
  624. * @returns {module:engine/model/element~Element|null} element Allowed parent or null if nothing was found.
  625. */
  626. findAllowedParent( node, position, limitElement ) {
  627. let parent = position.parent;
  628. while ( parent ) {
  629. if ( this.checkChild( parent, node ) ) {
  630. return parent;
  631. }
  632. if ( this.isLimit( parent ) ) {
  633. return null;
  634. }
  635. if ( parent === limitElement ) {
  636. return null;
  637. }
  638. parent = parent.parent;
  639. }
  640. return null;
  641. }
  642. /**
  643. * Removes attributes disallowed by the schema.
  644. *
  645. * @param {Iterable.<module:engine/model/node~Node>} nodes Nodes that will be filtered.
  646. * @param {module:engine/model/writer~Writer} writer
  647. */
  648. removeDisallowedAttributes( nodes, writer ) {
  649. for ( const node of nodes ) {
  650. for ( const attribute of node.getAttributeKeys() ) {
  651. if ( !this.checkAttribute( node, attribute ) ) {
  652. writer.removeAttribute( attribute, node );
  653. }
  654. }
  655. if ( node.is( 'element' ) ) {
  656. this.removeDisallowedAttributes( node.getChildren(), writer );
  657. }
  658. }
  659. }
  660. /**
  661. * @private
  662. */
  663. _clearCache() {
  664. this._compiledDefinitions = null;
  665. }
  666. /**
  667. * @private
  668. */
  669. _compile() {
  670. const compiledDefinitions = {};
  671. const sourceRules = this._sourceDefinitions;
  672. const itemNames = Object.keys( sourceRules );
  673. for ( const itemName of itemNames ) {
  674. compiledDefinitions[ itemName ] = compileBaseItemRule( sourceRules[ itemName ], itemName );
  675. }
  676. for ( const itemName of itemNames ) {
  677. compileAllowContentOf( compiledDefinitions, itemName );
  678. }
  679. for ( const itemName of itemNames ) {
  680. compileAllowWhere( compiledDefinitions, itemName );
  681. }
  682. for ( const itemName of itemNames ) {
  683. compileAllowAttributesOf( compiledDefinitions, itemName );
  684. compileInheritPropertiesFrom( compiledDefinitions, itemName );
  685. }
  686. for ( const itemName of itemNames ) {
  687. cleanUpAllowIn( compiledDefinitions, itemName );
  688. cleanUpAllowAttributes( compiledDefinitions, itemName );
  689. }
  690. this._compiledDefinitions = compiledDefinitions;
  691. }
  692. /**
  693. * @private
  694. * @param {module:engine/model/schema~SchemaCompiledItemDefinition} def
  695. * @param {module:engine/model/schema~SchemaContext} context
  696. * @param {Number} contextItemIndex
  697. */
  698. _checkContextMatch( def, context, contextItemIndex = context.length - 1 ) {
  699. const contextItem = context.getItem( contextItemIndex );
  700. if ( def.allowIn.includes( contextItem.name ) ) {
  701. if ( contextItemIndex == 0 ) {
  702. return true;
  703. } else {
  704. const parentRule = this.getDefinition( contextItem );
  705. return this._checkContextMatch( parentRule, context, contextItemIndex - 1 );
  706. }
  707. } else {
  708. return false;
  709. }
  710. }
  711. }
  712. mix( Schema, ObservableMixin );
  713. /**
  714. * Event fired when the {@link #checkChild} method is called. It allows plugging in
  715. * additional behavior – e.g. implementing rules which cannot be defined using the declarative
  716. * {@link module:engine/model/schema~SchemaItemDefinition} interface.
  717. *
  718. * **Note:** The {@link #addChildCheck} method is a more handy way to register callbacks. Internally,
  719. * it registers a listener to this event but comes with a simpler API and it is the recommended choice
  720. * in most of the cases.
  721. *
  722. * The {@link #checkChild} method fires an event because it is
  723. * {@link module:utils/observablemixin~ObservableMixin#decorate decorated} with it. Thanks to that you can
  724. * use this event in a various way, but the most important use case is overriding standard behaviour of the
  725. * `checkChild()` method. Let's see a typical listener template:
  726. *
  727. * schema.on( 'checkChild', ( evt, args ) => {
  728. * const context = args[ 0 ];
  729. * const childDefinition = args[ 1 ];
  730. * }, { priority: 'high' } );
  731. *
  732. * The listener is added with a `high` priority to be executed before the default method is really called. The `args` callback
  733. * parameter contains arguments passed to `checkChild( context, child )`. However, the `context` parameter is already
  734. * normalized to a {@link module:engine/model/schema~SchemaContext} instance and `child` to a
  735. * {@link module:engine/model/schema~SchemaCompiledItemDefinition} instance, so you don't have to worry about
  736. * the various ways how `context` and `child` may be passed to `checkChild()`.
  737. *
  738. * **Note:** `childDefinition` may be `undefined` if `checkChild()` was called with a non-registered element.
  739. *
  740. * So, in order to implement a rule "disallow `heading1` in `blockQuote`" you can add such a listener:
  741. *
  742. * schema.on( 'checkChild', ( evt, args ) => {
  743. * const context = args[ 0 ];
  744. * const childDefinition = args[ 1 ];
  745. *
  746. * if ( context.endsWith( 'blockQuote' ) && childDefinition && childDefinition.name == 'heading1' ) {
  747. * // Prevent next listeners from being called.
  748. * evt.stop();
  749. * // Set the checkChild()'s return value.
  750. * evt.return = false;
  751. * }
  752. * }, { priority: 'high' } );
  753. *
  754. * Allowing elements in specific contexts will be a far less common use case, because it's normally handled by
  755. * `allowIn` rule from {@link module:engine/model/schema~SchemaItemDefinition} but if you have a complex scenario
  756. * where `listItem` should be allowed only in element `foo` which must be in element `bar`, then this would be the way:
  757. *
  758. * schema.on( 'checkChild', ( evt, args ) => {
  759. * const context = args[ 0 ];
  760. * const childDefinition = args[ 1 ];
  761. *
  762. * if ( context.endsWith( 'bar foo' ) && childDefinition.name == 'listItem' ) {
  763. * // Prevent next listeners from being called.
  764. * evt.stop();
  765. * // Set the checkChild()'s return value.
  766. * evt.return = true;
  767. * }
  768. * }, { priority: 'high' } );
  769. *
  770. * @event checkChild
  771. * @param {Array} args The `checkChild()`'s arguments.
  772. */
  773. /**
  774. * Event fired when the {@link #checkAttribute} method is called. It allows plugging in
  775. * additional behavior – e.g. implementing rules which cannot be defined using the declarative
  776. * {@link module:engine/model/schema~SchemaItemDefinition} interface.
  777. *
  778. * **Note:** The {@link #addAttributeCheck} method is a more handy way to register callbacks. Internally,
  779. * it registers a listener to this event but comes with a simpler API and it is the recommended choice
  780. * in most of the cases.
  781. *
  782. * The {@link #checkAttribute} method fires an event because it's
  783. * {@link module:utils/observablemixin~ObservableMixin#decorate decorated} with it. Thanks to that you can
  784. * use this event in a various way, but the most important use case is overriding standard behaviour of the
  785. * `checkAttribute()` method. Let's see a typical listener template:
  786. *
  787. * schema.on( 'checkAttribute', ( evt, args ) => {
  788. * const context = args[ 0 ];
  789. * const attributeName = args[ 1 ];
  790. * }, { priority: 'high' } );
  791. *
  792. * The listener is added with a `high` priority to be executed before the default method is really called. The `args` callback
  793. * parameter contains arguments passed to `checkAttribute( context, attributeName )`. However, the `context` parameter is already
  794. * normalized to a {@link module:engine/model/schema~SchemaContext} instance, so you don't have to worry about
  795. * the various ways how `context` may be passed to `checkAttribute()`.
  796. *
  797. * So, in order to implement a rule "disallow `bold` in a text which is in a `heading1` you can add such a listener:
  798. *
  799. * schema.on( 'checkAttribute', ( evt, args ) => {
  800. * const context = args[ 0 ];
  801. * const atributeName = args[ 1 ];
  802. *
  803. * if ( context.endsWith( 'heading1 $text' ) && attributeName == 'bold' ) {
  804. * // Prevent next listeners from being called.
  805. * evt.stop();
  806. * // Set the checkAttribute()'s return value.
  807. * evt.return = false;
  808. * }
  809. * }, { priority: 'high' } );
  810. *
  811. * Allowing attributes in specific contexts will be a far less common use case, because it's normally handled by
  812. * `allowAttributes` rule from {@link module:engine/model/schema~SchemaItemDefinition} but if you have a complex scenario
  813. * where `bold` should be allowed only in element `foo` which must be in element `bar`, then this would be the way:
  814. *
  815. * schema.on( 'checkAttribute', ( evt, args ) => {
  816. * const context = args[ 0 ];
  817. * const atributeName = args[ 1 ];
  818. *
  819. * if ( context.endsWith( 'bar foo $text' ) && attributeName == 'bold' ) {
  820. * // Prevent next listeners from being called.
  821. * evt.stop();
  822. * // Set the checkAttribute()'s return value.
  823. * evt.return = true;
  824. * }
  825. * }, { priority: 'high' } );
  826. *
  827. * @event checkAttribute
  828. * @param {Array} args The `checkAttribute()`'s arguments.
  829. */
  830. /**
  831. * A definition of a {@link module:engine/model/schema~Schema schema} item.
  832. *
  833. * You can define the following rules:
  834. *
  835. * * `allowIn` – a string or an array of strings. Defines in which other items this item will be allowed.
  836. * * `allowAttributes` – a string or an array of strings. Defines allowed attributes of the given item.
  837. * * `allowContentOf` – a string or an array of strings. Inherit "allowed children" from other items.
  838. * * `allowWhere` – a string or an array of strings. Inherit "allowed in" from other items.
  839. * * `allowAttributesOf` – a string or an array of strings. Inherit attributes from other items.
  840. * * `inheritTypesFrom` – a string or an array of strings. Inherit `is*` properties of other items.
  841. * * `inheritAllFrom` – a string. A shorthand for `allowContentOf`, `allowWhere`, `allowAttributesOf`, `inheritTypesFrom`.
  842. * * additionall, you can define the following `is*` properties: `isBlock`, `isLimit`, `isObject`. Read about them below.
  843. *
  844. * # The is* properties
  845. *
  846. * There are 3 commonly used `is*` properties. Their role is to assign additional semantics to schema items.
  847. * You can define more properties but you will also need to implement support for them in the existing editor features.
  848. *
  849. * * `isBlock` – whether this item is paragraph-like. Generally speaking, a content is usually made out of blocks
  850. * like paragraphs, list items, images, headings, etc. All these elements are marked as blocks. A block
  851. * should not allow another block inside. Note: there's also the `$block` generic item which has `isBlock` set to `true`.
  852. * Most block type items will inherit from `$block` (through `inheritAllFrom`).
  853. * * `isLimit` – can be understood as whether this element should not be split by <kbd>Enter</kbd>.
  854. * Examples of limit elements – `$root`, table cell, image caption, etc. In other words, all actions which happen inside
  855. * a limit element are limitted to its content.
  856. * * `isObject` – whether item is "self-contained" and should be treated as a whole. Examples of object elements –
  857. * `image`, `table`, `video`, etc.
  858. *
  859. * # Generic items
  860. *
  861. * There are three basic generic items: `$root`, `$block` and `$text`.
  862. * They are defined as follows:
  863. *
  864. * this.schema.register( '$root', {
  865. * isLimit: true
  866. * } );
  867. * this.schema.register( '$block', {
  868. * allowIn: '$root',
  869. * isBlock: true
  870. * } );
  871. * this.schema.register( '$text', {
  872. * allowIn: '$block'
  873. * } );
  874. *
  875. * They reflect a typical editor content which is contained within one root, consists of several blocks
  876. * (paragraphs, lists items, headings, images) which, in turn, may contain text inside.
  877. *
  878. * By inheriting from the generic items you can define new items which will get extended by other editor features.
  879. * Read more about generic types in the {@linkTODO Defining schema} guide.
  880. *
  881. * # Example definitions
  882. *
  883. * Allow `paragraph` in roots and block quotes:
  884. *
  885. * schema.register( 'paragraph', {
  886. * allowIn: [ '$root', 'blockQuote' ],
  887. * isBlock: true
  888. * } );
  889. *
  890. * Allow `paragraph` everywhere where `$block` is allowed (i.e. in `$root`):
  891. *
  892. * schema.register( 'paragraph', {
  893. * allowWhere: '$block',
  894. * isBlock: true
  895. * } );
  896. *
  897. * Make `image` a block object, which is allowed everywhere where `$block` is.
  898. * Also, allow `src` and `alt` attributes on it:
  899. *
  900. * schema.register( 'image', {
  901. * allowWhere: '$block',
  902. * allowAttributes: [ 'src', 'alt' ],
  903. * isBlock: true,
  904. * isObject: true
  905. * } );
  906. *
  907. * Make `caption` allowed in `image` and make it allow all the content of `$block`s (usually, `$text`).
  908. * Also, mark it as a limit element so it can't be split:
  909. *
  910. * schema.register( 'caption', {
  911. * allowIn: 'image',
  912. * allowContentOf: '$block',
  913. * isLimit: true
  914. * } );
  915. *
  916. * Make `listItem` inherit all from `$block` but also allow additional attributes:
  917. *
  918. * schema.register( 'listItem', {
  919. * inheritAllFrom: '$block',
  920. * allowAttributes: [ 'type', 'indent' ]
  921. * } );
  922. *
  923. * Which translates to:
  924. *
  925. * schema.register( 'listItem', {
  926. * allowWhere: '$block',
  927. * allowContentOf: '$block',
  928. * allowAttributesOf: '$block',
  929. * inheritTypesFrom: '$block',
  930. * allowAttributes: [ 'type', 'indent' ]
  931. * } );
  932. *
  933. * # Tips
  934. *
  935. * * Check schema definitions of existing features to see how they are defined.
  936. * * If you want to publish your feature so other developers can use it, try to use
  937. * generic items as much as possible.
  938. * * Keep your model clean – limit it to the actual data and store information in an normalized way.
  939. * * Remember about definining the `is*` properties. They don't affect the allowed structures, but they can
  940. * affect how editor features treat your elements.
  941. *
  942. * @typedef {Object} module:engine/model/schema~SchemaItemDefinition
  943. */
  944. /**
  945. * A simplified version of {@link module:engine/model/schema~SchemaItemDefinition} after
  946. * compilation by the {@link module:engine/model/schema~Schema schema}.
  947. * Rules feed to the schema by {@link module:engine/model/schema~Schema#register}
  948. * and {@link module:engine/model/schema~Schema#extend} are defined in the
  949. * {@link module:engine/model/schema~SchemaItemDefinition} format.
  950. * Later on, they are compiled to `SchemaCompiledItemDefition` so when you use e.g.
  951. * the {@link module:engine/model/schema~Schema#getDefinition} method you get the compiled version.
  952. *
  953. * The compiled version contains only the following properties:
  954. *
  955. * * `name` property,
  956. * * `is*` properties,
  957. * * `allowIn` array,
  958. * * `allowAttributes` array.
  959. *
  960. * @typedef {Object} module:engine/model/schema~SchemaCompiledItemDefinition
  961. */
  962. /**
  963. * A schema context – a list of ancestors of a given position in the document.
  964. *
  965. * Considering such a position:
  966. *
  967. * <$root>
  968. * <blockQuote>
  969. * <paragraph>
  970. * ^
  971. * </paragraph>
  972. * </blockQuote>
  973. * </$root>
  974. *
  975. * The context of this position is its {@link module:engine/model/position~Position#getAncestors lists of ancestors}:
  976. *
  977. * [ rootElement, blockQuoteElement, paragraphElement ]
  978. *
  979. * Contexts are used in the {@link module:engine/model/schema~Schema#event:checkChild `Schema#checkChild`} and
  980. * {@link module:engine/model/schema~Schema#event:checkAttribute `Schema#checkAttribute`} events as a definition
  981. * of a place in the document where the check occurs. The context instances are created based on the first arguments
  982. * of the {@link module:engine/model/schema~Schema#checkChild `Schema#checkChild()`} and
  983. * {@link module:engine/model/schema~Schema#checkAttribute `Schema#checkAttribute()`} methods so when
  984. * using these methods you need to use {@link module:engine/model/schema~SchemaContextDefinition}s.
  985. */
  986. export class SchemaContext {
  987. /**
  988. * Creates an instance of the context.
  989. *
  990. * @param {module:engine/model/schema~SchemaContextDefinition|module:engine/model/schema~SchemaContext} context
  991. */
  992. constructor( context ) {
  993. if ( context instanceof SchemaContext ) {
  994. return context;
  995. }
  996. if ( !Array.isArray( context ) ) {
  997. // `context` is item or position.
  998. // Position#getAncestors() doesn't accept any parameters but it works just fine here.
  999. context = context.getAncestors( { includeSelf: true } );
  1000. }
  1001. if ( context[ 0 ] && typeof context[ 0 ] != 'string' && context[ 0 ].is( 'documentFragment' ) ) {
  1002. context.shift();
  1003. }
  1004. this._items = context.map( mapContextItem );
  1005. }
  1006. /**
  1007. * Number of items.
  1008. *
  1009. * @type {Number}
  1010. */
  1011. get length() {
  1012. return this._items.length;
  1013. }
  1014. /**
  1015. * The last item (the lowest node).
  1016. *
  1017. * @type {module:engine/model/schema~SchemaContextItem}
  1018. */
  1019. get last() {
  1020. return this._items[ this._items.length - 1 ];
  1021. }
  1022. /**
  1023. * Iterable interface.
  1024. *
  1025. * Iterates over all context items.
  1026. *
  1027. * @returns {Iterable.<module:engine/model/schema~SchemaContextItem>}
  1028. */
  1029. [ Symbol.iterator ]() {
  1030. return this._items[ Symbol.iterator ]();
  1031. }
  1032. /**
  1033. * Adds new item at the to of the context.
  1034. *
  1035. * @param {module:engine/model/node~Node|String} item Item to add.
  1036. */
  1037. addItem( item ) {
  1038. this._items.push( mapContextItem( item ) );
  1039. }
  1040. /**
  1041. * Gets an item on the given index.
  1042. *
  1043. * @returns {module:engine/model/schema~SchemaContextItem}
  1044. */
  1045. getItem( index ) {
  1046. return this._items[ index ];
  1047. }
  1048. /**
  1049. * Returns the names of items.
  1050. *
  1051. * @returns {Iterable.<String>}
  1052. */
  1053. * getNames() {
  1054. yield* this._items.map( item => item.name );
  1055. }
  1056. /**
  1057. * Checks whether the context ends with the given nodes.
  1058. *
  1059. * const ctx = new SchemaContext( [ rootElement, paragraphElement, textNode ] );
  1060. *
  1061. * ctx.endsWith( '$text' ); // -> true
  1062. * ctx.endsWith( 'paragraph $text' ); // -> true
  1063. * ctx.endsWith( '$root' ); // -> false
  1064. * ctx.endsWith( 'paragraph' ); // -> false
  1065. *
  1066. * @param {String} query
  1067. * @returns {Boolean}
  1068. */
  1069. endsWith( query ) {
  1070. return Array.from( this.getNames() ).join( ' ' ).endsWith( query );
  1071. }
  1072. }
  1073. /**
  1074. * The definition of a {@link module:engine/model/schema~SchemaContext schema context}.
  1075. *
  1076. * Contexts can be created in multiple ways:
  1077. *
  1078. * * By defining a **node** – in this cases this node and all its ancestors will be used.
  1079. * * By defining a **position** in the document – in this case all its ancestors will be used.
  1080. * * By defining an **array of nodes** – in this case this array defines the entire context.
  1081. * * By defining an **array of node names** (potentially, mixed with real nodes) – in this case
  1082. * nodes definied by strings will be "mocked". Using strings is not recommended as it
  1083. * means that the context will be unrealistic (e.g. attributes of these nodes are not specified).
  1084. * However, at times this may be the only way to define the context (e.g. when checking some
  1085. * hypothetical situation).
  1086. *
  1087. * Examples of context definitions passed to the {@link module:engine/model/schema~Schema#checkChild `Schema#checkChild()`}
  1088. * method:
  1089. *
  1090. * // Assuming that we have a $root > blockQuote > paragraph structure, the following code
  1091. * // will check node 'foo' in the following context:
  1092. * // [ rootElement, blockQuoteElement, paragraphElement ]
  1093. * const contextDefinition = paragraphElement;
  1094. * const childToCheck = 'foo';
  1095. * schema.checkChild( contextDefinition, childToCheck );
  1096. *
  1097. * // Also check in [ rootElement, blockQuoteElement, paragraphElement ].
  1098. * schema.checkChild( Position.createAt( paragraphElement ), 'foo' );
  1099. *
  1100. * // Check in [ rootElement, paragraphElement ].
  1101. * schema.checkChild( [ rootElement, paragraphElement ], 'foo' );
  1102. *
  1103. * // Check in [ fakeRootElement, fakeBarElement, paragraphElement ].
  1104. * schema.checkChild( [ '$root', 'bar', paragraphElement ], 'foo' );
  1105. *
  1106. * All these `checkChild()` calls will fire {@link module:engine/model/schema~Schema#event:checkChild `Schema#checkChild`}
  1107. * events in which `args[ 0 ]` is an instance of the context. Therefore, you can write a listener like this:
  1108. *
  1109. * schema.on( 'checkChild', ( evt, args ) => {
  1110. * const ctx = args[ 0 ];
  1111. *
  1112. * console.log( Array.from( ctx.getNames() ) );
  1113. * } );
  1114. *
  1115. * Which will log the following:
  1116. *
  1117. * [ '$root', 'blockQuote', 'paragraph' ]
  1118. * [ '$root', 'paragraph' ]
  1119. * [ '$root', 'bar', 'paragraph' ]
  1120. *
  1121. * Note: When using the {@link module:engine/model/schema~Schema#checkAttribute `Schema#checkAttribute()`} method
  1122. * you may want to check whether a text node may have an attribute. A {@link module:engine/model/text~Text} is a
  1123. * correct way to define a context so you can do this:
  1124. *
  1125. * schema.checkAttribute( textNode, 'bold' );
  1126. *
  1127. * But sometimes you want to check whether a text at a given position might've had some attribute,
  1128. * in which case you can create a context by mising an array of elements with a `'$text'` string:
  1129. *
  1130. * // Check in [ rootElement, paragraphElement, textNode ].
  1131. * schema.checkChild( [ ...positionInParagraph.getAncestors(), '$text' ], 'bold' );
  1132. *
  1133. * @typedef {module:engine/model/node~Node|module:engine/model/position~Position|
  1134. * Array.<String|module:engine/model/node~Node>} module:engine/model/schema~SchemaContextDefinition
  1135. */
  1136. /**
  1137. * An item of the {@link module:engine/model/schema~SchemaContext schema context}.
  1138. *
  1139. * It contains 3 properties:
  1140. *
  1141. * * `name` – the name of this item,
  1142. * * `* getAttributeKeys()` – a generator of keys of item attributes,
  1143. * * `getAttribute( keyName )` – a method to get attribute values.
  1144. *
  1145. * The context item interface is a highly simplified version of {@link module:engine/model/node~Node} and its role
  1146. * is to expose only the information which schema checks are able to provide (which is the name of the node and
  1147. * node's attributes).
  1148. *
  1149. * schema.on( 'checkChild', ( evt, args ) => {
  1150. * const ctx = args[ 0 ];
  1151. * const firstItem = ctx.getItem( 0 );
  1152. *
  1153. * console.log( firstItem.name ); // -> '$root'
  1154. * console.log( firstItem.getAttribute( 'foo' ) ); // -> 'bar'
  1155. * console.log( Array.from( firstItem.getAttributeKeys() ) ); // -> [ 'foo', 'faa' ]
  1156. * } );
  1157. *
  1158. * @typedef {Object} module:engine/model/schema~SchemaContextItem
  1159. */
  1160. function compileBaseItemRule( sourceItemRules, itemName ) {
  1161. const itemRule = {
  1162. name: itemName,
  1163. allowIn: [],
  1164. allowContentOf: [],
  1165. allowWhere: [],
  1166. allowAttributes: [],
  1167. allowAttributesOf: [],
  1168. inheritTypesFrom: []
  1169. };
  1170. copyTypes( sourceItemRules, itemRule );
  1171. copyProperty( sourceItemRules, itemRule, 'allowIn' );
  1172. copyProperty( sourceItemRules, itemRule, 'allowContentOf' );
  1173. copyProperty( sourceItemRules, itemRule, 'allowWhere' );
  1174. copyProperty( sourceItemRules, itemRule, 'allowAttributes' );
  1175. copyProperty( sourceItemRules, itemRule, 'allowAttributesOf' );
  1176. copyProperty( sourceItemRules, itemRule, 'inheritTypesFrom' );
  1177. makeInheritAllWork( sourceItemRules, itemRule );
  1178. return itemRule;
  1179. }
  1180. function compileAllowContentOf( compiledDefinitions, itemName ) {
  1181. for ( const allowContentOfItemName of compiledDefinitions[ itemName ].allowContentOf ) {
  1182. // The allowContentOf property may point to an unregistered element.
  1183. if ( compiledDefinitions[ allowContentOfItemName ] ) {
  1184. const allowedChildren = getAllowedChildren( compiledDefinitions, allowContentOfItemName );
  1185. allowedChildren.forEach( allowedItem => {
  1186. allowedItem.allowIn.push( itemName );
  1187. } );
  1188. }
  1189. }
  1190. delete compiledDefinitions[ itemName ].allowContentOf;
  1191. }
  1192. function compileAllowWhere( compiledDefinitions, itemName ) {
  1193. for ( const allowWhereItemName of compiledDefinitions[ itemName ].allowWhere ) {
  1194. const inheritFrom = compiledDefinitions[ allowWhereItemName ];
  1195. // The allowWhere property may point to an unregistered element.
  1196. if ( inheritFrom ) {
  1197. const allowedIn = inheritFrom.allowIn;
  1198. compiledDefinitions[ itemName ].allowIn.push( ...allowedIn );
  1199. }
  1200. }
  1201. delete compiledDefinitions[ itemName ].allowWhere;
  1202. }
  1203. function compileAllowAttributesOf( compiledDefinitions, itemName ) {
  1204. for ( const allowAttributeOfItem of compiledDefinitions[ itemName ].allowAttributesOf ) {
  1205. const inheritFrom = compiledDefinitions[ allowAttributeOfItem ];
  1206. if ( inheritFrom ) {
  1207. const inheritAttributes = inheritFrom.allowAttributes;
  1208. compiledDefinitions[ itemName ].allowAttributes.push( ...inheritAttributes );
  1209. }
  1210. }
  1211. delete compiledDefinitions[ itemName ].allowAttributesOf;
  1212. }
  1213. function compileInheritPropertiesFrom( compiledDefinitions, itemName ) {
  1214. const item = compiledDefinitions[ itemName ];
  1215. for ( const inheritPropertiesOfItem of item.inheritTypesFrom ) {
  1216. const inheritFrom = compiledDefinitions[ inheritPropertiesOfItem ];
  1217. if ( inheritFrom ) {
  1218. const typeNames = Object.keys( inheritFrom ).filter( name => name.startsWith( 'is' ) );
  1219. for ( const name of typeNames ) {
  1220. if ( !( name in item ) ) {
  1221. item[ name ] = inheritFrom[ name ];
  1222. }
  1223. }
  1224. }
  1225. }
  1226. delete item.inheritTypesFrom;
  1227. }
  1228. // Remove items which weren't registered (because it may break some checks or we'd need to complicate them).
  1229. // Make sure allowIn doesn't contain repeated values.
  1230. function cleanUpAllowIn( compiledDefinitions, itemName ) {
  1231. const itemRule = compiledDefinitions[ itemName ];
  1232. const existingItems = itemRule.allowIn.filter( itemToCheck => compiledDefinitions[ itemToCheck ] );
  1233. itemRule.allowIn = Array.from( new Set( existingItems ) );
  1234. }
  1235. function cleanUpAllowAttributes( compiledDefinitions, itemName ) {
  1236. const itemRule = compiledDefinitions[ itemName ];
  1237. itemRule.allowAttributes = Array.from( new Set( itemRule.allowAttributes ) );
  1238. }
  1239. function copyTypes( sourceItemRules, itemRule ) {
  1240. for ( const sourceItemRule of sourceItemRules ) {
  1241. const typeNames = Object.keys( sourceItemRule ).filter( name => name.startsWith( 'is' ) );
  1242. for ( const name of typeNames ) {
  1243. itemRule[ name ] = sourceItemRule[ name ];
  1244. }
  1245. }
  1246. }
  1247. function copyProperty( sourceItemRules, itemRule, propertyName ) {
  1248. for ( const sourceItemRule of sourceItemRules ) {
  1249. if ( typeof sourceItemRule[ propertyName ] == 'string' ) {
  1250. itemRule[ propertyName ].push( sourceItemRule[ propertyName ] );
  1251. } else if ( Array.isArray( sourceItemRule[ propertyName ] ) ) {
  1252. itemRule[ propertyName ].push( ...sourceItemRule[ propertyName ] );
  1253. }
  1254. }
  1255. }
  1256. function makeInheritAllWork( sourceItemRules, itemRule ) {
  1257. for ( const sourceItemRule of sourceItemRules ) {
  1258. const inheritFrom = sourceItemRule.inheritAllFrom;
  1259. if ( inheritFrom ) {
  1260. itemRule.allowContentOf.push( inheritFrom );
  1261. itemRule.allowWhere.push( inheritFrom );
  1262. itemRule.allowAttributesOf.push( inheritFrom );
  1263. itemRule.inheritTypesFrom.push( inheritFrom );
  1264. }
  1265. }
  1266. }
  1267. function getAllowedChildren( compiledDefinitions, itemName ) {
  1268. const itemRule = compiledDefinitions[ itemName ];
  1269. return getValues( compiledDefinitions ).filter( def => def.allowIn.includes( itemRule.name ) );
  1270. }
  1271. function getValues( obj ) {
  1272. return Object.keys( obj ).map( key => obj[ key ] );
  1273. }
  1274. function mapContextItem( ctxItem ) {
  1275. if ( typeof ctxItem == 'string' ) {
  1276. return {
  1277. name: ctxItem,
  1278. * getAttributeKeys() {},
  1279. getAttribute() {}
  1280. };
  1281. } else {
  1282. return {
  1283. // '$text' means text nodes and text proxies.
  1284. name: ctxItem.is( 'element' ) ? ctxItem.name : '$text',
  1285. * getAttributeKeys() {
  1286. yield* ctxItem.getAttributeKeys();
  1287. },
  1288. getAttribute( key ) {
  1289. return ctxItem.getAttribute( key );
  1290. }
  1291. };
  1292. }
  1293. }