element.js 25 KB

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