schema.js 54 KB

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