8
0

element.js 16 KB

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