schema.js 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549
  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|module:engine/model/documentselection~DocumentSelection} selection
  537. * 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( ( element, range ) => {
  544. const rangeCommonAncestor = range.getCommonAncestor();
  545. if ( !element ) {
  546. return rangeCommonAncestor;
  547. }
  548. return element.getCommonAncestor( rangeCommonAncestor, { includeSelf: true } );
  549. }, null );
  550. while ( !this.isLimit( element ) ) {
  551. if ( element.parent ) {
  552. element = element.parent;
  553. } else {
  554. break;
  555. }
  556. }
  557. return element;
  558. }
  559. /**
  560. * Checks whether the attribute is allowed in selection:
  561. *
  562. * * if the selection is not collapsed, then checks if the attribute is allowed on any of nodes in that range,
  563. * * if the selection is collapsed, then checks if on the selection position there's a text with the
  564. * specified attribute allowed.
  565. *
  566. * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection} selection
  567. * Selection which will be checked.
  568. * @param {String} attribute The name of the attribute to check.
  569. * @returns {Boolean}
  570. */
  571. checkAttributeInSelection( selection, attribute ) {
  572. if ( selection.isCollapsed ) {
  573. // Check whether schema allows for a text with the attribute in the selection.
  574. return this.checkAttribute( [ ...selection.getFirstPosition().getAncestors(), '$text' ], attribute );
  575. } else {
  576. const ranges = selection.getRanges();
  577. // For all ranges, check nodes in them until you find a node that is allowed to have the attribute.
  578. for ( const range of ranges ) {
  579. for ( const value of range ) {
  580. if ( this.checkAttribute( value.item, attribute ) ) {
  581. // If we found a node that is allowed to have the attribute, return true.
  582. return true;
  583. }
  584. }
  585. }
  586. }
  587. // If we haven't found such node, return false.
  588. return false;
  589. }
  590. /**
  591. * Transforms the given set of ranges into a set of ranges where the given attribute is allowed (and can be applied).
  592. *
  593. * @param {Array.<module:engine/model/range~Range>} ranges Ranges to be validated.
  594. * @param {String} attribute The name of the attribute to check.
  595. * @returns {Array.<module:engine/model/range~Range>} Ranges in which the attribute is allowed.
  596. */
  597. getValidRanges( ranges, attribute ) {
  598. const validRanges = [];
  599. for ( const range of ranges ) {
  600. let last = range.start;
  601. let from = range.start;
  602. const to = range.end;
  603. for ( const value of range.getWalker() ) {
  604. if ( !this.checkAttribute( value.item, attribute ) ) {
  605. if ( !from.isEqual( last ) ) {
  606. validRanges.push( new Range( from, last ) );
  607. }
  608. from = value.nextPosition;
  609. }
  610. last = value.nextPosition;
  611. }
  612. if ( from && !from.isEqual( to ) ) {
  613. validRanges.push( new Range( from, to ) );
  614. }
  615. }
  616. return validRanges;
  617. }
  618. /**
  619. * Basing on given the `position`, finds and returns a {@link module:engine/model/range~Range range} which is
  620. * nearest to that `position` and is a correct range for selection.
  621. *
  622. * The correct selection range might be collapsed when it is located in a position where the text node can be placed.
  623. * Non-collapsed range is returned when selection can be placed around element marked as an "object" in
  624. * the {@link module:engine/model/schema~Schema schema}.
  625. *
  626. * Direction of searching for the nearest correct selection range can be specified as:
  627. *
  628. * * `both` - searching will be performed in both ways,
  629. * * `forward` - searching will be performed only forward,
  630. * * `backward` - searching will be performed only backward.
  631. *
  632. * When valid selection range cannot be found, `null` is returned.
  633. *
  634. * @param {module:engine/model/position~Position} position Reference position where new selection range should be looked for.
  635. * @param {'both'|'forward'|'backward'} [direction='both'] Search direction.
  636. * @returns {module:engine/model/range~Range|null} Nearest selection range or `null` if one cannot be found.
  637. */
  638. getNearestSelectionRange( position, direction = 'both' ) {
  639. // Return collapsed range if provided position is valid.
  640. if ( this.checkChild( position, '$text' ) ) {
  641. return new Range( position );
  642. }
  643. let backwardWalker, forwardWalker;
  644. if ( direction == 'both' || direction == 'backward' ) {
  645. backwardWalker = new TreeWalker( { startPosition: position, direction: 'backward' } );
  646. }
  647. if ( direction == 'both' || direction == 'forward' ) {
  648. forwardWalker = new TreeWalker( { startPosition: position } );
  649. }
  650. for ( const data of combineWalkers( backwardWalker, forwardWalker ) ) {
  651. const type = ( data.walker == backwardWalker ? 'elementEnd' : 'elementStart' );
  652. const value = data.value;
  653. if ( value.type == type && this.isObject( value.item ) ) {
  654. return Range.createOn( value.item );
  655. }
  656. if ( this.checkChild( value.nextPosition, '$text' ) ) {
  657. return new Range( value.nextPosition );
  658. }
  659. }
  660. return null;
  661. }
  662. /**
  663. * Tries to find position ancestors that allows to insert given node.
  664. * It starts searching from the given position and goes node by node to the top of the model tree
  665. * as long as {@link module:engine/model/schema~Schema#isLimit limit element},
  666. * {@link module:engine/model/schema~Schema#isObject object element} or top-most ancestor won't be reached.
  667. *
  668. * @params {module:engine/model/node~Node} node Node for which allowed parent should be found.
  669. * @params {module:engine/model/position~Position} position Position from searching will start.
  670. * @returns {module:engine/model/element~Element|null} element Allowed parent or null if nothing was found.
  671. */
  672. findAllowedParent( node, position ) {
  673. let parent = position.parent;
  674. while ( parent ) {
  675. if ( this.checkChild( parent, node ) ) {
  676. return parent;
  677. }
  678. // Do not split limit elements and objects.
  679. if ( this.isLimit( parent ) || this.isObject( parent ) ) {
  680. return null;
  681. }
  682. parent = parent.parent;
  683. }
  684. return null;
  685. }
  686. /**
  687. * Removes attributes disallowed by the schema.
  688. *
  689. * @param {Iterable.<module:engine/model/node~Node>} nodes Nodes that will be filtered.
  690. * @param {module:engine/model/writer~Writer} writer
  691. */
  692. removeDisallowedAttributes( nodes, writer ) {
  693. for ( const node of nodes ) {
  694. for ( const attribute of node.getAttributeKeys() ) {
  695. if ( !this.checkAttribute( node, attribute ) ) {
  696. writer.removeAttribute( attribute, node );
  697. }
  698. }
  699. if ( node.is( 'element' ) ) {
  700. this.removeDisallowedAttributes( node.getChildren(), writer );
  701. }
  702. }
  703. }
  704. /**
  705. * @private
  706. */
  707. _clearCache() {
  708. this._compiledDefinitions = null;
  709. }
  710. /**
  711. * @private
  712. */
  713. _compile() {
  714. const compiledDefinitions = {};
  715. const sourceRules = this._sourceDefinitions;
  716. const itemNames = Object.keys( sourceRules );
  717. for ( const itemName of itemNames ) {
  718. compiledDefinitions[ itemName ] = compileBaseItemRule( sourceRules[ itemName ], itemName );
  719. }
  720. for ( const itemName of itemNames ) {
  721. compileAllowContentOf( compiledDefinitions, itemName );
  722. }
  723. for ( const itemName of itemNames ) {
  724. compileAllowWhere( compiledDefinitions, itemName );
  725. }
  726. for ( const itemName of itemNames ) {
  727. compileAllowAttributesOf( compiledDefinitions, itemName );
  728. compileInheritPropertiesFrom( compiledDefinitions, itemName );
  729. }
  730. for ( const itemName of itemNames ) {
  731. cleanUpAllowIn( compiledDefinitions, itemName );
  732. cleanUpAllowAttributes( compiledDefinitions, itemName );
  733. }
  734. this._compiledDefinitions = compiledDefinitions;
  735. }
  736. /**
  737. * @private
  738. * @param {module:engine/model/schema~SchemaCompiledItemDefinition} def
  739. * @param {module:engine/model/schema~SchemaContext} context
  740. * @param {Number} contextItemIndex
  741. */
  742. _checkContextMatch( def, context, contextItemIndex = context.length - 1 ) {
  743. const contextItem = context.getItem( contextItemIndex );
  744. if ( def.allowIn.includes( contextItem.name ) ) {
  745. if ( contextItemIndex == 0 ) {
  746. return true;
  747. } else {
  748. const parentRule = this.getDefinition( contextItem );
  749. return this._checkContextMatch( parentRule, context, contextItemIndex - 1 );
  750. }
  751. } else {
  752. return false;
  753. }
  754. }
  755. }
  756. mix( Schema, ObservableMixin );
  757. /**
  758. * Event fired when the {@link #checkChild} method is called. It allows plugging in
  759. * additional behavior – e.g. implementing rules which cannot be defined using the declarative
  760. * {@link module:engine/model/schema~SchemaItemDefinition} interface.
  761. *
  762. * **Note:** The {@link #addChildCheck} method is a more handy way to register callbacks. Internally,
  763. * it registers a listener to this event but comes with a simpler API and it is the recommended choice
  764. * in most of the cases.
  765. *
  766. * The {@link #checkChild} method fires an event because it is
  767. * {@link module:utils/observablemixin~ObservableMixin#decorate decorated} with it. Thanks to that you can
  768. * use this event in a various way, but the most important use case is overriding standard behaviour of the
  769. * `checkChild()` method. Let's see a typical listener template:
  770. *
  771. * schema.on( 'checkChild', ( evt, args ) => {
  772. * const context = args[ 0 ];
  773. * const childDefinition = args[ 1 ];
  774. * }, { priority: 'high' } );
  775. *
  776. * The listener is added with a `high` priority to be executed before the default method is really called. The `args` callback
  777. * parameter contains arguments passed to `checkChild( context, child )`. However, the `context` parameter is already
  778. * normalized to a {@link module:engine/model/schema~SchemaContext} instance and `child` to a
  779. * {@link module:engine/model/schema~SchemaCompiledItemDefinition} instance, so you don't have to worry about
  780. * the various ways how `context` and `child` may be passed to `checkChild()`.
  781. *
  782. * **Note:** `childDefinition` may be `undefined` if `checkChild()` was called with a non-registered element.
  783. *
  784. * So, in order to implement a rule "disallow `heading1` in `blockQuote`" you can add such a listener:
  785. *
  786. * schema.on( 'checkChild', ( evt, args ) => {
  787. * const context = args[ 0 ];
  788. * const childDefinition = args[ 1 ];
  789. *
  790. * if ( context.endsWith( 'blockQuote' ) && childDefinition && childDefinition.name == 'heading1' ) {
  791. * // Prevent next listeners from being called.
  792. * evt.stop();
  793. * // Set the checkChild()'s return value.
  794. * evt.return = false;
  795. * }
  796. * }, { priority: 'high' } );
  797. *
  798. * Allowing elements in specific contexts will be a far less common use case, because it's normally handled by
  799. * `allowIn` rule from {@link module:engine/model/schema~SchemaItemDefinition} but if you have a complex scenario
  800. * where `listItem` should be allowed only in element `foo` which must be in element `bar`, then this would be the way:
  801. *
  802. * schema.on( 'checkChild', ( evt, args ) => {
  803. * const context = args[ 0 ];
  804. * const childDefinition = args[ 1 ];
  805. *
  806. * if ( context.endsWith( 'bar foo' ) && childDefinition.name == 'listItem' ) {
  807. * // Prevent next listeners from being called.
  808. * evt.stop();
  809. * // Set the checkChild()'s return value.
  810. * evt.return = true;
  811. * }
  812. * }, { priority: 'high' } );
  813. *
  814. * @event checkChild
  815. * @param {Array} args The `checkChild()`'s arguments.
  816. */
  817. /**
  818. * Event fired when the {@link #checkAttribute} method is called. It allows plugging in
  819. * additional behavior – e.g. implementing rules which cannot be defined using the declarative
  820. * {@link module:engine/model/schema~SchemaItemDefinition} interface.
  821. *
  822. * **Note:** The {@link #addAttributeCheck} method is a more handy way to register callbacks. Internally,
  823. * it registers a listener to this event but comes with a simpler API and it is the recommended choice
  824. * in most of the cases.
  825. *
  826. * The {@link #checkAttribute} method fires an event because it's
  827. * {@link module:utils/observablemixin~ObservableMixin#decorate decorated} with it. Thanks to that you can
  828. * use this event in a various way, but the most important use case is overriding standard behaviour of the
  829. * `checkAttribute()` method. Let's see a typical listener template:
  830. *
  831. * schema.on( 'checkAttribute', ( evt, args ) => {
  832. * const context = args[ 0 ];
  833. * const attributeName = args[ 1 ];
  834. * }, { priority: 'high' } );
  835. *
  836. * The listener is added with a `high` priority to be executed before the default method is really called. The `args` callback
  837. * parameter contains arguments passed to `checkAttribute( context, attributeName )`. However, the `context` parameter is already
  838. * normalized to a {@link module:engine/model/schema~SchemaContext} instance, so you don't have to worry about
  839. * the various ways how `context` may be passed to `checkAttribute()`.
  840. *
  841. * So, in order to implement a rule "disallow `bold` in a text which is in a `heading1` you can add such a listener:
  842. *
  843. * schema.on( 'checkAttribute', ( evt, args ) => {
  844. * const context = args[ 0 ];
  845. * const atributeName = args[ 1 ];
  846. *
  847. * if ( context.endsWith( 'heading1 $text' ) && attributeName == 'bold' ) {
  848. * // Prevent next listeners from being called.
  849. * evt.stop();
  850. * // Set the checkAttribute()'s return value.
  851. * evt.return = false;
  852. * }
  853. * }, { priority: 'high' } );
  854. *
  855. * Allowing attributes in specific contexts will be a far less common use case, because it's normally handled by
  856. * `allowAttributes` rule from {@link module:engine/model/schema~SchemaItemDefinition} but if you have a complex scenario
  857. * where `bold` should be allowed only in element `foo` which must be in element `bar`, then this would be the way:
  858. *
  859. * schema.on( 'checkAttribute', ( evt, args ) => {
  860. * const context = args[ 0 ];
  861. * const atributeName = args[ 1 ];
  862. *
  863. * if ( context.endsWith( 'bar foo $text' ) && attributeName == 'bold' ) {
  864. * // Prevent next listeners from being called.
  865. * evt.stop();
  866. * // Set the checkAttribute()'s return value.
  867. * evt.return = true;
  868. * }
  869. * }, { priority: 'high' } );
  870. *
  871. * @event checkAttribute
  872. * @param {Array} args The `checkAttribute()`'s arguments.
  873. */
  874. /**
  875. * A definition of a {@link module:engine/model/schema~Schema schema} item.
  876. *
  877. * You can define the following rules:
  878. *
  879. * * `allowIn` – a string or an array of strings. Defines in which other items this item will be allowed.
  880. * * `allowAttributes` – a string or an array of strings. Defines allowed attributes of the given item.
  881. * * `allowContentOf` – a string or an array of strings. Inherit "allowed children" from other items.
  882. * * `allowWhere` – a string or an array of strings. Inherit "allowed in" from other items.
  883. * * `allowAttributesOf` – a string or an array of strings. Inherit attributes from other items.
  884. * * `inheritTypesFrom` – a string or an array of strings. Inherit `is*` properties of other items.
  885. * * `inheritAllFrom` – a string. A shorthand for `allowContentOf`, `allowWhere`, `allowAttributesOf`, `inheritTypesFrom`.
  886. * * additionall, you can define the following `is*` properties: `isBlock`, `isLimit`, `isObject`. Read about them below.
  887. *
  888. * # The is* properties
  889. *
  890. * There are 3 commonly used `is*` properties. Their role is to assign additional semantics to schema items.
  891. * You can define more properties but you will also need to implement support for them in the existing editor features.
  892. *
  893. * * `isBlock` – whether this item is paragraph-like. Generally speaking, a content is usually made out of blocks
  894. * like paragraphs, list items, images, headings, etc. All these elements are marked as blocks. A block
  895. * should not allow another block inside. Note: there's also the `$block` generic item which has `isBlock` set to `true`.
  896. * Most block type items will inherit from `$block` (through `inheritAllFrom`).
  897. * * `isLimit` – can be understood as whether this element should not be split by <kbd>Enter</kbd>.
  898. * Examples of limit elements – `$root`, table cell, image caption, etc. In other words, all actions which happen inside
  899. * a limit element are limitted to its content.
  900. * * `isObject` – whether item is "self-contained" and should be treated as a whole. Examples of object elements –
  901. * `image`, `table`, `video`, etc.
  902. *
  903. * # Generic items
  904. *
  905. * There are three basic generic items: `$root`, `$block` and `$text`.
  906. * They are defined as follows:
  907. *
  908. * this.schema.register( '$root', {
  909. * isLimit: true
  910. * } );
  911. * this.schema.register( '$block', {
  912. * allowIn: '$root',
  913. * isBlock: true
  914. * } );
  915. * this.schema.register( '$text', {
  916. * allowIn: '$block'
  917. * } );
  918. *
  919. * They reflect a typical editor content which is contained within one root, consists of several blocks
  920. * (paragraphs, lists items, headings, images) which, in turn, may contain text inside.
  921. *
  922. * By inheriting from the generic items you can define new items which will get extended by other editor features.
  923. * Read more about generic types in the {@linkTODO Defining schema} guide.
  924. *
  925. * # Example definitions
  926. *
  927. * Allow `paragraph` in roots and block quotes:
  928. *
  929. * schema.register( 'paragraph', {
  930. * allowIn: [ '$root', 'blockQuote' ],
  931. * isBlock: true
  932. * } );
  933. *
  934. * Allow `paragraph` everywhere where `$block` is allowed (i.e. in `$root`):
  935. *
  936. * schema.register( 'paragraph', {
  937. * allowWhere: '$block',
  938. * isBlock: true
  939. * } );
  940. *
  941. * Make `image` a block object, which is allowed everywhere where `$block` is.
  942. * Also, allow `src` and `alt` attributes on it:
  943. *
  944. * schema.register( 'image', {
  945. * allowWhere: '$block',
  946. * allowAttributes: [ 'src', 'alt' ],
  947. * isBlock: true,
  948. * isObject: true
  949. * } );
  950. *
  951. * Make `caption` allowed in `image` and make it allow all the content of `$block`s (usually, `$text`).
  952. * Also, mark it as a limit element so it can't be split:
  953. *
  954. * schema.register( 'caption', {
  955. * allowIn: 'image',
  956. * allowContentOf: '$block',
  957. * isLimit: true
  958. * } );
  959. *
  960. * Make `listItem` inherit all from `$block` but also allow additional attributes:
  961. *
  962. * schema.register( 'listItem', {
  963. * inheritAllFrom: '$block',
  964. * allowAttributes: [ 'listType', 'listIndent' ]
  965. * } );
  966. *
  967. * Which translates to:
  968. *
  969. * schema.register( 'listItem', {
  970. * allowWhere: '$block',
  971. * allowContentOf: '$block',
  972. * allowAttributesOf: '$block',
  973. * inheritTypesFrom: '$block',
  974. * allowAttributes: [ 'listType', 'listIndent' ]
  975. * } );
  976. *
  977. * # Tips
  978. *
  979. * * Check schema definitions of existing features to see how they are defined.
  980. * * If you want to publish your feature so other developers can use it, try to use
  981. * generic items as much as possible.
  982. * * Keep your model clean – limit it to the actual data and store information in an normalized way.
  983. * * Remember about definining the `is*` properties. They don't affect the allowed structures, but they can
  984. * affect how editor features treat your elements.
  985. *
  986. * @typedef {Object} module:engine/model/schema~SchemaItemDefinition
  987. */
  988. /**
  989. * A simplified version of {@link module:engine/model/schema~SchemaItemDefinition} after
  990. * compilation by the {@link module:engine/model/schema~Schema schema}.
  991. * Rules feed to the schema by {@link module:engine/model/schema~Schema#register}
  992. * and {@link module:engine/model/schema~Schema#extend} are defined in the
  993. * {@link module:engine/model/schema~SchemaItemDefinition} format.
  994. * Later on, they are compiled to `SchemaCompiledItemDefition` so when you use e.g.
  995. * the {@link module:engine/model/schema~Schema#getDefinition} method you get the compiled version.
  996. *
  997. * The compiled version contains only the following properties:
  998. *
  999. * * `name` property,
  1000. * * `is*` properties,
  1001. * * `allowIn` array,
  1002. * * `allowAttributes` array.
  1003. *
  1004. * @typedef {Object} module:engine/model/schema~SchemaCompiledItemDefinition
  1005. */
  1006. /**
  1007. * A schema context – a list of ancestors of a given position in the document.
  1008. *
  1009. * Considering such a position:
  1010. *
  1011. * <$root>
  1012. * <blockQuote>
  1013. * <paragraph>
  1014. * ^
  1015. * </paragraph>
  1016. * </blockQuote>
  1017. * </$root>
  1018. *
  1019. * The context of this position is its {@link module:engine/model/position~Position#getAncestors lists of ancestors}:
  1020. *
  1021. * [ rootElement, blockQuoteElement, paragraphElement ]
  1022. *
  1023. * Contexts are used in the {@link module:engine/model/schema~Schema#event:checkChild `Schema#checkChild`} and
  1024. * {@link module:engine/model/schema~Schema#event:checkAttribute `Schema#checkAttribute`} events as a definition
  1025. * of a place in the document where the check occurs. The context instances are created based on the first arguments
  1026. * of the {@link module:engine/model/schema~Schema#checkChild `Schema#checkChild()`} and
  1027. * {@link module:engine/model/schema~Schema#checkAttribute `Schema#checkAttribute()`} methods so when
  1028. * using these methods you need to use {@link module:engine/model/schema~SchemaContextDefinition}s.
  1029. */
  1030. export class SchemaContext {
  1031. /**
  1032. * Creates an instance of the context.
  1033. *
  1034. * @param {module:engine/model/schema~SchemaContextDefinition} context
  1035. */
  1036. constructor( context ) {
  1037. if ( context instanceof SchemaContext ) {
  1038. return context;
  1039. }
  1040. if ( typeof context == 'string' ) {
  1041. context = [ context ];
  1042. } else if ( !Array.isArray( context ) ) {
  1043. // `context` is item or position.
  1044. // Position#getAncestors() doesn't accept any parameters but it works just fine here.
  1045. context = context.getAncestors( { includeSelf: true } );
  1046. }
  1047. if ( context[ 0 ] && typeof context[ 0 ] != 'string' && context[ 0 ].is( 'documentFragment' ) ) {
  1048. context.shift();
  1049. }
  1050. this._items = context.map( mapContextItem );
  1051. }
  1052. /**
  1053. * Number of items.
  1054. *
  1055. * @type {Number}
  1056. */
  1057. get length() {
  1058. return this._items.length;
  1059. }
  1060. /**
  1061. * The last item (the lowest node).
  1062. *
  1063. * @type {module:engine/model/schema~SchemaContextItem}
  1064. */
  1065. get last() {
  1066. return this._items[ this._items.length - 1 ];
  1067. }
  1068. /**
  1069. * Iterable interface.
  1070. *
  1071. * Iterates over all context items.
  1072. *
  1073. * @returns {Iterable.<module:engine/model/schema~SchemaContextItem>}
  1074. */
  1075. [ Symbol.iterator ]() {
  1076. return this._items[ Symbol.iterator ]();
  1077. }
  1078. /**
  1079. * Returns new SchemaContext instance with additional item
  1080. *
  1081. * Item can be added as:
  1082. *
  1083. * const context = new SchemaContext( [ '$root' ] );
  1084. *
  1085. * // An element.
  1086. * const fooElement = writer.createElement( 'fooElement' );
  1087. * const newContext = context.push( fooElement ); // [ '$root', 'fooElement' ]
  1088. *
  1089. * // A text node.
  1090. * const text = writer.createText( 'foobar' );
  1091. * const newContext = context.push( text ); // [ '$root', '$text' ]
  1092. *
  1093. * // A string (element name).
  1094. * const newContext = context.push( 'barElement' ); // [ '$root', 'barElement' ]
  1095. *
  1096. * **Note** {module:engine/model/node~Node} that is already in the model tree will be added as the only item (without ancestors).
  1097. *
  1098. * @param {String|module:engine/model/node~Node|Array<String|module:engine/model/node~Node>} item Item that will be added
  1099. * to current context.
  1100. * @returns {module:engine/model/schema~SchemaContext} New SchemaContext instance with additional item.
  1101. */
  1102. push( item ) {
  1103. const ctx = new SchemaContext( [ item ] );
  1104. ctx._items = [ ...this._items, ...ctx._items ];
  1105. return ctx;
  1106. }
  1107. /**
  1108. * Gets an item on the given index.
  1109. *
  1110. * @returns {module:engine/model/schema~SchemaContextItem}
  1111. */
  1112. getItem( index ) {
  1113. return this._items[ index ];
  1114. }
  1115. /**
  1116. * Returns the names of items.
  1117. *
  1118. * @returns {Iterable.<String>}
  1119. */
  1120. * getNames() {
  1121. yield* this._items.map( item => item.name );
  1122. }
  1123. /**
  1124. * Checks whether the context ends with the given nodes.
  1125. *
  1126. * const ctx = new SchemaContext( [ rootElement, paragraphElement, textNode ] );
  1127. *
  1128. * ctx.endsWith( '$text' ); // -> true
  1129. * ctx.endsWith( 'paragraph $text' ); // -> true
  1130. * ctx.endsWith( '$root' ); // -> false
  1131. * ctx.endsWith( 'paragraph' ); // -> false
  1132. *
  1133. * @param {String} query
  1134. * @returns {Boolean}
  1135. */
  1136. endsWith( query ) {
  1137. return Array.from( this.getNames() ).join( ' ' ).endsWith( query );
  1138. }
  1139. }
  1140. /**
  1141. * The definition of a {@link module:engine/model/schema~SchemaContext schema context}.
  1142. *
  1143. * Contexts can be created in multiple ways:
  1144. *
  1145. * * By defining a **node** – in this cases this node and all its ancestors will be used.
  1146. * * By defining a **position** in the document – in this case all its ancestors will be used.
  1147. * * By defining an **array of nodes** – in this case this array defines the entire context.
  1148. * * By defining a **name of node** - in this case node will be "mocked". It is not recommended because context
  1149. * will be unrealistic (e.g. attributes of these nodes are not specified). However, at times this may be the only
  1150. * way to define the context (e.g. when checking some hypothetical situation).
  1151. * * By defining an **array of node names** (potentially, mixed with real nodes) – The same as **name of node**
  1152. * but it is possible to create a path.
  1153. * * By defining a {@link module:engine/model/schema~SchemaContext} instance - in this case the same instance as provided
  1154. * will be return.
  1155. *
  1156. * Examples of context definitions passed to the {@link module:engine/model/schema~Schema#checkChild `Schema#checkChild()`}
  1157. * method:
  1158. *
  1159. * // Assuming that we have a $root > blockQuote > paragraph structure, the following code
  1160. * // will check node 'foo' in the following context:
  1161. * // [ rootElement, blockQuoteElement, paragraphElement ]
  1162. * const contextDefinition = paragraphElement;
  1163. * const childToCheck = 'foo';
  1164. * schema.checkChild( contextDefinition, childToCheck );
  1165. *
  1166. * // Also check in [ rootElement, blockQuoteElement, paragraphElement ].
  1167. * schema.checkChild( Position.createAt( paragraphElement ), 'foo' );
  1168. *
  1169. * // Check in [ rootElement, paragraphElement ].
  1170. * schema.checkChild( [ rootElement, paragraphElement ], 'foo' );
  1171. *
  1172. * // Check only fakeParagraphElement.
  1173. * schema.checkChild( 'paragraph', 'foo' );
  1174. *
  1175. * // Check in [ fakeRootElement, fakeBarElement, paragraphElement ].
  1176. * schema.checkChild( [ '$root', 'bar', paragraphElement ], 'foo' );
  1177. *
  1178. * All these `checkChild()` calls will fire {@link module:engine/model/schema~Schema#event:checkChild `Schema#checkChild`}
  1179. * events in which `args[ 0 ]` is an instance of the context. Therefore, you can write a listener like this:
  1180. *
  1181. * schema.on( 'checkChild', ( evt, args ) => {
  1182. * const ctx = args[ 0 ];
  1183. *
  1184. * console.log( Array.from( ctx.getNames() ) );
  1185. * } );
  1186. *
  1187. * Which will log the following:
  1188. *
  1189. * [ '$root', 'blockQuote', 'paragraph' ]
  1190. * [ '$root', 'paragraph' ]
  1191. * [ '$root', 'bar', 'paragraph' ]
  1192. *
  1193. * Note: When using the {@link module:engine/model/schema~Schema#checkAttribute `Schema#checkAttribute()`} method
  1194. * you may want to check whether a text node may have an attribute. A {@link module:engine/model/text~Text} is a
  1195. * correct way to define a context so you can do this:
  1196. *
  1197. * schema.checkAttribute( textNode, 'bold' );
  1198. *
  1199. * But sometimes you want to check whether a text at a given position might've had some attribute,
  1200. * in which case you can create a context by mising an array of elements with a `'$text'` string:
  1201. *
  1202. * // Check in [ rootElement, paragraphElement, textNode ].
  1203. * schema.checkChild( [ ...positionInParagraph.getAncestors(), '$text' ], 'bold' );
  1204. *
  1205. * @typedef {module:engine/model/node~Node|module:engine/model/position~Position|module:engine/model/schema~SchemaContext|
  1206. * String|Array.<String|module:engine/model/node~Node>} module:engine/model/schema~SchemaContextDefinition
  1207. */
  1208. /**
  1209. * An item of the {@link module:engine/model/schema~SchemaContext schema context}.
  1210. *
  1211. * It contains 3 properties:
  1212. *
  1213. * * `name` – the name of this item,
  1214. * * `* getAttributeKeys()` – a generator of keys of item attributes,
  1215. * * `getAttribute( keyName )` – a method to get attribute values.
  1216. *
  1217. * The context item interface is a highly simplified version of {@link module:engine/model/node~Node} and its role
  1218. * is to expose only the information which schema checks are able to provide (which is the name of the node and
  1219. * node's attributes).
  1220. *
  1221. * schema.on( 'checkChild', ( evt, args ) => {
  1222. * const ctx = args[ 0 ];
  1223. * const firstItem = ctx.getItem( 0 );
  1224. *
  1225. * console.log( firstItem.name ); // -> '$root'
  1226. * console.log( firstItem.getAttribute( 'foo' ) ); // -> 'bar'
  1227. * console.log( Array.from( firstItem.getAttributeKeys() ) ); // -> [ 'foo', 'faa' ]
  1228. * } );
  1229. *
  1230. * @typedef {Object} module:engine/model/schema~SchemaContextItem
  1231. */
  1232. function compileBaseItemRule( sourceItemRules, itemName ) {
  1233. const itemRule = {
  1234. name: itemName,
  1235. allowIn: [],
  1236. allowContentOf: [],
  1237. allowWhere: [],
  1238. allowAttributes: [],
  1239. allowAttributesOf: [],
  1240. inheritTypesFrom: []
  1241. };
  1242. copyTypes( sourceItemRules, itemRule );
  1243. copyProperty( sourceItemRules, itemRule, 'allowIn' );
  1244. copyProperty( sourceItemRules, itemRule, 'allowContentOf' );
  1245. copyProperty( sourceItemRules, itemRule, 'allowWhere' );
  1246. copyProperty( sourceItemRules, itemRule, 'allowAttributes' );
  1247. copyProperty( sourceItemRules, itemRule, 'allowAttributesOf' );
  1248. copyProperty( sourceItemRules, itemRule, 'inheritTypesFrom' );
  1249. makeInheritAllWork( sourceItemRules, itemRule );
  1250. return itemRule;
  1251. }
  1252. function compileAllowContentOf( compiledDefinitions, itemName ) {
  1253. for ( const allowContentOfItemName of compiledDefinitions[ itemName ].allowContentOf ) {
  1254. // The allowContentOf property may point to an unregistered element.
  1255. if ( compiledDefinitions[ allowContentOfItemName ] ) {
  1256. const allowedChildren = getAllowedChildren( compiledDefinitions, allowContentOfItemName );
  1257. allowedChildren.forEach( allowedItem => {
  1258. allowedItem.allowIn.push( itemName );
  1259. } );
  1260. }
  1261. }
  1262. delete compiledDefinitions[ itemName ].allowContentOf;
  1263. }
  1264. function compileAllowWhere( compiledDefinitions, itemName ) {
  1265. for ( const allowWhereItemName of compiledDefinitions[ itemName ].allowWhere ) {
  1266. const inheritFrom = compiledDefinitions[ allowWhereItemName ];
  1267. // The allowWhere property may point to an unregistered element.
  1268. if ( inheritFrom ) {
  1269. const allowedIn = inheritFrom.allowIn;
  1270. compiledDefinitions[ itemName ].allowIn.push( ...allowedIn );
  1271. }
  1272. }
  1273. delete compiledDefinitions[ itemName ].allowWhere;
  1274. }
  1275. function compileAllowAttributesOf( compiledDefinitions, itemName ) {
  1276. for ( const allowAttributeOfItem of compiledDefinitions[ itemName ].allowAttributesOf ) {
  1277. const inheritFrom = compiledDefinitions[ allowAttributeOfItem ];
  1278. if ( inheritFrom ) {
  1279. const inheritAttributes = inheritFrom.allowAttributes;
  1280. compiledDefinitions[ itemName ].allowAttributes.push( ...inheritAttributes );
  1281. }
  1282. }
  1283. delete compiledDefinitions[ itemName ].allowAttributesOf;
  1284. }
  1285. function compileInheritPropertiesFrom( compiledDefinitions, itemName ) {
  1286. const item = compiledDefinitions[ itemName ];
  1287. for ( const inheritPropertiesOfItem of item.inheritTypesFrom ) {
  1288. const inheritFrom = compiledDefinitions[ inheritPropertiesOfItem ];
  1289. if ( inheritFrom ) {
  1290. const typeNames = Object.keys( inheritFrom ).filter( name => name.startsWith( 'is' ) );
  1291. for ( const name of typeNames ) {
  1292. if ( !( name in item ) ) {
  1293. item[ name ] = inheritFrom[ name ];
  1294. }
  1295. }
  1296. }
  1297. }
  1298. delete item.inheritTypesFrom;
  1299. }
  1300. // Remove items which weren't registered (because it may break some checks or we'd need to complicate them).
  1301. // Make sure allowIn doesn't contain repeated values.
  1302. function cleanUpAllowIn( compiledDefinitions, itemName ) {
  1303. const itemRule = compiledDefinitions[ itemName ];
  1304. const existingItems = itemRule.allowIn.filter( itemToCheck => compiledDefinitions[ itemToCheck ] );
  1305. itemRule.allowIn = Array.from( new Set( existingItems ) );
  1306. }
  1307. function cleanUpAllowAttributes( compiledDefinitions, itemName ) {
  1308. const itemRule = compiledDefinitions[ itemName ];
  1309. itemRule.allowAttributes = Array.from( new Set( itemRule.allowAttributes ) );
  1310. }
  1311. function copyTypes( sourceItemRules, itemRule ) {
  1312. for ( const sourceItemRule of sourceItemRules ) {
  1313. const typeNames = Object.keys( sourceItemRule ).filter( name => name.startsWith( 'is' ) );
  1314. for ( const name of typeNames ) {
  1315. itemRule[ name ] = sourceItemRule[ name ];
  1316. }
  1317. }
  1318. }
  1319. function copyProperty( sourceItemRules, itemRule, propertyName ) {
  1320. for ( const sourceItemRule of sourceItemRules ) {
  1321. if ( typeof sourceItemRule[ propertyName ] == 'string' ) {
  1322. itemRule[ propertyName ].push( sourceItemRule[ propertyName ] );
  1323. } else if ( Array.isArray( sourceItemRule[ propertyName ] ) ) {
  1324. itemRule[ propertyName ].push( ...sourceItemRule[ propertyName ] );
  1325. }
  1326. }
  1327. }
  1328. function makeInheritAllWork( sourceItemRules, itemRule ) {
  1329. for ( const sourceItemRule of sourceItemRules ) {
  1330. const inheritFrom = sourceItemRule.inheritAllFrom;
  1331. if ( inheritFrom ) {
  1332. itemRule.allowContentOf.push( inheritFrom );
  1333. itemRule.allowWhere.push( inheritFrom );
  1334. itemRule.allowAttributesOf.push( inheritFrom );
  1335. itemRule.inheritTypesFrom.push( inheritFrom );
  1336. }
  1337. }
  1338. }
  1339. function getAllowedChildren( compiledDefinitions, itemName ) {
  1340. const itemRule = compiledDefinitions[ itemName ];
  1341. return getValues( compiledDefinitions ).filter( def => def.allowIn.includes( itemRule.name ) );
  1342. }
  1343. function getValues( obj ) {
  1344. return Object.keys( obj ).map( key => obj[ key ] );
  1345. }
  1346. function mapContextItem( ctxItem ) {
  1347. if ( typeof ctxItem == 'string' ) {
  1348. return {
  1349. name: ctxItem,
  1350. * getAttributeKeys() {},
  1351. getAttribute() {}
  1352. };
  1353. } else {
  1354. return {
  1355. // '$text' means text nodes and text proxies.
  1356. name: ctxItem.is( 'element' ) ? ctxItem.name : '$text',
  1357. * getAttributeKeys() {
  1358. yield* ctxItem.getAttributeKeys();
  1359. },
  1360. getAttribute( key ) {
  1361. return ctxItem.getAttribute( key );
  1362. }
  1363. };
  1364. }
  1365. }
  1366. // Generator function returning values from provided walkers, switching between them at each iteration. If only one walker
  1367. // is provided it will return data only from that walker.
  1368. //
  1369. // @param {module:engine/module/treewalker~TreeWalker} [backward] Walker iterating in backward direction.
  1370. // @param {module:engine/module/treewalker~TreeWalker} [forward] Walker iterating in forward direction.
  1371. // @returns {Iterable.<Object>} Object returned at each iteration contains `value` and `walker` (informing which walker returned
  1372. // given value) fields.
  1373. function* combineWalkers( backward, forward ) {
  1374. let done = false;
  1375. while ( !done ) {
  1376. done = true;
  1377. if ( backward ) {
  1378. const step = backward.next();
  1379. if ( !step.done ) {
  1380. done = false;
  1381. yield {
  1382. walker: backward,
  1383. value: step.value
  1384. };
  1385. }
  1386. }
  1387. if ( forward ) {
  1388. const step = forward.next();
  1389. if ( !step.done ) {
  1390. done = false;
  1391. yield {
  1392. walker: forward,
  1393. value: step.value
  1394. };
  1395. }
  1396. }
  1397. }
  1398. }