element.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  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/view/element
  7. */
  8. import Node from './node';
  9. import Text from './text';
  10. import TextProxy from './textproxy';
  11. import objectToMap from '@ckeditor/ckeditor5-utils/src/objecttomap';
  12. import isIterable from '@ckeditor/ckeditor5-utils/src/isiterable';
  13. import Matcher from './matcher';
  14. import { isPlainObject } from 'lodash-es';
  15. import StylesMap from './stylesmap';
  16. // @if CK_DEBUG_ENGINE // const { convertMapToTags } = require( '../dev-utils/utils' );
  17. /**
  18. * View element.
  19. *
  20. * The editing engine does not define a fixed semantics of its elements (it is "DTD-free").
  21. * This is why the type of the {@link module:engine/view/element~Element} need to
  22. * be defined by the feature developer. When creating an element you should use one of the following methods:
  23. *
  24. * * {@link module:engine/view/downcastwriter~DowncastWriter#createContainerElement `downcastWriter#createContainerElement()`}
  25. * in order to create a {@link module:engine/view/containerelement~ContainerElement},
  26. * * {@link module:engine/view/downcastwriter~DowncastWriter#createAttributeElement `downcastWriter#createAttributeElement()`}
  27. * in order to create a {@link module:engine/view/attributeelement~AttributeElement},
  28. * * {@link module:engine/view/downcastwriter~DowncastWriter#createEmptyElement `downcastWriter#createEmptyElement()`}
  29. * in order to create a {@link module:engine/view/emptyelement~EmptyElement}.
  30. * * {@link module:engine/view/downcastwriter~DowncastWriter#createUIElement `downcastWriter#createUIElement()`}
  31. * in order to create a {@link module:engine/view/uielement~UIElement}.
  32. * * {@link module:engine/view/downcastwriter~DowncastWriter#createEditableElement `downcastWriter#createEditableElement()`}
  33. * in order to create a {@link module:engine/view/editableelement~EditableElement}.
  34. *
  35. * Note that for view elements which are not created from the model, like elements from mutations, paste or
  36. * {@link module:engine/controller/datacontroller~DataController#set data.set} it is not possible to define the type of the element.
  37. * In such cases the {@link module:engine/view/upcastwriter~UpcastWriter#createElement `UpcastWriter#createElement()`} method
  38. * should be used to create generic view elements.
  39. *
  40. * @extends module:engine/view/node~Node
  41. */
  42. export default class Element extends Node {
  43. /**
  44. * Creates a view element.
  45. *
  46. * Attributes can be passed in various formats:
  47. *
  48. * new Element( 'div', { class: 'editor', contentEditable: 'true' } ); // object
  49. * new Element( 'div', [ [ 'class', 'editor' ], [ 'contentEditable', 'true' ] ] ); // map-like iterator
  50. * new Element( 'div', mapOfAttributes ); // map
  51. *
  52. * @protected
  53. * @param {String} name Node name.
  54. * @param {Object|Iterable} [attrs] Collection of attributes.
  55. * @param {module:engine/view/node~Node|Iterable.<module:engine/view/node~Node>} [children]
  56. * A list of nodes to be inserted into created element.
  57. */
  58. constructor( name, attrs, children ) {
  59. super();
  60. /**
  61. * Name of the element.
  62. *
  63. * @readonly
  64. * @member {String}
  65. */
  66. this.name = name;
  67. /**
  68. * Map of attributes, where attributes names are keys and attributes values are values.
  69. *
  70. * @protected
  71. * @member {Map} #_attrs
  72. */
  73. this._attrs = parseAttributes( attrs );
  74. /**
  75. * Array of child nodes.
  76. *
  77. * @protected
  78. * @member {Array.<module:engine/view/node~Node>}
  79. */
  80. this._children = [];
  81. if ( children ) {
  82. this._insertChild( 0, children );
  83. }
  84. /**
  85. * Set of classes associated with element instance.
  86. *
  87. * @protected
  88. * @member {Set}
  89. */
  90. this._classes = new Set();
  91. if ( this._attrs.has( 'class' ) ) {
  92. // Remove class attribute and handle it by class set.
  93. const classString = this._attrs.get( 'class' );
  94. parseClasses( this._classes, classString );
  95. this._attrs.delete( 'class' );
  96. }
  97. /**
  98. * Normalized styles.
  99. *
  100. * @protected
  101. * @member {module:engine/view/stylesmap~StylesMap} module:engine/view/element~Element#_styles
  102. */
  103. this._styles = new StylesMap();
  104. if ( this._attrs.has( 'style' ) ) {
  105. // Remove style attribute and handle it by styles map.
  106. this._styles.setStyle( this._attrs.get( 'style' ) );
  107. this._attrs.delete( 'style' );
  108. }
  109. /**
  110. * Map of custom properties.
  111. * Custom properties can be added to element instance, will be cloned but not rendered into DOM.
  112. *
  113. * @protected
  114. * @member {Map}
  115. */
  116. this._customProperties = new Map();
  117. }
  118. /**
  119. * Number of element's children.
  120. *
  121. * @readonly
  122. * @type {Number}
  123. */
  124. get childCount() {
  125. return this._children.length;
  126. }
  127. /**
  128. * Is `true` if there are no nodes inside this element, `false` otherwise.
  129. *
  130. * @readonly
  131. * @type {Boolean}
  132. */
  133. get isEmpty() {
  134. return this._children.length === 0;
  135. }
  136. /**
  137. * Checks whether this object is of the given.
  138. *
  139. * element.is( 'element' ); // -> true
  140. * element.is( 'node' ); // -> true
  141. * element.is( 'view:element' ); // -> true
  142. * element.is( 'view:node' ); // -> true
  143. *
  144. * element.is( 'model:element' ); // -> false
  145. * element.is( 'documentSelection' ); // -> false
  146. *
  147. * Assuming that the object being checked is an element, you can also check its
  148. * {@link module:engine/view/element~Element#name name}:
  149. *
  150. * element.is( 'img' ); // -> true if this is an <img> element
  151. * element.is( 'element', 'img' ); // -> same as above
  152. * text.is( 'img' ); -> false
  153. *
  154. * {@link module:engine/view/node~Node#is Check the entire list of view objects} which implement the `is()` method.
  155. *
  156. * @param {String} type Type to check when `name` parameter is present.
  157. * Otherwise, it acts like the `name` parameter.
  158. * @param {String} [name] Element name.
  159. * @returns {Boolean}
  160. */
  161. is( type, name = null ) {
  162. const cutType = type.replace( /^view:/, '' );
  163. if ( !name ) {
  164. return cutType == 'element' || cutType == this.name || super.is( type );
  165. } else {
  166. return cutType == 'element' && name == this.name;
  167. }
  168. }
  169. /**
  170. * Gets child at the given index.
  171. *
  172. * @param {Number} index Index of child.
  173. * @returns {module:engine/view/node~Node} Child node.
  174. */
  175. getChild( index ) {
  176. return this._children[ index ];
  177. }
  178. /**
  179. * Gets index of the given child node. Returns `-1` if child node is not found.
  180. *
  181. * @param {module:engine/view/node~Node} node Child node.
  182. * @returns {Number} Index of the child node.
  183. */
  184. getChildIndex( node ) {
  185. return this._children.indexOf( node );
  186. }
  187. /**
  188. * Gets child nodes iterator.
  189. *
  190. * @returns {Iterable.<module:engine/view/node~Node>} Child nodes iterator.
  191. */
  192. getChildren() {
  193. return this._children[ Symbol.iterator ]();
  194. }
  195. /**
  196. * Returns an iterator that contains the keys for attributes. Order of inserting attributes is not preserved.
  197. *
  198. * @returns {Iterable.<String>} Keys for attributes.
  199. */
  200. * getAttributeKeys() {
  201. if ( this._classes.size > 0 ) {
  202. yield 'class';
  203. }
  204. if ( this._styles.size > 0 ) {
  205. yield 'style';
  206. }
  207. yield* this._attrs.keys();
  208. }
  209. /**
  210. * Returns iterator that iterates over this element's attributes.
  211. *
  212. * Attributes are returned as arrays containing two items. First one is attribute key and second is attribute value.
  213. * This format is accepted by native `Map` object and also can be passed in `Node` constructor.
  214. *
  215. * @returns {Iterable.<*>}
  216. */
  217. * getAttributes() {
  218. yield* this._attrs.entries();
  219. if ( this._classes.size > 0 ) {
  220. yield [ 'class', this.getAttribute( 'class' ) ];
  221. }
  222. if ( this._styles.size > 0 ) {
  223. yield [ 'style', this.getAttribute( 'style' ) ];
  224. }
  225. }
  226. /**
  227. * Gets attribute by key. If attribute is not present - returns undefined.
  228. *
  229. * @param {String} key Attribute key.
  230. * @returns {String|undefined} Attribute value.
  231. */
  232. getAttribute( key ) {
  233. if ( key == 'class' ) {
  234. if ( this._classes.size > 0 ) {
  235. return [ ...this._classes ].join( ' ' );
  236. }
  237. return undefined;
  238. }
  239. if ( key == 'style' ) {
  240. return this._styles.getInlineStyle();
  241. }
  242. return this._attrs.get( key );
  243. }
  244. /**
  245. * Returns a boolean indicating whether an attribute with the specified key exists in the element.
  246. *
  247. * @param {String} key Attribute key.
  248. * @returns {Boolean} `true` if attribute with the specified key exists in the element, false otherwise.
  249. */
  250. hasAttribute( key ) {
  251. if ( key == 'class' ) {
  252. return this._classes.size > 0;
  253. }
  254. if ( key == 'style' ) {
  255. return this._styles.size > 0;
  256. }
  257. return this._attrs.has( key );
  258. }
  259. /**
  260. * Checks if this element is similar to other element.
  261. * Both elements should have the same name and attributes to be considered as similar. Two similar elements
  262. * can contain different set of children nodes.
  263. *
  264. * @param {module:engine/view/element~Element} otherElement
  265. * @returns {Boolean}
  266. */
  267. isSimilar( otherElement ) {
  268. if ( !( otherElement instanceof Element ) ) {
  269. return false;
  270. }
  271. // If exactly the same Element is provided - return true immediately.
  272. if ( this === otherElement ) {
  273. return true;
  274. }
  275. // Check element name.
  276. if ( this.name != otherElement.name ) {
  277. return false;
  278. }
  279. // Check number of attributes, classes and styles.
  280. if ( this._attrs.size !== otherElement._attrs.size || this._classes.size !== otherElement._classes.size ||
  281. this._styles.size !== otherElement._styles.size ) {
  282. return false;
  283. }
  284. // Check if attributes are the same.
  285. for ( const [ key, value ] of this._attrs ) {
  286. if ( !otherElement._attrs.has( key ) || otherElement._attrs.get( key ) !== value ) {
  287. return false;
  288. }
  289. }
  290. // Check if classes are the same.
  291. for ( const className of this._classes ) {
  292. if ( !otherElement._classes.has( className ) ) {
  293. return false;
  294. }
  295. }
  296. // Check if styles are the same.
  297. for ( const property of this._styles.getStyleNames() ) {
  298. if (
  299. !otherElement._styles.hasProperty( property ) ||
  300. otherElement._styles.getInlineProperty( property ) !== this._styles.getInlineProperty( property )
  301. ) {
  302. return false;
  303. }
  304. }
  305. return true;
  306. }
  307. /**
  308. * Returns true if class is present.
  309. * If more then one class is provided - returns true only when all classes are present.
  310. *
  311. * element.hasClass( 'foo' ); // Returns true if 'foo' class is present.
  312. * element.hasClass( 'foo', 'bar' ); // Returns true if 'foo' and 'bar' classes are both present.
  313. *
  314. * @param {...String} className
  315. */
  316. hasClass( ...className ) {
  317. for ( const name of className ) {
  318. if ( !this._classes.has( name ) ) {
  319. return false;
  320. }
  321. }
  322. return true;
  323. }
  324. /**
  325. * Returns iterator that contains all class names.
  326. *
  327. * @returns {Iterable.<String>}
  328. */
  329. getClassNames() {
  330. return this._classes.keys();
  331. }
  332. /**
  333. * Returns style value for given property.
  334. * Undefined is returned if style does not exist.
  335. *
  336. * @param {String} property
  337. * @returns {String|undefined}
  338. */
  339. getStyle( property ) {
  340. return this._styles.getInlineProperty( property );
  341. }
  342. /**
  343. * Returns a normalized style object or single style value.
  344. *
  345. * For an element with style set to: margin:1px 2px 3em;
  346. *
  347. * element.getNormalizedStyle( 'margin' ) );
  348. *
  349. * will return:
  350. *
  351. * {
  352. * top: '1px',
  353. * right: '2px',
  354. * bottom: '3em',
  355. * left: '2px' // a normalized value from margin shorthand
  356. * }
  357. *
  358. * and reading for single style value:
  359. *
  360. * styles.getNormalizedStyle( 'margin-left' );
  361. *
  362. * Will return a `2px` string.
  363. *
  364. * *Note*: This method will only return normalized styles if a style processor was defined. Otherwise the style names are not
  365. * normalized.
  366. *
  367. * @param {String} property Name of CSS property
  368. * @returns {Object|String|undefined}
  369. */
  370. getNormalizedStyle( property ) {
  371. return this._styles.getNormalized( property );
  372. }
  373. /**
  374. * Returns iterator that contains all style names.
  375. *
  376. * @returns {Iterable.<String>}
  377. */
  378. getStyleNames() {
  379. return this._styles.getStyleNames();
  380. }
  381. /**
  382. * Returns true if style keys are present.
  383. * If more then one style property is provided - returns true only when all properties are present.
  384. *
  385. * element.hasStyle( 'color' ); // Returns true if 'border-top' style is present.
  386. * element.hasStyle( 'color', 'border-top' ); // Returns true if 'color' and 'border-top' styles are both present.
  387. *
  388. * @param {...String} property
  389. */
  390. hasStyle( ...property ) {
  391. for ( const name of property ) {
  392. if ( !this._styles.hasProperty( name ) ) {
  393. return false;
  394. }
  395. }
  396. return true;
  397. }
  398. /**
  399. * Returns ancestor element that match specified pattern.
  400. * Provided patterns should be compatible with {@link module:engine/view/matcher~Matcher Matcher} as it is used internally.
  401. *
  402. * @see module:engine/view/matcher~Matcher
  403. * @param {Object|String|RegExp|Function} patterns Patterns used to match correct ancestor.
  404. * See {@link module:engine/view/matcher~Matcher}.
  405. * @returns {module:engine/view/element~Element|null} Found element or `null` if no matching ancestor was found.
  406. */
  407. findAncestor( ...patterns ) {
  408. const matcher = new Matcher( ...patterns );
  409. let parent = this.parent;
  410. while ( parent ) {
  411. if ( matcher.match( parent ) ) {
  412. return parent;
  413. }
  414. parent = parent.parent;
  415. }
  416. return null;
  417. }
  418. /**
  419. * Returns the custom property value for the given key.
  420. *
  421. * @param {String|Symbol} key
  422. * @returns {*}
  423. */
  424. getCustomProperty( key ) {
  425. return this._customProperties.get( key );
  426. }
  427. /**
  428. * Returns an iterator which iterates over this element's custom properties.
  429. * Iterator provides `[ key, value ]` pairs for each stored property.
  430. *
  431. * @returns {Iterable.<*>}
  432. */
  433. * getCustomProperties() {
  434. yield* this._customProperties.entries();
  435. }
  436. /**
  437. * Returns identity string based on element's name, styles, classes and other attributes.
  438. * Two elements that {@link #isSimilar are similar} will have same identity string.
  439. * It has the following format:
  440. *
  441. * 'name class="class1,class2" style="style1:value1;style2:value2" attr1="val1" attr2="val2"'
  442. *
  443. * For example:
  444. *
  445. * const element = writer.createContainerElement( 'foo', {
  446. * banana: '10',
  447. * apple: '20',
  448. * style: 'color: red; border-color: white;',
  449. * class: 'baz'
  450. * } );
  451. *
  452. * // returns 'foo class="baz" style="border-color:white;color:red" apple="20" banana="10"'
  453. * element.getIdentity();
  454. *
  455. * NOTE: Classes, styles and other attributes are sorted alphabetically.
  456. *
  457. * @returns {String}
  458. */
  459. getIdentity() {
  460. const classes = Array.from( this._classes ).sort().join( ',' );
  461. const styles = this._styles.getInlineStyle();
  462. const attributes = Array.from( this._attrs ).map( i => `${ i[ 0 ] }="${ i[ 1 ] }"` ).sort().join( ' ' );
  463. return this.name +
  464. ( classes == '' ? '' : ` class="${ classes }"` ) +
  465. ( !styles ? '' : ` style="${ styles }"` ) +
  466. ( attributes == '' ? '' : ` ${ attributes }` );
  467. }
  468. /**
  469. * Clones provided element.
  470. *
  471. * @protected
  472. * @param {Boolean} [deep=false] If set to `true` clones element and all its children recursively. When set to `false`,
  473. * element will be cloned without any children.
  474. * @returns {module:engine/view/element~Element} Clone of this element.
  475. */
  476. _clone( deep = false ) {
  477. const childrenClone = [];
  478. if ( deep ) {
  479. for ( const child of this.getChildren() ) {
  480. childrenClone.push( child._clone( deep ) );
  481. }
  482. }
  483. // ContainerElement and AttributeElement should be also cloned properly.
  484. const cloned = new this.constructor( this.name, this._attrs, childrenClone );
  485. // Classes and styles are cloned separately - this solution is faster than adding them back to attributes and
  486. // parse once again in constructor.
  487. cloned._classes = new Set( this._classes );
  488. cloned._styles.insertProperty( this._styles.getNormalized() );
  489. // Clone custom properties.
  490. cloned._customProperties = new Map( this._customProperties );
  491. // Clone filler offset method.
  492. // We can't define this method in a prototype because it's behavior which
  493. // is changed by e.g. toWidget() function from ckeditor5-widget. Perhaps this should be one of custom props.
  494. cloned.getFillerOffset = this.getFillerOffset;
  495. return cloned;
  496. }
  497. /**
  498. * {@link module:engine/view/element~Element#_insertChild Insert} a child node or a list of child nodes at the end of this node
  499. * and sets the parent of these nodes to this element.
  500. *
  501. * @see module:engine/view/downcastwriter~DowncastWriter#insert
  502. * @protected
  503. * @param {module:engine/view/item~Item|Iterable.<module:engine/view/item~Item>} items Items to be inserted.
  504. * @fires module:engine/view/node~Node#change
  505. * @returns {Number} Number of appended nodes.
  506. */
  507. _appendChild( items ) {
  508. return this._insertChild( this.childCount, items );
  509. }
  510. /**
  511. * Inserts a child node or a list of child nodes on the given index and sets the parent of these nodes to
  512. * this element.
  513. *
  514. * @see module:engine/view/downcastwriter~DowncastWriter#insert
  515. * @protected
  516. * @param {Number} index Position where nodes should be inserted.
  517. * @param {module:engine/view/item~Item|Iterable.<module:engine/view/item~Item>} items Items to be inserted.
  518. * @fires module:engine/view/node~Node#change
  519. * @returns {Number} Number of inserted nodes.
  520. */
  521. _insertChild( index, items ) {
  522. this._fireChange( 'children', this );
  523. let count = 0;
  524. const nodes = normalize( items );
  525. for ( const node of nodes ) {
  526. // If node that is being added to this element is already inside another element, first remove it from the old parent.
  527. if ( node.parent !== null ) {
  528. node._remove();
  529. }
  530. node.parent = this;
  531. this._children.splice( index, 0, node );
  532. index++;
  533. count++;
  534. }
  535. return count;
  536. }
  537. /**
  538. * Removes number of child nodes starting at the given index and set the parent of these nodes to `null`.
  539. *
  540. * @see module:engine/view/downcastwriter~DowncastWriter#remove
  541. * @protected
  542. * @param {Number} index Number of the first node to remove.
  543. * @param {Number} [howMany=1] Number of nodes to remove.
  544. * @fires module:engine/view/node~Node#change
  545. * @returns {Array.<module:engine/view/node~Node>} The array of removed nodes.
  546. */
  547. _removeChildren( index, howMany = 1 ) {
  548. this._fireChange( 'children', this );
  549. for ( let i = index; i < index + howMany; i++ ) {
  550. this._children[ i ].parent = null;
  551. }
  552. return this._children.splice( index, howMany );
  553. }
  554. /**
  555. * Adds or overwrite attribute with a specified key and value.
  556. *
  557. * @see module:engine/view/downcastwriter~DowncastWriter#setAttribute
  558. * @protected
  559. * @param {String} key Attribute key.
  560. * @param {String} value Attribute value.
  561. * @fires module:engine/view/node~Node#change
  562. */
  563. _setAttribute( key, value ) {
  564. value = String( value );
  565. this._fireChange( 'attributes', this );
  566. if ( key == 'class' ) {
  567. parseClasses( this._classes, value );
  568. } else if ( key == 'style' ) {
  569. this._styles.setStyle( value );
  570. } else {
  571. this._attrs.set( key, value );
  572. }
  573. }
  574. /**
  575. * Removes attribute from the element.
  576. *
  577. * @see module:engine/view/downcastwriter~DowncastWriter#removeAttribute
  578. * @protected
  579. * @param {String} key Attribute key.
  580. * @returns {Boolean} Returns true if an attribute existed and has been removed.
  581. * @fires module:engine/view/node~Node#change
  582. */
  583. _removeAttribute( key ) {
  584. this._fireChange( 'attributes', this );
  585. // Remove class attribute.
  586. if ( key == 'class' ) {
  587. if ( this._classes.size > 0 ) {
  588. this._classes.clear();
  589. return true;
  590. }
  591. return false;
  592. }
  593. // Remove style attribute.
  594. if ( key == 'style' ) {
  595. if ( this._styles.size ) {
  596. this._styles.clear();
  597. return true;
  598. }
  599. return false;
  600. }
  601. // Remove other attributes.
  602. return this._attrs.delete( key );
  603. }
  604. /**
  605. * Adds specified class.
  606. *
  607. * element._addClass( 'foo' ); // Adds 'foo' class.
  608. * element._addClass( [ 'foo', 'bar' ] ); // Adds 'foo' and 'bar' classes.
  609. *
  610. * @see module:engine/view/downcastwriter~DowncastWriter#addClass
  611. * @protected
  612. * @param {Array.<String>|String} className
  613. * @fires module:engine/view/node~Node#change
  614. */
  615. _addClass( className ) {
  616. this._fireChange( 'attributes', this );
  617. className = Array.isArray( className ) ? className : [ className ];
  618. className.forEach( name => this._classes.add( name ) );
  619. }
  620. /**
  621. * Removes specified class.
  622. *
  623. * element._removeClass( 'foo' ); // Removes 'foo' class.
  624. * element._removeClass( [ 'foo', 'bar' ] ); // Removes both 'foo' and 'bar' classes.
  625. *
  626. * @see module:engine/view/downcastwriter~DowncastWriter#removeClass
  627. * @protected
  628. * @param {Array.<String>|String} className
  629. * @fires module:engine/view/node~Node#change
  630. */
  631. _removeClass( className ) {
  632. this._fireChange( 'attributes', this );
  633. className = Array.isArray( className ) ? className : [ className ];
  634. className.forEach( name => this._classes.delete( name ) );
  635. }
  636. /**
  637. * Adds style to the element.
  638. *
  639. * element._setStyle( 'color', 'red' );
  640. * element._setStyle( {
  641. * color: 'red',
  642. * position: 'fixed'
  643. * } );
  644. *
  645. * @see module:engine/view/downcastwriter~DowncastWriter#setStyle
  646. * @protected
  647. * @param {String|Object} property Property name or object with key - value pairs.
  648. * @param {String} [value] Value to set. This parameter is ignored if object is provided as the first parameter.
  649. * @fires module:engine/view/node~Node#change
  650. */
  651. _setStyle( property, value ) {
  652. this._fireChange( 'attributes', this );
  653. this._styles.insertProperty( property, value );
  654. }
  655. /**
  656. * Removes specified style.
  657. *
  658. * element._removeStyle( 'color' ); // Removes 'color' style.
  659. * element._removeStyle( [ 'color', 'border-top' ] ); // Removes both 'color' and 'border-top' styles.
  660. *
  661. * @see module:engine/view/downcastwriter~DowncastWriter#removeStyle
  662. * @protected
  663. * @param {Array.<String>|String} property
  664. * @fires module:engine/view/node~Node#change
  665. */
  666. _removeStyle( property ) {
  667. this._fireChange( 'attributes', this );
  668. property = Array.isArray( property ) ? property : [ property ];
  669. property.forEach( name => this._styles.removeProperty( name ) );
  670. }
  671. /**
  672. * Sets a custom property. Unlike attributes, custom properties are not rendered to the DOM,
  673. * so they can be used to add special data to elements.
  674. *
  675. * @see module:engine/view/downcastwriter~DowncastWriter#setCustomProperty
  676. * @protected
  677. * @param {String|Symbol} key
  678. * @param {*} value
  679. */
  680. _setCustomProperty( key, value ) {
  681. this._customProperties.set( key, value );
  682. }
  683. /**
  684. * Removes the custom property stored under the given key.
  685. *
  686. * @see module:engine/view/downcastwriter~DowncastWriter#removeCustomProperty
  687. * @protected
  688. * @param {String|Symbol} key
  689. * @returns {Boolean} Returns true if property was removed.
  690. */
  691. _removeCustomProperty( key ) {
  692. return this._customProperties.delete( key );
  693. }
  694. /**
  695. * Returns block {@link module:engine/view/filler filler} offset or `null` if block filler is not needed.
  696. *
  697. * @abstract
  698. * @method module:engine/view/element~Element#getFillerOffset
  699. */
  700. // @if CK_DEBUG_ENGINE // printTree( level = 0) {
  701. // @if CK_DEBUG_ENGINE // let string = '';
  702. // @if CK_DEBUG_ENGINE // string += '\t'.repeat( level ) + `<${ this.name }${ convertMapToTags( this.getAttributes() ) }>`;
  703. // @if CK_DEBUG_ENGINE // for ( const child of this.getChildren() ) {
  704. // @if CK_DEBUG_ENGINE // if ( child.is( 'text' ) ) {
  705. // @if CK_DEBUG_ENGINE // string += '\n' + '\t'.repeat( level + 1 ) + child.data;
  706. // @if CK_DEBUG_ENGINE // } else {
  707. // @if CK_DEBUG_ENGINE // string += '\n' + child.printTree( level + 1 );
  708. // @if CK_DEBUG_ENGINE // }
  709. // @if CK_DEBUG_ENGINE // }
  710. // @if CK_DEBUG_ENGINE // if ( this.childCount ) {
  711. // @if CK_DEBUG_ENGINE // string += '\n' + '\t'.repeat( level );
  712. // @if CK_DEBUG_ENGINE // }
  713. // @if CK_DEBUG_ENGINE // string += `</${ this.name }>`;
  714. // @if CK_DEBUG_ENGINE // return string;
  715. // @if CK_DEBUG_ENGINE // }
  716. // @if CK_DEBUG_ENGINE // logTree() {
  717. // @if CK_DEBUG_ENGINE // console.log( this.printTree() );
  718. // @if CK_DEBUG_ENGINE // }
  719. }
  720. // Parses attributes provided to the element constructor before they are applied to an element. If attributes are passed
  721. // as an object (instead of `Map`), the object is transformed to the map. Attributes with `null` value are removed.
  722. // Attributes with non-`String` value are converted to `String`.
  723. //
  724. // @param {Object|Map} attrs Attributes to parse.
  725. // @returns {Map} Parsed attributes.
  726. function parseAttributes( attrs ) {
  727. if ( isPlainObject( attrs ) ) {
  728. attrs = objectToMap( attrs );
  729. } else {
  730. attrs = new Map( attrs );
  731. }
  732. for ( const [ key, value ] of attrs ) {
  733. if ( value === null ) {
  734. attrs.delete( key );
  735. } else if ( typeof value != 'string' ) {
  736. attrs.set( key, String( value ) );
  737. }
  738. }
  739. return attrs;
  740. }
  741. // Parses class attribute and puts all classes into classes set.
  742. // Classes set s cleared before insertion.
  743. //
  744. // @param {Set.<String>} classesSet Set to insert parsed classes.
  745. // @param {String} classesString String with classes to parse.
  746. function parseClasses( classesSet, classesString ) {
  747. const classArray = classesString.split( /\s+/ );
  748. classesSet.clear();
  749. classArray.forEach( name => classesSet.add( name ) );
  750. }
  751. // Converts strings to Text and non-iterables to arrays.
  752. //
  753. // @param {String|module:engine/view/item~Item|Iterable.<String|module:engine/view/item~Item>}
  754. // @returns {Iterable.<module:engine/view/node~Node>}
  755. function normalize( nodes ) {
  756. // Separate condition because string is iterable.
  757. if ( typeof nodes == 'string' ) {
  758. return [ new Text( nodes ) ];
  759. }
  760. if ( !isIterable( nodes ) ) {
  761. nodes = [ nodes ];
  762. }
  763. // Array.from to enable .map() on non-arrays.
  764. return Array.from( nodes )
  765. .map( node => {
  766. if ( typeof node == 'string' ) {
  767. return new Text( node );
  768. }
  769. if ( node instanceof TextProxy ) {
  770. return new Text( node.data );
  771. }
  772. return node;
  773. } );
  774. }