schema.js 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601
  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/range/position or the root otherwise.
  545. *
  546. * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection|
  547. * module:engine/model/range~Range|module:engine/model/position~Position} selectionOrRangeOrPosition
  548. * The selection/range/position to check.
  549. * @returns {module:engine/model/element~Element} The lowest limit element containing
  550. * the entire `selectionOrRangeOrPosition`.
  551. */
  552. getLimitElement( selectionOrRangeOrPosition ) {
  553. let element;
  554. if ( selectionOrRangeOrPosition instanceof Position ) {
  555. element = selectionOrRangeOrPosition.parent;
  556. } else {
  557. const ranges = selectionOrRangeOrPosition instanceof Range ?
  558. [ selectionOrRangeOrPosition ] :
  559. Array.from( selectionOrRangeOrPosition.getRanges() );
  560. // Find the common ancestor for all selection's ranges.
  561. element = ranges
  562. .reduce( ( element, range ) => {
  563. const rangeCommonAncestor = range.getCommonAncestor();
  564. if ( !element ) {
  565. return rangeCommonAncestor;
  566. }
  567. return element.getCommonAncestor( rangeCommonAncestor, { includeSelf: true } );
  568. }, null );
  569. }
  570. while ( !this.isLimit( element ) ) {
  571. if ( element.parent ) {
  572. element = element.parent;
  573. } else {
  574. break;
  575. }
  576. }
  577. return element;
  578. }
  579. /**
  580. * Checks whether the attribute is allowed in selection:
  581. *
  582. * * if the selection is not collapsed, then checks if the attribute is allowed on any of nodes in that range,
  583. * * if the selection is collapsed, then checks if on the selection position there's a text with the
  584. * specified attribute allowed.
  585. *
  586. * @param {module:engine/model/selection~Selection|module:engine/model/documentselection~DocumentSelection} selection
  587. * Selection which will be checked.
  588. * @param {String} attribute The name of the attribute to check.
  589. * @returns {Boolean}
  590. */
  591. checkAttributeInSelection( selection, attribute ) {
  592. if ( selection.isCollapsed ) {
  593. // Check whether schema allows for a text with the attribute in the selection.
  594. return this.checkAttribute( [ ...selection.getFirstPosition().getAncestors(), '$text' ], attribute );
  595. } else {
  596. const ranges = selection.getRanges();
  597. // For all ranges, check nodes in them until you find a node that is allowed to have the attribute.
  598. for ( const range of ranges ) {
  599. for ( const value of range ) {
  600. if ( this.checkAttribute( value.item, attribute ) ) {
  601. // If we found a node that is allowed to have the attribute, return true.
  602. return true;
  603. }
  604. }
  605. }
  606. }
  607. // If we haven't found such node, return false.
  608. return false;
  609. }
  610. /**
  611. * Transforms the given set of ranges into a set of ranges where the given attribute is allowed (and can be applied).
  612. *
  613. * @param {Array.<module:engine/model/range~Range>} ranges Ranges to be validated.
  614. * @param {String} attribute The name of the attribute to check.
  615. * @returns {Iterator.<module:engine/model/range~Range>} Ranges in which the attribute is allowed.
  616. */
  617. * getValidRanges( ranges, attribute ) {
  618. ranges = convertToMinimalFlatRanges( ranges );
  619. for ( const range of ranges ) {
  620. yield* this._getValidRangesForRange( range, attribute );
  621. }
  622. }
  623. /**
  624. * Takes a flat range and an attribute name. Traverses the range recursively and deeply to find and return all ranges
  625. * inside the given range on which the attribute can be applied.
  626. *
  627. * This is a helper function for {@link ~Schema#getValidRanges}.
  628. *
  629. * @private
  630. * @param {module:engine/model/range~Range} range Range to process.
  631. * @param {String} attribute The name of the attribute to check.
  632. * @returns {Iterator.<module:engine/model/range~Range>} Ranges in which the attribute is allowed.
  633. */
  634. * _getValidRangesForRange( range, attribute ) {
  635. let start = range.start;
  636. let end = range.start;
  637. for ( const item of range.getItems( { shallow: true } ) ) {
  638. if ( item.is( 'element' ) ) {
  639. yield* this._getValidRangesForRange( Range.createIn( item ), attribute );
  640. }
  641. if ( !this.checkAttribute( item, attribute ) ) {
  642. if ( !start.isEqual( end ) ) {
  643. yield new Range( start, end );
  644. }
  645. start = Position.createAfter( item );
  646. }
  647. end = Position.createAfter( item );
  648. }
  649. if ( !start.isEqual( end ) ) {
  650. yield new Range( start, end );
  651. }
  652. }
  653. /**
  654. * Basing on given `position`, finds and returns a {@link module:engine/model/range~Range range} which is
  655. * nearest to that `position` and is a correct range for selection.
  656. *
  657. * The correct selection range might be collapsed when it is located in a position where the text node can be placed.
  658. * Non-collapsed range is returned when selection can be placed around element marked as an "object" in
  659. * the {@link module:engine/model/schema~Schema schema}.
  660. *
  661. * Direction of searching for the nearest correct selection range can be specified as:
  662. *
  663. * * `both` - searching will be performed in both ways,
  664. * * `forward` - searching will be performed only forward,
  665. * * `backward` - searching will be performed only backward.
  666. *
  667. * When valid selection range cannot be found, `null` is returned.
  668. *
  669. * @param {module:engine/model/position~Position} position Reference position where new selection range should be looked for.
  670. * @param {'both'|'forward'|'backward'} [direction='both'] Search direction.
  671. * @returns {module:engine/model/range~Range|null} Nearest selection range or `null` if one cannot be found.
  672. */
  673. getNearestSelectionRange( position, direction = 'both' ) {
  674. // Return collapsed range if provided position is valid.
  675. if ( this.checkChild( position, '$text' ) ) {
  676. return new Range( position );
  677. }
  678. let backwardWalker, forwardWalker;
  679. if ( direction == 'both' || direction == 'backward' ) {
  680. backwardWalker = new TreeWalker( { startPosition: position, direction: 'backward' } );
  681. }
  682. if ( direction == 'both' || direction == 'forward' ) {
  683. forwardWalker = new TreeWalker( { startPosition: position } );
  684. }
  685. for ( const data of combineWalkers( backwardWalker, forwardWalker ) ) {
  686. const type = ( data.walker == backwardWalker ? 'elementEnd' : 'elementStart' );
  687. const value = data.value;
  688. if ( value.type == type && this.isObject( value.item ) ) {
  689. return Range.createOn( value.item );
  690. }
  691. if ( this.checkChild( value.nextPosition, '$text' ) ) {
  692. return new Range( value.nextPosition );
  693. }
  694. }
  695. return null;
  696. }
  697. /**
  698. * Tries to find position ancestors that allows to insert given node.
  699. * It starts searching from the given position and goes node by node to the top of the model tree
  700. * as long as {@link module:engine/model/schema~Schema#isLimit limit element},
  701. * {@link module:engine/model/schema~Schema#isObject object element} or top-most ancestor won't be reached.
  702. *
  703. * @params {module:engine/model/node~Node} node Node for which allowed parent should be found.
  704. * @params {module:engine/model/position~Position} position Position from searching will start.
  705. * @returns {module:engine/model/element~Element|null} element Allowed parent or null if nothing was found.
  706. */
  707. findAllowedParent( node, position ) {
  708. let parent = position.parent;
  709. while ( parent ) {
  710. if ( this.checkChild( parent, node ) ) {
  711. return parent;
  712. }
  713. // Do not split limit elements.
  714. if ( this.isLimit( parent ) ) {
  715. return null;
  716. }
  717. parent = parent.parent;
  718. }
  719. return null;
  720. }
  721. /**
  722. * Removes attributes disallowed by the schema.
  723. *
  724. * @param {Iterable.<module:engine/model/node~Node>} nodes Nodes that will be filtered.
  725. * @param {module:engine/model/writer~Writer} writer
  726. */
  727. removeDisallowedAttributes( nodes, writer ) {
  728. for ( const node of nodes ) {
  729. for ( const attribute of node.getAttributeKeys() ) {
  730. if ( !this.checkAttribute( node, attribute ) ) {
  731. writer.removeAttribute( attribute, node );
  732. }
  733. }
  734. if ( node.is( 'element' ) ) {
  735. this.removeDisallowedAttributes( node.getChildren(), writer );
  736. }
  737. }
  738. }
  739. /**
  740. * @private
  741. */
  742. _clearCache() {
  743. this._compiledDefinitions = null;
  744. }
  745. /**
  746. * @private
  747. */
  748. _compile() {
  749. const compiledDefinitions = {};
  750. const sourceRules = this._sourceDefinitions;
  751. const itemNames = Object.keys( sourceRules );
  752. for ( const itemName of itemNames ) {
  753. compiledDefinitions[ itemName ] = compileBaseItemRule( sourceRules[ itemName ], itemName );
  754. }
  755. for ( const itemName of itemNames ) {
  756. compileAllowContentOf( compiledDefinitions, itemName );
  757. }
  758. for ( const itemName of itemNames ) {
  759. compileAllowWhere( compiledDefinitions, itemName );
  760. }
  761. for ( const itemName of itemNames ) {
  762. compileAllowAttributesOf( compiledDefinitions, itemName );
  763. compileInheritPropertiesFrom( compiledDefinitions, itemName );
  764. }
  765. for ( const itemName of itemNames ) {
  766. cleanUpAllowIn( compiledDefinitions, itemName );
  767. cleanUpAllowAttributes( compiledDefinitions, itemName );
  768. }
  769. this._compiledDefinitions = compiledDefinitions;
  770. }
  771. /**
  772. * @private
  773. * @param {module:engine/model/schema~SchemaCompiledItemDefinition} def
  774. * @param {module:engine/model/schema~SchemaContext} context
  775. * @param {Number} contextItemIndex
  776. */
  777. _checkContextMatch( def, context, contextItemIndex = context.length - 1 ) {
  778. const contextItem = context.getItem( contextItemIndex );
  779. if ( def.allowIn.includes( contextItem.name ) ) {
  780. if ( contextItemIndex == 0 ) {
  781. return true;
  782. } else {
  783. const parentRule = this.getDefinition( contextItem );
  784. return this._checkContextMatch( parentRule, context, contextItemIndex - 1 );
  785. }
  786. } else {
  787. return false;
  788. }
  789. }
  790. }
  791. mix( Schema, ObservableMixin );
  792. /**
  793. * Event fired when the {@link #checkChild} method is called. It allows plugging in
  794. * additional behavior – e.g. implementing rules which cannot be defined using the declarative
  795. * {@link module:engine/model/schema~SchemaItemDefinition} interface.
  796. *
  797. * **Note:** The {@link #addChildCheck} method is a more handy way to register callbacks. Internally,
  798. * it registers a listener to this event but comes with a simpler API and it is the recommended choice
  799. * in most of the cases.
  800. *
  801. * The {@link #checkChild} method fires an event because it is
  802. * {@link module:utils/observablemixin~ObservableMixin#decorate decorated} with it. Thanks to that you can
  803. * use this event in a various way, but the most important use case is overriding standard behaviour of the
  804. * `checkChild()` method. Let's see a typical listener template:
  805. *
  806. * schema.on( 'checkChild', ( evt, args ) => {
  807. * const context = args[ 0 ];
  808. * const childDefinition = args[ 1 ];
  809. * }, { priority: 'high' } );
  810. *
  811. * The listener is added with a `high` priority to be executed before the default method is really called. The `args` callback
  812. * parameter contains arguments passed to `checkChild( context, child )`. However, the `context` parameter is already
  813. * normalized to a {@link module:engine/model/schema~SchemaContext} instance and `child` to a
  814. * {@link module:engine/model/schema~SchemaCompiledItemDefinition} instance, so you don't have to worry about
  815. * the various ways how `context` and `child` may be passed to `checkChild()`.
  816. *
  817. * **Note:** `childDefinition` may be `undefined` if `checkChild()` was called with a non-registered element.
  818. *
  819. * So, in order to implement a rule "disallow `heading1` in `blockQuote`" you can add such a listener:
  820. *
  821. * schema.on( 'checkChild', ( evt, args ) => {
  822. * const context = args[ 0 ];
  823. * const childDefinition = args[ 1 ];
  824. *
  825. * if ( context.endsWith( 'blockQuote' ) && childDefinition && childDefinition.name == 'heading1' ) {
  826. * // Prevent next listeners from being called.
  827. * evt.stop();
  828. * // Set the checkChild()'s return value.
  829. * evt.return = false;
  830. * }
  831. * }, { priority: 'high' } );
  832. *
  833. * Allowing elements in specific contexts will be a far less common use case, because it's normally handled by
  834. * `allowIn` rule from {@link module:engine/model/schema~SchemaItemDefinition} but if you have a complex scenario
  835. * where `listItem` should be allowed only in element `foo` which must be in element `bar`, then this would be the way:
  836. *
  837. * schema.on( 'checkChild', ( evt, args ) => {
  838. * const context = args[ 0 ];
  839. * const childDefinition = args[ 1 ];
  840. *
  841. * if ( context.endsWith( 'bar foo' ) && childDefinition.name == 'listItem' ) {
  842. * // Prevent next listeners from being called.
  843. * evt.stop();
  844. * // Set the checkChild()'s return value.
  845. * evt.return = true;
  846. * }
  847. * }, { priority: 'high' } );
  848. *
  849. * @event checkChild
  850. * @param {Array} args The `checkChild()`'s arguments.
  851. */
  852. /**
  853. * Event fired when the {@link #checkAttribute} method is called. It allows plugging in
  854. * additional behavior – e.g. implementing rules which cannot be defined using the declarative
  855. * {@link module:engine/model/schema~SchemaItemDefinition} interface.
  856. *
  857. * **Note:** The {@link #addAttributeCheck} method is a more handy way to register callbacks. Internally,
  858. * it registers a listener to this event but comes with a simpler API and it is the recommended choice
  859. * in most of the cases.
  860. *
  861. * The {@link #checkAttribute} method fires an event because it's
  862. * {@link module:utils/observablemixin~ObservableMixin#decorate decorated} with it. Thanks to that you can
  863. * use this event in a various way, but the most important use case is overriding standard behaviour of the
  864. * `checkAttribute()` method. Let's see a typical listener template:
  865. *
  866. * schema.on( 'checkAttribute', ( evt, args ) => {
  867. * const context = args[ 0 ];
  868. * const attributeName = args[ 1 ];
  869. * }, { priority: 'high' } );
  870. *
  871. * The listener is added with a `high` priority to be executed before the default method is really called. The `args` callback
  872. * parameter contains arguments passed to `checkAttribute( context, attributeName )`. However, the `context` parameter is already
  873. * normalized to a {@link module:engine/model/schema~SchemaContext} instance, so you don't have to worry about
  874. * the various ways how `context` may be passed to `checkAttribute()`.
  875. *
  876. * So, in order to implement a rule "disallow `bold` in a text which is in a `heading1` you can add such a listener:
  877. *
  878. * schema.on( 'checkAttribute', ( evt, args ) => {
  879. * const context = args[ 0 ];
  880. * const atributeName = args[ 1 ];
  881. *
  882. * if ( context.endsWith( 'heading1 $text' ) && attributeName == 'bold' ) {
  883. * // Prevent next listeners from being called.
  884. * evt.stop();
  885. * // Set the checkAttribute()'s return value.
  886. * evt.return = false;
  887. * }
  888. * }, { priority: 'high' } );
  889. *
  890. * Allowing attributes in specific contexts will be a far less common use case, because it's normally handled by
  891. * `allowAttributes` rule from {@link module:engine/model/schema~SchemaItemDefinition} but if you have a complex scenario
  892. * where `bold` should be allowed only in element `foo` which must be in element `bar`, then this would be the way:
  893. *
  894. * schema.on( 'checkAttribute', ( evt, args ) => {
  895. * const context = args[ 0 ];
  896. * const atributeName = args[ 1 ];
  897. *
  898. * if ( context.endsWith( 'bar foo $text' ) && attributeName == 'bold' ) {
  899. * // Prevent next listeners from being called.
  900. * evt.stop();
  901. * // Set the checkAttribute()'s return value.
  902. * evt.return = true;
  903. * }
  904. * }, { priority: 'high' } );
  905. *
  906. * @event checkAttribute
  907. * @param {Array} args The `checkAttribute()`'s arguments.
  908. */
  909. /**
  910. * A definition of a {@link module:engine/model/schema~Schema schema} item.
  911. *
  912. * You can define the following rules:
  913. *
  914. * * `allowIn` &ndash; A string or an array of strings. Defines in which other items this item will be allowed.
  915. * * `allowAttributes` &ndash; A string or an array of strings. Defines allowed attributes of the given item.
  916. * * `allowContentOf` &ndash; A string or an array of strings. Inherits "allowed children" from other items.
  917. * * `allowWhere` &ndash; A string or an array of strings. Inherits "allowed in" from other items.
  918. * * `allowAttributesOf` &ndash; A string or an array of strings. Inherits attributes from other items.
  919. * * `inheritTypesFrom` &ndash; A string or an array of strings. Inherits `is*` properties of other items.
  920. * * `inheritAllFrom` &ndash; A string. A shorthand for `allowContentOf`, `allowWhere`, `allowAttributesOf`, `inheritTypesFrom`.
  921. * * Additionally, you can define the following `is*` properties: `isBlock`, `isLimit`, `isObject`. Read about them below.
  922. *
  923. * # The is* properties
  924. *
  925. * There are 3 commonly used `is*` properties. Their role is to assign additional semantics to schema items.
  926. * You can define more properties but you will also need to implement support for them in the existing editor features.
  927. *
  928. * * `isBlock` &ndash; Whether this item is paragraph-like. Generally speaking, content is usually made out of blocks
  929. * like paragraphs, list items, images, headings, etc. All these elements are marked as blocks. A block
  930. * should not allow another block inside. Note: There is also the `$block` generic item which has `isBlock` set to `true`.
  931. * Most block type items will inherit from `$block` (through `inheritAllFrom`).
  932. * * `isLimit` &ndash; It can be understood as whether this element should not be split by <kbd>Enter</kbd>.
  933. * Examples of limit elements: `$root`, table cell, image caption, etc. In other words, all actions that happen inside
  934. * a limit element are limited to its content. **Note:** All objects (`isObject`) are treated as limit elements, too.
  935. * * `isObject` &ndash; Whether an item is "self-contained" and should be treated as a whole. Examples of object elements:
  936. * `image`, `table`, `video`, etc. **Note:** An object is also a limit, so
  937. * {@link module:engine/model/schema~Schema#isLimit `isLimit()`}
  938. * returns `true` for object elements automatically.
  939. *
  940. * # Generic items
  941. *
  942. * There are three basic generic items: `$root`, `$block` and `$text`.
  943. * They are defined as follows:
  944. *
  945. * this.schema.register( '$root', {
  946. * isLimit: true
  947. * } );
  948. * this.schema.register( '$block', {
  949. * allowIn: '$root',
  950. * isBlock: true
  951. * } );
  952. * this.schema.register( '$text', {
  953. * allowIn: '$block'
  954. * } );
  955. *
  956. * They reflect typical editor content that is contained within one root, consists of several blocks
  957. * (paragraphs, lists items, headings, images) which, in turn, may contain text inside.
  958. *
  959. * By inheriting from the generic items you can define new items which will get extended by other editor features.
  960. * Read more about generic types in the {@linkTODO Defining schema} guide.
  961. *
  962. * # Example definitions
  963. *
  964. * Allow `paragraph` in roots and block quotes:
  965. *
  966. * schema.register( 'paragraph', {
  967. * allowIn: [ '$root', 'blockQuote' ],
  968. * isBlock: true
  969. * } );
  970. *
  971. * Allow `paragraph` everywhere where `$block` is allowed (i.e. in `$root`):
  972. *
  973. * schema.register( 'paragraph', {
  974. * allowWhere: '$block',
  975. * isBlock: true
  976. * } );
  977. *
  978. * Make `image` a block object, which is allowed everywhere where `$block` is.
  979. * Also, allow `src` and `alt` attributes in it:
  980. *
  981. * schema.register( 'image', {
  982. * allowWhere: '$block',
  983. * allowAttributes: [ 'src', 'alt' ],
  984. * isBlock: true,
  985. * isObject: true
  986. * } );
  987. *
  988. * Make `caption` allowed in `image` and make it allow all the content of `$block`s (usually, `$text`).
  989. * Also, mark it as a limit element so it cannot be split:
  990. *
  991. * schema.register( 'caption', {
  992. * allowIn: 'image',
  993. * allowContentOf: '$block',
  994. * isLimit: true
  995. * } );
  996. *
  997. * Make `listItem` inherit all from `$block` but also allow additional attributes:
  998. *
  999. * schema.register( 'listItem', {
  1000. * inheritAllFrom: '$block',
  1001. * allowAttributes: [ 'listType', 'listIndent' ]
  1002. * } );
  1003. *
  1004. * Which translates to:
  1005. *
  1006. * schema.register( 'listItem', {
  1007. * allowWhere: '$block',
  1008. * allowContentOf: '$block',
  1009. * allowAttributesOf: '$block',
  1010. * inheritTypesFrom: '$block',
  1011. * allowAttributes: [ 'listType', 'listIndent' ]
  1012. * } );
  1013. *
  1014. * # Tips
  1015. *
  1016. * * Check schema definitions of existing features to see how they are defined.
  1017. * * If you want to publish your feature so other developers can use it, try to use
  1018. * generic items as much as possible.
  1019. * * Keep your model clean. Limit it to the actual data and store information in a normalized way.
  1020. * * Remember about definining the `is*` properties. They do not affect the allowed structures, but they can
  1021. * affect how the editor features treat your elements.
  1022. *
  1023. * @typedef {Object} module:engine/model/schema~SchemaItemDefinition
  1024. */
  1025. /**
  1026. * A simplified version of {@link module:engine/model/schema~SchemaItemDefinition} after
  1027. * compilation by the {@link module:engine/model/schema~Schema schema}.
  1028. * Rules fed to the schema by {@link module:engine/model/schema~Schema#register}
  1029. * and {@link module:engine/model/schema~Schema#extend} methods are defined in the
  1030. * {@link module:engine/model/schema~SchemaItemDefinition} format.
  1031. * Later on, they are compiled to `SchemaCompiledItemDefition` so when you use e.g.
  1032. * the {@link module:engine/model/schema~Schema#getDefinition} method you get the compiled version.
  1033. *
  1034. * The compiled version contains only the following properties:
  1035. *
  1036. * * The `name` property,
  1037. * * The `is*` properties,
  1038. * * The `allowIn` array,
  1039. * * The `allowAttributes` array.
  1040. *
  1041. * @typedef {Object} module:engine/model/schema~SchemaCompiledItemDefinition
  1042. */
  1043. /**
  1044. * A schema context &mdash; a list of ancestors of a given position in the document.
  1045. *
  1046. * Considering such position:
  1047. *
  1048. * <$root>
  1049. * <blockQuote>
  1050. * <paragraph>
  1051. * ^
  1052. * </paragraph>
  1053. * </blockQuote>
  1054. * </$root>
  1055. *
  1056. * The context of this position is its {@link module:engine/model/position~Position#getAncestors lists of ancestors}:
  1057. *
  1058. * [ rootElement, blockQuoteElement, paragraphElement ]
  1059. *
  1060. * Contexts are used in the {@link module:engine/model/schema~Schema#event:checkChild `Schema#checkChild`} and
  1061. * {@link module:engine/model/schema~Schema#event:checkAttribute `Schema#checkAttribute`} events as a definition
  1062. * of a place in the document where the check occurs. The context instances are created based on the first arguments
  1063. * of the {@link module:engine/model/schema~Schema#checkChild `Schema#checkChild()`} and
  1064. * {@link module:engine/model/schema~Schema#checkAttribute `Schema#checkAttribute()`} methods so when
  1065. * using these methods you need to use {@link module:engine/model/schema~SchemaContextDefinition}s.
  1066. */
  1067. export class SchemaContext {
  1068. /**
  1069. * Creates an instance of the context.
  1070. *
  1071. * @param {module:engine/model/schema~SchemaContextDefinition} context
  1072. */
  1073. constructor( context ) {
  1074. if ( context instanceof SchemaContext ) {
  1075. return context;
  1076. }
  1077. if ( typeof context == 'string' ) {
  1078. context = [ context ];
  1079. } else if ( !Array.isArray( context ) ) {
  1080. // `context` is item or position.
  1081. // Position#getAncestors() doesn't accept any parameters but it works just fine here.
  1082. context = context.getAncestors( { includeSelf: true } );
  1083. }
  1084. if ( context[ 0 ] && typeof context[ 0 ] != 'string' && context[ 0 ].is( 'documentFragment' ) ) {
  1085. context.shift();
  1086. }
  1087. this._items = context.map( mapContextItem );
  1088. }
  1089. /**
  1090. * The number of items.
  1091. *
  1092. * @type {Number}
  1093. */
  1094. get length() {
  1095. return this._items.length;
  1096. }
  1097. /**
  1098. * The last item (the lowest node).
  1099. *
  1100. * @type {module:engine/model/schema~SchemaContextItem}
  1101. */
  1102. get last() {
  1103. return this._items[ this._items.length - 1 ];
  1104. }
  1105. /**
  1106. * Iterable interface.
  1107. *
  1108. * Iterates over all context items.
  1109. *
  1110. * @returns {Iterable.<module:engine/model/schema~SchemaContextItem>}
  1111. */
  1112. [ Symbol.iterator ]() {
  1113. return this._items[ Symbol.iterator ]();
  1114. }
  1115. /**
  1116. * Returns a new schema context instance with an additional item.
  1117. *
  1118. * Item can be added as:
  1119. *
  1120. * const context = new SchemaContext( [ '$root' ] );
  1121. *
  1122. * // An element.
  1123. * const fooElement = writer.createElement( 'fooElement' );
  1124. * const newContext = context.push( fooElement ); // [ '$root', 'fooElement' ]
  1125. *
  1126. * // A text node.
  1127. * const text = writer.createText( 'foobar' );
  1128. * const newContext = context.push( text ); // [ '$root', '$text' ]
  1129. *
  1130. * // A string (element name).
  1131. * const newContext = context.push( 'barElement' ); // [ '$root', 'barElement' ]
  1132. *
  1133. * **Note** {module:engine/model/node~Node} that is already in the model tree will be added as the only item (without ancestors).
  1134. *
  1135. * @param {String|module:engine/model/node~Node|Array<String|module:engine/model/node~Node>} item An item that will be added
  1136. * to the current context.
  1137. * @returns {module:engine/model/schema~SchemaContext} A new schema context instance with an additional item.
  1138. */
  1139. push( item ) {
  1140. const ctx = new SchemaContext( [ item ] );
  1141. ctx._items = [ ...this._items, ...ctx._items ];
  1142. return ctx;
  1143. }
  1144. /**
  1145. * Gets an item on the given index.
  1146. *
  1147. * @returns {module:engine/model/schema~SchemaContextItem}
  1148. */
  1149. getItem( index ) {
  1150. return this._items[ index ];
  1151. }
  1152. /**
  1153. * Returns the names of items.
  1154. *
  1155. * @returns {Iterable.<String>}
  1156. */
  1157. * getNames() {
  1158. yield* this._items.map( item => item.name );
  1159. }
  1160. /**
  1161. * Checks whether the context ends with the given nodes.
  1162. *
  1163. * const ctx = new SchemaContext( [ rootElement, paragraphElement, textNode ] );
  1164. *
  1165. * ctx.endsWith( '$text' ); // -> true
  1166. * ctx.endsWith( 'paragraph $text' ); // -> true
  1167. * ctx.endsWith( '$root' ); // -> false
  1168. * ctx.endsWith( 'paragraph' ); // -> false
  1169. *
  1170. * @param {String} query
  1171. * @returns {Boolean}
  1172. */
  1173. endsWith( query ) {
  1174. return Array.from( this.getNames() ).join( ' ' ).endsWith( query );
  1175. }
  1176. }
  1177. /**
  1178. * The definition of a {@link module:engine/model/schema~SchemaContext schema context}.
  1179. *
  1180. * Contexts can be created in multiple ways:
  1181. *
  1182. * * By defining a **node** – in this cases this node and all its ancestors will be used.
  1183. * * By defining a **position** in the document – in this case all its ancestors will be used.
  1184. * * By defining an **array of nodes** – in this case this array defines the entire context.
  1185. * * By defining a **name of node** - in this case node will be "mocked". It is not recommended because context
  1186. * will be unrealistic (e.g. attributes of these nodes are not specified). However, at times this may be the only
  1187. * way to define the context (e.g. when checking some hypothetical situation).
  1188. * * By defining an **array of node names** (potentially, mixed with real nodes) – The same as **name of node**
  1189. * but it is possible to create a path.
  1190. * * By defining a {@link module:engine/model/schema~SchemaContext} instance - in this case the same instance as provided
  1191. * will be return.
  1192. *
  1193. * Examples of context definitions passed to the {@link module:engine/model/schema~Schema#checkChild `Schema#checkChild()`}
  1194. * method:
  1195. *
  1196. * // Assuming that we have a $root > blockQuote > paragraph structure, the following code
  1197. * // will check node 'foo' in the following context:
  1198. * // [ rootElement, blockQuoteElement, paragraphElement ]
  1199. * const contextDefinition = paragraphElement;
  1200. * const childToCheck = 'foo';
  1201. * schema.checkChild( contextDefinition, childToCheck );
  1202. *
  1203. * // Also check in [ rootElement, blockQuoteElement, paragraphElement ].
  1204. * schema.checkChild( Position.createAt( paragraphElement ), 'foo' );
  1205. *
  1206. * // Check in [ rootElement, paragraphElement ].
  1207. * schema.checkChild( [ rootElement, paragraphElement ], 'foo' );
  1208. *
  1209. * // Check only fakeParagraphElement.
  1210. * schema.checkChild( 'paragraph', 'foo' );
  1211. *
  1212. * // Check in [ fakeRootElement, fakeBarElement, paragraphElement ].
  1213. * schema.checkChild( [ '$root', 'bar', paragraphElement ], 'foo' );
  1214. *
  1215. * All these `checkChild()` calls will fire {@link module:engine/model/schema~Schema#event:checkChild `Schema#checkChild`}
  1216. * events in which `args[ 0 ]` is an instance of the context. Therefore, you can write a listener like this:
  1217. *
  1218. * schema.on( 'checkChild', ( evt, args ) => {
  1219. * const ctx = args[ 0 ];
  1220. *
  1221. * console.log( Array.from( ctx.getNames() ) );
  1222. * } );
  1223. *
  1224. * Which will log the following:
  1225. *
  1226. * [ '$root', 'blockQuote', 'paragraph' ]
  1227. * [ '$root', 'paragraph' ]
  1228. * [ '$root', 'bar', 'paragraph' ]
  1229. *
  1230. * Note: When using the {@link module:engine/model/schema~Schema#checkAttribute `Schema#checkAttribute()`} method
  1231. * you may want to check whether a text node may have an attribute. A {@link module:engine/model/text~Text} is a
  1232. * correct way to define a context so you can do this:
  1233. *
  1234. * schema.checkAttribute( textNode, 'bold' );
  1235. *
  1236. * But sometimes you want to check whether a text at a given position might've had some attribute,
  1237. * in which case you can create a context by mising an array of elements with a `'$text'` string:
  1238. *
  1239. * // Check in [ rootElement, paragraphElement, textNode ].
  1240. * schema.checkChild( [ ...positionInParagraph.getAncestors(), '$text' ], 'bold' );
  1241. *
  1242. * @typedef {module:engine/model/node~Node|module:engine/model/position~Position|module:engine/model/schema~SchemaContext|
  1243. * String|Array.<String|module:engine/model/node~Node>} module:engine/model/schema~SchemaContextDefinition
  1244. */
  1245. /**
  1246. * An item of the {@link module:engine/model/schema~SchemaContext schema context}.
  1247. *
  1248. * It contains 3 properties:
  1249. *
  1250. * * `name` – the name of this item,
  1251. * * `* getAttributeKeys()` – a generator of keys of item attributes,
  1252. * * `getAttribute( keyName )` – a method to get attribute values.
  1253. *
  1254. * The context item interface is a highly simplified version of {@link module:engine/model/node~Node} and its role
  1255. * is to expose only the information which schema checks are able to provide (which is the name of the node and
  1256. * node's attributes).
  1257. *
  1258. * schema.on( 'checkChild', ( evt, args ) => {
  1259. * const ctx = args[ 0 ];
  1260. * const firstItem = ctx.getItem( 0 );
  1261. *
  1262. * console.log( firstItem.name ); // -> '$root'
  1263. * console.log( firstItem.getAttribute( 'foo' ) ); // -> 'bar'
  1264. * console.log( Array.from( firstItem.getAttributeKeys() ) ); // -> [ 'foo', 'faa' ]
  1265. * } );
  1266. *
  1267. * @typedef {Object} module:engine/model/schema~SchemaContextItem
  1268. */
  1269. function compileBaseItemRule( sourceItemRules, itemName ) {
  1270. const itemRule = {
  1271. name: itemName,
  1272. allowIn: [],
  1273. allowContentOf: [],
  1274. allowWhere: [],
  1275. allowAttributes: [],
  1276. allowAttributesOf: [],
  1277. inheritTypesFrom: []
  1278. };
  1279. copyTypes( sourceItemRules, itemRule );
  1280. copyProperty( sourceItemRules, itemRule, 'allowIn' );
  1281. copyProperty( sourceItemRules, itemRule, 'allowContentOf' );
  1282. copyProperty( sourceItemRules, itemRule, 'allowWhere' );
  1283. copyProperty( sourceItemRules, itemRule, 'allowAttributes' );
  1284. copyProperty( sourceItemRules, itemRule, 'allowAttributesOf' );
  1285. copyProperty( sourceItemRules, itemRule, 'inheritTypesFrom' );
  1286. makeInheritAllWork( sourceItemRules, itemRule );
  1287. return itemRule;
  1288. }
  1289. function compileAllowContentOf( compiledDefinitions, itemName ) {
  1290. for ( const allowContentOfItemName of compiledDefinitions[ itemName ].allowContentOf ) {
  1291. // The allowContentOf property may point to an unregistered element.
  1292. if ( compiledDefinitions[ allowContentOfItemName ] ) {
  1293. const allowedChildren = getAllowedChildren( compiledDefinitions, allowContentOfItemName );
  1294. allowedChildren.forEach( allowedItem => {
  1295. allowedItem.allowIn.push( itemName );
  1296. } );
  1297. }
  1298. }
  1299. delete compiledDefinitions[ itemName ].allowContentOf;
  1300. }
  1301. function compileAllowWhere( compiledDefinitions, itemName ) {
  1302. for ( const allowWhereItemName of compiledDefinitions[ itemName ].allowWhere ) {
  1303. const inheritFrom = compiledDefinitions[ allowWhereItemName ];
  1304. // The allowWhere property may point to an unregistered element.
  1305. if ( inheritFrom ) {
  1306. const allowedIn = inheritFrom.allowIn;
  1307. compiledDefinitions[ itemName ].allowIn.push( ...allowedIn );
  1308. }
  1309. }
  1310. delete compiledDefinitions[ itemName ].allowWhere;
  1311. }
  1312. function compileAllowAttributesOf( compiledDefinitions, itemName ) {
  1313. for ( const allowAttributeOfItem of compiledDefinitions[ itemName ].allowAttributesOf ) {
  1314. const inheritFrom = compiledDefinitions[ allowAttributeOfItem ];
  1315. if ( inheritFrom ) {
  1316. const inheritAttributes = inheritFrom.allowAttributes;
  1317. compiledDefinitions[ itemName ].allowAttributes.push( ...inheritAttributes );
  1318. }
  1319. }
  1320. delete compiledDefinitions[ itemName ].allowAttributesOf;
  1321. }
  1322. function compileInheritPropertiesFrom( compiledDefinitions, itemName ) {
  1323. const item = compiledDefinitions[ itemName ];
  1324. for ( const inheritPropertiesOfItem of item.inheritTypesFrom ) {
  1325. const inheritFrom = compiledDefinitions[ inheritPropertiesOfItem ];
  1326. if ( inheritFrom ) {
  1327. const typeNames = Object.keys( inheritFrom ).filter( name => name.startsWith( 'is' ) );
  1328. for ( const name of typeNames ) {
  1329. if ( !( name in item ) ) {
  1330. item[ name ] = inheritFrom[ name ];
  1331. }
  1332. }
  1333. }
  1334. }
  1335. delete item.inheritTypesFrom;
  1336. }
  1337. // Remove items which weren't registered (because it may break some checks or we'd need to complicate them).
  1338. // Make sure allowIn doesn't contain repeated values.
  1339. function cleanUpAllowIn( compiledDefinitions, itemName ) {
  1340. const itemRule = compiledDefinitions[ itemName ];
  1341. const existingItems = itemRule.allowIn.filter( itemToCheck => compiledDefinitions[ itemToCheck ] );
  1342. itemRule.allowIn = Array.from( new Set( existingItems ) );
  1343. }
  1344. function cleanUpAllowAttributes( compiledDefinitions, itemName ) {
  1345. const itemRule = compiledDefinitions[ itemName ];
  1346. itemRule.allowAttributes = Array.from( new Set( itemRule.allowAttributes ) );
  1347. }
  1348. function copyTypes( sourceItemRules, itemRule ) {
  1349. for ( const sourceItemRule of sourceItemRules ) {
  1350. const typeNames = Object.keys( sourceItemRule ).filter( name => name.startsWith( 'is' ) );
  1351. for ( const name of typeNames ) {
  1352. itemRule[ name ] = sourceItemRule[ name ];
  1353. }
  1354. }
  1355. }
  1356. function copyProperty( sourceItemRules, itemRule, propertyName ) {
  1357. for ( const sourceItemRule of sourceItemRules ) {
  1358. if ( typeof sourceItemRule[ propertyName ] == 'string' ) {
  1359. itemRule[ propertyName ].push( sourceItemRule[ propertyName ] );
  1360. } else if ( Array.isArray( sourceItemRule[ propertyName ] ) ) {
  1361. itemRule[ propertyName ].push( ...sourceItemRule[ propertyName ] );
  1362. }
  1363. }
  1364. }
  1365. function makeInheritAllWork( sourceItemRules, itemRule ) {
  1366. for ( const sourceItemRule of sourceItemRules ) {
  1367. const inheritFrom = sourceItemRule.inheritAllFrom;
  1368. if ( inheritFrom ) {
  1369. itemRule.allowContentOf.push( inheritFrom );
  1370. itemRule.allowWhere.push( inheritFrom );
  1371. itemRule.allowAttributesOf.push( inheritFrom );
  1372. itemRule.inheritTypesFrom.push( inheritFrom );
  1373. }
  1374. }
  1375. }
  1376. function getAllowedChildren( compiledDefinitions, itemName ) {
  1377. const itemRule = compiledDefinitions[ itemName ];
  1378. return getValues( compiledDefinitions ).filter( def => def.allowIn.includes( itemRule.name ) );
  1379. }
  1380. function getValues( obj ) {
  1381. return Object.keys( obj ).map( key => obj[ key ] );
  1382. }
  1383. function mapContextItem( ctxItem ) {
  1384. if ( typeof ctxItem == 'string' ) {
  1385. return {
  1386. name: ctxItem,
  1387. * getAttributeKeys() {},
  1388. getAttribute() {}
  1389. };
  1390. } else {
  1391. return {
  1392. // '$text' means text nodes and text proxies.
  1393. name: ctxItem.is( 'element' ) ? ctxItem.name : '$text',
  1394. * getAttributeKeys() {
  1395. yield* ctxItem.getAttributeKeys();
  1396. },
  1397. getAttribute( key ) {
  1398. return ctxItem.getAttribute( key );
  1399. }
  1400. };
  1401. }
  1402. }
  1403. // Generator function returning values from provided walkers, switching between them at each iteration. If only one walker
  1404. // is provided it will return data only from that walker.
  1405. //
  1406. // @param {module:engine/module/treewalker~TreeWalker} [backward] Walker iterating in backward direction.
  1407. // @param {module:engine/module/treewalker~TreeWalker} [forward] Walker iterating in forward direction.
  1408. // @returns {Iterable.<Object>} Object returned at each iteration contains `value` and `walker` (informing which walker returned
  1409. // given value) fields.
  1410. function* combineWalkers( backward, forward ) {
  1411. let done = false;
  1412. while ( !done ) {
  1413. done = true;
  1414. if ( backward ) {
  1415. const step = backward.next();
  1416. if ( !step.done ) {
  1417. done = false;
  1418. yield {
  1419. walker: backward,
  1420. value: step.value
  1421. };
  1422. }
  1423. }
  1424. if ( forward ) {
  1425. const step = forward.next();
  1426. if ( !step.done ) {
  1427. done = false;
  1428. yield {
  1429. walker: forward,
  1430. value: step.value
  1431. };
  1432. }
  1433. }
  1434. }
  1435. }
  1436. // Takes an array of non-intersecting ranges. For each of them gets minimal flat ranges covering that range and returns
  1437. // all those minimal flat ranges.
  1438. //
  1439. // @param {Array.<module:engine/model/range~Range>} ranges Ranges to process.
  1440. // @returns {Iterator.<module:engine/model/range~Range>} Minimal flat ranges of given `ranges`.
  1441. function* convertToMinimalFlatRanges( ranges ) {
  1442. for ( const range of ranges ) {
  1443. yield* range.getMinimalFlatRanges();
  1444. }
  1445. }