schema.js 64 KB

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