schema.js 54 KB

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