element.js 26 KB

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