schema.js 55 KB

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