element.js 25 KB

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