element.js 17 KB

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