element.js 27 KB

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