schema.js 61 KB

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