schema.js 50 KB

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