node.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module engine/model/node
  7. */
  8. import toMap from '@ckeditor/ckeditor5-utils/src/tomap';
  9. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  10. /**
  11. * Model node. Most basic structure of model tree.
  12. *
  13. * This is an abstract class that is a base for other classes representing different nodes in model.
  14. *
  15. * **Note:** If a node is detached from the model tree, you can manipulate it using it's API.
  16. * However, it is **very important** that nodes already attached to model tree should be only changed through
  17. * {@link module:engine/model/document~Document#batch Batch API}.
  18. *
  19. * Changes done by `Node` methods, like {@link module:engine/model/element~Element#insertChildren insertChildren} or
  20. * {@link module:engine/model/node~Node#setAttribute setAttribute}
  21. * do not generate {@link module:engine/model/operation/operation~Operation operations}
  22. * which are essential for correct editor work if you modify nodes in {@link module:engine/model/document~Document document} root.
  23. *
  24. * The flow of working on `Node` (and classes that inherits from it) is as such:
  25. * 1. You can create a `Node` instance, modify it using it's API.
  26. * 2. Add `Node` to the model using `Batch` API.
  27. * 3. Change `Node` that was already added to the model using `Batch` API.
  28. *
  29. * Similarly, you cannot use `Batch` API on a node that has not been added to the model tree, with the exception
  30. * of {@link module:engine/model/batch~Batch#insert inserting} that node to the model tree.
  31. *
  32. * Be aware that using {@link module:engine/model/batch~Batch#remove remove from Batch API} does not allow to use `Node` API because
  33. * the information about `Node` is still kept in model document.
  34. *
  35. * In case of {@link module:engine/model/element~Element element node}, adding and removing children also counts as changing a node and
  36. * follows same rules.
  37. */
  38. export default class Node {
  39. /**
  40. * Creates a model node.
  41. *
  42. * This is an abstract class, so this constructor should not be used directly.
  43. *
  44. * @abstract
  45. * @param {Object} [attrs] Node's attributes. See {@link module:utils/tomap~toMap} for a list of accepted values.
  46. */
  47. constructor( attrs ) {
  48. /**
  49. * Parent of this node. It could be {@link module:engine/model/element~Element}
  50. * or {@link module:engine/model/documentfragment~DocumentFragment}.
  51. * Equals to `null` if the node has no parent.
  52. *
  53. * @readonly
  54. * @member {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment|null}
  55. */
  56. this.parent = null;
  57. /**
  58. * Attributes set on this node.
  59. *
  60. * @private
  61. * @member {Map} module:engine/model/node~Node#_attrs
  62. */
  63. this._attrs = toMap( attrs );
  64. }
  65. /**
  66. * Index of this node in it's parent or `null` if the node has no parent.
  67. *
  68. * Accessing this property throws an error if this node's parent element does not contain it.
  69. * This means that model tree got broken.
  70. *
  71. * @readonly
  72. * @type {Number|null}
  73. */
  74. get index() {
  75. let pos;
  76. if ( !this.parent ) {
  77. return null;
  78. }
  79. if ( ( pos = this.parent.getChildIndex( this ) ) === null ) {
  80. /**
  81. * The node's parent does not contain this node.
  82. *
  83. * @error node-not-found-in-parent
  84. */
  85. throw new CKEditorError( 'model-node-not-found-in-parent: The node\'s parent does not contain this node.' );
  86. }
  87. return pos;
  88. }
  89. /**
  90. * Offset at which this node starts in it's parent. It is equal to the sum of {@link #offsetSize offsetSize}
  91. * of all it's previous siblings. Equals to `null` if node has no parent.
  92. *
  93. * Accessing this property throws an error if this node's parent element does not contain it.
  94. * This means that model tree got broken.
  95. *
  96. * @readonly
  97. * @type {Number|Null}
  98. */
  99. get startOffset() {
  100. let pos;
  101. if ( !this.parent ) {
  102. return null;
  103. }
  104. if ( ( pos = this.parent.getChildStartOffset( this ) ) === null ) {
  105. /**
  106. * The node's parent does not contain this node.
  107. *
  108. * @error node-not-found-in-parent
  109. */
  110. throw new CKEditorError( 'model-node-not-found-in-parent: The node\'s parent does not contain this node.' );
  111. }
  112. return pos;
  113. }
  114. /**
  115. * Offset size of this node. Represents how much "offset space" is occupied by the node in it's parent.
  116. * It is important for {@link module:engine/model/position~Position position}. When node has `offsetSize` greater than `1`, position
  117. * can be placed between that node start and end. `offsetSize` greater than `1` is for nodes that represents more
  118. * than one entity, i.e. {@link module:engine/model/text~Text text node}.
  119. *
  120. * @readonly
  121. * @type {Number}
  122. */
  123. get offsetSize() {
  124. return 1;
  125. }
  126. /**
  127. * Offset at which this node ends in it's parent. It is equal to the sum of this node's
  128. * {@link module:engine/model/node~Node#startOffset start offset} and {@link #offsetSize offset size}.
  129. * Equals to `null` if the node has no parent.
  130. *
  131. * @readonly
  132. * @type {Number|null}
  133. */
  134. get endOffset() {
  135. if ( !this.parent ) {
  136. return null;
  137. }
  138. return this.startOffset + this.offsetSize;
  139. }
  140. /**
  141. * Node's next sibling or `null` if the node is a last child of it's parent or if the node has no parent.
  142. *
  143. * @readonly
  144. * @type {module:engine/model/node~Node|null}
  145. */
  146. get nextSibling() {
  147. const index = this.index;
  148. return ( index !== null && this.parent.getChild( index + 1 ) ) || null;
  149. }
  150. /**
  151. * Node's previous sibling or `null` if the node is a first child of it's parent or if the node has no parent.
  152. *
  153. * @readonly
  154. * @type {module:engine/model/node~Node|null}
  155. */
  156. get previousSibling() {
  157. const index = this.index;
  158. return ( index !== null && this.parent.getChild( index - 1 ) ) || null;
  159. }
  160. /**
  161. * The top-most ancestor of the node. If node has no parent it is the root itself. If the node is a part
  162. * of {@link module:engine/model/documentfragment~DocumentFragment}, it's `root` is equal to that `DocumentFragment`.
  163. *
  164. * @readonly
  165. * @type {module:engine/model/node~Node|module:engine/model/documentfragment~DocumentFragment}
  166. */
  167. get root() {
  168. let root = this;
  169. while ( root.parent ) {
  170. root = root.parent;
  171. }
  172. return root;
  173. }
  174. /**
  175. * {@link module:engine/model/document~Document Document} that owns this node or `null` if the node has no parent or is inside
  176. * a {@link module:engine/model/documentfragment~DocumentFragment DocumentFragment}.
  177. *
  178. * @readonly
  179. * @type {module:engine/model/document~Document|null}
  180. */
  181. get document() {
  182. // This is a top element of a sub-tree.
  183. if ( this.root == this ) {
  184. return null;
  185. }
  186. // Root may be `DocumentFragment` which does not have document property.
  187. return this.root.document || null;
  188. }
  189. /**
  190. * Creates a copy of this node, that is a node with exactly same attributes, and returns it.
  191. *
  192. * @returns {module:engine/model/node~Node} Node with same attributes as this node.
  193. */
  194. clone() {
  195. return new Node( this._attrs );
  196. }
  197. /**
  198. * Gets path to the node. The path is an array containing starting offsets of consecutive ancestors of this node,
  199. * beginning from {@link module:engine/model/node~Node#root root}, down to this node's starting offset. The path can be used to
  200. * create {@link module:engine/model/position~Position Position} instance.
  201. *
  202. * const abc = new Text( 'abc' );
  203. * const foo = new Text( 'foo' );
  204. * const h1 = new Element( 'h1', null, new Text( 'header' ) );
  205. * const p = new Element( 'p', null, [ abc, foo ] );
  206. * const div = new Element( 'div', null, [ h1, p ] );
  207. * foo.getPath(); // Returns [ 1, 3 ]. `foo` is in `p` which is in `div`. `p` starts at offset 1, while `foo` at 3.
  208. * h1.getPath(); // Returns [ 0 ].
  209. * div.getPath(); // Returns [].
  210. *
  211. * @returns {Array.<Number>} The path.
  212. */
  213. getPath() {
  214. const path = [];
  215. let node = this;
  216. while ( node.parent ) {
  217. path.unshift( node.startOffset );
  218. node = node.parent;
  219. }
  220. return path;
  221. }
  222. /**
  223. * Returns ancestors array of this node.
  224. *
  225. * @param {Object} options Options object.
  226. * @param {Boolean} [options.includeNode=false] When set to `true` this node will be also included in parent's array.
  227. * @param {Boolean} [options.parentFirst=false] When set to `true`, array will be sorted from node's parent to root element,
  228. * otherwise root element will be the first item in the array.
  229. * @returns {Array} Array with ancestors.
  230. */
  231. getAncestors( options = { includeNode: false, parentFirst: false } ) {
  232. const ancestors = [];
  233. let parent = options.includeNode ? this : this.parent;
  234. while ( parent ) {
  235. ancestors[ options.parentFirst ? 'push' : 'unshift' ]( parent );
  236. parent = parent.parent;
  237. }
  238. return ancestors;
  239. }
  240. /**
  241. * Removes this node from it's parent.
  242. */
  243. remove() {
  244. this.parent.removeChildren( this.index );
  245. }
  246. /**
  247. * Checks if the node has an attribute with given key.
  248. *
  249. * @param {String} key Key of attribute to check.
  250. * @returns {Boolean} `true` if attribute with given key is set on node, `false` otherwise.
  251. */
  252. hasAttribute( key ) {
  253. return this._attrs.has( key );
  254. }
  255. /**
  256. * Gets an attribute value for given key or `undefined` if that attribute is not set on node.
  257. *
  258. * @param {String} key Key of attribute to look for.
  259. * @returns {*} Attribute value or `undefined`.
  260. */
  261. getAttribute( key ) {
  262. return this._attrs.get( key );
  263. }
  264. /**
  265. * Returns iterator that iterates over this node's attributes.
  266. *
  267. * Attributes are returned as arrays containing two items. First one is attribute key and second is attribute value.
  268. * This format is accepted by native `Map` object and also can be passed in `Node` constructor.
  269. *
  270. * @returns {Iterable.<*>}
  271. */
  272. getAttributes() {
  273. return this._attrs.entries();
  274. }
  275. /**
  276. * Returns iterator that iterates over this node's attribute keys.
  277. *
  278. * @returns {Iterator.<String>}
  279. */
  280. getAttributeKeys() {
  281. return this._attrs.keys();
  282. }
  283. /**
  284. * Sets attribute on the node. If attribute with the same key already is set, it's value is overwritten.
  285. *
  286. * @param {String} key Key of attribute to set.
  287. * @param {*} value Attribute value.
  288. */
  289. setAttribute( key, value ) {
  290. this._attrs.set( key, value );
  291. }
  292. /**
  293. * Removes all attributes from the node and sets given attributes.
  294. *
  295. * @param {Object} [attrs] Attributes to set. See {@link module:utils/tomap~toMap} for a list of accepted values.
  296. */
  297. setAttributesTo( attrs ) {
  298. this._attrs = toMap( attrs );
  299. }
  300. /**
  301. * Removes an attribute with given key from the node.
  302. *
  303. * @param {String} key Key of attribute to remove.
  304. * @returns {Boolean} `true` if the attribute was set on the element, `false` otherwise.
  305. */
  306. removeAttribute( key ) {
  307. return this._attrs.delete( key );
  308. }
  309. /**
  310. * Removes all attributes from the node.
  311. */
  312. clearAttributes() {
  313. this._attrs.clear();
  314. }
  315. /**
  316. * Converts `Node` to plain object and returns it.
  317. *
  318. * @returns {Object} `Node` converted to plain object.
  319. */
  320. toJSON() {
  321. let json = {};
  322. if ( this._attrs.size ) {
  323. json.attributes = [ ...this._attrs ];
  324. }
  325. return json;
  326. }
  327. /**
  328. * Checks whether given model tree object is of given type.
  329. *
  330. * This method is useful when processing model tree objects that are of unknown type. For example, a function
  331. * may return {@link module:engine/model/documentfragment~DocumentFragment} or {@link module:engine/model/node~Node}
  332. * that can be either text node or element. This method can be used to check what kind of object is returned.
  333. *
  334. * obj.is( 'node' ); // true for any node, false for document fragment
  335. * obj.is( 'documentFragment' ); // true for document fragment, false for any node
  336. * obj.is( 'element' ); // true for any element, false for text node or document fragment
  337. * obj.is( 'element', 'paragraph' ); // true only for element which name is 'paragraph'
  338. * obj.is( 'paragraph' ); // shortcut for obj.is( 'element', 'paragraph' )
  339. * obj.is( 'text' ); // true for text node, false for element and document fragment
  340. * obj.is( 'textProxy' ); // true for text proxy object
  341. *
  342. * @method #is
  343. * @param {'element'|'rootElement'|'text'|'textProxy'|'documentFragment'} type
  344. * @returns {Boolean}
  345. */
  346. }