element.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. /**
  2. * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. import Node from './node.js';
  6. import Text from './text.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. * Number of element's children.
  96. *
  97. * @readonly
  98. * @type {Number}
  99. */
  100. get childCount() {
  101. return this._children.length;
  102. }
  103. /**
  104. * Is `true` if there are no nodes inside this element, `false` otherwise.
  105. *
  106. * @readonly
  107. * @type {Boolean}
  108. */
  109. get isEmpty() {
  110. return this._children.length === 0;
  111. }
  112. /**
  113. * Clones provided element.
  114. *
  115. * @param {Boolean} deep If set to `true` clones element and all its children recursively. When set to `false`,
  116. * element will be cloned without any children.
  117. * @returns {engine.view.Element} Clone of this element.
  118. */
  119. clone( deep ) {
  120. const childrenClone = [];
  121. if ( deep ) {
  122. for ( let child of this.getChildren() ) {
  123. childrenClone.push( child.clone( deep ) );
  124. }
  125. }
  126. // ContainerElement and AttributeElement should be also cloned properly.
  127. const cloned = new this.constructor( this.name, this._attrs, childrenClone );
  128. // Classes and styles are cloned separately - this solution is faster than adding them back to attributes and
  129. // parse once again in constructor.
  130. cloned._classes = new Set( this._classes );
  131. cloned._styles = new Map( this._styles );
  132. return cloned;
  133. }
  134. /**
  135. * {@link engine.view.Element#insert Insert} a child node or a list of child nodes at the end of this node and sets
  136. * the parent of these nodes to this element.
  137. *
  138. * @fires engine.view.Node#change
  139. * @param {engine.view.Node|Iterable.<engine.view.Node>} nodes Node or the list of nodes to be inserted.
  140. * @returns {Number} Number of appended nodes.
  141. */
  142. appendChildren( nodes ) {
  143. return this.insertChildren( this.childCount, nodes );
  144. }
  145. /**
  146. * Gets child at the given index.
  147. *
  148. * @param {Number} index Index of child.
  149. * @returns {engine.view.Node} Child node.
  150. */
  151. getChild( index ) {
  152. return this._children[ index ];
  153. }
  154. /**
  155. * Gets index of the given child node. Returns `-1` if child node is not found.
  156. *
  157. * @param {engine.view.Node} node Child node.
  158. * @returns {Number} Index of the child node.
  159. */
  160. getChildIndex( node ) {
  161. return this._children.indexOf( node );
  162. }
  163. /**
  164. * Gets child nodes iterator.
  165. *
  166. * @returns {Iterable.<engine.view.Node>} Child nodes iterator.
  167. */
  168. getChildren() {
  169. return this._children[ Symbol.iterator ]();
  170. }
  171. /**
  172. * Returns an iterator that contains the keys for attributes. Order of inserting attributes is not preserved.
  173. *
  174. * @returns {Iterator.<String>} Keys for attributes.
  175. */
  176. *getAttributeKeys() {
  177. if ( this._classes.size > 0 ) {
  178. yield 'class';
  179. }
  180. if ( this._styles.size > 0 ) {
  181. yield 'style';
  182. }
  183. // This is not an optimal solution because of https://github.com/ckeditor/ckeditor5-engine/issues/454.
  184. // It can be simplified to `yield* this._attrs.keys();`.
  185. for ( let key of this._attrs.keys() ) {
  186. yield key;
  187. }
  188. }
  189. /**
  190. * Returns iterator that iterates over this element's attributes.
  191. *
  192. * Attributes are returned as arrays containing two items. First one is attribute key and second is attribute value.
  193. * This format is accepted by native `Map` object and also can be passed in `Node` constructor.
  194. *
  195. * @returns {Iterable.<*>}
  196. */
  197. *getAttributes() {
  198. yield* this._attrs.entries();
  199. if ( this._classes.size > 0 ) {
  200. yield [ 'class', this.getAttribute( 'class' ) ];
  201. }
  202. if ( this._styles.size > 0 ) {
  203. yield [ 'style', this.getAttribute( 'style' ) ];
  204. }
  205. }
  206. /**
  207. * Gets attribute by key. If attribute is not present - returns undefined.
  208. *
  209. * @param {String} key Attribute key.
  210. * @returns {String|undefined} Attribute value.
  211. */
  212. getAttribute( key ) {
  213. if ( key == 'class' ) {
  214. if ( this._classes.size > 0 ) {
  215. return [ ...this._classes ].join( ' ' );
  216. }
  217. return undefined;
  218. }
  219. if ( key == 'style' ) {
  220. if ( this._styles.size > 0 ) {
  221. let styleString = '';
  222. for ( let [ property, value ] of this._styles ) {
  223. styleString += `${ property }:${ value };`;
  224. }
  225. return styleString;
  226. }
  227. return undefined;
  228. }
  229. return this._attrs.get( key );
  230. }
  231. /**
  232. * Returns a boolean indicating whether an attribute with the specified key exists in the element.
  233. *
  234. * @param {String} key Attribute key.
  235. * @returns {Boolean} `true` if attribute with the specified key exists in the element, false otherwise.
  236. */
  237. hasAttribute( key ) {
  238. if ( key == 'class' ) {
  239. return this._classes.size > 0;
  240. }
  241. if ( key == 'style' ) {
  242. return this._styles.size > 0;
  243. }
  244. return this._attrs.has( key );
  245. }
  246. /**
  247. * Adds or overwrite attribute with a specified key and value.
  248. *
  249. * @param {String} key Attribute key.
  250. * @param {String} value Attribute value.
  251. * @fires engine.view.Node#change
  252. */
  253. setAttribute( key, value ) {
  254. this._fireChange( 'attributes', this );
  255. if ( key == 'class' ) {
  256. parseClasses( this._classes, value );
  257. } else if ( key == 'style' ) {
  258. parseInlineStyles( this._styles, value );
  259. } else {
  260. this._attrs.set( key, value );
  261. }
  262. }
  263. /**
  264. * Inserts a child node or a list of child nodes on the given index and sets the parent of these nodes to
  265. * this element.
  266. *
  267. * @param {Number} index Position where nodes should be inserted.
  268. * @param {engine.view.Node|Iterable.<engine.view.Node>} nodes Node or the list of nodes to be inserted.
  269. * @fires engine.view.Node#change
  270. * @returns {Number} Number of inserted nodes.
  271. */
  272. insertChildren( index, nodes ) {
  273. this._fireChange( 'children', this );
  274. let count = 0;
  275. nodes = normalize( nodes );
  276. for ( let node of nodes ) {
  277. node.parent = this;
  278. this._children.splice( index, 0, node );
  279. index++;
  280. count++;
  281. }
  282. return count;
  283. }
  284. /**
  285. * Removes attribute from the element.
  286. *
  287. * @param {String} key Attribute key.
  288. * @returns {Boolean} Returns true if an attribute existed and has been removed.
  289. * @fires engine.view.Node#change
  290. */
  291. removeAttribute( key ) {
  292. this._fireChange( 'attributes', this );
  293. // Remove class attribute.
  294. if ( key == 'class' ) {
  295. if ( this._classes.size > 0 ) {
  296. this._classes.clear();
  297. return true;
  298. }
  299. return false;
  300. }
  301. // Remove style attribute.
  302. if ( key == 'style' ) {
  303. if ( this._styles.size > 0 ) {
  304. this._styles.clear();
  305. return true;
  306. }
  307. return false;
  308. }
  309. // Remove other attributes.
  310. return this._attrs.delete( key );
  311. }
  312. /**
  313. * Removes number of child nodes starting at the given index and set the parent of these nodes to `null`.
  314. *
  315. * @param {Number} index Number of the first node to remove.
  316. * @param {Number} [howMany=1] Number of nodes to remove.
  317. * @returns {Array.<engine.view.Node>} The array of removed nodes.
  318. * @fires engine.view.Node#change
  319. */
  320. removeChildren( index, howMany = 1 ) {
  321. this._fireChange( 'children', this );
  322. for ( let i = index; i < index + howMany; i++ ) {
  323. this._children[ i ].parent = null;
  324. }
  325. return this._children.splice( index, howMany );
  326. }
  327. /**
  328. * Checks if this element is similar to other element.
  329. * Both elements should have the same name and attributes to be considered as similar. Two similar elements
  330. * can contain different set of children nodes.
  331. *
  332. * @param {engine.view.Element} otherElement
  333. * @returns {Boolean}
  334. */
  335. isSimilar( otherElement ) {
  336. if ( !( otherElement instanceof Element ) ) {
  337. return false;
  338. }
  339. // If exactly the same Element is provided - return true immediately.
  340. if ( this === otherElement ) {
  341. return true;
  342. }
  343. // Check element name.
  344. if ( this.name != otherElement.name ) {
  345. return false;
  346. }
  347. // Check number of attributes, classes and styles.
  348. if ( this._attrs.size !== otherElement._attrs.size || this._classes.size !== otherElement._classes.size ||
  349. this._styles.size !== otherElement._styles.size ) {
  350. return false;
  351. }
  352. // Check if attributes are the same.
  353. for ( let [ key, value ] of this._attrs ) {
  354. if ( !otherElement._attrs.has( key ) || otherElement._attrs.get( key ) !== value ) {
  355. return false;
  356. }
  357. }
  358. // Check if classes are the same.
  359. for ( let className of this._classes ) {
  360. if ( !otherElement._classes.has( className ) ) {
  361. return false;
  362. }
  363. }
  364. // Check if styles are the same.
  365. for ( let [ property, value ] of this._styles ) {
  366. if ( !otherElement._styles.has( property ) || otherElement._styles.get( property ) !== value ) {
  367. return false;
  368. }
  369. }
  370. return true;
  371. }
  372. /**
  373. * Adds specified class.
  374. *
  375. * element.addClass( 'foo' ); // Adds 'foo' class.
  376. * element.addClass( 'foo', 'bar' ); // Adds 'foo' and 'bar' classes.
  377. *
  378. * @param {...String} className
  379. * @fires engine.view.Node#change
  380. */
  381. addClass( ...className ) {
  382. this._fireChange( 'attributes', this );
  383. className.forEach( name => this._classes.add( name ) );
  384. }
  385. /**
  386. * Removes specified class.
  387. *
  388. * element.removeClass( 'foo' ); // Removes 'foo' class.
  389. * element.removeClass( 'foo', 'bar' ); // Removes both 'foo' and 'bar' classes.
  390. *
  391. * @param {...String} className
  392. * @fires engine.view.Node#change
  393. */
  394. removeClass( ...className ) {
  395. this._fireChange( 'attributes', this );
  396. className.forEach( name => this._classes.delete( name ) );
  397. }
  398. /**
  399. * Returns true if class is present.
  400. * If more then one class is provided - returns true only when all classes are present.
  401. *
  402. * element.hasClass( 'foo' ); // Returns true if 'foo' class is present.
  403. * element.hasClass( 'foo', 'bar' ); // Returns true if 'foo' and 'bar' classes are both present.
  404. *
  405. * @param {...String} className
  406. */
  407. hasClass( ...className ) {
  408. for ( let name of className ) {
  409. if ( !this._classes.has( name ) ) {
  410. return false;
  411. }
  412. }
  413. return true;
  414. }
  415. /**
  416. * Returns iterator that contains all class names.
  417. *
  418. * @returns {Iterator.<String>}
  419. */
  420. getClassNames() {
  421. return this._classes.keys();
  422. }
  423. /**
  424. * Adds style to the element.
  425. *
  426. * element.setStyle( 'color', 'red' );
  427. * element.setStyle( {
  428. * color: 'red',
  429. * position: 'fixed'
  430. * } );
  431. *
  432. * @param {String|Object} property Property name or object with key - value pairs.
  433. * @param {String} [value] Value to set. This parameter is ignored if object is provided as the first parameter.
  434. * @fires engine.view.Node#change
  435. */
  436. setStyle( property, value ) {
  437. this._fireChange( 'attributes', this );
  438. if ( isPlainObject( property ) ) {
  439. const keys = Object.keys( property );
  440. for ( let key of keys ) {
  441. this._styles.set( key, property[ key ] );
  442. }
  443. } else {
  444. this._styles.set( property, value );
  445. }
  446. }
  447. /**
  448. * Returns style value for given property.
  449. * Undefined is returned if style does not exist.
  450. *
  451. * @param {String} property
  452. * @returns {String|undefined}
  453. */
  454. getStyle( property ) {
  455. return this._styles.get( property );
  456. }
  457. /**
  458. * Returns iterator that contains all style names.
  459. *
  460. * @returns {Iterator.<String>}
  461. */
  462. getStyleNames() {
  463. return this._styles.keys();
  464. }
  465. /**
  466. * Returns true if style keys are present.
  467. * If more then one style property is provided - returns true only when all properties are present.
  468. *
  469. * element.hasStyle( 'color' ); // Returns true if 'border-top' style is present.
  470. * element.hasStyle( 'color', 'border-top' ); // Returns true if 'color' and 'border-top' styles are both present.
  471. *
  472. * @param {...String} property
  473. */
  474. hasStyle( ...property ) {
  475. for ( let name of property ) {
  476. if ( !this._styles.has( name ) ) {
  477. return false;
  478. }
  479. }
  480. return true;
  481. }
  482. /**
  483. * Removes specified style.
  484. *
  485. * element.removeStyle( 'color' ); // Removes 'color' style.
  486. * element.removeStyle( 'color', 'border-top' ); // Removes both 'color' and 'border-top' styles.
  487. *
  488. * @param {...String} property
  489. * @fires engine.view.Node#change
  490. */
  491. removeStyle( ...property ) {
  492. this._fireChange( 'attributes', this );
  493. property.forEach( name => this._styles.delete( name ) );
  494. }
  495. }
  496. // Parses inline styles and puts property - value pairs into styles map.
  497. // Styles map is cleared before insertion.
  498. //
  499. // @param {Map.<String, String>} stylesMap Map to insert parsed properties and values.
  500. // @param {String} stylesString Styles to parse.
  501. function parseInlineStyles( stylesMap, stylesString ) {
  502. const regex = /\s*([^:;\s]+)\s*:\s*([^;]+)\s*(?=;|$)/g;
  503. let matchStyle;
  504. stylesMap.clear();
  505. while ( ( matchStyle = regex.exec( stylesString ) ) !== null ) {
  506. stylesMap.set( matchStyle[ 1 ], matchStyle[ 2 ].trim() );
  507. }
  508. }
  509. // Parses class attribute and puts all classes into classes set.
  510. // Classes set s cleared before insertion.
  511. //
  512. // @param {Set.<String>} classesSet Set to insert parsed classes.
  513. // @param {String} classesString String with classes to parse.
  514. function parseClasses( classesSet, classesString ) {
  515. const classArray = classesString.split( /\s+/ );
  516. classesSet.clear();
  517. classArray.forEach( name => classesSet.add( name ) );
  518. }
  519. // Converts strings to Text and non-iterables to arrays.
  520. //
  521. // @param {String|engine.view.Node|Iterable.<String|engine.view.Node>}
  522. // @return {Iterable.<engine.view.Node>}
  523. function normalize( nodes ) {
  524. // Separate condition because string is iterable.
  525. if ( typeof nodes == 'string' ) {
  526. return [ new Text( nodes ) ];
  527. }
  528. if ( !isIterable( nodes ) ) {
  529. nodes = [ nodes ];
  530. }
  531. // Array.from to enable .map() on non-arrays.
  532. return Array.from( nodes ).map( ( node ) => typeof node == 'string' ? new Text( node ) : node );
  533. }