8
0

schema.js 50 KB

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