8
0

element.js 26 KB

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