schema.js 55 KB

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