element.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917
  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.setTo( 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.isEmpty ) {
  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.isEmpty ) {
  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. const inlineStyle = this._styles.toString();
  241. return inlineStyle == '' ? undefined : inlineStyle;
  242. }
  243. return this._attrs.get( key );
  244. }
  245. /**
  246. * Returns a boolean indicating whether an attribute with the specified key exists in the element.
  247. *
  248. * @param {String} key Attribute key.
  249. * @returns {Boolean} `true` if attribute with the specified key exists in the element, false otherwise.
  250. */
  251. hasAttribute( key ) {
  252. if ( key == 'class' ) {
  253. return this._classes.size > 0;
  254. }
  255. if ( key == 'style' ) {
  256. return !this._styles.isEmpty;
  257. }
  258. return this._attrs.has( key );
  259. }
  260. /**
  261. * Checks if this element is similar to other element.
  262. * Both elements should have the same name and attributes to be considered as similar. Two similar elements
  263. * can contain different set of children nodes.
  264. *
  265. * @param {module:engine/view/element~Element} otherElement
  266. * @returns {Boolean}
  267. */
  268. isSimilar( otherElement ) {
  269. if ( !( otherElement instanceof Element ) ) {
  270. return false;
  271. }
  272. // If exactly the same Element is provided - return true immediately.
  273. if ( this === otherElement ) {
  274. return true;
  275. }
  276. // Check element name.
  277. if ( this.name != otherElement.name ) {
  278. return false;
  279. }
  280. // Check number of attributes, classes and styles.
  281. if ( this._attrs.size !== otherElement._attrs.size || this._classes.size !== otherElement._classes.size ||
  282. this._styles.size !== otherElement._styles.size ) {
  283. return false;
  284. }
  285. // Check if attributes are the same.
  286. for ( const [ key, value ] of this._attrs ) {
  287. if ( !otherElement._attrs.has( key ) || otherElement._attrs.get( key ) !== value ) {
  288. return false;
  289. }
  290. }
  291. // Check if classes are the same.
  292. for ( const className of this._classes ) {
  293. if ( !otherElement._classes.has( className ) ) {
  294. return false;
  295. }
  296. }
  297. // Check if styles are the same.
  298. for ( const property of this._styles.getStyleNames() ) {
  299. if (
  300. !otherElement._styles.has( property ) ||
  301. otherElement._styles.getAsString( property ) !== this._styles.getAsString( property )
  302. ) {
  303. return false;
  304. }
  305. }
  306. return true;
  307. }
  308. /**
  309. * Returns true if class is present.
  310. * If more then one class is provided - returns true only when all classes are present.
  311. *
  312. * element.hasClass( 'foo' ); // Returns true if 'foo' class is present.
  313. * element.hasClass( 'foo', 'bar' ); // Returns true if 'foo' and 'bar' classes are both present.
  314. *
  315. * @param {...String} className
  316. */
  317. hasClass( ...className ) {
  318. for ( const name of className ) {
  319. if ( !this._classes.has( name ) ) {
  320. return false;
  321. }
  322. }
  323. return true;
  324. }
  325. /**
  326. * Returns iterator that contains all class names.
  327. *
  328. * @returns {Iterable.<String>}
  329. */
  330. getClassNames() {
  331. return this._classes.keys();
  332. }
  333. /**
  334. * Returns style value for the given property mae.
  335. * If the style does not exist `undefined` is returned.
  336. *
  337. * **Note**: This method can work with normalized style names if
  338. * {@link module:engine/view/document~Document#addStyleProcessorRules a particular style processor rule is enabled}.
  339. * See {@link module:engine/view/stylesmap~StylesMap#getAsString `StylesMap#getAsString()`} for details.
  340. *
  341. * For an element with style set to `'margin:1px'`:
  342. *
  343. * // Enable 'margin' shorthand processing:
  344. * editor.editing.view.document.addStyleProcessorRules( addMarginRules );
  345. *
  346. * const element = view.change( writer => {
  347. * const element = writer.createElement();
  348. * writer.setStyle( 'margin', '1px' );
  349. * writer.setStyle( 'margin-bottom', '3em' );
  350. *
  351. * return element;
  352. * } );
  353. *
  354. * element.getStyle( 'margin' ); // -> 'margin: 1px 1px 3em;'
  355. *
  356. * @param {String} property
  357. * @returns {String|undefined}
  358. */
  359. getStyle( property ) {
  360. return this._styles.getAsString( property );
  361. }
  362. /**
  363. * Returns a normalized style object or single style value.
  364. *
  365. * For an element with style set to: margin:1px 2px 3em;
  366. *
  367. * element.getNormalizedStyle( 'margin' ) );
  368. *
  369. * will return:
  370. *
  371. * {
  372. * top: '1px',
  373. * right: '2px',
  374. * bottom: '3em',
  375. * left: '2px' // a normalized value from margin shorthand
  376. * }
  377. *
  378. * and reading for single style value:
  379. *
  380. * styles.getNormalizedStyle( 'margin-left' );
  381. *
  382. * Will return a `2px` string.
  383. *
  384. * **Note**: This method will return normalized values only if
  385. * {@link module:engine/view/document~Document#addStyleProcessorRules a particular style processor rule is enabled}.
  386. * See {@link module:engine/view/stylesmap~StylesMap#getNormalized `StylesMap#getNormalized()`} for details.
  387. *
  388. *
  389. * @param {String} property Name of CSS property
  390. * @returns {Object|String|undefined}
  391. */
  392. getNormalizedStyle( property ) {
  393. return this._styles.getNormalized( property );
  394. }
  395. /**
  396. * Returns iterator that contains all style names.
  397. *
  398. * @returns {Iterable.<String>}
  399. */
  400. getStyleNames() {
  401. return this._styles.getStyleNames();
  402. }
  403. /**
  404. * Returns true if style keys are present.
  405. * If more then one style property is provided - returns true only when all properties are present.
  406. *
  407. * element.hasStyle( 'color' ); // Returns true if 'border-top' style is present.
  408. * element.hasStyle( 'color', 'border-top' ); // Returns true if 'color' and 'border-top' styles are both present.
  409. *
  410. * @param {...String} property
  411. */
  412. hasStyle( ...property ) {
  413. for ( const name of property ) {
  414. if ( !this._styles.has( name ) ) {
  415. return false;
  416. }
  417. }
  418. return true;
  419. }
  420. /**
  421. * Returns ancestor element that match specified pattern.
  422. * Provided patterns should be compatible with {@link module:engine/view/matcher~Matcher Matcher} as it is used internally.
  423. *
  424. * @see module:engine/view/matcher~Matcher
  425. * @param {Object|String|RegExp|Function} patterns Patterns used to match correct ancestor.
  426. * See {@link module:engine/view/matcher~Matcher}.
  427. * @returns {module:engine/view/element~Element|null} Found element or `null` if no matching ancestor was found.
  428. */
  429. findAncestor( ...patterns ) {
  430. const matcher = new Matcher( ...patterns );
  431. let parent = this.parent;
  432. while ( parent ) {
  433. if ( matcher.match( parent ) ) {
  434. return parent;
  435. }
  436. parent = parent.parent;
  437. }
  438. return null;
  439. }
  440. /**
  441. * Returns the custom property value for the given key.
  442. *
  443. * @param {String|Symbol} key
  444. * @returns {*}
  445. */
  446. getCustomProperty( key ) {
  447. return this._customProperties.get( key );
  448. }
  449. /**
  450. * Returns an iterator which iterates over this element's custom properties.
  451. * Iterator provides `[ key, value ]` pairs for each stored property.
  452. *
  453. * @returns {Iterable.<*>}
  454. */
  455. * getCustomProperties() {
  456. yield* this._customProperties.entries();
  457. }
  458. /**
  459. * Returns identity string based on element's name, styles, classes and other attributes.
  460. * Two elements that {@link #isSimilar are similar} will have same identity string.
  461. * It has the following format:
  462. *
  463. * 'name class="class1,class2" style="style1:value1;style2:value2" attr1="val1" attr2="val2"'
  464. *
  465. * For example:
  466. *
  467. * const element = writer.createContainerElement( 'foo', {
  468. * banana: '10',
  469. * apple: '20',
  470. * style: 'color: red; border-color: white;',
  471. * class: 'baz'
  472. * } );
  473. *
  474. * // returns 'foo class="baz" style="border-color:white;color:red" apple="20" banana="10"'
  475. * element.getIdentity();
  476. *
  477. * **Note**: Classes, styles and other attributes are sorted alphabetically.
  478. *
  479. * @returns {String}
  480. */
  481. getIdentity() {
  482. const classes = Array.from( this._classes ).sort().join( ',' );
  483. const styles = this._styles.toString();
  484. const attributes = Array.from( this._attrs ).map( i => `${ i[ 0 ] }="${ i[ 1 ] }"` ).sort().join( ' ' );
  485. return this.name +
  486. ( classes == '' ? '' : ` class="${ classes }"` ) +
  487. ( !styles ? '' : ` style="${ styles }"` ) +
  488. ( attributes == '' ? '' : ` ${ attributes }` );
  489. }
  490. /**
  491. * Clones provided element.
  492. *
  493. * @protected
  494. * @param {Boolean} [deep=false] If set to `true` clones element and all its children recursively. When set to `false`,
  495. * element will be cloned without any children.
  496. * @returns {module:engine/view/element~Element} Clone of this element.
  497. */
  498. _clone( deep = false ) {
  499. const childrenClone = [];
  500. if ( deep ) {
  501. for ( const child of this.getChildren() ) {
  502. childrenClone.push( child._clone( deep ) );
  503. }
  504. }
  505. // ContainerElement and AttributeElement should be also cloned properly.
  506. const cloned = new this.constructor( this.name, this._attrs, childrenClone );
  507. // Classes and styles are cloned separately - this solution is faster than adding them back to attributes and
  508. // parse once again in constructor.
  509. cloned._classes = new Set( this._classes );
  510. cloned._styles.set( this._styles.getNormalized() );
  511. // Clone custom properties.
  512. cloned._customProperties = new Map( this._customProperties );
  513. // Clone filler offset method.
  514. // We can't define this method in a prototype because it's behavior which
  515. // is changed by e.g. toWidget() function from ckeditor5-widget. Perhaps this should be one of custom props.
  516. cloned.getFillerOffset = this.getFillerOffset;
  517. return cloned;
  518. }
  519. /**
  520. * {@link module:engine/view/element~Element#_insertChild Insert} a child node or a list of child nodes at the end of this node
  521. * and sets the parent of these nodes to this element.
  522. *
  523. * @see module:engine/view/downcastwriter~DowncastWriter#insert
  524. * @protected
  525. * @param {module:engine/view/item~Item|Iterable.<module:engine/view/item~Item>} items Items to be inserted.
  526. * @fires module:engine/view/node~Node#change
  527. * @returns {Number} Number of appended nodes.
  528. */
  529. _appendChild( items ) {
  530. return this._insertChild( this.childCount, items );
  531. }
  532. /**
  533. * Inserts a child node or a list of child nodes on the given index and sets the parent of these nodes to
  534. * this element.
  535. *
  536. * @see module:engine/view/downcastwriter~DowncastWriter#insert
  537. * @protected
  538. * @param {Number} index Position where nodes should be inserted.
  539. * @param {module:engine/view/item~Item|Iterable.<module:engine/view/item~Item>} items Items to be inserted.
  540. * @fires module:engine/view/node~Node#change
  541. * @returns {Number} Number of inserted nodes.
  542. */
  543. _insertChild( index, items ) {
  544. this._fireChange( 'children', this );
  545. let count = 0;
  546. const nodes = normalize( items );
  547. for ( const node of nodes ) {
  548. // If node that is being added to this element is already inside another element, first remove it from the old parent.
  549. if ( node.parent !== null ) {
  550. node._remove();
  551. }
  552. node.parent = this;
  553. this._children.splice( index, 0, node );
  554. index++;
  555. count++;
  556. }
  557. return count;
  558. }
  559. /**
  560. * Removes number of child nodes starting at the given index and set the parent of these nodes to `null`.
  561. *
  562. * @see module:engine/view/downcastwriter~DowncastWriter#remove
  563. * @protected
  564. * @param {Number} index Number of the first node to remove.
  565. * @param {Number} [howMany=1] Number of nodes to remove.
  566. * @fires module:engine/view/node~Node#change
  567. * @returns {Array.<module:engine/view/node~Node>} The array of removed nodes.
  568. */
  569. _removeChildren( index, howMany = 1 ) {
  570. this._fireChange( 'children', this );
  571. for ( let i = index; i < index + howMany; i++ ) {
  572. this._children[ i ].parent = null;
  573. }
  574. return this._children.splice( index, howMany );
  575. }
  576. /**
  577. * Adds or overwrite attribute with a specified key and value.
  578. *
  579. * @see module:engine/view/downcastwriter~DowncastWriter#setAttribute
  580. * @protected
  581. * @param {String} key Attribute key.
  582. * @param {String} value Attribute value.
  583. * @fires module:engine/view/node~Node#change
  584. */
  585. _setAttribute( key, value ) {
  586. value = String( value );
  587. this._fireChange( 'attributes', this );
  588. if ( key == 'class' ) {
  589. parseClasses( this._classes, value );
  590. } else if ( key == 'style' ) {
  591. this._styles.setTo( value );
  592. } else {
  593. this._attrs.set( key, value );
  594. }
  595. }
  596. /**
  597. * Removes attribute from the element.
  598. *
  599. * @see module:engine/view/downcastwriter~DowncastWriter#removeAttribute
  600. * @protected
  601. * @param {String} key Attribute key.
  602. * @returns {Boolean} Returns true if an attribute existed and has been removed.
  603. * @fires module:engine/view/node~Node#change
  604. */
  605. _removeAttribute( key ) {
  606. this._fireChange( 'attributes', this );
  607. // Remove class attribute.
  608. if ( key == 'class' ) {
  609. if ( this._classes.size > 0 ) {
  610. this._classes.clear();
  611. return true;
  612. }
  613. return false;
  614. }
  615. // Remove style attribute.
  616. if ( key == 'style' ) {
  617. if ( !this._styles.isEmpty ) {
  618. this._styles.clear();
  619. return true;
  620. }
  621. return false;
  622. }
  623. // Remove other attributes.
  624. return this._attrs.delete( key );
  625. }
  626. /**
  627. * Adds specified class.
  628. *
  629. * element._addClass( 'foo' ); // Adds 'foo' class.
  630. * element._addClass( [ 'foo', 'bar' ] ); // Adds 'foo' and 'bar' classes.
  631. *
  632. * @see module:engine/view/downcastwriter~DowncastWriter#addClass
  633. * @protected
  634. * @param {Array.<String>|String} className
  635. * @fires module:engine/view/node~Node#change
  636. */
  637. _addClass( className ) {
  638. this._fireChange( 'attributes', this );
  639. className = Array.isArray( className ) ? className : [ className ];
  640. className.forEach( name => this._classes.add( name ) );
  641. }
  642. /**
  643. * Removes specified class.
  644. *
  645. * element._removeClass( 'foo' ); // Removes 'foo' class.
  646. * element._removeClass( [ 'foo', 'bar' ] ); // Removes both 'foo' and 'bar' classes.
  647. *
  648. * @see module:engine/view/downcastwriter~DowncastWriter#removeClass
  649. * @protected
  650. * @param {Array.<String>|String} className
  651. * @fires module:engine/view/node~Node#change
  652. */
  653. _removeClass( className ) {
  654. this._fireChange( 'attributes', this );
  655. className = Array.isArray( className ) ? className : [ className ];
  656. className.forEach( name => this._classes.delete( name ) );
  657. }
  658. /**
  659. * Adds style to the element.
  660. *
  661. * element._setStyle( 'color', 'red' );
  662. * element._setStyle( {
  663. * color: 'red',
  664. * position: 'fixed'
  665. * } );
  666. *
  667. * **Note**: This method can work with normalized style names if
  668. * {@link module:engine/view/document~Document#addStyleProcessorRules a particular style processor rule is enabled}.
  669. * See {@link module:engine/view/stylesmap~StylesMap#set `StylesMap#set()`} for details.
  670. *
  671. * @see module:engine/view/downcastwriter~DowncastWriter#setStyle
  672. * @protected
  673. * @param {String|Object} property Property name or object with key - value pairs.
  674. * @param {String} [value] Value to set. This parameter is ignored if object is provided as the first parameter.
  675. * @fires module:engine/view/node~Node#change
  676. */
  677. _setStyle( property, value ) {
  678. this._fireChange( 'attributes', this );
  679. this._styles.set( property, value );
  680. }
  681. /**
  682. * Removes specified style.
  683. *
  684. * element._removeStyle( 'color' ); // Removes 'color' style.
  685. * element._removeStyle( [ 'color', 'border-top' ] ); // Removes both 'color' and 'border-top' styles.
  686. *
  687. * **Note**: This method can work with normalized style names if
  688. * {@link module:engine/view/document~Document#addStyleProcessorRules a particular style processor rule is enabled}.
  689. * See {@link module:engine/view/stylesmap~StylesMap#remove `StylesMap#remove()`} for details.
  690. *
  691. * @see module:engine/view/downcastwriter~DowncastWriter#removeStyle
  692. * @protected
  693. * @param {Array.<String>|String} property
  694. * @fires module:engine/view/node~Node#change
  695. */
  696. _removeStyle( property ) {
  697. this._fireChange( 'attributes', this );
  698. property = Array.isArray( property ) ? property : [ property ];
  699. property.forEach( name => this._styles.remove( name ) );
  700. }
  701. /**
  702. * Sets a custom property. Unlike attributes, custom properties are not rendered to the DOM,
  703. * so they can be used to add special data to elements.
  704. *
  705. * @see module:engine/view/downcastwriter~DowncastWriter#setCustomProperty
  706. * @protected
  707. * @param {String|Symbol} key
  708. * @param {*} value
  709. */
  710. _setCustomProperty( key, value ) {
  711. this._customProperties.set( key, value );
  712. }
  713. /**
  714. * Removes the custom property stored under the given key.
  715. *
  716. * @see module:engine/view/downcastwriter~DowncastWriter#removeCustomProperty
  717. * @protected
  718. * @param {String|Symbol} key
  719. * @returns {Boolean} Returns true if property was removed.
  720. */
  721. _removeCustomProperty( key ) {
  722. return this._customProperties.delete( key );
  723. }
  724. /**
  725. * Returns block {@link module:engine/view/filler filler} offset or `null` if block filler is not needed.
  726. *
  727. * @abstract
  728. * @method module:engine/view/element~Element#getFillerOffset
  729. */
  730. // @if CK_DEBUG_ENGINE // printTree( level = 0) {
  731. // @if CK_DEBUG_ENGINE // let string = '';
  732. // @if CK_DEBUG_ENGINE // string += '\t'.repeat( level ) + `<${ this.name }${ convertMapToTags( this.getAttributes() ) }>`;
  733. // @if CK_DEBUG_ENGINE // for ( const child of this.getChildren() ) {
  734. // @if CK_DEBUG_ENGINE // if ( child.is( 'text' ) ) {
  735. // @if CK_DEBUG_ENGINE // string += '\n' + '\t'.repeat( level + 1 ) + child.data;
  736. // @if CK_DEBUG_ENGINE // } else {
  737. // @if CK_DEBUG_ENGINE // string += '\n' + child.printTree( level + 1 );
  738. // @if CK_DEBUG_ENGINE // }
  739. // @if CK_DEBUG_ENGINE // }
  740. // @if CK_DEBUG_ENGINE // if ( this.childCount ) {
  741. // @if CK_DEBUG_ENGINE // string += '\n' + '\t'.repeat( level );
  742. // @if CK_DEBUG_ENGINE // }
  743. // @if CK_DEBUG_ENGINE // string += `</${ this.name }>`;
  744. // @if CK_DEBUG_ENGINE // return string;
  745. // @if CK_DEBUG_ENGINE // }
  746. // @if CK_DEBUG_ENGINE // logTree() {
  747. // @if CK_DEBUG_ENGINE // console.log( this.printTree() );
  748. // @if CK_DEBUG_ENGINE // }
  749. }
  750. // Parses attributes provided to the element constructor before they are applied to an element. If attributes are passed
  751. // as an object (instead of `Map`), the object is transformed to the map. Attributes with `null` value are removed.
  752. // Attributes with non-`String` value are converted to `String`.
  753. //
  754. // @param {Object|Map} attrs Attributes to parse.
  755. // @returns {Map} Parsed attributes.
  756. function parseAttributes( attrs ) {
  757. if ( attrs instanceof Map ) {
  758. attrs = new Map( attrs );
  759. } else {
  760. attrs = objectToMap( attrs );
  761. }
  762. for ( const [ key, value ] of attrs ) {
  763. if ( value === null ) {
  764. attrs.delete( key );
  765. } else if ( typeof value != 'string' ) {
  766. attrs.set( key, String( value ) );
  767. }
  768. }
  769. return attrs;
  770. }
  771. // Parses class attribute and puts all classes into classes set.
  772. // Classes set s cleared before insertion.
  773. //
  774. // @param {Set.<String>} classesSet Set to insert parsed classes.
  775. // @param {String} classesString String with classes to parse.
  776. function parseClasses( classesSet, classesString ) {
  777. const classArray = classesString.split( /\s+/ );
  778. classesSet.clear();
  779. classArray.forEach( name => classesSet.add( name ) );
  780. }
  781. // Converts strings to Text and non-iterables to arrays.
  782. //
  783. // @param {String|module:engine/view/item~Item|Iterable.<String|module:engine/view/item~Item>}
  784. // @returns {Iterable.<module:engine/view/node~Node>}
  785. function normalize( nodes ) {
  786. // Separate condition because string is iterable.
  787. if ( typeof nodes == 'string' ) {
  788. return [ new Text( nodes ) ];
  789. }
  790. if ( !isIterable( nodes ) ) {
  791. nodes = [ nodes ];
  792. }
  793. // Array.from to enable .map() on non-arrays.
  794. return Array.from( nodes )
  795. .map( node => {
  796. if ( typeof node == 'string' ) {
  797. return new Text( node );
  798. }
  799. if ( node instanceof TextProxy ) {
  800. return new Text( node.data );
  801. }
  802. return node;
  803. } );
  804. }