element.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871
  1. /**
  2. * @license Copyright (c) 2003-2017, 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';
  9. import Text from './text';
  10. import objectToMap from '@ckeditor/ckeditor5-utils/src/objecttomap';
  11. import isIterable from '@ckeditor/ckeditor5-utils/src/isiterable';
  12. import isPlainObject from '@ckeditor/ckeditor5-utils/src/lib/lodash/isPlainObject';
  13. import Matcher from './matcher';
  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. * Map of custom properties.
  99. * Custom properties can be added to element instance, will be cloned but not rendered into DOM.
  100. *
  101. * @protected
  102. * @memeber {Map}
  103. */
  104. this._customProperties = new Map();
  105. }
  106. /**
  107. * Number of element's children.
  108. *
  109. * @readonly
  110. * @type {Number}
  111. */
  112. get childCount() {
  113. return this._children.length;
  114. }
  115. /**
  116. * Is `true` if there are no nodes inside this element, `false` otherwise.
  117. *
  118. * @readonly
  119. * @type {Boolean}
  120. */
  121. get isEmpty() {
  122. return this._children.length === 0;
  123. }
  124. /**
  125. * Checks whether given view tree object is of given type.
  126. *
  127. * Read more in {@link module:engine/view/node~Node#is}.
  128. *
  129. * @param {String} type
  130. * @param {String} [name] Element name.
  131. * @returns {Boolean}
  132. */
  133. is( type, name = null ) {
  134. if ( !name ) {
  135. return type == 'element' || type == this.name;
  136. } else {
  137. return type == 'element' && name == this.name;
  138. }
  139. }
  140. /**
  141. * Clones provided element.
  142. *
  143. * @param {Boolean} [deep=false] If set to `true` clones element and all its children recursively. When set to `false`,
  144. * element will be cloned without any children.
  145. * @returns {module:engine/view/element~Element} Clone of this element.
  146. */
  147. clone( deep = false ) {
  148. const childrenClone = [];
  149. if ( deep ) {
  150. for ( const child of this.getChildren() ) {
  151. childrenClone.push( child.clone( deep ) );
  152. }
  153. }
  154. // ContainerElement and AttributeElement should be also cloned properly.
  155. const cloned = new this.constructor( this.name, this._attrs, childrenClone );
  156. // Classes and styles are cloned separately - this solution is faster than adding them back to attributes and
  157. // parse once again in constructor.
  158. cloned._classes = new Set( this._classes );
  159. cloned._styles = new Map( this._styles );
  160. // Clone custom properties.
  161. cloned._customProperties = new Map( this._customProperties );
  162. // Clone filler offset method.
  163. // We can't define this method in a prototype because it's behavior which
  164. // is changed by e.g. toWidget() function from ckeditor5-widget. Perhaps this should be one of custom props.
  165. cloned.getFillerOffset = this.getFillerOffset;
  166. return cloned;
  167. }
  168. /**
  169. * {@link module:engine/view/element~Element#insertChildren Insert} a child node or a list of child nodes at the end of this node
  170. * and sets the parent of these nodes to this element.
  171. *
  172. * @fires module:engine/view/node~Node#change
  173. * @param {module:engine/view/node~Node|Iterable.<module:engine/view/node~Node>} nodes Node or the list of nodes to be inserted.
  174. * @returns {Number} Number of appended nodes.
  175. */
  176. appendChildren( nodes ) {
  177. return this.insertChildren( this.childCount, nodes );
  178. }
  179. /**
  180. * Gets child at the given index.
  181. *
  182. * @param {Number} index Index of child.
  183. * @returns {module:engine/view/node~Node} Child node.
  184. */
  185. getChild( index ) {
  186. return this._children[ index ];
  187. }
  188. /**
  189. * Gets index of the given child node. Returns `-1` if child node is not found.
  190. *
  191. * @param {module:engine/view/node~Node} node Child node.
  192. * @returns {Number} Index of the child node.
  193. */
  194. getChildIndex( node ) {
  195. return this._children.indexOf( node );
  196. }
  197. /**
  198. * Gets child nodes iterator.
  199. *
  200. * @returns {Iterable.<module:engine/view/node~Node>} Child nodes iterator.
  201. */
  202. getChildren() {
  203. return this._children[ Symbol.iterator ]();
  204. }
  205. /**
  206. * Returns an iterator that contains the keys for attributes. Order of inserting attributes is not preserved.
  207. *
  208. * @returns {Iterator.<String>} Keys for attributes.
  209. */
  210. * getAttributeKeys() {
  211. if ( this._classes.size > 0 ) {
  212. yield 'class';
  213. }
  214. if ( this._styles.size > 0 ) {
  215. yield 'style';
  216. }
  217. // This is not an optimal solution because of https://github.com/ckeditor/ckeditor5-engine/issues/454.
  218. // It can be simplified to `yield* this._attrs.keys();`.
  219. for ( const key of this._attrs.keys() ) {
  220. yield key;
  221. }
  222. }
  223. /**
  224. * Returns iterator that iterates over this element's attributes.
  225. *
  226. * Attributes are returned as arrays containing two items. First one is attribute key and second is attribute value.
  227. * This format is accepted by native `Map` object and also can be passed in `Node` constructor.
  228. *
  229. * @returns {Iterable.<*>}
  230. */
  231. * getAttributes() {
  232. yield* this._attrs.entries();
  233. if ( this._classes.size > 0 ) {
  234. yield [ 'class', this.getAttribute( 'class' ) ];
  235. }
  236. if ( this._styles.size > 0 ) {
  237. yield [ 'style', this.getAttribute( 'style' ) ];
  238. }
  239. }
  240. /**
  241. * Gets attribute by key. If attribute is not present - returns undefined.
  242. *
  243. * @param {String} key Attribute key.
  244. * @returns {String|undefined} Attribute value.
  245. */
  246. getAttribute( key ) {
  247. if ( key == 'class' ) {
  248. if ( this._classes.size > 0 ) {
  249. return [ ...this._classes ].join( ' ' );
  250. }
  251. return undefined;
  252. }
  253. if ( key == 'style' ) {
  254. if ( this._styles.size > 0 ) {
  255. let styleString = '';
  256. for ( const [ property, value ] of this._styles ) {
  257. styleString += `${ property }:${ value };`;
  258. }
  259. return styleString;
  260. }
  261. return undefined;
  262. }
  263. return this._attrs.get( key );
  264. }
  265. /**
  266. * Returns a boolean indicating whether an attribute with the specified key exists in the element.
  267. *
  268. * @param {String} key Attribute key.
  269. * @returns {Boolean} `true` if attribute with the specified key exists in the element, false otherwise.
  270. */
  271. hasAttribute( key ) {
  272. if ( key == 'class' ) {
  273. return this._classes.size > 0;
  274. }
  275. if ( key == 'style' ) {
  276. return this._styles.size > 0;
  277. }
  278. return this._attrs.has( key );
  279. }
  280. /**
  281. * Adds or overwrite attribute with a specified key and value.
  282. *
  283. * @param {String} key Attribute key.
  284. * @param {String} value Attribute value.
  285. * @fires module:engine/view/node~Node#change
  286. */
  287. setAttribute( key, value ) {
  288. this._fireChange( 'attributes', this );
  289. if ( key == 'class' ) {
  290. parseClasses( this._classes, value );
  291. } else if ( key == 'style' ) {
  292. parseInlineStyles( this._styles, value );
  293. } else {
  294. this._attrs.set( key, value );
  295. }
  296. }
  297. /**
  298. * Inserts a child node or a list of child nodes on the given index and sets the parent of these nodes to
  299. * this element.
  300. *
  301. * @param {Number} index Position where nodes should be inserted.
  302. * @param {module:engine/view/node~Node|Iterable.<module:engine/view/node~Node>} nodes Node or the list of nodes to be inserted.
  303. * @fires module:engine/view/node~Node#change
  304. * @returns {Number} Number of inserted nodes.
  305. */
  306. insertChildren( index, nodes ) {
  307. this._fireChange( 'children', this );
  308. let count = 0;
  309. nodes = normalize( nodes );
  310. for ( const node of nodes ) {
  311. // If node that is being added to this element is already inside another element, first remove it from the old parent.
  312. if ( node.parent !== null ) {
  313. node.remove();
  314. }
  315. node.parent = this;
  316. this._children.splice( index, 0, node );
  317. index++;
  318. count++;
  319. }
  320. return count;
  321. }
  322. /**
  323. * Removes attribute from the element.
  324. *
  325. * @param {String} key Attribute key.
  326. * @returns {Boolean} Returns true if an attribute existed and has been removed.
  327. * @fires module:engine/view/node~Node#change
  328. */
  329. removeAttribute( key ) {
  330. this._fireChange( 'attributes', this );
  331. // Remove class attribute.
  332. if ( key == 'class' ) {
  333. if ( this._classes.size > 0 ) {
  334. this._classes.clear();
  335. return true;
  336. }
  337. return false;
  338. }
  339. // Remove style attribute.
  340. if ( key == 'style' ) {
  341. if ( this._styles.size > 0 ) {
  342. this._styles.clear();
  343. return true;
  344. }
  345. return false;
  346. }
  347. // Remove other attributes.
  348. return this._attrs.delete( key );
  349. }
  350. /**
  351. * Removes number of child nodes starting at the given index and set the parent of these nodes to `null`.
  352. *
  353. * @param {Number} index Number of the first node to remove.
  354. * @param {Number} [howMany=1] Number of nodes to remove.
  355. * @returns {Array.<module:engine/view/node~Node>} The array of removed nodes.
  356. * @fires module:engine/view/node~Node#change
  357. */
  358. removeChildren( index, howMany = 1 ) {
  359. this._fireChange( 'children', this );
  360. for ( let i = index; i < index + howMany; i++ ) {
  361. this._children[ i ].parent = null;
  362. }
  363. return this._children.splice( index, howMany );
  364. }
  365. /**
  366. * Checks if this element is similar to other element.
  367. * Both elements should have the same name and attributes to be considered as similar. Two similar elements
  368. * can contain different set of children nodes.
  369. *
  370. * @param {module:engine/view/element~Element} otherElement
  371. * @returns {Boolean}
  372. */
  373. isSimilar( otherElement ) {
  374. if ( !( otherElement instanceof Element ) ) {
  375. return false;
  376. }
  377. // If exactly the same Element is provided - return true immediately.
  378. if ( this === otherElement ) {
  379. return true;
  380. }
  381. // Check element name.
  382. if ( this.name != otherElement.name ) {
  383. return false;
  384. }
  385. // Check number of attributes, classes and styles.
  386. if ( this._attrs.size !== otherElement._attrs.size || this._classes.size !== otherElement._classes.size ||
  387. this._styles.size !== otherElement._styles.size ) {
  388. return false;
  389. }
  390. // Check if attributes are the same.
  391. for ( const [ key, value ] of this._attrs ) {
  392. if ( !otherElement._attrs.has( key ) || otherElement._attrs.get( key ) !== value ) {
  393. return false;
  394. }
  395. }
  396. // Check if classes are the same.
  397. for ( const className of this._classes ) {
  398. if ( !otherElement._classes.has( className ) ) {
  399. return false;
  400. }
  401. }
  402. // Check if styles are the same.
  403. for ( const [ property, value ] of this._styles ) {
  404. if ( !otherElement._styles.has( property ) || otherElement._styles.get( property ) !== value ) {
  405. return false;
  406. }
  407. }
  408. return true;
  409. }
  410. /**
  411. * Adds specified class.
  412. *
  413. * element.addClass( 'foo' ); // Adds 'foo' class.
  414. * element.addClass( 'foo', 'bar' ); // Adds 'foo' and 'bar' classes.
  415. *
  416. * @param {...String} className
  417. * @fires module:engine/view/node~Node#change
  418. */
  419. addClass( ...className ) {
  420. this._fireChange( 'attributes', this );
  421. className.forEach( name => this._classes.add( name ) );
  422. }
  423. /**
  424. * Removes specified class.
  425. *
  426. * element.removeClass( 'foo' ); // Removes 'foo' class.
  427. * element.removeClass( 'foo', 'bar' ); // Removes both 'foo' and 'bar' classes.
  428. *
  429. * @param {...String} className
  430. * @fires module:engine/view/node~Node#change
  431. */
  432. removeClass( ...className ) {
  433. this._fireChange( 'attributes', this );
  434. className.forEach( name => this._classes.delete( name ) );
  435. }
  436. /**
  437. * Returns true if class is present.
  438. * If more then one class is provided - returns true only when all classes are present.
  439. *
  440. * element.hasClass( 'foo' ); // Returns true if 'foo' class is present.
  441. * element.hasClass( 'foo', 'bar' ); // Returns true if 'foo' and 'bar' classes are both present.
  442. *
  443. * @param {...String} className
  444. */
  445. hasClass( ...className ) {
  446. for ( const name of className ) {
  447. if ( !this._classes.has( name ) ) {
  448. return false;
  449. }
  450. }
  451. return true;
  452. }
  453. /**
  454. * Returns iterator that contains all class names.
  455. *
  456. * @returns {Iterator.<String>}
  457. */
  458. getClassNames() {
  459. return this._classes.keys();
  460. }
  461. /**
  462. * Adds style to the element.
  463. *
  464. * element.setStyle( 'color', 'red' );
  465. * element.setStyle( {
  466. * color: 'red',
  467. * position: 'fixed'
  468. * } );
  469. *
  470. * @param {String|Object} property Property name or object with key - value pairs.
  471. * @param {String} [value] Value to set. This parameter is ignored if object is provided as the first parameter.
  472. * @fires module:engine/view/node~Node#change
  473. */
  474. setStyle( property, value ) {
  475. this._fireChange( 'attributes', this );
  476. if ( isPlainObject( property ) ) {
  477. const keys = Object.keys( property );
  478. for ( const key of keys ) {
  479. this._styles.set( key, property[ key ] );
  480. }
  481. } else {
  482. this._styles.set( property, value );
  483. }
  484. }
  485. /**
  486. * Returns style value for given property.
  487. * Undefined is returned if style does not exist.
  488. *
  489. * @param {String} property
  490. * @returns {String|undefined}
  491. */
  492. getStyle( property ) {
  493. return this._styles.get( property );
  494. }
  495. /**
  496. * Returns iterator that contains all style names.
  497. *
  498. * @returns {Iterator.<String>}
  499. */
  500. getStyleNames() {
  501. return this._styles.keys();
  502. }
  503. /**
  504. * Returns true if style keys are present.
  505. * If more then one style property is provided - returns true only when all properties are present.
  506. *
  507. * element.hasStyle( 'color' ); // Returns true if 'border-top' style is present.
  508. * element.hasStyle( 'color', 'border-top' ); // Returns true if 'color' and 'border-top' styles are both present.
  509. *
  510. * @param {...String} property
  511. */
  512. hasStyle( ...property ) {
  513. for ( const name of property ) {
  514. if ( !this._styles.has( name ) ) {
  515. return false;
  516. }
  517. }
  518. return true;
  519. }
  520. /**
  521. * Removes specified style.
  522. *
  523. * element.removeStyle( 'color' ); // Removes 'color' style.
  524. * element.removeStyle( 'color', 'border-top' ); // Removes both 'color' and 'border-top' styles.
  525. *
  526. * @param {...String} property
  527. * @fires module:engine/view/node~Node#change
  528. */
  529. removeStyle( ...property ) {
  530. this._fireChange( 'attributes', this );
  531. property.forEach( name => this._styles.delete( name ) );
  532. }
  533. /**
  534. * Returns ancestor element that match specified pattern.
  535. * Provided patterns should be compatible with {@link module:engine/view/matcher~Matcher Matcher} as it is used internally.
  536. *
  537. * @see module:engine/view/matcher~Matcher
  538. * @param {Object|String|RegExp|Function} patterns Patterns used to match correct ancestor.
  539. * See {@link module:engine/view/matcher~Matcher}.
  540. * @returns {module:engine/view/element~Element|null} Found element or `null` if no matching ancestor was found.
  541. */
  542. findAncestor( ...patterns ) {
  543. const matcher = new Matcher( ...patterns );
  544. let parent = this.parent;
  545. while ( parent ) {
  546. if ( matcher.match( parent ) ) {
  547. return parent;
  548. }
  549. parent = parent.parent;
  550. }
  551. return null;
  552. }
  553. /**
  554. * Sets a custom property. Unlike attributes, custom properties are not rendered to the DOM,
  555. * so they can be used to add special data to elements.
  556. *
  557. * @param {String|Symbol} key
  558. * @param {*} value
  559. */
  560. setCustomProperty( key, value ) {
  561. this._customProperties.set( key, value );
  562. }
  563. /**
  564. * Returns the custom property value for the given key.
  565. *
  566. * @param {String|Symbol} key
  567. * @returns {*}
  568. */
  569. getCustomProperty( key ) {
  570. return this._customProperties.get( key );
  571. }
  572. /**
  573. * Removes the custom property stored under the given key.
  574. *
  575. * @param {String|Symbol} key
  576. * @returns {Boolean} Returns true if property was removed.
  577. */
  578. removeCustomProperty( key ) {
  579. return this._customProperties.delete( key );
  580. }
  581. /**
  582. * Returns an iterator which iterates over this element's custom properties.
  583. * Iterator provides [key, value] pair for each stored property.
  584. *
  585. * @returns {Iterable.<*>}
  586. */
  587. * getCustomProperties() {
  588. yield* this._customProperties.entries();
  589. }
  590. /**
  591. * Returns identity string based on element's name, styles, classes and other attributes.
  592. * Two elements that {@link #isSimilar are similar} will have same identity string.
  593. * It has the following format:
  594. *
  595. * 'name class="class1,class2" style="style1:value1;style2:value2" attr1="val1" attr2="val2"'
  596. *
  597. * For example:
  598. *
  599. * const element = new ViewElement( 'foo' );
  600. * element.setAttribute( 'banana', '10' );
  601. * element.setAttribute( 'apple', '20' );
  602. * element.setStyle( 'color', 'red' );
  603. * element.setStyle( 'border-color', 'white' );
  604. * element.addClass( 'baz' );
  605. *
  606. * // returns 'foo class="baz" style="border-color:white;color:red" apple="20" banana="10"'
  607. * element.getIdentity();
  608. *
  609. * NOTE: Classes, styles and other attributes are sorted alphabetically.
  610. *
  611. * @returns {String}
  612. */
  613. getIdentity() {
  614. const classes = Array.from( this._classes ).sort().join( ',' );
  615. const styles = Array.from( this._styles ).map( i => `${ i[ 0 ] }:${ i[ 1 ] }` ).sort().join( ';' );
  616. const attributes = Array.from( this._attrs ).map( i => `${ i[ 0 ] }="${ i[ 1 ] }"` ).sort().join( ' ' );
  617. return this.name +
  618. ( classes == '' ? '' : ` class="${ classes }"` ) +
  619. ( styles == '' ? '' : ` style="${ styles }"` ) +
  620. ( attributes == '' ? '' : ` ${ attributes }` );
  621. }
  622. /**
  623. * Creates element instance from provided viewElementDefinition.
  624. *
  625. * @param {module:engine/view/viewelementdefinition~ViewElementDefinition} viewElementDefinition
  626. * @returns {Element}
  627. */
  628. static fromViewDefinition( viewElementDefinition ) {
  629. const attributes = {};
  630. const classes = viewElementDefinition.classes;
  631. if ( classes ) {
  632. attributes.class = Array.isArray( classes ) ? classes.join( ' ' ) : classes;
  633. }
  634. const stylesObject = viewElementDefinition.styles;
  635. if ( stylesObject ) {
  636. attributes.style = toStylesString( stylesObject );
  637. }
  638. const attributesObject = viewElementDefinition.attributes;
  639. if ( attributesObject ) {
  640. for ( const key in attributesObject ) {
  641. attributes[ key ] = attributesObject[ key ];
  642. }
  643. }
  644. return new this( viewElementDefinition.name, attributes );
  645. function toStylesString( stylesObject ) {
  646. const styles = [];
  647. for ( const key in stylesObject ) {
  648. styles.push( key + ':' + stylesObject[ key ] );
  649. }
  650. return styles.join( ';' );
  651. }
  652. }
  653. /**
  654. * Returns block {@link module:engine/view/filler filler} offset or `null` if block filler is not needed.
  655. *
  656. * @abstract
  657. * @method module:engine/view/element~Element#getFillerOffset
  658. */
  659. }
  660. // Parses inline styles and puts property - value pairs into styles map.
  661. // Styles map is cleared before insertion.
  662. //
  663. // @param {Map.<String, String>} stylesMap Map to insert parsed properties and values.
  664. // @param {String} stylesString Styles to parse.
  665. function parseInlineStyles( stylesMap, stylesString ) {
  666. // `null` if no quote was found in input string or last found quote was a closing quote. See below.
  667. let quoteType = null;
  668. let propertyNameStart = 0;
  669. let propertyValueStart = 0;
  670. let propertyName = null;
  671. stylesMap.clear();
  672. // Do not set anything if input string is empty.
  673. if ( stylesString === '' ) {
  674. return;
  675. }
  676. // Fix inline styles that do not end with `;` so they are compatible with algorithm below.
  677. if ( stylesString.charAt( stylesString.length - 1 ) != ';' ) {
  678. stylesString = stylesString + ';';
  679. }
  680. // Seek the whole string for "special characters".
  681. for ( let i = 0; i < stylesString.length; i++ ) {
  682. const char = stylesString.charAt( i );
  683. if ( quoteType === null ) {
  684. // No quote found yet or last found quote was a closing quote.
  685. switch ( char ) {
  686. case ':':
  687. // Most of time colon means that property name just ended.
  688. // Sometimes however `:` is found inside property value (for example in background image url).
  689. if ( !propertyName ) {
  690. // Treat this as end of property only if property name is not already saved.
  691. // Save property name.
  692. propertyName = stylesString.substr( propertyNameStart, i - propertyNameStart );
  693. // Save this point as the start of property value.
  694. propertyValueStart = i + 1;
  695. }
  696. break;
  697. case '"':
  698. case '\'':
  699. // Opening quote found (this is an opening quote, because `quoteType` is `null`).
  700. quoteType = char;
  701. break;
  702. // eslint-disable-next-line no-case-declarations
  703. case ';':
  704. // Property value just ended.
  705. // Use previously stored property value start to obtain property value.
  706. const propertyValue = stylesString.substr( propertyValueStart, i - propertyValueStart );
  707. if ( propertyName ) {
  708. // Save parsed part.
  709. stylesMap.set( propertyName.trim(), propertyValue.trim() );
  710. }
  711. propertyName = null;
  712. // Save this point as property name start. Property name starts immediately after previous property value ends.
  713. propertyNameStart = i + 1;
  714. break;
  715. }
  716. } else if ( char === quoteType ) {
  717. // If a quote char is found and it is a closing quote, mark this fact by `null`-ing `quoteType`.
  718. quoteType = null;
  719. }
  720. }
  721. }
  722. // Parses class attribute and puts all classes into classes set.
  723. // Classes set s cleared before insertion.
  724. //
  725. // @param {Set.<String>} classesSet Set to insert parsed classes.
  726. // @param {String} classesString String with classes to parse.
  727. function parseClasses( classesSet, classesString ) {
  728. const classArray = classesString.split( /\s+/ );
  729. classesSet.clear();
  730. classArray.forEach( name => classesSet.add( name ) );
  731. }
  732. // Converts strings to Text and non-iterables to arrays.
  733. //
  734. // @param {String|module:engine/view/node~Node|Iterable.<String|module:engine/view/node~Node>}
  735. // @return {Iterable.<module:engine/view/node~Node>}
  736. function normalize( nodes ) {
  737. // Separate condition because string is iterable.
  738. if ( typeof nodes == 'string' ) {
  739. return [ new Text( nodes ) ];
  740. }
  741. if ( !isIterable( nodes ) ) {
  742. nodes = [ nodes ];
  743. }
  744. // Array.from to enable .map() on non-arrays.
  745. return Array.from( nodes )
  746. .map( node => {
  747. return typeof node == 'string' ? new Text( node ) : node;
  748. } );
  749. }