element.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. /**
  2. * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. 'use strict';
  6. import Node from './node.js';
  7. import utils from '../../utils/utils.js';
  8. import isPlainObject from '../../utils/lib/lodash/isPlainObject.js';
  9. /**
  10. * Tree view element.
  11. *
  12. * @memberOf engine.treeView
  13. * @extends engine.treeView.Node
  14. */
  15. export default class Element extends Node {
  16. /**
  17. * Creates a tree view element.
  18. *
  19. * Attributes can be passed in various formats:
  20. *
  21. * new Element( 'div', { 'class': 'editor', 'contentEditable': 'true' } ); // object
  22. * new Element( 'div', [ [ 'class', 'editor' ], [ 'contentEditable', 'true' ] ] ); // map-like iterator
  23. * new Element( 'div', mapOfAttributes ); // map
  24. *
  25. * @param {String} name Node name.
  26. * @param {Object|Iterable} [attrs] Collection of attributes.
  27. * @param {engine.treeView.Node|Iterable.<engine.treeView.Node>} [children] List of nodes to be inserted into created element.
  28. */
  29. constructor( name, attrs, children ) {
  30. super();
  31. /**
  32. * Name of the element.
  33. *
  34. * @readonly
  35. * @member {String} engine.treeView.Element#name
  36. */
  37. this.name = name;
  38. /**
  39. * Map of attributes, where attributes names are keys and attributes values are values.
  40. *
  41. * @protected
  42. * @member {Map} engine.treeView.Element#_attrs
  43. */
  44. if ( isPlainObject( attrs ) ) {
  45. this._attrs = utils.objectToMap( attrs );
  46. } else {
  47. this._attrs = new Map( attrs );
  48. }
  49. /**
  50. * Array of child nodes.
  51. *
  52. * @protected
  53. * @member {Array.<engine.treeView.Node>} engine.treeView.Element#_children
  54. */
  55. this._children = [];
  56. if ( children ) {
  57. this.insertChildren( 0, children );
  58. }
  59. /**
  60. * Set of classes associated with element instance.
  61. *
  62. * @protected
  63. * @member {Set} engine.treeView.Element#_classes
  64. */
  65. this._classes = new Set();
  66. if ( this._attrs.has( 'class' ) ) {
  67. // Remove class attribute and handle it by class set.
  68. const classString = this._attrs.get( 'class' );
  69. parseClasses( this._classes, classString );
  70. this._attrs.delete( 'class' );
  71. }
  72. /**
  73. * Map of styles.
  74. *
  75. * @protected
  76. * @member {Set} engine.treeView.Element#_styles
  77. */
  78. this._styles = new Map();
  79. if ( this._attrs.has( 'style' ) ) {
  80. // Remove style attribute and handle it by styles map.
  81. parseInlineStyles( this._styles, this._attrs.get( 'style' ) );
  82. this._attrs.delete( 'style' );
  83. }
  84. }
  85. /**
  86. * Clones provided element.
  87. *
  88. * @param {Boolean} deep If set to `true` clones element and all its children recursively. When set to `false`,
  89. * element will be cloned without any children.
  90. * @returns {Element} Clone of this element.
  91. */
  92. clone( deep ) {
  93. const childrenClone = [];
  94. if ( deep ) {
  95. for ( let child of this.getChildren() ) {
  96. childrenClone.push( child.clone( deep ) );
  97. }
  98. }
  99. const cloned = new Element( this.name, this._attrs, childrenClone );
  100. // Classes and styles are cloned separately - this solution is faster than adding them back to attributes and
  101. // parse once again in constructor.
  102. cloned._classes = new Set( this._classes );
  103. cloned._styles = new Map( this._styles );
  104. return cloned;
  105. }
  106. /**
  107. * {@link engine.treeView.Element#insert Insert} a child node or a list of child nodes at the end of this node and sets
  108. * the parent of these nodes to this element.
  109. *
  110. * @fires engine.treeView.Node#change
  111. * @param {engine.treeView.Node|Iterable.<engine.treeView.Node>} nodes Node or the list of nodes to be inserted.
  112. * @returns {Number} Number of appended nodes.
  113. */
  114. appendChildren( nodes ) {
  115. return this.insertChildren( this.getChildCount(), nodes );
  116. }
  117. /**
  118. * Gets child at the given index.
  119. *
  120. * @param {Number} index Index of child.
  121. * @returns {engine.treeView.Node} Child node.
  122. */
  123. getChild( index ) {
  124. return this._children[ index ];
  125. }
  126. /**
  127. * Gets the number of element's children.
  128. *
  129. * @returns {Number} The number of element's children.
  130. */
  131. getChildCount() {
  132. return this._children.length;
  133. }
  134. /**
  135. * Gets index of the given child node. Returns `-1` if child node is not found.
  136. *
  137. * @param {engine.treeView.Node} node Child node.
  138. * @returns {Number} Index of the child node.
  139. */
  140. getChildIndex( node ) {
  141. return this._children.indexOf( node );
  142. }
  143. /**
  144. * Gets child nodes iterator.
  145. *
  146. * @returns {Iterable.<engine.treeView.Node>} Child nodes iterator.
  147. */
  148. getChildren() {
  149. return this._children[ Symbol.iterator ]();
  150. }
  151. /**
  152. * Returns an iterator that contains the keys for attributes.
  153. * Order of inserting attributes is not preserved.
  154. *
  155. * @returns {Iterator.<String>} Keys for attributes.
  156. */
  157. *getAttributeKeys() {
  158. if ( this._classes.size > 0 ) {
  159. yield 'class';
  160. }
  161. if ( this._styles.size > 0 ) {
  162. yield 'style';
  163. }
  164. yield* this._attrs.keys();
  165. }
  166. /**
  167. * Gets attribute by key. If attribute is not present - returns undefined.
  168. *
  169. * @param {String} key Attribute key.
  170. * @returns {String|undefined} Attribute value.
  171. */
  172. getAttribute( key ) {
  173. if ( key == 'class' ) {
  174. if ( this._classes.size > 0 ) {
  175. return [ ...this._classes ].join( ' ' );
  176. }
  177. return undefined;
  178. }
  179. if ( key == 'style' ) {
  180. if ( this._styles.size > 0 ) {
  181. let styleString = '';
  182. for ( let [ property, value ] of this._styles ) {
  183. styleString += `${ property }:${ value };`;
  184. }
  185. return styleString;
  186. }
  187. return undefined;
  188. }
  189. return this._attrs.get( key );
  190. }
  191. /**
  192. * Returns a boolean indicating whether an attribute with the specified key exists in the element.
  193. *
  194. * @param {String} key Attribute key.
  195. * @returns {Boolean} `true` if attribute with the specified key exists in the element, false otherwise.
  196. */
  197. hasAttribute( key ) {
  198. if ( key == 'class' ) {
  199. return this._classes.size > 0;
  200. }
  201. if ( key == 'style' ) {
  202. return this._styles.size > 0;
  203. }
  204. return this._attrs.has( key );
  205. }
  206. /**
  207. * Adds or overwrite attribute with a specified key and value.
  208. *
  209. * @param {String} key Attribute key.
  210. * @param {String} value Attribute value.
  211. * @fires engine.treeView.Node#change
  212. */
  213. setAttribute( key, value ) {
  214. this._fireChange( 'ATTRIBUTES', this );
  215. if ( key == 'class' ) {
  216. parseClasses( this._classes, value );
  217. } else if ( key == 'style' ) {
  218. parseInlineStyles( this._styles, value );
  219. } else {
  220. this._attrs.set( key, value );
  221. }
  222. }
  223. /**
  224. * Inserts a child node or a list of child nodes on the given index and sets the parent of these nodes to
  225. * this element.
  226. *
  227. * @param {Number} index Position where nodes should be inserted.
  228. * @param {engine.treeView.Node|Iterable.<engine.treeView.Node>} nodes Node or the list of nodes to be inserted.
  229. * @fires engine.treeView.Node#change
  230. * @returns {Number} Number of inserted nodes.
  231. */
  232. insertChildren( index, nodes ) {
  233. this._fireChange( 'CHILDREN', this );
  234. let count = 0;
  235. if ( !utils.isIterable( nodes ) ) {
  236. nodes = [ nodes ];
  237. }
  238. for ( let node of nodes ) {
  239. node.parent = this;
  240. this._children.splice( index, 0, node );
  241. index++;
  242. count++;
  243. }
  244. return count;
  245. }
  246. /**
  247. * Removes attribute from the element.
  248. *
  249. * @param {String} key Attribute key.
  250. * @returns {Boolean} Returns true if an attribute existed and has been removed.
  251. * @fires engine.treeView.Node#change
  252. */
  253. removeAttribute( key ) {
  254. this._fireChange( 'ATTRIBUTES', this );
  255. // Remove class attribute.
  256. if ( key == 'class' ) {
  257. if ( this._classes.size > 0 ) {
  258. this._classes.clear();
  259. return true;
  260. }
  261. return false;
  262. }
  263. // Remove style attribute.
  264. if ( key == 'style' ) {
  265. if ( this._styles.size > 0 ) {
  266. this._styles.clear();
  267. return true;
  268. }
  269. return false;
  270. }
  271. // Remove other attributes.
  272. return this._attrs.delete( key );
  273. }
  274. /**
  275. * Removes number of child nodes starting at the given index and set the parent of these nodes to `null`.
  276. *
  277. * @param {Number} index Number of the first node to remove.
  278. * @param {Number} [howMany=1] Number of nodes to remove.
  279. * @returns {Array.<engine.treeView.Node>} The array of removed nodes.
  280. * @fires engine.treeView.Node#change
  281. */
  282. removeChildren( index, howMany = 1 ) {
  283. this._fireChange( 'CHILDREN', this );
  284. for ( let i = index; i < index + howMany; i++ ) {
  285. this._children[ i ].parent = null;
  286. }
  287. return this._children.splice( index, howMany );
  288. }
  289. /**
  290. * Checks if this element is similar to other element.
  291. * Both elements should have the same name and attributes to be considered as similar. Two similar elements
  292. * can contain different set of children nodes.
  293. *
  294. * @param {Element} otherElement
  295. * @returns {Boolean}
  296. */
  297. isSimilar( otherElement ) {
  298. if ( !( otherElement instanceof Element ) ) {
  299. return false;
  300. }
  301. // If exactly the same Element is provided - return true immediately.
  302. if ( this === otherElement ) {
  303. return true;
  304. }
  305. // Check element name.
  306. if ( this.name != otherElement.name ) {
  307. return false;
  308. }
  309. // Check number of attributes, classes and styles.
  310. if ( this._attrs.size !== otherElement._attrs.size || this._classes.size !== otherElement._classes.size ||
  311. this._styles.size !== otherElement._styles.size ) {
  312. return false;
  313. }
  314. // Check if attributes are the same.
  315. for ( let [ key, value ] of this._attrs ) {
  316. if ( !otherElement._attrs.has( key ) || otherElement._attrs.get( key ) !== value ) {
  317. return false;
  318. }
  319. }
  320. // Check if classes are the same.
  321. for ( let className of this._classes ) {
  322. if ( !otherElement._classes.has( className ) ) {
  323. return false;
  324. }
  325. }
  326. // Check if styles are the same.
  327. for ( let [ property, value ] of this._styles ) {
  328. if ( !otherElement._styles.has( property ) || otherElement._styles.get( property ) !== value ) {
  329. return false;
  330. }
  331. }
  332. return true;
  333. }
  334. /**
  335. * Adds specified class.
  336. *
  337. * element.addClass( 'foo' ); // Adds 'foo' class.
  338. * element.addClass( 'foo', 'bar' ); // Adds 'foo' and 'bar' classes.
  339. *
  340. * @param {...String} className
  341. * @fires engine.treeView.Node#change
  342. */
  343. addClass( ...className ) {
  344. this._fireChange( 'ATTRIBUTES', this );
  345. className.forEach( name => this._classes.add( name ) );
  346. }
  347. /**
  348. * Removes specified class.
  349. *
  350. * element.removeClass( 'foo' ); // Removes 'foo' class.
  351. * element.removeClass( 'foo', 'bar' ); // Removes both 'foo' and 'bar' classes.
  352. *
  353. * @param {...String} className
  354. * @fires engine.treeView.Node#change
  355. */
  356. removeClass( ...className ) {
  357. this._fireChange( 'ATTRIBUTES', this );
  358. className.forEach( name => this._classes.delete( name ) );
  359. }
  360. /**
  361. * Returns true if class is present.
  362. * If more then one class is provided - returns true only when all classes are present.
  363. *
  364. * element.hasClass( 'foo' ); // Returns true if 'foo' class is present.
  365. * element.hasClass( 'foo', 'bar' ); // Returns true if 'foo' and 'bar' classes are both present.
  366. *
  367. * @param {...String} className
  368. */
  369. hasClass( ...className ) {
  370. for ( let name of className ) {
  371. if ( !this._classes.has( name ) ) {
  372. return false;
  373. }
  374. }
  375. return true;
  376. }
  377. /**
  378. * Adds style to the element.
  379. *
  380. * element.setStyle( 'color', 'red' );
  381. * element.setStyle( {
  382. * color: 'red',
  383. * position: 'fixed'
  384. * } );
  385. *
  386. * @param {String|Object} property Property name or object with key - value pairs.
  387. * @param {String} [value] Value to set. This parameter is ignored if object is provided as the first parameter.
  388. * @fires engine.treeView.Node#change
  389. */
  390. setStyle( property, value ) {
  391. this._fireChange( 'ATTRIBUTES', this );
  392. if ( isPlainObject( property ) ) {
  393. const keys = Object.keys( property );
  394. for ( let key of keys ) {
  395. this._styles.set( key, property[ key ] );
  396. }
  397. } else {
  398. this._styles.set( property, value );
  399. }
  400. }
  401. /**
  402. * Returns style value for given property.
  403. * Undefined is returned if style does not exist.
  404. *
  405. * @param {String} property
  406. * @returns {String|undefined}
  407. */
  408. getStyle( property ) {
  409. return this._styles.get( property );
  410. }
  411. /**
  412. * Returns true if style keys are present.
  413. * If more then one style property is provided - returns true only when all properties are present.
  414. *
  415. * element.hasStyle( 'color' ); // Returns true if 'border-top' style is present.
  416. * element.hasStyle( 'color', 'border-top' ); // Returns true if 'color' and 'border-top' styles are both present.
  417. *
  418. * @param {...String} property
  419. */
  420. hasStyle( ...property ) {
  421. for ( let name of property ) {
  422. if ( !this._styles.has( name ) ) {
  423. return false;
  424. }
  425. }
  426. return true;
  427. }
  428. /**
  429. * Removes specified style.
  430. *
  431. * element.removeStyle( 'color' ); // Removes 'color' style.
  432. * element.removeStyle( 'color', 'border-top' ); // Removes both 'color' and 'border-top' styles.
  433. *
  434. * @param {...String} property
  435. * @fires engine.treeView.Node#change
  436. */
  437. removeStyle( ...property ) {
  438. this._fireChange( 'ATTRIBUTES', this );
  439. property.forEach( name => this._styles.delete( name ) );
  440. }
  441. }
  442. // Parses inline styles and puts property - value pairs into styles map.
  443. // Styles map is cleared before insertion.
  444. //
  445. // @param {Map.<String, String>} stylesMap Map to insert parsed properties and values.
  446. // @param {String} stylesString Styles to parse.
  447. function parseInlineStyles( stylesMap, stylesString ) {
  448. const regex = /\s*([^:;\s]+)\s*:\s*([^;]+)\s*(?=;|$)/g;
  449. let matchStyle;
  450. stylesMap.clear();
  451. while ( ( matchStyle = regex.exec( stylesString ) ) !== null ) {
  452. stylesMap.set( matchStyle[ 1 ], matchStyle[ 2 ].trim() );
  453. }
  454. }
  455. // Parses class attribute and puts all classes into classes set.
  456. // Classes set s cleared before insertion.
  457. //
  458. // @param {Set.<String>} classesSet Set to insert parsed classes.
  459. // @param {String} classesString String with classes to parse.
  460. function parseClasses( classesSet, classesString ) {
  461. const classArray = classesString.split( /\s+/ );
  462. classesSet.clear();
  463. classArray.forEach( name => classesSet.add( name ) );
  464. }