element.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  1. /**
  2. * @license Copyright (c) 2003-2018, 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 TextProxy from './textproxy';
  11. import objectToMap from '@ckeditor/ckeditor5-utils/src/objecttomap';
  12. import isIterable from '@ckeditor/ckeditor5-utils/src/isiterable';
  13. import isPlainObject from '@ckeditor/ckeditor5-utils/src/lib/lodash/isPlainObject';
  14. import Matcher from './matcher';
  15. /**
  16. * View element.
  17. *
  18. * Editing engine does not define fixed HTML DTD. This is why the type of the {@link module:engine/view/element~Element} need to
  19. * be defined by the feature developer. Creating an element you should use {@link module:engine/view/containerelement~ContainerElement}
  20. * class, {@link module:engine/view/attributeelement~AttributeElement} class or {@link module:engine/view/emptyelement~EmptyElement} class.
  21. *
  22. * Note that for view elements which are not created from model, like elements from mutations, paste or
  23. * {@link module:engine/controller/datacontroller~DataController#set data.set} it is not possible to define the type of the element, so
  24. * these will be instances of the {@link module:engine/view/element~Element}.
  25. *
  26. * @extends module:engine/view/node~Node
  27. */
  28. export default class Element extends Node {
  29. /**
  30. * Creates a view element.
  31. *
  32. * Attributes can be passed in various formats:
  33. *
  34. * new Element( 'div', { 'class': 'editor', 'contentEditable': 'true' } ); // object
  35. * new Element( 'div', [ [ 'class', 'editor' ], [ 'contentEditable', 'true' ] ] ); // map-like iterator
  36. * new Element( 'div', mapOfAttributes ); // map
  37. *
  38. * **Note:** Constructor of this class shouldn't be used directly in the code. Use the
  39. * {@link module:engine/view/writer~Writer#createAttributeElement} for inline element,
  40. * {@link module:engine/view/writer~Writer#createContainerElement} for block element,
  41. * {@link module:engine/view/writer~Writer#createEditableElement} for editable element,
  42. * {@link module:engine/view/writer~Writer#createEmptyElement} for empty element or
  43. * {@link module:engine/view/writer~Writer#createUIElement} for UI element instead.
  44. *
  45. * @protected
  46. * @param {String} name Node name.
  47. * @param {Object|Iterable} [attrs] Collection of attributes.
  48. * @param {module:engine/view/node~Node|Iterable.<module:engine/view/node~Node>} [children]
  49. * List of nodes to be inserted into created element.
  50. */
  51. constructor( name, attrs, children ) {
  52. super();
  53. /**
  54. * Name of the element.
  55. *
  56. * @readonly
  57. * @member {String}
  58. */
  59. this.name = name;
  60. /**
  61. * Map of attributes, where attributes names are keys and attributes values are values.
  62. *
  63. * @protected
  64. * @member {Map} #_attrs
  65. */
  66. this._attrs = parseAttributes( attrs );
  67. /**
  68. * Array of child nodes.
  69. *
  70. * @protected
  71. * @member {Array.<module:engine/view/node~Node>}
  72. */
  73. this._children = [];
  74. if ( children ) {
  75. this._insertChildren( 0, children );
  76. }
  77. /**
  78. * Set of classes associated with element instance.
  79. *
  80. * @protected
  81. * @member {Set}
  82. */
  83. this._classes = new Set();
  84. if ( this._attrs.has( 'class' ) ) {
  85. // Remove class attribute and handle it by class set.
  86. const classString = this._attrs.get( 'class' );
  87. parseClasses( this._classes, classString );
  88. this._attrs.delete( 'class' );
  89. }
  90. /**
  91. * Map of styles.
  92. *
  93. * @protected
  94. * @member {Set} module:engine/view/element~Element#_styles
  95. */
  96. this._styles = new Map();
  97. if ( this._attrs.has( 'style' ) ) {
  98. // Remove style attribute and handle it by styles map.
  99. parseInlineStyles( this._styles, this._attrs.get( 'style' ) );
  100. this._attrs.delete( 'style' );
  101. }
  102. /**
  103. * Map of custom properties.
  104. * Custom properties can be added to element instance, will be cloned but not rendered into DOM.
  105. *
  106. * @protected
  107. * @memeber {Map}
  108. */
  109. this._customProperties = new Map();
  110. }
  111. /**
  112. * Number of element's children.
  113. *
  114. * @readonly
  115. * @type {Number}
  116. */
  117. get childCount() {
  118. return this._children.length;
  119. }
  120. /**
  121. * Is `true` if there are no nodes inside this element, `false` otherwise.
  122. *
  123. * @readonly
  124. * @type {Boolean}
  125. */
  126. get isEmpty() {
  127. return this._children.length === 0;
  128. }
  129. /**
  130. * Checks whether given view tree object is of given type.
  131. *
  132. * Read more in {@link module:engine/view/node~Node#is}.
  133. *
  134. * @param {String} type
  135. * @param {String} [name] Element name.
  136. * @returns {Boolean}
  137. */
  138. is( type, name = null ) {
  139. if ( !name ) {
  140. return type == 'element' || type == this.name;
  141. } else {
  142. return type == 'element' && name == this.name;
  143. }
  144. }
  145. /**
  146. * Gets child at the given index.
  147. *
  148. * @param {Number} index Index of child.
  149. * @returns {module:engine/view/node~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 {module:engine/view/node~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.<module:engine/view/node~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 {Iterable.<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 ( const 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 ( const [ 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. * Checks if this element is similar to other element.
  248. * Both elements should have the same name and attributes to be considered as similar. Two similar elements
  249. * can contain different set of children nodes.
  250. *
  251. * @param {module:engine/view/element~Element} otherElement
  252. * @returns {Boolean}
  253. */
  254. isSimilar( otherElement ) {
  255. if ( !( otherElement instanceof Element ) ) {
  256. return false;
  257. }
  258. // If exactly the same Element is provided - return true immediately.
  259. if ( this === otherElement ) {
  260. return true;
  261. }
  262. // Check element name.
  263. if ( this.name != otherElement.name ) {
  264. return false;
  265. }
  266. // Check number of attributes, classes and styles.
  267. if ( this._attrs.size !== otherElement._attrs.size || this._classes.size !== otherElement._classes.size ||
  268. this._styles.size !== otherElement._styles.size ) {
  269. return false;
  270. }
  271. // Check if attributes are the same.
  272. for ( const [ key, value ] of this._attrs ) {
  273. if ( !otherElement._attrs.has( key ) || otherElement._attrs.get( key ) !== value ) {
  274. return false;
  275. }
  276. }
  277. // Check if classes are the same.
  278. for ( const className of this._classes ) {
  279. if ( !otherElement._classes.has( className ) ) {
  280. return false;
  281. }
  282. }
  283. // Check if styles are the same.
  284. for ( const [ property, value ] of this._styles ) {
  285. if ( !otherElement._styles.has( property ) || otherElement._styles.get( property ) !== value ) {
  286. return false;
  287. }
  288. }
  289. return true;
  290. }
  291. /**
  292. * Returns true if class is present.
  293. * If more then one class is provided - returns true only when all classes are present.
  294. *
  295. * element.hasClass( 'foo' ); // Returns true if 'foo' class is present.
  296. * element.hasClass( 'foo', 'bar' ); // Returns true if 'foo' and 'bar' classes are both present.
  297. *
  298. * @param {...String} className
  299. */
  300. hasClass( ...className ) {
  301. for ( const name of className ) {
  302. if ( !this._classes.has( name ) ) {
  303. return false;
  304. }
  305. }
  306. return true;
  307. }
  308. /**
  309. * Returns iterator that contains all class names.
  310. *
  311. * @returns {Iterable.<String>}
  312. */
  313. getClassNames() {
  314. return this._classes.keys();
  315. }
  316. /**
  317. * Returns style value for given property.
  318. * Undefined is returned if style does not exist.
  319. *
  320. * @param {String} property
  321. * @returns {String|undefined}
  322. */
  323. getStyle( property ) {
  324. return this._styles.get( property );
  325. }
  326. /**
  327. * Returns iterator that contains all style names.
  328. *
  329. * @returns {Iterable.<String>}
  330. */
  331. getStyleNames() {
  332. return this._styles.keys();
  333. }
  334. /**
  335. * Returns true if style keys are present.
  336. * If more then one style property is provided - returns true only when all properties are present.
  337. *
  338. * element.hasStyle( 'color' ); // Returns true if 'border-top' style is present.
  339. * element.hasStyle( 'color', 'border-top' ); // Returns true if 'color' and 'border-top' styles are both present.
  340. *
  341. * @param {...String} property
  342. */
  343. hasStyle( ...property ) {
  344. for ( const name of property ) {
  345. if ( !this._styles.has( name ) ) {
  346. return false;
  347. }
  348. }
  349. return true;
  350. }
  351. /**
  352. * Returns ancestor element that match specified pattern.
  353. * Provided patterns should be compatible with {@link module:engine/view/matcher~Matcher Matcher} as it is used internally.
  354. *
  355. * @see module:engine/view/matcher~Matcher
  356. * @param {Object|String|RegExp|Function} patterns Patterns used to match correct ancestor.
  357. * See {@link module:engine/view/matcher~Matcher}.
  358. * @returns {module:engine/view/element~Element|null} Found element or `null` if no matching ancestor was found.
  359. */
  360. findAncestor( ...patterns ) {
  361. const matcher = new Matcher( ...patterns );
  362. let parent = this.parent;
  363. while ( parent ) {
  364. if ( matcher.match( parent ) ) {
  365. return parent;
  366. }
  367. parent = parent.parent;
  368. }
  369. return null;
  370. }
  371. /**
  372. * Returns the custom property value for the given key.
  373. *
  374. * @param {String|Symbol} key
  375. * @returns {*}
  376. */
  377. getCustomProperty( key ) {
  378. return this._customProperties.get( key );
  379. }
  380. /**
  381. * Returns an iterator which iterates over this element's custom properties.
  382. * Iterator provides `[ key, value ]` pairs for each stored property.
  383. *
  384. * @returns {Iterable.<*>}
  385. */
  386. * getCustomProperties() {
  387. yield* this._customProperties.entries();
  388. }
  389. /**
  390. * Returns identity string based on element's name, styles, classes and other attributes.
  391. * Two elements that {@link #isSimilar are similar} will have same identity string.
  392. * It has the following format:
  393. *
  394. * 'name class="class1,class2" style="style1:value1;style2:value2" attr1="val1" attr2="val2"'
  395. *
  396. * For example:
  397. *
  398. * const element = writer.createContainerElement( 'foo', {
  399. * banana: '10',
  400. * apple: '20',
  401. * style: 'color: red; border-color: white;',
  402. * class: 'baz'
  403. * } );
  404. *
  405. * // returns 'foo class="baz" style="border-color:white;color:red" apple="20" banana="10"'
  406. * element.getIdentity();
  407. *
  408. * NOTE: Classes, styles and other attributes are sorted alphabetically.
  409. *
  410. * @returns {String}
  411. */
  412. getIdentity() {
  413. const classes = Array.from( this._classes ).sort().join( ',' );
  414. const styles = Array.from( this._styles ).map( i => `${ i[ 0 ] }:${ i[ 1 ] }` ).sort().join( ';' );
  415. const attributes = Array.from( this._attrs ).map( i => `${ i[ 0 ] }="${ i[ 1 ] }"` ).sort().join( ' ' );
  416. return this.name +
  417. ( classes == '' ? '' : ` class="${ classes }"` ) +
  418. ( styles == '' ? '' : ` style="${ styles }"` ) +
  419. ( attributes == '' ? '' : ` ${ attributes }` );
  420. }
  421. /**
  422. * Clones provided element.
  423. *
  424. * @protected
  425. * @param {Boolean} [deep=false] If set to `true` clones element and all its children recursively. When set to `false`,
  426. * element will be cloned without any children.
  427. * @returns {module:engine/view/element~Element} Clone of this element.
  428. */
  429. _clone( deep = false ) {
  430. const childrenClone = [];
  431. if ( deep ) {
  432. for ( const child of this.getChildren() ) {
  433. childrenClone.push( child._clone( deep ) );
  434. }
  435. }
  436. // ContainerElement and AttributeElement should be also cloned properly.
  437. const cloned = new this.constructor( this.name, this._attrs, childrenClone );
  438. // Classes and styles are cloned separately - this solution is faster than adding them back to attributes and
  439. // parse once again in constructor.
  440. cloned._classes = new Set( this._classes );
  441. cloned._styles = new Map( this._styles );
  442. // Clone custom properties.
  443. cloned._customProperties = new Map( this._customProperties );
  444. // Clone filler offset method.
  445. // We can't define this method in a prototype because it's behavior which
  446. // is changed by e.g. toWidget() function from ckeditor5-widget. Perhaps this should be one of custom props.
  447. cloned.getFillerOffset = this.getFillerOffset;
  448. return cloned;
  449. }
  450. /**
  451. * {@link module:engine/view/element~Element#_insertChildren Insert} a child node or a list of child nodes at the end of this node
  452. * and sets the parent of these nodes to this element.
  453. *
  454. * @see module:engine/view/writer~Writer#insert
  455. * @protected
  456. * @param {module:engine/view/item~Item|Iterable.<module:engine/view/item~Item>} items Items to be inserted.
  457. * @fires module:engine/view/node~Node#change
  458. * @returns {Number} Number of appended nodes.
  459. */
  460. _appendChildren( items ) {
  461. return this._insertChildren( this.childCount, items );
  462. }
  463. /**
  464. * Inserts a child node or a list of child nodes on the given index and sets the parent of these nodes to
  465. * this element.
  466. *
  467. * @see module:engine/view/writer~Writer#insert
  468. * @protected
  469. * @param {Number} index Position where nodes should be inserted.
  470. * @param {module:engine/view/item~Item|Iterable.<module:engine/view/item~Item>} items Items to be inserted.
  471. * @fires module:engine/view/node~Node#change
  472. * @returns {Number} Number of inserted nodes.
  473. */
  474. _insertChildren( index, items ) {
  475. this._fireChange( 'children', this );
  476. let count = 0;
  477. const nodes = normalize( items );
  478. for ( const node of nodes ) {
  479. // If node that is being added to this element is already inside another element, first remove it from the old parent.
  480. if ( node.parent !== null ) {
  481. node._remove();
  482. }
  483. node.parent = this;
  484. this._children.splice( index, 0, node );
  485. index++;
  486. count++;
  487. }
  488. return count;
  489. }
  490. /**
  491. * Removes number of child nodes starting at the given index and set the parent of these nodes to `null`.
  492. *
  493. * @see module:engine/view/writer~Writer#remove
  494. * @param {Number} index Number of the first node to remove.
  495. * @param {Number} [howMany=1] Number of nodes to remove.
  496. * @fires module:engine/view/node~Node#change
  497. * @returns {Array.<module:engine/view/node~Node>} The array of removed nodes.
  498. */
  499. _removeChildren( index, howMany = 1 ) {
  500. this._fireChange( 'children', this );
  501. for ( let i = index; i < index + howMany; i++ ) {
  502. this._children[ i ].parent = null;
  503. }
  504. return this._children.splice( index, howMany );
  505. }
  506. /**
  507. * Adds or overwrite attribute with a specified key and value.
  508. *
  509. * @see module:engine/view/writer~Writer#setAttribute
  510. * @protected
  511. * @param {String} key Attribute key.
  512. * @param {String} value Attribute value.
  513. * @fires module:engine/view/node~Node#change
  514. */
  515. _setAttribute( key, value ) {
  516. value = String( value );
  517. this._fireChange( 'attributes', this );
  518. if ( key == 'class' ) {
  519. parseClasses( this._classes, value );
  520. } else if ( key == 'style' ) {
  521. parseInlineStyles( this._styles, value );
  522. } else {
  523. this._attrs.set( key, value );
  524. }
  525. }
  526. /**
  527. * Removes attribute from the element.
  528. *
  529. * @see module:engine/view/writer~Writer#removeAttribute
  530. * @protected
  531. * @param {String} key Attribute key.
  532. * @returns {Boolean} Returns true if an attribute existed and has been removed.
  533. * @fires module:engine/view/node~Node#change
  534. */
  535. _removeAttribute( key ) {
  536. this._fireChange( 'attributes', this );
  537. // Remove class attribute.
  538. if ( key == 'class' ) {
  539. if ( this._classes.size > 0 ) {
  540. this._classes.clear();
  541. return true;
  542. }
  543. return false;
  544. }
  545. // Remove style attribute.
  546. if ( key == 'style' ) {
  547. if ( this._styles.size > 0 ) {
  548. this._styles.clear();
  549. return true;
  550. }
  551. return false;
  552. }
  553. // Remove other attributes.
  554. return this._attrs.delete( key );
  555. }
  556. /**
  557. * Adds specified class.
  558. *
  559. * element._addClass( 'foo' ); // Adds 'foo' class.
  560. * element._addClass( [ 'foo', 'bar' ] ); // Adds 'foo' and 'bar' classes.
  561. *
  562. * @see module:engine/view/writer~Writer#addClass
  563. * @protected
  564. * @param {Array.<String>|String} className
  565. * @fires module:engine/view/node~Node#change
  566. */
  567. _addClass( className ) {
  568. this._fireChange( 'attributes', this );
  569. className = Array.isArray( className ) ? className : [ className ];
  570. className.forEach( name => this._classes.add( name ) );
  571. }
  572. /**
  573. * Removes specified class.
  574. *
  575. * element._removeClass( 'foo' ); // Removes 'foo' class.
  576. * element._removeClass( [ 'foo', 'bar' ] ); // Removes both 'foo' and 'bar' classes.
  577. *
  578. * @see module:engine/view/writer~Writer#removeClass
  579. * @param {Array.<String>|String} className
  580. * @fires module:engine/view/node~Node#change
  581. */
  582. _removeClass( className ) {
  583. this._fireChange( 'attributes', this );
  584. className = Array.isArray( className ) ? className : [ className ];
  585. className.forEach( name => this._classes.delete( name ) );
  586. }
  587. /**
  588. * Adds style to the element.
  589. *
  590. * element._setStyle( 'color', 'red' );
  591. * element._setStyle( {
  592. * color: 'red',
  593. * position: 'fixed'
  594. * } );
  595. *
  596. * @see module:engine/view/writer~Writer#setStyle
  597. * @protected
  598. * @param {String|Object} property Property name or object with key - value pairs.
  599. * @param {String} [value] Value to set. This parameter is ignored if object is provided as the first parameter.
  600. * @fires module:engine/view/node~Node#change
  601. */
  602. _setStyle( property, value ) {
  603. this._fireChange( 'attributes', this );
  604. if ( isPlainObject( property ) ) {
  605. const keys = Object.keys( property );
  606. for ( const key of keys ) {
  607. this._styles.set( key, property[ key ] );
  608. }
  609. } else {
  610. this._styles.set( property, value );
  611. }
  612. }
  613. /**
  614. * Removes specified style.
  615. *
  616. * element._removeStyle( 'color' ); // Removes 'color' style.
  617. * element._removeStyle( [ 'color', 'border-top' ] ); // Removes both 'color' and 'border-top' styles.
  618. *
  619. * @see module:engine/view/writer~Writer#removeStyle
  620. * @protected
  621. * @param {Array.<String>|String} property
  622. * @fires module:engine/view/node~Node#change
  623. */
  624. _removeStyle( property ) {
  625. this._fireChange( 'attributes', this );
  626. property = Array.isArray( property ) ? property : [ property ];
  627. property.forEach( name => this._styles.delete( name ) );
  628. }
  629. /**
  630. * Sets a custom property. Unlike attributes, custom properties are not rendered to the DOM,
  631. * so they can be used to add special data to elements.
  632. *
  633. * @see module:engine/view/writer~Writer#setCustomProperty
  634. * @protected
  635. * @param {String|Symbol} key
  636. * @param {*} value
  637. */
  638. _setCustomProperty( key, value ) {
  639. this._customProperties.set( key, value );
  640. }
  641. /**
  642. * Removes the custom property stored under the given key.
  643. *
  644. * @see module:engine/view/writer~Writer#removeCustomProperty
  645. * @protected
  646. * @param {String|Symbol} key
  647. * @returns {Boolean} Returns true if property was removed.
  648. */
  649. _removeCustomProperty( key ) {
  650. return this._customProperties.delete( key );
  651. }
  652. /**
  653. * Returns block {@link module:engine/view/filler filler} offset or `null` if block filler is not needed.
  654. *
  655. * @abstract
  656. * @method module:engine/view/element~Element#getFillerOffset
  657. */
  658. }
  659. // Parses attributes provided to the element constructor before they are applied to an element. If attributes are passed
  660. // as an object (instead of `Map`), the object is transformed to the map. Attributes with `null` value are removed.
  661. // Attributes with non-`String` value are converted to `String`.
  662. //
  663. // @param {Object|Map} attrs Attributes to parse.
  664. // @returns {Map} Parsed attributes.
  665. function parseAttributes( attrs ) {
  666. if ( isPlainObject( attrs ) ) {
  667. attrs = objectToMap( attrs );
  668. } else {
  669. attrs = new Map( attrs );
  670. }
  671. for ( const [ key, value ] of attrs ) {
  672. if ( value === null ) {
  673. attrs.delete( key );
  674. } else if ( typeof value != 'string' ) {
  675. attrs.set( key, String( value ) );
  676. }
  677. }
  678. return attrs;
  679. }
  680. // Parses inline styles and puts property - value pairs into styles map.
  681. // Styles map is cleared before insertion.
  682. //
  683. // @param {Map.<String, String>} stylesMap Map to insert parsed properties and values.
  684. // @param {String} stylesString Styles to parse.
  685. function parseInlineStyles( stylesMap, stylesString ) {
  686. // `null` if no quote was found in input string or last found quote was a closing quote. See below.
  687. let quoteType = null;
  688. let propertyNameStart = 0;
  689. let propertyValueStart = 0;
  690. let propertyName = null;
  691. stylesMap.clear();
  692. // Do not set anything if input string is empty.
  693. if ( stylesString === '' ) {
  694. return;
  695. }
  696. // Fix inline styles that do not end with `;` so they are compatible with algorithm below.
  697. if ( stylesString.charAt( stylesString.length - 1 ) != ';' ) {
  698. stylesString = stylesString + ';';
  699. }
  700. // Seek the whole string for "special characters".
  701. for ( let i = 0; i < stylesString.length; i++ ) {
  702. const char = stylesString.charAt( i );
  703. if ( quoteType === null ) {
  704. // No quote found yet or last found quote was a closing quote.
  705. switch ( char ) {
  706. case ':':
  707. // Most of time colon means that property name just ended.
  708. // Sometimes however `:` is found inside property value (for example in background image url).
  709. if ( !propertyName ) {
  710. // Treat this as end of property only if property name is not already saved.
  711. // Save property name.
  712. propertyName = stylesString.substr( propertyNameStart, i - propertyNameStart );
  713. // Save this point as the start of property value.
  714. propertyValueStart = i + 1;
  715. }
  716. break;
  717. case '"':
  718. case '\'':
  719. // Opening quote found (this is an opening quote, because `quoteType` is `null`).
  720. quoteType = char;
  721. break;
  722. // eslint-disable-next-line no-case-declarations
  723. case ';':
  724. // Property value just ended.
  725. // Use previously stored property value start to obtain property value.
  726. const propertyValue = stylesString.substr( propertyValueStart, i - propertyValueStart );
  727. if ( propertyName ) {
  728. // Save parsed part.
  729. stylesMap.set( propertyName.trim(), propertyValue.trim() );
  730. }
  731. propertyName = null;
  732. // Save this point as property name start. Property name starts immediately after previous property value ends.
  733. propertyNameStart = i + 1;
  734. break;
  735. }
  736. } else if ( char === quoteType ) {
  737. // If a quote char is found and it is a closing quote, mark this fact by `null`-ing `quoteType`.
  738. quoteType = null;
  739. }
  740. }
  741. }
  742. // Parses class attribute and puts all classes into classes set.
  743. // Classes set s cleared before insertion.
  744. //
  745. // @param {Set.<String>} classesSet Set to insert parsed classes.
  746. // @param {String} classesString String with classes to parse.
  747. function parseClasses( classesSet, classesString ) {
  748. const classArray = classesString.split( /\s+/ );
  749. classesSet.clear();
  750. classArray.forEach( name => classesSet.add( name ) );
  751. }
  752. // Converts strings to Text and non-iterables to arrays.
  753. //
  754. // @param {String|module:engine/view/item~Item|Iterable.<String|module:engine/view/item~Item>}
  755. // @return {Iterable.<module:engine/view/node~Node>}
  756. function normalize( nodes ) {
  757. // Separate condition because string is iterable.
  758. if ( typeof nodes == 'string' ) {
  759. return [ new Text( nodes ) ];
  760. }
  761. if ( !isIterable( nodes ) ) {
  762. nodes = [ nodes ];
  763. }
  764. // Array.from to enable .map() on non-arrays.
  765. return Array.from( nodes )
  766. .map( node => {
  767. if ( typeof node == 'string' ) {
  768. return new Text( node );
  769. }
  770. if ( node instanceof TextProxy ) {
  771. return new Text( node.data );
  772. }
  773. return node;
  774. } );
  775. }