element.js 9.9 KB

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