element.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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/model/element
  7. */
  8. import Node from './node';
  9. import NodeList from './nodelist';
  10. import Text from './text';
  11. import TextProxy from './textproxy';
  12. import isIterable from '@ckeditor/ckeditor5-utils/src/isiterable';
  13. // @if CK_DEBUG_ENGINE // const { stringifyMap, convertMapToStringifiedObject, convertMapToTags } = require( '../dev-utils/utils' );
  14. /**
  15. * Model element. Type of {@link module:engine/model/node~Node node} that has a {@link module:engine/model/element~Element#name name} and
  16. * {@link module:engine/model/element~Element#getChildren child nodes}.
  17. *
  18. * **Important**: see {@link module:engine/model/node~Node} to read about restrictions using `Element` and `Node` API.
  19. *
  20. * @extends module:engine/model/node~Node
  21. */
  22. export default class Element extends Node {
  23. /**
  24. * Creates a model element.
  25. *
  26. * **Note:** Constructor of this class shouldn't be used directly in the code.
  27. * Use the {@link module:engine/model/writer~Writer#createElement} method instead.
  28. *
  29. * @protected
  30. * @param {String} name Element's name.
  31. * @param {Object} [attrs] Element's attributes. See {@link module:utils/tomap~toMap} for a list of accepted values.
  32. * @param {module:engine/model/node~Node|Iterable.<module:engine/model/node~Node>} [children]
  33. * One or more nodes to be inserted as children of created element.
  34. */
  35. constructor( name, attrs, children ) {
  36. super( attrs );
  37. /**
  38. * Element name.
  39. *
  40. * @readonly
  41. * @member {String} module:engine/model/element~Element#name
  42. */
  43. this.name = name;
  44. /**
  45. * List of children nodes.
  46. *
  47. * @private
  48. * @member {module:engine/model/nodelist~NodeList} module:engine/model/element~Element#_children
  49. */
  50. this._children = new NodeList();
  51. if ( children ) {
  52. this._insertChild( 0, children );
  53. }
  54. }
  55. /**
  56. * Number of this element's children.
  57. *
  58. * @readonly
  59. * @type {Number}
  60. */
  61. get childCount() {
  62. return this._children.length;
  63. }
  64. /**
  65. * Sum of {@link module:engine/model/node~Node#offsetSize offset sizes} of all of this element's children.
  66. *
  67. * @readonly
  68. * @type {Number}
  69. */
  70. get maxOffset() {
  71. return this._children.maxOffset;
  72. }
  73. /**
  74. * Is `true` if there are no nodes inside this element, `false` otherwise.
  75. *
  76. * @readonly
  77. * @type {Boolean}
  78. */
  79. get isEmpty() {
  80. return this.childCount === 0;
  81. }
  82. /**
  83. * Checks whether this object is of the given.
  84. *
  85. * element.is( 'element' ); // -> true
  86. * element.is( 'node' ); // -> true
  87. * element.is( 'model:element' ); // -> true
  88. * element.is( 'model:node' ); // -> true
  89. *
  90. * element.is( 'view:element' ); // -> false
  91. * element.is( 'documentSelection' ); // -> false
  92. *
  93. * Assuming that the object being checked is an element, you can also check its
  94. * {@link module:engine/model/element~Element#name name}:
  95. *
  96. * element.is( 'image' ); // -> true if this is an <image> element
  97. * element.is( 'element', 'image' ); // -> same as above
  98. * text.is( 'image' ); -> false
  99. *
  100. * {@link module:engine/model/node~Node#is Check the entire list of model objects} which implement the `is()` method.
  101. *
  102. * @param {String} type Type to check when `name` parameter is present.
  103. * Otherwise, it acts like the `name` parameter.
  104. * @param {String} [name] Element name.
  105. * @returns {Boolean}
  106. */
  107. is( type, name = null ) {
  108. if ( !name ) {
  109. return type === 'element' || type === 'model:element' ||
  110. type === this.name || type === 'model:' + this.name ||
  111. // From super.is(). This is highly utilised method and cannot call super. See ckeditor/ckeditor5#6529.
  112. type === 'node' || type === 'model:node';
  113. }
  114. return name === this.name && ( type === 'element' || type === 'model:element' );
  115. }
  116. /**
  117. * Gets the child at the given index.
  118. *
  119. * @param {Number} index Index of child.
  120. * @returns {module:engine/model/node~Node} Child node.
  121. */
  122. getChild( index ) {
  123. return this._children.getNode( index );
  124. }
  125. /**
  126. * Returns an iterator that iterates over all of this element's children.
  127. *
  128. * @returns {Iterable.<module:engine/model/node~Node>}
  129. */
  130. getChildren() {
  131. return this._children[ Symbol.iterator ]();
  132. }
  133. /**
  134. * Returns an index of the given child node. Returns `null` if given node is not a child of this element.
  135. *
  136. * @param {module:engine/model/node~Node} node Child node to look for.
  137. * @returns {Number} Child node's index in this element.
  138. */
  139. getChildIndex( node ) {
  140. return this._children.getNodeIndex( node );
  141. }
  142. /**
  143. * Returns the starting offset of given child. Starting offset is equal to the sum of
  144. * {@link module:engine/model/node~Node#offsetSize offset sizes} of all node's siblings that are before it. Returns `null` if
  145. * given node is not a child of this element.
  146. *
  147. * @param {module:engine/model/node~Node} node Child node to look for.
  148. * @returns {Number} Child node's starting offset.
  149. */
  150. getChildStartOffset( node ) {
  151. return this._children.getNodeStartOffset( node );
  152. }
  153. /**
  154. * Returns index of a node that occupies given offset. If given offset is too low, returns `0`. If given offset is
  155. * too high, returns {@link module:engine/model/element~Element#getChildIndex index after last child}.
  156. *
  157. * const textNode = new Text( 'foo' );
  158. * const pElement = new Element( 'p' );
  159. * const divElement = new Element( [ textNode, pElement ] );
  160. * divElement.offsetToIndex( -1 ); // Returns 0, because offset is too low.
  161. * divElement.offsetToIndex( 0 ); // Returns 0, because offset 0 is taken by `textNode` which is at index 0.
  162. * divElement.offsetToIndex( 1 ); // Returns 0, because `textNode` has `offsetSize` equal to 3, so it occupies offset 1 too.
  163. * divElement.offsetToIndex( 2 ); // Returns 0.
  164. * divElement.offsetToIndex( 3 ); // Returns 1.
  165. * divElement.offsetToIndex( 4 ); // Returns 2. There are no nodes at offset 4, so last available index is returned.
  166. *
  167. * @param {Number} offset Offset to look for.
  168. * @returns {Number}
  169. */
  170. offsetToIndex( offset ) {
  171. return this._children.offsetToIndex( offset );
  172. }
  173. /**
  174. * Returns a descendant node by its path relative to this element.
  175. *
  176. * // <this>a<b>c</b></this>
  177. * this.getNodeByPath( [ 0 ] ); // -> "a"
  178. * this.getNodeByPath( [ 1 ] ); // -> <b>
  179. * this.getNodeByPath( [ 1, 0 ] ); // -> "c"
  180. *
  181. * @param {Array.<Number>} relativePath Path of the node to find, relative to this element.
  182. * @returns {module:engine/model/node~Node}
  183. */
  184. getNodeByPath( relativePath ) {
  185. let node = this; // eslint-disable-line consistent-this
  186. for ( const index of relativePath ) {
  187. node = node.getChild( node.offsetToIndex( index ) );
  188. }
  189. return node;
  190. }
  191. /**
  192. * Converts `Element` instance to plain object and returns it. Takes care of converting all of this element's children.
  193. *
  194. * @returns {Object} `Element` instance converted to plain object.
  195. */
  196. toJSON() {
  197. const json = super.toJSON();
  198. json.name = this.name;
  199. if ( this._children.length > 0 ) {
  200. json.children = [];
  201. for ( const node of this._children ) {
  202. json.children.push( node.toJSON() );
  203. }
  204. }
  205. return json;
  206. }
  207. /**
  208. * Creates a copy of this element and returns it. Created element has the same name and attributes as the original element.
  209. * If clone is deep, the original element's children are also cloned. If not, then empty element is returned.
  210. *
  211. * @protected
  212. * @param {Boolean} [deep=false] If set to `true` clones element and all its children recursively. When set to `false`,
  213. * element will be cloned without any child.
  214. */
  215. _clone( deep = false ) {
  216. const children = deep ? Array.from( this._children ).map( node => node._clone( true ) ) : null;
  217. return new Element( this.name, this.getAttributes(), children );
  218. }
  219. /**
  220. * {@link module:engine/model/element~Element#_insertChild Inserts} one or more nodes at the end of this element.
  221. *
  222. * @see module:engine/model/writer~Writer#append
  223. * @protected
  224. * @param {module:engine/model/item~Item|Iterable.<module:engine/model/item~Item>} nodes Nodes to be inserted.
  225. */
  226. _appendChild( nodes ) {
  227. this._insertChild( this.childCount, nodes );
  228. }
  229. /**
  230. * Inserts one or more nodes at the given index and sets {@link module:engine/model/node~Node#parent parent} of these nodes
  231. * to this element.
  232. *
  233. * @see module:engine/model/writer~Writer#insert
  234. * @protected
  235. * @param {Number} index Index at which nodes should be inserted.
  236. * @param {module:engine/model/item~Item|Iterable.<module:engine/model/item~Item>} items Items to be inserted.
  237. */
  238. _insertChild( index, items ) {
  239. const nodes = normalize( items );
  240. for ( const node of nodes ) {
  241. // If node that is being added to this element is already inside another element, first remove it from the old parent.
  242. if ( node.parent !== null ) {
  243. node._remove();
  244. }
  245. node.parent = this;
  246. }
  247. this._children._insertNodes( index, nodes );
  248. }
  249. /**
  250. * Removes one or more nodes starting at the given index and sets
  251. * {@link module:engine/model/node~Node#parent parent} of these nodes to `null`.
  252. *
  253. * @see module:engine/model/writer~Writer#remove
  254. * @protected
  255. * @param {Number} index Index of the first node to remove.
  256. * @param {Number} [howMany=1] Number of nodes to remove.
  257. * @returns {Array.<module:engine/model/node~Node>} Array containing removed nodes.
  258. */
  259. _removeChildren( index, howMany = 1 ) {
  260. const nodes = this._children._removeNodes( index, howMany );
  261. for ( const node of nodes ) {
  262. node.parent = null;
  263. }
  264. return nodes;
  265. }
  266. /**
  267. * Creates an `Element` instance from given plain object (i.e. parsed JSON string).
  268. * Converts `Element` children to proper nodes.
  269. *
  270. * @param {Object} json Plain object to be converted to `Element`.
  271. * @returns {module:engine/model/element~Element} `Element` instance created using given plain object.
  272. */
  273. static fromJSON( json ) {
  274. let children = null;
  275. if ( json.children ) {
  276. children = [];
  277. for ( const child of json.children ) {
  278. if ( child.name ) {
  279. // If child has name property, it is an Element.
  280. children.push( Element.fromJSON( child ) );
  281. } else {
  282. // Otherwise, it is a Text node.
  283. children.push( Text.fromJSON( child ) );
  284. }
  285. }
  286. }
  287. return new Element( json.name, json.attributes, children );
  288. }
  289. // @if CK_DEBUG_ENGINE // toString() {
  290. // @if CK_DEBUG_ENGINE // return `<${ this.rootName || this.name }>`;
  291. // @if CK_DEBUG_ENGINE // }
  292. // @if CK_DEBUG_ENGINE // log() {
  293. // @if CK_DEBUG_ENGINE // console.log( 'ModelElement: ' + this );
  294. // @if CK_DEBUG_ENGINE // }
  295. // @if CK_DEBUG_ENGINE // logExtended() {
  296. // @if CK_DEBUG_ENGINE // console.log( `ModelElement: ${ this }, ${ this.childCount } children,
  297. // @if CK_DEBUG_ENGINE // attrs: ${ convertMapToStringifiedObject( this.getAttributes() ) }` );
  298. // @if CK_DEBUG_ENGINE // }
  299. // @if CK_DEBUG_ENGINE // logAll() {
  300. // @if CK_DEBUG_ENGINE // console.log( '--------------------' );
  301. // @if CK_DEBUG_ENGINE //
  302. // @if CK_DEBUG_ENGINE // this.logExtended();
  303. // @if CK_DEBUG_ENGINE // console.log( 'List of children:' );
  304. // @if CK_DEBUG_ENGINE //
  305. // @if CK_DEBUG_ENGINE // for ( const child of this.getChildren() ) {
  306. // @if CK_DEBUG_ENGINE // child.log();
  307. // @if CK_DEBUG_ENGINE // }
  308. // @if CK_DEBUG_ENGINE // }
  309. // @if CK_DEBUG_ENGINE // printTree( level = 0) {
  310. // @if CK_DEBUG_ENGINE // let string = '';
  311. // @if CK_DEBUG_ENGINE // string += '\t'.repeat( level );
  312. // @if CK_DEBUG_ENGINE // string += `<${ this.rootName || this.name }${ convertMapToTags( this.getAttributes() ) }>`;
  313. // @if CK_DEBUG_ENGINE // for ( const child of this.getChildren() ) {
  314. // @if CK_DEBUG_ENGINE // string += '\n';
  315. // @if CK_DEBUG_ENGINE // if ( child.is( 'text' ) ) {
  316. // @if CK_DEBUG_ENGINE // const textAttrs = convertMapToTags( child._attrs );
  317. // @if CK_DEBUG_ENGINE // string += '\t'.repeat( level + 1 );
  318. // @if CK_DEBUG_ENGINE // if ( textAttrs !== '' ) {
  319. // @if CK_DEBUG_ENGINE // string += `<$text${ textAttrs }>` + child.data + '</$text>';
  320. // @if CK_DEBUG_ENGINE // } else {
  321. // @if CK_DEBUG_ENGINE // string += child.data;
  322. // @if CK_DEBUG_ENGINE // }
  323. // @if CK_DEBUG_ENGINE // } else {
  324. // @if CK_DEBUG_ENGINE // string += child.printTree( level + 1 );
  325. // @if CK_DEBUG_ENGINE // }
  326. // @if CK_DEBUG_ENGINE // }
  327. // @if CK_DEBUG_ENGINE // if ( this.childCount ) {
  328. // @if CK_DEBUG_ENGINE // string += '\n' + '\t'.repeat( level );
  329. // @if CK_DEBUG_ENGINE // }
  330. // @if CK_DEBUG_ENGINE // string += `</${ this.rootName || this.name }>`;
  331. // @if CK_DEBUG_ENGINE // return string;
  332. // @if CK_DEBUG_ENGINE // }
  333. // @if CK_DEBUG_ENGINE // logTree() {
  334. // @if CK_DEBUG_ENGINE // console.log( this.printTree() );
  335. // @if CK_DEBUG_ENGINE // }
  336. }
  337. // Converts strings to Text and non-iterables to arrays.
  338. //
  339. // @param {String|module:engine/model/item~Item|Iterable.<String|module:engine/model/item~Item>}
  340. // @returns {Iterable.<module:engine/model/node~Node>}
  341. function normalize( nodes ) {
  342. // Separate condition because string is iterable.
  343. if ( typeof nodes == 'string' ) {
  344. return [ new Text( nodes ) ];
  345. }
  346. if ( !isIterable( nodes ) ) {
  347. nodes = [ nodes ];
  348. }
  349. // Array.from to enable .map() on non-arrays.
  350. return Array.from( nodes )
  351. .map( node => {
  352. if ( typeof node == 'string' ) {
  353. return new Text( node );
  354. }
  355. if ( node instanceof TextProxy ) {
  356. return new Text( node.data, node.getAttributes() );
  357. }
  358. return node;
  359. } );
  360. }