8
0

schema.js 53 KB

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