schema.js 54 KB

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