element.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  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 toMap from '@ckeditor/ckeditor5-utils/src/tomap';
  12. import isIterable from '@ckeditor/ckeditor5-utils/src/isiterable';
  13. import Matcher from './matcher';
  14. import StylesMap from './stylesmap';
  15. // @if CK_DEBUG_ENGINE // const { convertMapToTags } = require( '../dev-utils/utils' );
  16. /**
  17. * View element.
  18. *
  19. * The editing engine does not define a fixed semantics of its elements (it is "DTD-free").
  20. * This is why the type of the {@link module:engine/view/element~Element} need to
  21. * be defined by the feature developer. When creating an element you should use one of the following methods:
  22. *
  23. * * {@link module:engine/view/downcastwriter~DowncastWriter#createContainerElement `downcastWriter#createContainerElement()`}
  24. * in order to create a {@link module:engine/view/containerelement~ContainerElement},
  25. * * {@link module:engine/view/downcastwriter~DowncastWriter#createAttributeElement `downcastWriter#createAttributeElement()`}
  26. * in order to create a {@link module:engine/view/attributeelement~AttributeElement},
  27. * * {@link module:engine/view/downcastwriter~DowncastWriter#createEmptyElement `downcastWriter#createEmptyElement()`}
  28. * in order to create a {@link module:engine/view/emptyelement~EmptyElement}.
  29. * * {@link module:engine/view/downcastwriter~DowncastWriter#createUIElement `downcastWriter#createUIElement()`}
  30. * in order to create a {@link module:engine/view/uielement~UIElement}.
  31. * * {@link module:engine/view/downcastwriter~DowncastWriter#createEditableElement `downcastWriter#createEditableElement()`}
  32. * in order to create a {@link module:engine/view/editableelement~EditableElement}.
  33. *
  34. * Note that for view elements which are not created from the model, like elements from mutations, paste or
  35. * {@link module:engine/controller/datacontroller~DataController#set data.set} it is not possible to define the type of the element.
  36. * In such cases the {@link module:engine/view/upcastwriter~UpcastWriter#createElement `UpcastWriter#createElement()`} method
  37. * should be used to create generic view elements.
  38. *
  39. * @extends module:engine/view/node~Node
  40. */
  41. export default class Element extends Node {
  42. /**
  43. * Creates a view element.
  44. *
  45. * Attributes can be passed in various formats:
  46. *
  47. * new Element( viewDocument, 'div', { class: 'editor', contentEditable: 'true' } ); // object
  48. * new Element( viewDocument, 'div', [ [ 'class', 'editor' ], [ 'contentEditable', 'true' ] ] ); // map-like iterator
  49. * new Element( viewDocument, 'div', mapOfAttributes ); // map
  50. *
  51. * @protected
  52. * @param {module:engine/view/document~Document} document The document instance to which this element belongs.
  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( document, name, attrs, children ) {
  59. super( document );
  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( this.document.stylesProcessor );
  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/controller/datacontroller~DataController#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.data.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/controller/datacontroller~DataController#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.document, 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( this.document, 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. node.document = this.document;
  554. this._children.splice( index, 0, node );
  555. index++;
  556. count++;
  557. }
  558. return count;
  559. }
  560. /**
  561. * Removes number of child nodes starting at the given index and set the parent of these nodes to `null`.
  562. *
  563. * @see module:engine/view/downcastwriter~DowncastWriter#remove
  564. * @protected
  565. * @param {Number} index Number of the first node to remove.
  566. * @param {Number} [howMany=1] Number of nodes to remove.
  567. * @fires module:engine/view/node~Node#change
  568. * @returns {Array.<module:engine/view/node~Node>} The array of removed nodes.
  569. */
  570. _removeChildren( index, howMany = 1 ) {
  571. this._fireChange( 'children', this );
  572. for ( let i = index; i < index + howMany; i++ ) {
  573. this._children[ i ].parent = null;
  574. }
  575. return this._children.splice( index, howMany );
  576. }
  577. /**
  578. * Adds or overwrite attribute with a specified key and value.
  579. *
  580. * @see module:engine/view/downcastwriter~DowncastWriter#setAttribute
  581. * @protected
  582. * @param {String} key Attribute key.
  583. * @param {String} value Attribute value.
  584. * @fires module:engine/view/node~Node#change
  585. */
  586. _setAttribute( key, value ) {
  587. value = String( value );
  588. this._fireChange( 'attributes', this );
  589. if ( key == 'class' ) {
  590. parseClasses( this._classes, value );
  591. } else if ( key == 'style' ) {
  592. this._styles.setTo( value );
  593. } else {
  594. this._attrs.set( key, value );
  595. }
  596. }
  597. /**
  598. * Removes attribute from the element.
  599. *
  600. * @see module:engine/view/downcastwriter~DowncastWriter#removeAttribute
  601. * @protected
  602. * @param {String} key Attribute key.
  603. * @returns {Boolean} Returns true if an attribute existed and has been removed.
  604. * @fires module:engine/view/node~Node#change
  605. */
  606. _removeAttribute( key ) {
  607. this._fireChange( 'attributes', this );
  608. // Remove class attribute.
  609. if ( key == 'class' ) {
  610. if ( this._classes.size > 0 ) {
  611. this._classes.clear();
  612. return true;
  613. }
  614. return false;
  615. }
  616. // Remove style attribute.
  617. if ( key == 'style' ) {
  618. if ( !this._styles.isEmpty ) {
  619. this._styles.clear();
  620. return true;
  621. }
  622. return false;
  623. }
  624. // Remove other attributes.
  625. return this._attrs.delete( key );
  626. }
  627. /**
  628. * Adds specified class.
  629. *
  630. * element._addClass( 'foo' ); // Adds 'foo' class.
  631. * element._addClass( [ 'foo', 'bar' ] ); // Adds 'foo' and 'bar' classes.
  632. *
  633. * @see module:engine/view/downcastwriter~DowncastWriter#addClass
  634. * @protected
  635. * @param {Array.<String>|String} className
  636. * @fires module:engine/view/node~Node#change
  637. */
  638. _addClass( className ) {
  639. this._fireChange( 'attributes', this );
  640. className = Array.isArray( className ) ? className : [ className ];
  641. className.forEach( name => this._classes.add( name ) );
  642. }
  643. /**
  644. * Removes specified class.
  645. *
  646. * element._removeClass( 'foo' ); // Removes 'foo' class.
  647. * element._removeClass( [ 'foo', 'bar' ] ); // Removes both 'foo' and 'bar' classes.
  648. *
  649. * @see module:engine/view/downcastwriter~DowncastWriter#removeClass
  650. * @protected
  651. * @param {Array.<String>|String} className
  652. * @fires module:engine/view/node~Node#change
  653. */
  654. _removeClass( className ) {
  655. this._fireChange( 'attributes', this );
  656. className = Array.isArray( className ) ? className : [ className ];
  657. className.forEach( name => this._classes.delete( name ) );
  658. }
  659. /**
  660. * Adds style to the element.
  661. *
  662. * element._setStyle( 'color', 'red' );
  663. * element._setStyle( {
  664. * color: 'red',
  665. * position: 'fixed'
  666. * } );
  667. *
  668. * **Note**: This method can work with normalized style names if
  669. * {@link module:engine/controller/datacontroller~DataController#addStyleProcessorRules a particular style processor rule is enabled}.
  670. * See {@link module:engine/view/stylesmap~StylesMap#set `StylesMap#set()`} for details.
  671. *
  672. * @see module:engine/view/downcastwriter~DowncastWriter#setStyle
  673. * @protected
  674. * @param {String|Object} property Property name or object with key - value pairs.
  675. * @param {String} [value] Value to set. This parameter is ignored if object is provided as the first parameter.
  676. * @fires module:engine/view/node~Node#change
  677. */
  678. _setStyle( property, value ) {
  679. this._fireChange( 'attributes', this );
  680. this._styles.set( property, value );
  681. }
  682. /**
  683. * Removes specified style.
  684. *
  685. * element._removeStyle( 'color' ); // Removes 'color' style.
  686. * element._removeStyle( [ 'color', 'border-top' ] ); // Removes both 'color' and 'border-top' styles.
  687. *
  688. * **Note**: This method can work with normalized style names if
  689. * {@link module:engine/controller/datacontroller~DataController#addStyleProcessorRules a particular style processor rule is enabled}.
  690. * See {@link module:engine/view/stylesmap~StylesMap#remove `StylesMap#remove()`} for details.
  691. *
  692. * @see module:engine/view/downcastwriter~DowncastWriter#removeStyle
  693. * @protected
  694. * @param {Array.<String>|String} property
  695. * @fires module:engine/view/node~Node#change
  696. */
  697. _removeStyle( property ) {
  698. this._fireChange( 'attributes', this );
  699. property = Array.isArray( property ) ? property : [ property ];
  700. property.forEach( name => this._styles.remove( name ) );
  701. }
  702. /**
  703. * Sets a custom property. Unlike attributes, custom properties are not rendered to the DOM,
  704. * so they can be used to add special data to elements.
  705. *
  706. * @see module:engine/view/downcastwriter~DowncastWriter#setCustomProperty
  707. * @protected
  708. * @param {String|Symbol} key
  709. * @param {*} value
  710. */
  711. _setCustomProperty( key, value ) {
  712. this._customProperties.set( key, value );
  713. }
  714. /**
  715. * Removes the custom property stored under the given key.
  716. *
  717. * @see module:engine/view/downcastwriter~DowncastWriter#removeCustomProperty
  718. * @protected
  719. * @param {String|Symbol} key
  720. * @returns {Boolean} Returns true if property was removed.
  721. */
  722. _removeCustomProperty( key ) {
  723. return this._customProperties.delete( key );
  724. }
  725. /**
  726. * Returns block {@link module:engine/view/filler filler} offset or `null` if block filler is not needed.
  727. *
  728. * @abstract
  729. * @method module:engine/view/element~Element#getFillerOffset
  730. */
  731. // @if CK_DEBUG_ENGINE // printTree( level = 0) {
  732. // @if CK_DEBUG_ENGINE // let string = '';
  733. // @if CK_DEBUG_ENGINE // string += '\t'.repeat( level ) + `<${ this.name }${ convertMapToTags( this.getAttributes() ) }>`;
  734. // @if CK_DEBUG_ENGINE // for ( const child of this.getChildren() ) {
  735. // @if CK_DEBUG_ENGINE // if ( child.is( 'text' ) ) {
  736. // @if CK_DEBUG_ENGINE // string += '\n' + '\t'.repeat( level + 1 ) + child.data;
  737. // @if CK_DEBUG_ENGINE // } else {
  738. // @if CK_DEBUG_ENGINE // string += '\n' + child.printTree( level + 1 );
  739. // @if CK_DEBUG_ENGINE // }
  740. // @if CK_DEBUG_ENGINE // }
  741. // @if CK_DEBUG_ENGINE // if ( this.childCount ) {
  742. // @if CK_DEBUG_ENGINE // string += '\n' + '\t'.repeat( level );
  743. // @if CK_DEBUG_ENGINE // }
  744. // @if CK_DEBUG_ENGINE // string += `</${ this.name }>`;
  745. // @if CK_DEBUG_ENGINE // return string;
  746. // @if CK_DEBUG_ENGINE // }
  747. // @if CK_DEBUG_ENGINE // logTree() {
  748. // @if CK_DEBUG_ENGINE // console.log( this.printTree() );
  749. // @if CK_DEBUG_ENGINE // }
  750. }
  751. // Parses attributes provided to the element constructor before they are applied to an element. If attributes are passed
  752. // as an object (instead of `Iterable`), the object is transformed to the map. Attributes with `null` value are removed.
  753. // Attributes with non-`String` value are converted to `String`.
  754. //
  755. // @param {Object|Iterable} attrs Attributes to parse.
  756. // @returns {Map} Parsed attributes.
  757. function parseAttributes( attrs ) {
  758. attrs = toMap( attrs );
  759. for ( const [ key, value ] of attrs ) {
  760. if ( value === null ) {
  761. attrs.delete( key );
  762. } else if ( typeof value != 'string' ) {
  763. attrs.set( key, String( value ) );
  764. }
  765. }
  766. return attrs;
  767. }
  768. // Parses class attribute and puts all classes into classes set.
  769. // Classes set s cleared before insertion.
  770. //
  771. // @param {Set.<String>} classesSet Set to insert parsed classes.
  772. // @param {String} classesString String with classes to parse.
  773. function parseClasses( classesSet, classesString ) {
  774. const classArray = classesString.split( /\s+/ );
  775. classesSet.clear();
  776. classArray.forEach( name => classesSet.add( name ) );
  777. }
  778. // Converts strings to Text and non-iterables to arrays.
  779. //
  780. // @param {String|module:engine/view/item~Item|Iterable.<String|module:engine/view/item~Item>}
  781. // @returns {Iterable.<module:engine/view/node~Node>}
  782. function normalize( document, nodes ) {
  783. // Separate condition because string is iterable.
  784. if ( typeof nodes == 'string' ) {
  785. return [ new Text( document, nodes ) ];
  786. }
  787. if ( !isIterable( nodes ) ) {
  788. nodes = [ nodes ];
  789. }
  790. // Array.from to enable .map() on non-arrays.
  791. return Array.from( nodes )
  792. .map( node => {
  793. if ( typeof node == 'string' ) {
  794. return new Text( document, node );
  795. }
  796. if ( node instanceof TextProxy ) {
  797. return new Text( document, node.data );
  798. }
  799. return node;
  800. } );
  801. }