element.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. /**
  2. * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /**
  6. * @module engine/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. const cutType = type.replace( /^model:/, '' );
  109. if ( !name ) {
  110. return cutType == 'element' || cutType == this.name || super.is( type );
  111. } else {
  112. return cutType == 'element' && name == this.name;
  113. }
  114. }
  115. /**
  116. * Gets the child at the given index.
  117. *
  118. * @param {Number} index Index of child.
  119. * @returns {module:engine/model/node~Node} Child node.
  120. */
  121. getChild( index ) {
  122. return this._children.getNode( index );
  123. }
  124. /**
  125. * Returns an iterator that iterates over all of this element's children.
  126. *
  127. * @returns {Iterable.<module:engine/model/node~Node>}
  128. */
  129. getChildren() {
  130. return this._children[ Symbol.iterator ]();
  131. }
  132. /**
  133. * Returns an index of the given child node. Returns `null` if given node is not a child of this element.
  134. *
  135. * @param {module:engine/model/node~Node} node Child node to look for.
  136. * @returns {Number} Child node's index in this element.
  137. */
  138. getChildIndex( node ) {
  139. return this._children.getNodeIndex( node );
  140. }
  141. /**
  142. * Returns the starting offset of given child. Starting offset is equal to the sum of
  143. * {@link module:engine/model/node~Node#offsetSize offset sizes} of all node's siblings that are before it. Returns `null` if
  144. * given node is not a child of this element.
  145. *
  146. * @param {module:engine/model/node~Node} node Child node to look for.
  147. * @returns {Number} Child node's starting offset.
  148. */
  149. getChildStartOffset( node ) {
  150. return this._children.getNodeStartOffset( node );
  151. }
  152. /**
  153. * Returns index of a node that occupies given offset. If given offset is too low, returns `0`. If given offset is
  154. * too high, returns {@link module:engine/model/element~Element#getChildIndex index after last child}.
  155. *
  156. * const textNode = new Text( 'foo' );
  157. * const pElement = new Element( 'p' );
  158. * const divElement = new Element( [ textNode, pElement ] );
  159. * divElement.offsetToIndex( -1 ); // Returns 0, because offset is too low.
  160. * divElement.offsetToIndex( 0 ); // Returns 0, because offset 0 is taken by `textNode` which is at index 0.
  161. * divElement.offsetToIndex( 1 ); // Returns 0, because `textNode` has `offsetSize` equal to 3, so it occupies offset 1 too.
  162. * divElement.offsetToIndex( 2 ); // Returns 0.
  163. * divElement.offsetToIndex( 3 ); // Returns 1.
  164. * divElement.offsetToIndex( 4 ); // Returns 2. There are no nodes at offset 4, so last available index is returned.
  165. *
  166. * @param {Number} offset Offset to look for.
  167. * @returns {Number}
  168. */
  169. offsetToIndex( offset ) {
  170. return this._children.offsetToIndex( offset );
  171. }
  172. /**
  173. * Returns a descendant node by its path relative to this element.
  174. *
  175. * // <this>a<b>c</b></this>
  176. * this.getNodeByPath( [ 0 ] ); // -> "a"
  177. * this.getNodeByPath( [ 1 ] ); // -> <b>
  178. * this.getNodeByPath( [ 1, 0 ] ); // -> "c"
  179. *
  180. * @param {Array.<Number>} relativePath Path of the node to find, relative to this element.
  181. * @returns {module:engine/model/node~Node}
  182. */
  183. getNodeByPath( relativePath ) {
  184. let node = this; // eslint-disable-line consistent-this
  185. for ( const index of relativePath ) {
  186. node = node.getChild( node.offsetToIndex( index ) );
  187. }
  188. return node;
  189. }
  190. /**
  191. * Converts `Element` instance to plain object and returns it. Takes care of converting all of this element's children.
  192. *
  193. * @returns {Object} `Element` instance converted to plain object.
  194. */
  195. toJSON() {
  196. const json = super.toJSON();
  197. json.name = this.name;
  198. if ( this._children.length > 0 ) {
  199. json.children = [];
  200. for ( const node of this._children ) {
  201. json.children.push( node.toJSON() );
  202. }
  203. }
  204. return json;
  205. }
  206. /**
  207. * Creates a copy of this element and returns it. Created element has the same name and attributes as the original element.
  208. * If clone is deep, the original element's children are also cloned. If not, then empty element is removed.
  209. *
  210. * @protected
  211. * @param {Boolean} [deep=false] If set to `true` clones element and all its children recursively. When set to `false`,
  212. * element will be cloned without any child.
  213. */
  214. _clone( deep = false ) {
  215. const children = deep ? Array.from( this._children ).map( node => node._clone( true ) ) : null;
  216. return new Element( this.name, this.getAttributes(), children );
  217. }
  218. /**
  219. * {@link module:engine/model/element~Element#_insertChild Inserts} one or more nodes at the end of this element.
  220. *
  221. * @see module:engine/model/writer~Writer#append
  222. * @protected
  223. * @param {module:engine/model/item~Item|Iterable.<module:engine/model/item~Item>} nodes Nodes to be inserted.
  224. */
  225. _appendChild( nodes ) {
  226. this._insertChild( this.childCount, nodes );
  227. }
  228. /**
  229. * Inserts one or more nodes at the given index and sets {@link module:engine/model/node~Node#parent parent} of these nodes
  230. * to this element.
  231. *
  232. * @see module:engine/model/writer~Writer#insert
  233. * @protected
  234. * @param {Number} index Index at which nodes should be inserted.
  235. * @param {module:engine/model/item~Item|Iterable.<module:engine/model/item~Item>} items Items to be inserted.
  236. */
  237. _insertChild( index, items ) {
  238. const nodes = normalize( items );
  239. for ( const node of nodes ) {
  240. // If node that is being added to this element is already inside another element, first remove it from the old parent.
  241. if ( node.parent !== null ) {
  242. node._remove();
  243. }
  244. node.parent = this;
  245. }
  246. this._children._insertNodes( index, nodes );
  247. }
  248. /**
  249. * Removes one or more nodes starting at the given index and sets
  250. * {@link module:engine/model/node~Node#parent parent} of these nodes to `null`.
  251. *
  252. * @see module:engine/model/writer~Writer#remove
  253. * @protected
  254. * @param {Number} index Index of the first node to remove.
  255. * @param {Number} [howMany=1] Number of nodes to remove.
  256. * @returns {Array.<module:engine/model/node~Node>} Array containing removed nodes.
  257. */
  258. _removeChildren( index, howMany = 1 ) {
  259. const nodes = this._children._removeNodes( index, howMany );
  260. for ( const node of nodes ) {
  261. node.parent = null;
  262. }
  263. return nodes;
  264. }
  265. /**
  266. * Creates an `Element` instance from given plain object (i.e. parsed JSON string).
  267. * Converts `Element` children to proper nodes.
  268. *
  269. * @param {Object} json Plain object to be converted to `Element`.
  270. * @returns {module:engine/model/element~Element} `Element` instance created using given plain object.
  271. */
  272. static fromJSON( json ) {
  273. let children = null;
  274. if ( json.children ) {
  275. children = [];
  276. for ( const child of json.children ) {
  277. if ( child.name ) {
  278. // If child has name property, it is an Element.
  279. children.push( Element.fromJSON( child ) );
  280. } else {
  281. // Otherwise, it is a Text node.
  282. children.push( Text.fromJSON( child ) );
  283. }
  284. }
  285. }
  286. return new Element( json.name, json.attributes, children );
  287. }
  288. // @if CK_DEBUG_ENGINE // toString() {
  289. // @if CK_DEBUG_ENGINE // return `<${ this.rootName || this.name }>`;
  290. // @if CK_DEBUG_ENGINE // }
  291. // @if CK_DEBUG_ENGINE // log() {
  292. // @if CK_DEBUG_ENGINE // console.log( 'ModelElement: ' + this );
  293. // @if CK_DEBUG_ENGINE // }
  294. // @if CK_DEBUG_ENGINE // logExtended() {
  295. // @if CK_DEBUG_ENGINE // console.log( `ModelElement: ${ this }, ${ this.childCount } children,
  296. // @if CK_DEBUG_ENGINE // attrs: ${ convertMapToStringifiedObject( this.getAttributes() ) }` );
  297. // @if CK_DEBUG_ENGINE // }
  298. // @if CK_DEBUG_ENGINE // logAll() {
  299. // @if CK_DEBUG_ENGINE // console.log( '--------------------' );
  300. // @if CK_DEBUG_ENGINE //
  301. // @if CK_DEBUG_ENGINE // this.logExtended();
  302. // @if CK_DEBUG_ENGINE // console.log( 'List of children:' );
  303. // @if CK_DEBUG_ENGINE //
  304. // @if CK_DEBUG_ENGINE // for ( const child of this.getChildren() ) {
  305. // @if CK_DEBUG_ENGINE // child.log();
  306. // @if CK_DEBUG_ENGINE // }
  307. // @if CK_DEBUG_ENGINE // }
  308. // @if CK_DEBUG_ENGINE // printTree( level = 0) {
  309. // @if CK_DEBUG_ENGINE // let string = '';
  310. // @if CK_DEBUG_ENGINE // string += '\t'.repeat( level );
  311. // @if CK_DEBUG_ENGINE // string += `<${ this.rootName || this.name }${ convertMapToTags( this.getAttributes() ) }>`;
  312. // @if CK_DEBUG_ENGINE // for ( const child of this.getChildren() ) {
  313. // @if CK_DEBUG_ENGINE // string += '\n';
  314. // @if CK_DEBUG_ENGINE // if ( child.is( 'text' ) ) {
  315. // @if CK_DEBUG_ENGINE // const textAttrs = convertMapToTags( child._attrs );
  316. // @if CK_DEBUG_ENGINE // string += '\t'.repeat( level + 1 );
  317. // @if CK_DEBUG_ENGINE // if ( textAttrs !== '' ) {
  318. // @if CK_DEBUG_ENGINE // string += `<$text${ textAttrs }>` + child.data + '</$text>';
  319. // @if CK_DEBUG_ENGINE // } else {
  320. // @if CK_DEBUG_ENGINE // string += child.data;
  321. // @if CK_DEBUG_ENGINE // }
  322. // @if CK_DEBUG_ENGINE // } else {
  323. // @if CK_DEBUG_ENGINE // string += child.printTree( level + 1 );
  324. // @if CK_DEBUG_ENGINE // }
  325. // @if CK_DEBUG_ENGINE // }
  326. // @if CK_DEBUG_ENGINE // if ( this.childCount ) {
  327. // @if CK_DEBUG_ENGINE // string += '\n' + '\t'.repeat( level );
  328. // @if CK_DEBUG_ENGINE // }
  329. // @if CK_DEBUG_ENGINE // string += `</${ this.rootName || this.name }>`;
  330. // @if CK_DEBUG_ENGINE // return string;
  331. // @if CK_DEBUG_ENGINE // }
  332. // @if CK_DEBUG_ENGINE // logTree() {
  333. // @if CK_DEBUG_ENGINE // console.log( this.printTree() );
  334. // @if CK_DEBUG_ENGINE // }
  335. }
  336. // Converts strings to Text and non-iterables to arrays.
  337. //
  338. // @param {String|module:engine/model/item~Item|Iterable.<String|module:engine/model/item~Item>}
  339. // @returns {Iterable.<module:engine/model/node~Node>}
  340. function normalize( nodes ) {
  341. // Separate condition because string is iterable.
  342. if ( typeof nodes == 'string' ) {
  343. return [ new Text( nodes ) ];
  344. }
  345. if ( !isIterable( nodes ) ) {
  346. nodes = [ nodes ];
  347. }
  348. // Array.from to enable .map() on non-arrays.
  349. return Array.from( nodes )
  350. .map( node => {
  351. if ( typeof node == 'string' ) {
  352. return new Text( node );
  353. }
  354. if ( node instanceof TextProxy ) {
  355. return new Text( node.data, node.getAttributes() );
  356. }
  357. return node;
  358. } );
  359. }