schema.js 55 KB

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