schema.js 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562
  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` or `isObject` property
  315. * (all objects are also limits).
  316. *
  317. * schema.isLimit( 'paragraph' ); // -> false
  318. * schema.isLimit( '$root' ); // -> true
  319. * schema.isLimit( editor.model.document.getRoot() ); // -> true
  320. * schema.isLimit( 'image' ); // -> true
  321. *
  322. * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
  323. */
  324. isLimit( item ) {
  325. const def = this.getDefinition( item );
  326. if ( !def ) {
  327. return false;
  328. }
  329. return !!( def.isLimit || def.isObject );
  330. }
  331. /**
  332. * Returns `true` if the given item is defined to be
  333. * a object element by {@link module:engine/model/schema~SchemaItemDefinition}'s `isObject` property.
  334. *
  335. * schema.isObject( 'paragraph' ); // -> false
  336. * schema.isObject( 'image' ); // -> true
  337. *
  338. * const imageElement = writer.createElement( 'image' );
  339. * schema.isObject( imageElement ); // -> true
  340. *
  341. * @param {module:engine/model/item~Item|module:engine/model/schema~SchemaContextItem|String} item
  342. */
  343. isObject( item ) {
  344. const def = this.getDefinition( item );
  345. return !!( def && def.isObject );
  346. }
  347. /**
  348. * Checks whether the given node (`child`) can be a child of the given context.
  349. *
  350. * schema.checkChild( model.document.getRoot(), paragraph ); // -> false
  351. *
  352. * schema.register( 'paragraph', {
  353. * allowIn: '$root'
  354. * } );
  355. * schema.checkChild( model.document.getRoot(), paragraph ); // -> true
  356. *
  357. * Note: When verifying whether the given node can be a child of the given context, the
  358. * schema also verifies the entire context &mdash; from its root to its last element. Therefore, it is possible
  359. * for `checkChild()` to return `false` even though the context's last element can contain the checked child.
  360. * It happens if one of the context's elements does not allow its child.
  361. *
  362. * @fires checkChild
  363. * @param {module:engine/model/schema~SchemaContextDefinition} context The context in which the child will be checked.
  364. * @param {module:engine/model/node~Node|String} def The child to check.
  365. */
  366. checkChild( context, def ) {
  367. // Note: context and child are already normalized here to a SchemaContext and SchemaCompiledItemDefinition.
  368. if ( !def ) {
  369. return false;
  370. }
  371. return this._checkContextMatch( def, context );
  372. }
  373. /**
  374. * Checks whether the given attribute can be applied in the given context (on the last
  375. * item of the context).
  376. *
  377. * schema.checkAttribute( textNode, 'bold' ); // -> false
  378. *
  379. * schema.extend( '$text', {
  380. * allowAttributes: 'bold'
  381. * } );
  382. * schema.checkAttribute( textNode, 'bold' ); // -> true
  383. *
  384. * @fires checkAttribute
  385. * @param {module:engine/model/schema~SchemaContextDefinition} context The context in which the attribute will be checked.
  386. * @param {String} attributeName
  387. */
  388. checkAttribute( context, attributeName ) {
  389. const def = this.getDefinition( context.last );
  390. if ( !def ) {
  391. return false;
  392. }
  393. return def.allowAttributes.includes( attributeName );
  394. }
  395. /**
  396. * Checks whether the given element (`elementToMerge`) can be merged with the specified base element (`positionOrBaseElement`).
  397. *
  398. * In other words &mdash; whether `elementToMerge`'s children {@link #checkChild are allowed} in the `positionOrBaseElement`.
  399. *
  400. * This check ensures that elements merged with {@link module:engine/model/writer~Writer#merge `Writer#merge()`}
  401. * will be valid.
  402. *
  403. * Instead of elements, you can pass the instance of the {@link module:engine/model/position~Position} class as the
  404. * `positionOrBaseElement`. It means that the elements before and after the position will be checked whether they can be merged.
  405. *
  406. * @param {module:engine/model/position~Position|module:engine/model/element~Element} positionOrBaseElement The position or base
  407. * element to which the `elementToMerge` will be merged.
  408. * @param {module:engine/model/element~Element} elementToMerge The element to merge. Required if `positionOrBaseElement` is an element.
  409. * @returns {Boolean}
  410. */
  411. checkMerge( positionOrBaseElement, elementToMerge = null ) {
  412. if ( positionOrBaseElement instanceof Position ) {
  413. const nodeBefore = positionOrBaseElement.nodeBefore;
  414. const nodeAfter = positionOrBaseElement.nodeAfter;
  415. if ( !( nodeBefore instanceof Element ) ) {
  416. /**
  417. * The node before the merge position must be an element.
  418. *
  419. * @error schema-check-merge-no-element-before
  420. */
  421. throw new CKEditorError( 'schema-check-merge-no-element-before: The node before the merge position must be an element.' );
  422. }
  423. if ( !( nodeAfter instanceof Element ) ) {
  424. /**
  425. * The node after the merge position must be an element.
  426. *
  427. * @error schema-check-merge-no-element-after
  428. */
  429. throw new CKEditorError( 'schema-check-merge-no-element-after: The node after the merge position must be an element.' );
  430. }
  431. return this.checkMerge( nodeBefore, nodeAfter );
  432. }
  433. for ( const child of elementToMerge.getChildren() ) {
  434. if ( !this.checkChild( positionOrBaseElement, child ) ) {
  435. return false;
  436. }
  437. }
  438. return true;
  439. }
  440. /**
  441. * Allows registering a callback to the {@link #checkChild} method calls.
  442. *
  443. * Callbacks allow you to implement rules which are not otherwise possible to achieve
  444. * by using the declarative API of {@link module:engine/model/schema~SchemaItemDefinition}.
  445. * For example, by using this method you can disallow elements in specific contexts.
  446. *
  447. * This method is a shorthand for using the {@link #event:checkChild} event. For even better control,
  448. * you can use that event instead.
  449. *
  450. * Example:
  451. *
  452. * // Disallow heading1 directly inside a blockQuote.
  453. * schema.addChildCheck( ( context, childDefinition ) => {
  454. * if ( context.endsWith( 'blockQuote' ) && childDefinition.name == 'heading1' ) {
  455. * return false;
  456. * }
  457. * } );
  458. *
  459. * Which translates to:
  460. *
  461. * schema.on( 'checkChild', ( evt, args ) => {
  462. * const context = args[ 0 ];
  463. * const childDefinition = args[ 1 ];
  464. *
  465. * if ( context.endsWith( 'blockQuote' ) && childDefinition && childDefinition.name == 'heading1' ) {
  466. * // Prevent next listeners from being called.
  467. * evt.stop();
  468. * // Set the checkChild()'s return value.
  469. * evt.return = false;
  470. * }
  471. * }, { priority: 'high' } );
  472. *
  473. * @param {Function} callback The callback to be called. It is called with two parameters:
  474. * {@link module:engine/model/schema~SchemaContext} (context) instance and
  475. * {@link module:engine/model/schema~SchemaCompiledItemDefinition} (child-to-check definition).
  476. * The callback may return `true/false` to override `checkChild()`'s return value. If it does not return
  477. * a boolean value, the default algorithm (or other callbacks) will define `checkChild()`'s return value.
  478. */
  479. addChildCheck( callback ) {
  480. this.on( 'checkChild', ( evt, [ ctx, childDef ] ) => {
  481. // checkChild() was called with a non-registered child.
  482. // In 99% cases such check should return false, so not to overcomplicate all callbacks
  483. // don't even execute them.
  484. if ( !childDef ) {
  485. return;
  486. }
  487. const retValue = callback( ctx, childDef );
  488. if ( typeof retValue == 'boolean' ) {
  489. evt.stop();
  490. evt.return = retValue;
  491. }
  492. }, { priority: 'high' } );
  493. }
  494. /**
  495. * Allows registering a callback to the {@link #checkAttribute} method calls.
  496. *
  497. * Callbacks allow you to implement rules which are not otherwise possible to achieve
  498. * by using the declarative API of {@link module:engine/model/schema~SchemaItemDefinition}.
  499. * For example, by using this method you can disallow attribute if node to which it is applied
  500. * is contained within some other element (e.g. you want to disallow `bold` on `$text` within `heading1`).
  501. *
  502. * This method is a shorthand for using the {@link #event:checkAttribute} event. For even better control,
  503. * you can use that event instead.
  504. *
  505. * Example:
  506. *
  507. * // Disallow bold on $text inside heading1.
  508. * schema.addChildCheck( ( context, attributeName ) => {
  509. * if ( context.endsWith( 'heading1 $text' ) && attributeName == 'bold' ) {
  510. * return false;
  511. * }
  512. * } );
  513. *
  514. * Which translates to:
  515. *
  516. * schema.on( 'checkAttribute', ( evt, args ) => {
  517. * const context = args[ 0 ];
  518. * const attributeName = args[ 1 ];
  519. *
  520. * if ( context.endsWith( 'heading1 $text' ) && attributeName == 'bold' ) {
  521. * // Prevent next listeners from being called.
  522. * evt.stop();
  523. * // Set the checkAttribute()'s return value.
  524. * evt.return = false;
  525. * }
  526. * }, { priority: 'high' } );
  527. *
  528. * @param {Function} callback The callback to be called. It is called with two parameters:
  529. * {@link module:engine/model/schema~SchemaContext} (context) instance and attribute name.
  530. * The callback may return `true/false` to override `checkAttribute()`'s return value. If it does not return
  531. * a boolean value, the default algorithm (or other callbacks) will define `checkAttribute()`'s return value.
  532. */
  533. addAttributeCheck( callback ) {
  534. this.on( 'checkAttribute', ( evt, [ ctx, attributeName ] ) => {
  535. const retValue = callback( ctx, attributeName );
  536. if ( typeof retValue == 'boolean' ) {
  537. evt.stop();
  538. evt.return = retValue;
  539. }
  540. }, { priority: 'high' } );
  541. }
  542. /**
  543. * Returns the lowest {@link module:engine/model/schema~Schema#isLimit limit element} containing the entire
  544. * selection or the root otherwise.
  545. *
  546. * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection} selection
  547. * Selection which returns the common ancestor.
  548. * @returns {module:engine/model/element~Element}
  549. */
  550. getLimitElement( selection ) {
  551. // Find the common ancestor for all selection's ranges.
  552. let element = Array.from( selection.getRanges() )
  553. .reduce( ( element, range ) => {
  554. const rangeCommonAncestor = range.getCommonAncestor();
  555. if ( !element ) {
  556. return rangeCommonAncestor;
  557. }
  558. return element.getCommonAncestor( rangeCommonAncestor, { includeSelf: true } );
  559. }, null );
  560. while ( !this.isLimit( element ) ) {
  561. if ( element.parent ) {
  562. element = element.parent;
  563. } else {
  564. break;
  565. }
  566. }
  567. return element;
  568. }
  569. /**
  570. * Checks whether the attribute is allowed in selection:
  571. *
  572. * * if the selection is not collapsed, then checks if the attribute is allowed on any of nodes in that range,
  573. * * if the selection is collapsed, then checks if on the selection position there's a text with the
  574. * specified attribute allowed.
  575. *
  576. * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection} selection
  577. * Selection which will be checked.
  578. * @param {String} attribute The name of the attribute to check.
  579. * @returns {Boolean}
  580. */
  581. checkAttributeInSelection( selection, attribute ) {
  582. if ( selection.isCollapsed ) {
  583. // Check whether schema allows for a text with the attribute in the selection.
  584. return this.checkAttribute( [ ...selection.getFirstPosition().getAncestors(), '$text' ], attribute );
  585. } else {
  586. const ranges = selection.getRanges();
  587. // For all ranges, check nodes in them until you find a node that is allowed to have the attribute.
  588. for ( const range of ranges ) {
  589. for ( const value of range ) {
  590. if ( this.checkAttribute( value.item, attribute ) ) {
  591. // If we found a node that is allowed to have the attribute, return true.
  592. return true;
  593. }
  594. }
  595. }
  596. }
  597. // If we haven't found such node, return false.
  598. return false;
  599. }
  600. /**
  601. * Transforms the given set of ranges into a set of ranges where the given attribute is allowed (and can be applied).
  602. *
  603. * @param {Array.<module:engine/model/range~Range>} ranges Ranges to be validated.
  604. * @param {String} attribute The name of the attribute to check.
  605. * @returns {Array.<module:engine/model/range~Range>} Ranges in which the attribute is allowed.
  606. */
  607. getValidRanges( ranges, attribute ) {
  608. const validRanges = [];
  609. for ( const range of ranges ) {
  610. let last = range.start;
  611. let from = range.start;
  612. const to = range.end;
  613. for ( const value of range.getWalker() ) {
  614. if ( !this.checkAttribute( value.item, attribute ) ) {
  615. if ( !from.isEqual( last ) ) {
  616. validRanges.push( new Range( from, last ) );
  617. }
  618. from = value.nextPosition;
  619. }
  620. last = value.nextPosition;
  621. }
  622. if ( from && !from.isEqual( to ) ) {
  623. validRanges.push( new Range( from, to ) );
  624. }
  625. }
  626. return validRanges;
  627. }
  628. /**
  629. * Basing on given the `position`, finds and returns a {@link module:engine/model/range~Range range} which is
  630. * nearest to that `position` and is a correct range for selection.
  631. *
  632. * The correct selection range might be collapsed when it is located in a position where the text node can be placed.
  633. * Non-collapsed range is returned when selection can be placed around element marked as an "object" in
  634. * the {@link module:engine/model/schema~Schema schema}.
  635. *
  636. * Direction of searching for the nearest correct selection range can be specified as:
  637. *
  638. * * `both` - searching will be performed in both ways,
  639. * * `forward` - searching will be performed only forward,
  640. * * `backward` - searching will be performed only backward.
  641. *
  642. * When valid selection range cannot be found, `null` is returned.
  643. *
  644. * @param {module:engine/model/position~Position} position Reference position where new selection range should be looked for.
  645. * @param {'both'|'forward'|'backward'} [direction='both'] Search direction.
  646. * @returns {module:engine/model/range~Range|null} Nearest selection range or `null` if one cannot be found.
  647. */
  648. getNearestSelectionRange( position, direction = 'both' ) {
  649. // Return collapsed range if provided position is valid.
  650. if ( this.checkChild( position, '$text' ) ) {
  651. return new Range( position );
  652. }
  653. let backwardWalker, forwardWalker;
  654. if ( direction == 'both' || direction == 'backward' ) {
  655. backwardWalker = new TreeWalker( { startPosition: position, direction: 'backward' } );
  656. }
  657. if ( direction == 'both' || direction == 'forward' ) {
  658. forwardWalker = new TreeWalker( { startPosition: position } );
  659. }
  660. for ( const data of combineWalkers( backwardWalker, forwardWalker ) ) {
  661. const type = ( data.walker == backwardWalker ? 'elementEnd' : 'elementStart' );
  662. const value = data.value;
  663. if ( value.type == type && this.isObject( value.item ) ) {
  664. return Range.createOn( value.item );
  665. }
  666. if ( this.checkChild( value.nextPosition, '$text' ) ) {
  667. return new Range( value.nextPosition );
  668. }
  669. }
  670. return null;
  671. }
  672. /**
  673. * Tries to find position ancestors that allows to insert given node.
  674. * It starts searching from the given position and goes node by node to the top of the model tree
  675. * as long as {@link module:engine/model/schema~Schema#isLimit limit element},
  676. * {@link module:engine/model/schema~Schema#isObject object element} or top-most ancestor won't be reached.
  677. *
  678. * @params {module:engine/model/node~Node} node Node for which allowed parent should be found.
  679. * @params {module:engine/model/position~Position} position Position from searching will start.
  680. * @returns {module:engine/model/element~Element|null} element Allowed parent or null if nothing was found.
  681. */
  682. findAllowedParent( node, position ) {
  683. let parent = position.parent;
  684. while ( parent ) {
  685. if ( this.checkChild( parent, node ) ) {
  686. return parent;
  687. }
  688. // Do not split limit elements.
  689. if ( this.isLimit( parent ) ) {
  690. return null;
  691. }
  692. parent = parent.parent;
  693. }
  694. return null;
  695. }
  696. /**
  697. * Removes attributes disallowed by the schema.
  698. *
  699. * @param {Iterable.<module:engine/model/node~Node>} nodes Nodes that will be filtered.
  700. * @param {module:engine/model/writer~Writer} writer
  701. */
  702. removeDisallowedAttributes( nodes, writer ) {
  703. for ( const node of nodes ) {
  704. for ( const attribute of node.getAttributeKeys() ) {
  705. if ( !this.checkAttribute( node, attribute ) ) {
  706. writer.removeAttribute( attribute, node );
  707. }
  708. }
  709. if ( node.is( 'element' ) ) {
  710. this.removeDisallowedAttributes( node.getChildren(), writer );
  711. }
  712. }
  713. }
  714. /**
  715. * @private
  716. */
  717. _clearCache() {
  718. this._compiledDefinitions = null;
  719. }
  720. /**
  721. * @private
  722. */
  723. _compile() {
  724. const compiledDefinitions = {};
  725. const sourceRules = this._sourceDefinitions;
  726. const itemNames = Object.keys( sourceRules );
  727. for ( const itemName of itemNames ) {
  728. compiledDefinitions[ itemName ] = compileBaseItemRule( sourceRules[ itemName ], itemName );
  729. }
  730. for ( const itemName of itemNames ) {
  731. compileAllowContentOf( compiledDefinitions, itemName );
  732. }
  733. for ( const itemName of itemNames ) {
  734. compileAllowWhere( compiledDefinitions, itemName );
  735. }
  736. for ( const itemName of itemNames ) {
  737. compileAllowAttributesOf( compiledDefinitions, itemName );
  738. compileInheritPropertiesFrom( compiledDefinitions, itemName );
  739. }
  740. for ( const itemName of itemNames ) {
  741. cleanUpAllowIn( compiledDefinitions, itemName );
  742. cleanUpAllowAttributes( compiledDefinitions, itemName );
  743. }
  744. this._compiledDefinitions = compiledDefinitions;
  745. }
  746. /**
  747. * @private
  748. * @param {module:engine/model/schema~SchemaCompiledItemDefinition} def
  749. * @param {module:engine/model/schema~SchemaContext} context
  750. * @param {Number} contextItemIndex
  751. */
  752. _checkContextMatch( def, context, contextItemIndex = context.length - 1 ) {
  753. const contextItem = context.getItem( contextItemIndex );
  754. if ( def.allowIn.includes( contextItem.name ) ) {
  755. if ( contextItemIndex == 0 ) {
  756. return true;
  757. } else {
  758. const parentRule = this.getDefinition( contextItem );
  759. return this._checkContextMatch( parentRule, context, contextItemIndex - 1 );
  760. }
  761. } else {
  762. return false;
  763. }
  764. }
  765. }
  766. mix( Schema, ObservableMixin );
  767. /**
  768. * Event fired when the {@link #checkChild} method is called. It allows plugging in
  769. * additional behavior – e.g. implementing rules which cannot be defined using the declarative
  770. * {@link module:engine/model/schema~SchemaItemDefinition} interface.
  771. *
  772. * **Note:** The {@link #addChildCheck} method is a more handy way to register callbacks. Internally,
  773. * it registers a listener to this event but comes with a simpler API and it is the recommended choice
  774. * in most of the cases.
  775. *
  776. * The {@link #checkChild} method fires an event because it is
  777. * {@link module:utils/observablemixin~ObservableMixin#decorate decorated} with it. Thanks to that you can
  778. * use this event in a various way, but the most important use case is overriding standard behaviour of the
  779. * `checkChild()` method. Let's see a typical listener template:
  780. *
  781. * schema.on( 'checkChild', ( evt, args ) => {
  782. * const context = args[ 0 ];
  783. * const childDefinition = args[ 1 ];
  784. * }, { priority: 'high' } );
  785. *
  786. * The listener is added with a `high` priority to be executed before the default method is really called. The `args` callback
  787. * parameter contains arguments passed to `checkChild( context, child )`. However, the `context` parameter is already
  788. * normalized to a {@link module:engine/model/schema~SchemaContext} instance and `child` to a
  789. * {@link module:engine/model/schema~SchemaCompiledItemDefinition} instance, so you don't have to worry about
  790. * the various ways how `context` and `child` may be passed to `checkChild()`.
  791. *
  792. * **Note:** `childDefinition` may be `undefined` if `checkChild()` was called with a non-registered element.
  793. *
  794. * So, in order to implement a rule "disallow `heading1` in `blockQuote`" you can add such a listener:
  795. *
  796. * schema.on( 'checkChild', ( evt, args ) => {
  797. * const context = args[ 0 ];
  798. * const childDefinition = args[ 1 ];
  799. *
  800. * if ( context.endsWith( 'blockQuote' ) && childDefinition && childDefinition.name == 'heading1' ) {
  801. * // Prevent next listeners from being called.
  802. * evt.stop();
  803. * // Set the checkChild()'s return value.
  804. * evt.return = false;
  805. * }
  806. * }, { priority: 'high' } );
  807. *
  808. * Allowing elements in specific contexts will be a far less common use case, because it's normally handled by
  809. * `allowIn` rule from {@link module:engine/model/schema~SchemaItemDefinition} but if you have a complex scenario
  810. * where `listItem` should be allowed only in element `foo` which must be in element `bar`, then this would be the way:
  811. *
  812. * schema.on( 'checkChild', ( evt, args ) => {
  813. * const context = args[ 0 ];
  814. * const childDefinition = args[ 1 ];
  815. *
  816. * if ( context.endsWith( 'bar foo' ) && childDefinition.name == 'listItem' ) {
  817. * // Prevent next listeners from being called.
  818. * evt.stop();
  819. * // Set the checkChild()'s return value.
  820. * evt.return = true;
  821. * }
  822. * }, { priority: 'high' } );
  823. *
  824. * @event checkChild
  825. * @param {Array} args The `checkChild()`'s arguments.
  826. */
  827. /**
  828. * Event fired when the {@link #checkAttribute} method is called. It allows plugging in
  829. * additional behavior – e.g. implementing rules which cannot be defined using the declarative
  830. * {@link module:engine/model/schema~SchemaItemDefinition} interface.
  831. *
  832. * **Note:** The {@link #addAttributeCheck} method is a more handy way to register callbacks. Internally,
  833. * it registers a listener to this event but comes with a simpler API and it is the recommended choice
  834. * in most of the cases.
  835. *
  836. * The {@link #checkAttribute} method fires an event because it's
  837. * {@link module:utils/observablemixin~ObservableMixin#decorate decorated} with it. Thanks to that you can
  838. * use this event in a various way, but the most important use case is overriding standard behaviour of the
  839. * `checkAttribute()` method. Let's see a typical listener template:
  840. *
  841. * schema.on( 'checkAttribute', ( evt, args ) => {
  842. * const context = args[ 0 ];
  843. * const attributeName = args[ 1 ];
  844. * }, { priority: 'high' } );
  845. *
  846. * The listener is added with a `high` priority to be executed before the default method is really called. The `args` callback
  847. * parameter contains arguments passed to `checkAttribute( context, attributeName )`. However, the `context` parameter is already
  848. * normalized to a {@link module:engine/model/schema~SchemaContext} instance, so you don't have to worry about
  849. * the various ways how `context` may be passed to `checkAttribute()`.
  850. *
  851. * So, in order to implement a rule "disallow `bold` in a text which is in a `heading1` you can add such a listener:
  852. *
  853. * schema.on( 'checkAttribute', ( evt, args ) => {
  854. * const context = args[ 0 ];
  855. * const atributeName = args[ 1 ];
  856. *
  857. * if ( context.endsWith( 'heading1 $text' ) && attributeName == 'bold' ) {
  858. * // Prevent next listeners from being called.
  859. * evt.stop();
  860. * // Set the checkAttribute()'s return value.
  861. * evt.return = false;
  862. * }
  863. * }, { priority: 'high' } );
  864. *
  865. * Allowing attributes in specific contexts will be a far less common use case, because it's normally handled by
  866. * `allowAttributes` rule from {@link module:engine/model/schema~SchemaItemDefinition} but if you have a complex scenario
  867. * where `bold` should be allowed only in element `foo` which must be in element `bar`, then this would be the way:
  868. *
  869. * schema.on( 'checkAttribute', ( evt, args ) => {
  870. * const context = args[ 0 ];
  871. * const atributeName = args[ 1 ];
  872. *
  873. * if ( context.endsWith( 'bar foo $text' ) && attributeName == 'bold' ) {
  874. * // Prevent next listeners from being called.
  875. * evt.stop();
  876. * // Set the checkAttribute()'s return value.
  877. * evt.return = true;
  878. * }
  879. * }, { priority: 'high' } );
  880. *
  881. * @event checkAttribute
  882. * @param {Array} args The `checkAttribute()`'s arguments.
  883. */
  884. /**
  885. * A definition of a {@link module:engine/model/schema~Schema schema} item.
  886. *
  887. * You can define the following rules:
  888. *
  889. * * `allowIn` &ndash; A string or an array of strings. Defines in which other items this item will be allowed.
  890. * * `allowAttributes` &ndash; A string or an array of strings. Defines allowed attributes of the given item.
  891. * * `allowContentOf` &ndash; A string or an array of strings. Inherits "allowed children" from other items.
  892. * * `allowWhere` &ndash; A string or an array of strings. Inherits "allowed in" from other items.
  893. * * `allowAttributesOf` &ndash; A string or an array of strings. Inherits attributes from other items.
  894. * * `inheritTypesFrom` &ndash; A string or an array of strings. Inherits `is*` properties of other items.
  895. * * `inheritAllFrom` &ndash; A string. A shorthand for `allowContentOf`, `allowWhere`, `allowAttributesOf`, `inheritTypesFrom`.
  896. * * Additionally, you can define the following `is*` properties: `isBlock`, `isLimit`, `isObject`. Read about them below.
  897. *
  898. * # The is* properties
  899. *
  900. * There are 3 commonly used `is*` properties. Their role is to assign additional semantics to schema items.
  901. * You can define more properties but you will also need to implement support for them in the existing editor features.
  902. *
  903. * * `isBlock` &ndash; Whether this item is paragraph-like. Generally speaking, content is usually made out of blocks
  904. * like paragraphs, list items, images, headings, etc. All these elements are marked as blocks. A block
  905. * should not allow another block inside. Note: There is also the `$block` generic item which has `isBlock` set to `true`.
  906. * Most block type items will inherit from `$block` (through `inheritAllFrom`).
  907. * * `isLimit` &ndash; It can be understood as whether this element should not be split by <kbd>Enter</kbd>.
  908. * Examples of limit elements: `$root`, table cell, image caption, etc. In other words, all actions that happen inside
  909. * a limit element are limited to its content. **Note:** All objects (`isObject`) are treated as limit elements, too.
  910. * * `isObject` &ndash; Whether an item is "self-contained" and should be treated as a whole. Examples of object elements:
  911. * `image`, `table`, `video`, etc. **Note:** An object is also a limit, so
  912. * {@link module:engine/model/schema~Schema#isLimit `isLimit()`}
  913. * returns `true` for object elements automatically.
  914. *
  915. * # Generic items
  916. *
  917. * There are three basic generic items: `$root`, `$block` and `$text`.
  918. * They are defined as follows:
  919. *
  920. * this.schema.register( '$root', {
  921. * isLimit: true
  922. * } );
  923. * this.schema.register( '$block', {
  924. * allowIn: '$root',
  925. * isBlock: true
  926. * } );
  927. * this.schema.register( '$text', {
  928. * allowIn: '$block'
  929. * } );
  930. *
  931. * They reflect typical editor content that is contained within one root, consists of several blocks
  932. * (paragraphs, lists items, headings, images) which, in turn, may contain text inside.
  933. *
  934. * By inheriting from the generic items you can define new items which will get extended by other editor features.
  935. * Read more about generic types in the {@linkTODO Defining schema} guide.
  936. *
  937. * # Example definitions
  938. *
  939. * Allow `paragraph` in roots and block quotes:
  940. *
  941. * schema.register( 'paragraph', {
  942. * allowIn: [ '$root', 'blockQuote' ],
  943. * isBlock: true
  944. * } );
  945. *
  946. * Allow `paragraph` everywhere where `$block` is allowed (i.e. in `$root`):
  947. *
  948. * schema.register( 'paragraph', {
  949. * allowWhere: '$block',
  950. * isBlock: true
  951. * } );
  952. *
  953. * Make `image` a block object, which is allowed everywhere where `$block` is.
  954. * Also, allow `src` and `alt` attributes in it:
  955. *
  956. * schema.register( 'image', {
  957. * allowWhere: '$block',
  958. * allowAttributes: [ 'src', 'alt' ],
  959. * isBlock: true,
  960. * isObject: true
  961. * } );
  962. *
  963. * Make `caption` allowed in `image` and make it allow all the content of `$block`s (usually, `$text`).
  964. * Also, mark it as a limit element so it cannot be split:
  965. *
  966. * schema.register( 'caption', {
  967. * allowIn: 'image',
  968. * allowContentOf: '$block',
  969. * isLimit: true
  970. * } );
  971. *
  972. * Make `listItem` inherit all from `$block` but also allow additional attributes:
  973. *
  974. * schema.register( 'listItem', {
  975. * inheritAllFrom: '$block',
  976. * allowAttributes: [ 'listType', 'listIndent' ]
  977. * } );
  978. *
  979. * Which translates to:
  980. *
  981. * schema.register( 'listItem', {
  982. * allowWhere: '$block',
  983. * allowContentOf: '$block',
  984. * allowAttributesOf: '$block',
  985. * inheritTypesFrom: '$block',
  986. * allowAttributes: [ 'listType', 'listIndent' ]
  987. * } );
  988. *
  989. * # Tips
  990. *
  991. * * Check schema definitions of existing features to see how they are defined.
  992. * * If you want to publish your feature so other developers can use it, try to use
  993. * generic items as much as possible.
  994. * * Keep your model clean. Limit it to the actual data and store information in a normalized way.
  995. * * Remember about definining the `is*` properties. They do not affect the allowed structures, but they can
  996. * affect how the editor features treat your elements.
  997. *
  998. * @typedef {Object} module:engine/model/schema~SchemaItemDefinition
  999. */
  1000. /**
  1001. * A simplified version of {@link module:engine/model/schema~SchemaItemDefinition} after
  1002. * compilation by the {@link module:engine/model/schema~Schema schema}.
  1003. * Rules fed to the schema by {@link module:engine/model/schema~Schema#register}
  1004. * and {@link module:engine/model/schema~Schema#extend} methods are defined in the
  1005. * {@link module:engine/model/schema~SchemaItemDefinition} format.
  1006. * Later on, they are compiled to `SchemaCompiledItemDefition` so when you use e.g.
  1007. * the {@link module:engine/model/schema~Schema#getDefinition} method you get the compiled version.
  1008. *
  1009. * The compiled version contains only the following properties:
  1010. *
  1011. * * The `name` property,
  1012. * * The `is*` properties,
  1013. * * The `allowIn` array,
  1014. * * The `allowAttributes` array.
  1015. *
  1016. * @typedef {Object} module:engine/model/schema~SchemaCompiledItemDefinition
  1017. */
  1018. /**
  1019. * A schema context &mdash; a list of ancestors of a given position in the document.
  1020. *
  1021. * Considering such position:
  1022. *
  1023. * <$root>
  1024. * <blockQuote>
  1025. * <paragraph>
  1026. * ^
  1027. * </paragraph>
  1028. * </blockQuote>
  1029. * </$root>
  1030. *
  1031. * The context of this position is its {@link module:engine/model/position~Position#getAncestors lists of ancestors}:
  1032. *
  1033. * [ rootElement, blockQuoteElement, paragraphElement ]
  1034. *
  1035. * Contexts are used in the {@link module:engine/model/schema~Schema#event:checkChild `Schema#checkChild`} and
  1036. * {@link module:engine/model/schema~Schema#event:checkAttribute `Schema#checkAttribute`} events as a definition
  1037. * of a place in the document where the check occurs. The context instances are created based on the first arguments
  1038. * of the {@link module:engine/model/schema~Schema#checkChild `Schema#checkChild()`} and
  1039. * {@link module:engine/model/schema~Schema#checkAttribute `Schema#checkAttribute()`} methods so when
  1040. * using these methods you need to use {@link module:engine/model/schema~SchemaContextDefinition}s.
  1041. */
  1042. export class SchemaContext {
  1043. /**
  1044. * Creates an instance of the context.
  1045. *
  1046. * @param {module:engine/model/schema~SchemaContextDefinition} context
  1047. */
  1048. constructor( context ) {
  1049. if ( context instanceof SchemaContext ) {
  1050. return context;
  1051. }
  1052. if ( typeof context == 'string' ) {
  1053. context = [ context ];
  1054. } else if ( !Array.isArray( context ) ) {
  1055. // `context` is item or position.
  1056. // Position#getAncestors() doesn't accept any parameters but it works just fine here.
  1057. context = context.getAncestors( { includeSelf: true } );
  1058. }
  1059. if ( context[ 0 ] && typeof context[ 0 ] != 'string' && context[ 0 ].is( 'documentFragment' ) ) {
  1060. context.shift();
  1061. }
  1062. this._items = context.map( mapContextItem );
  1063. }
  1064. /**
  1065. * The number of items.
  1066. *
  1067. * @type {Number}
  1068. */
  1069. get length() {
  1070. return this._items.length;
  1071. }
  1072. /**
  1073. * The last item (the lowest node).
  1074. *
  1075. * @type {module:engine/model/schema~SchemaContextItem}
  1076. */
  1077. get last() {
  1078. return this._items[ this._items.length - 1 ];
  1079. }
  1080. /**
  1081. * Iterable interface.
  1082. *
  1083. * Iterates over all context items.
  1084. *
  1085. * @returns {Iterable.<module:engine/model/schema~SchemaContextItem>}
  1086. */
  1087. [ Symbol.iterator ]() {
  1088. return this._items[ Symbol.iterator ]();
  1089. }
  1090. /**
  1091. * Returns a new schema context instance with an additional item.
  1092. *
  1093. * Item can be added as:
  1094. *
  1095. * const context = new SchemaContext( [ '$root' ] );
  1096. *
  1097. * // An element.
  1098. * const fooElement = writer.createElement( 'fooElement' );
  1099. * const newContext = context.push( fooElement ); // [ '$root', 'fooElement' ]
  1100. *
  1101. * // A text node.
  1102. * const text = writer.createText( 'foobar' );
  1103. * const newContext = context.push( text ); // [ '$root', '$text' ]
  1104. *
  1105. * // A string (element name).
  1106. * const newContext = context.push( 'barElement' ); // [ '$root', 'barElement' ]
  1107. *
  1108. * **Note** {module:engine/model/node~Node} that is already in the model tree will be added as the only item (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( Position.createAt( paragraphElement ), '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. function compileBaseItemRule( sourceItemRules, itemName ) {
  1245. const itemRule = {
  1246. name: itemName,
  1247. allowIn: [],
  1248. allowContentOf: [],
  1249. allowWhere: [],
  1250. allowAttributes: [],
  1251. allowAttributesOf: [],
  1252. inheritTypesFrom: []
  1253. };
  1254. copyTypes( sourceItemRules, itemRule );
  1255. copyProperty( sourceItemRules, itemRule, 'allowIn' );
  1256. copyProperty( sourceItemRules, itemRule, 'allowContentOf' );
  1257. copyProperty( sourceItemRules, itemRule, 'allowWhere' );
  1258. copyProperty( sourceItemRules, itemRule, 'allowAttributes' );
  1259. copyProperty( sourceItemRules, itemRule, 'allowAttributesOf' );
  1260. copyProperty( sourceItemRules, itemRule, 'inheritTypesFrom' );
  1261. makeInheritAllWork( sourceItemRules, itemRule );
  1262. return itemRule;
  1263. }
  1264. function compileAllowContentOf( compiledDefinitions, itemName ) {
  1265. for ( const allowContentOfItemName of compiledDefinitions[ itemName ].allowContentOf ) {
  1266. // The allowContentOf property may point to an unregistered element.
  1267. if ( compiledDefinitions[ allowContentOfItemName ] ) {
  1268. const allowedChildren = getAllowedChildren( compiledDefinitions, allowContentOfItemName );
  1269. allowedChildren.forEach( allowedItem => {
  1270. allowedItem.allowIn.push( itemName );
  1271. } );
  1272. }
  1273. }
  1274. delete compiledDefinitions[ itemName ].allowContentOf;
  1275. }
  1276. function compileAllowWhere( compiledDefinitions, itemName ) {
  1277. for ( const allowWhereItemName of compiledDefinitions[ itemName ].allowWhere ) {
  1278. const inheritFrom = compiledDefinitions[ allowWhereItemName ];
  1279. // The allowWhere property may point to an unregistered element.
  1280. if ( inheritFrom ) {
  1281. const allowedIn = inheritFrom.allowIn;
  1282. compiledDefinitions[ itemName ].allowIn.push( ...allowedIn );
  1283. }
  1284. }
  1285. delete compiledDefinitions[ itemName ].allowWhere;
  1286. }
  1287. function compileAllowAttributesOf( compiledDefinitions, itemName ) {
  1288. for ( const allowAttributeOfItem of compiledDefinitions[ itemName ].allowAttributesOf ) {
  1289. const inheritFrom = compiledDefinitions[ allowAttributeOfItem ];
  1290. if ( inheritFrom ) {
  1291. const inheritAttributes = inheritFrom.allowAttributes;
  1292. compiledDefinitions[ itemName ].allowAttributes.push( ...inheritAttributes );
  1293. }
  1294. }
  1295. delete compiledDefinitions[ itemName ].allowAttributesOf;
  1296. }
  1297. function compileInheritPropertiesFrom( compiledDefinitions, itemName ) {
  1298. const item = compiledDefinitions[ itemName ];
  1299. for ( const inheritPropertiesOfItem of item.inheritTypesFrom ) {
  1300. const inheritFrom = compiledDefinitions[ inheritPropertiesOfItem ];
  1301. if ( inheritFrom ) {
  1302. const typeNames = Object.keys( inheritFrom ).filter( name => name.startsWith( 'is' ) );
  1303. for ( const name of typeNames ) {
  1304. if ( !( name in item ) ) {
  1305. item[ name ] = inheritFrom[ name ];
  1306. }
  1307. }
  1308. }
  1309. }
  1310. delete item.inheritTypesFrom;
  1311. }
  1312. // Remove items which weren't registered (because it may break some checks or we'd need to complicate them).
  1313. // Make sure allowIn doesn't contain repeated values.
  1314. function cleanUpAllowIn( compiledDefinitions, itemName ) {
  1315. const itemRule = compiledDefinitions[ itemName ];
  1316. const existingItems = itemRule.allowIn.filter( itemToCheck => compiledDefinitions[ itemToCheck ] );
  1317. itemRule.allowIn = Array.from( new Set( existingItems ) );
  1318. }
  1319. function cleanUpAllowAttributes( compiledDefinitions, itemName ) {
  1320. const itemRule = compiledDefinitions[ itemName ];
  1321. itemRule.allowAttributes = Array.from( new Set( itemRule.allowAttributes ) );
  1322. }
  1323. function copyTypes( sourceItemRules, itemRule ) {
  1324. for ( const sourceItemRule of sourceItemRules ) {
  1325. const typeNames = Object.keys( sourceItemRule ).filter( name => name.startsWith( 'is' ) );
  1326. for ( const name of typeNames ) {
  1327. itemRule[ name ] = sourceItemRule[ name ];
  1328. }
  1329. }
  1330. }
  1331. function copyProperty( sourceItemRules, itemRule, propertyName ) {
  1332. for ( const sourceItemRule of sourceItemRules ) {
  1333. if ( typeof sourceItemRule[ propertyName ] == 'string' ) {
  1334. itemRule[ propertyName ].push( sourceItemRule[ propertyName ] );
  1335. } else if ( Array.isArray( sourceItemRule[ propertyName ] ) ) {
  1336. itemRule[ propertyName ].push( ...sourceItemRule[ propertyName ] );
  1337. }
  1338. }
  1339. }
  1340. function makeInheritAllWork( sourceItemRules, itemRule ) {
  1341. for ( const sourceItemRule of sourceItemRules ) {
  1342. const inheritFrom = sourceItemRule.inheritAllFrom;
  1343. if ( inheritFrom ) {
  1344. itemRule.allowContentOf.push( inheritFrom );
  1345. itemRule.allowWhere.push( inheritFrom );
  1346. itemRule.allowAttributesOf.push( inheritFrom );
  1347. itemRule.inheritTypesFrom.push( inheritFrom );
  1348. }
  1349. }
  1350. }
  1351. function getAllowedChildren( compiledDefinitions, itemName ) {
  1352. const itemRule = compiledDefinitions[ itemName ];
  1353. return getValues( compiledDefinitions ).filter( def => def.allowIn.includes( itemRule.name ) );
  1354. }
  1355. function getValues( obj ) {
  1356. return Object.keys( obj ).map( key => obj[ key ] );
  1357. }
  1358. function mapContextItem( ctxItem ) {
  1359. if ( typeof ctxItem == 'string' ) {
  1360. return {
  1361. name: ctxItem,
  1362. * getAttributeKeys() {},
  1363. getAttribute() {}
  1364. };
  1365. } else {
  1366. return {
  1367. // '$text' means text nodes and text proxies.
  1368. name: ctxItem.is( 'element' ) ? ctxItem.name : '$text',
  1369. * getAttributeKeys() {
  1370. yield* ctxItem.getAttributeKeys();
  1371. },
  1372. getAttribute( key ) {
  1373. return ctxItem.getAttribute( key );
  1374. }
  1375. };
  1376. }
  1377. }
  1378. // Generator function returning values from provided walkers, switching between them at each iteration. If only one walker
  1379. // is provided it will return data only from that walker.
  1380. //
  1381. // @param {module:engine/module/treewalker~TreeWalker} [backward] Walker iterating in backward direction.
  1382. // @param {module:engine/module/treewalker~TreeWalker} [forward] Walker iterating in forward direction.
  1383. // @returns {Iterable.<Object>} Object returned at each iteration contains `value` and `walker` (informing which walker returned
  1384. // given value) fields.
  1385. function* combineWalkers( backward, forward ) {
  1386. let done = false;
  1387. while ( !done ) {
  1388. done = true;
  1389. if ( backward ) {
  1390. const step = backward.next();
  1391. if ( !step.done ) {
  1392. done = false;
  1393. yield {
  1394. walker: backward,
  1395. value: step.value
  1396. };
  1397. }
  1398. }
  1399. if ( forward ) {
  1400. const step = forward.next();
  1401. if ( !step.done ) {
  1402. done = false;
  1403. yield {
  1404. walker: forward,
  1405. value: step.value
  1406. };
  1407. }
  1408. }
  1409. }
  1410. }