element.js 15 KB

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