node.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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/writer~Writer Writer 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/writer~Writer#insert inserting} that node to the model tree.
  31. *
  32. * Be aware that using {@link module:engine/model/writer~Writer#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. throw new CKEditorError( 'model-node-not-found-in-parent: The node\'s parent does not contain this node.' );
  81. }
  82. return pos;
  83. }
  84. /**
  85. * Offset at which this node starts in it's parent. It is equal to the sum of {@link #offsetSize offsetSize}
  86. * of all it's previous siblings. Equals to `null` if node has no parent.
  87. *
  88. * Accessing this property throws an error if this node's parent element does not contain it.
  89. * This means that model tree got broken.
  90. *
  91. * @readonly
  92. * @type {Number|Null}
  93. */
  94. get startOffset() {
  95. let pos;
  96. if ( !this.parent ) {
  97. return null;
  98. }
  99. if ( ( pos = this.parent.getChildStartOffset( this ) ) === null ) {
  100. throw new CKEditorError( 'model-node-not-found-in-parent: The node\'s parent does not contain this node.' );
  101. }
  102. return pos;
  103. }
  104. /**
  105. * Offset size of this node. Represents how much "offset space" is occupied by the node in it's parent.
  106. * It is important for {@link module:engine/model/position~Position position}. When node has `offsetSize` greater than `1`, position
  107. * can be placed between that node start and end. `offsetSize` greater than `1` is for nodes that represents more
  108. * than one entity, i.e. {@link module:engine/model/text~Text text node}.
  109. *
  110. * @readonly
  111. * @type {Number}
  112. */
  113. get offsetSize() {
  114. return 1;
  115. }
  116. /**
  117. * Offset at which this node ends in it's parent. It is equal to the sum of this node's
  118. * {@link module:engine/model/node~Node#startOffset start offset} and {@link #offsetSize offset size}.
  119. * Equals to `null` if the node has no parent.
  120. *
  121. * @readonly
  122. * @type {Number|null}
  123. */
  124. get endOffset() {
  125. if ( !this.parent ) {
  126. return null;
  127. }
  128. return this.startOffset + this.offsetSize;
  129. }
  130. /**
  131. * Node's next sibling or `null` if the node is a last child of it's parent or if the node has no parent.
  132. *
  133. * @readonly
  134. * @type {module:engine/model/node~Node|null}
  135. */
  136. get nextSibling() {
  137. const index = this.index;
  138. return ( index !== null && this.parent.getChild( index + 1 ) ) || null;
  139. }
  140. /**
  141. * Node's previous sibling or `null` if the node is a first 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 previousSibling() {
  147. const index = this.index;
  148. return ( index !== null && this.parent.getChild( index - 1 ) ) || null;
  149. }
  150. /**
  151. * The top-most ancestor of the node. If node has no parent it is the root itself. If the node is a part
  152. * of {@link module:engine/model/documentfragment~DocumentFragment}, it's `root` is equal to that `DocumentFragment`.
  153. *
  154. * @readonly
  155. * @type {module:engine/model/node~Node|module:engine/model/documentfragment~DocumentFragment}
  156. */
  157. get root() {
  158. let root = this; // eslint-disable-line consistent-this
  159. while ( root.parent ) {
  160. root = root.parent;
  161. }
  162. return root;
  163. }
  164. /**
  165. * {@link module:engine/model/document~Document Document} that owns this node or `null` if the node has no parent or is inside
  166. * a {@link module:engine/model/documentfragment~DocumentFragment DocumentFragment}.
  167. *
  168. * @readonly
  169. * @type {module:engine/model/document~Document|null}
  170. */
  171. get document() {
  172. // This is a top element of a sub-tree.
  173. if ( this.root == this ) {
  174. return null;
  175. }
  176. // Root may be `DocumentFragment` which does not have document property.
  177. return this.root.document || null;
  178. }
  179. /**
  180. * Creates a copy of this node, that is a node with exactly same attributes, and returns it.
  181. *
  182. * @returns {module:engine/model/node~Node} Node with same attributes as this node.
  183. */
  184. clone() {
  185. return new Node( this._attrs );
  186. }
  187. /**
  188. * Gets path to the node. The path is an array containing starting offsets of consecutive ancestors of this node,
  189. * beginning from {@link module:engine/model/node~Node#root root}, down to this node's starting offset. The path can be used to
  190. * create {@link module:engine/model/position~Position Position} instance.
  191. *
  192. * const abc = new Text( 'abc' );
  193. * const foo = new Text( 'foo' );
  194. * const h1 = new Element( 'h1', null, new Text( 'header' ) );
  195. * const p = new Element( 'p', null, [ abc, foo ] );
  196. * const div = new Element( 'div', null, [ h1, p ] );
  197. * foo.getPath(); // Returns [ 1, 3 ]. `foo` is in `p` which is in `div`. `p` starts at offset 1, while `foo` at 3.
  198. * h1.getPath(); // Returns [ 0 ].
  199. * div.getPath(); // Returns [].
  200. *
  201. * @returns {Array.<Number>} The path.
  202. */
  203. getPath() {
  204. const path = [];
  205. let node = this; // eslint-disable-line consistent-this
  206. while ( node.parent ) {
  207. path.unshift( node.startOffset );
  208. node = node.parent;
  209. }
  210. return path;
  211. }
  212. /**
  213. * Returns ancestors array of this node.
  214. *
  215. * @param {Object} options Options object.
  216. * @param {Boolean} [options.includeSelf=false] When set to `true` this node will be also included in parent's array.
  217. * @param {Boolean} [options.parentFirst=false] When set to `true`, array will be sorted from node's parent to root element,
  218. * otherwise root element will be the first item in the array.
  219. * @returns {Array} Array with ancestors.
  220. */
  221. getAncestors( options = { includeSelf: false, parentFirst: false } ) {
  222. const ancestors = [];
  223. let parent = options.includeSelf ? this : this.parent;
  224. while ( parent ) {
  225. ancestors[ options.parentFirst ? 'push' : 'unshift' ]( parent );
  226. parent = parent.parent;
  227. }
  228. return ancestors;
  229. }
  230. /**
  231. * Returns a {@link module:engine/model/element~Element} or {@link module:engine/model/documentfragment~DocumentFragment}
  232. * which is a common ancestor of both nodes.
  233. *
  234. * @param {module:engine/model/node~Node} node The second node.
  235. * @param {Object} options Options object.
  236. * @param {Boolean} [options.includeSelf=false] When set to `true` both nodes will be considered "ancestors" too.
  237. * Which means that if e.g. node A is inside B, then their common ancestor will be B.
  238. * @returns {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment|null}
  239. */
  240. getCommonAncestor( node, options = {} ) {
  241. const ancestorsA = this.getAncestors( options );
  242. const ancestorsB = node.getAncestors( options );
  243. let i = 0;
  244. while ( ancestorsA[ i ] == ancestorsB[ i ] && ancestorsA[ i ] ) {
  245. i++;
  246. }
  247. return i === 0 ? null : ancestorsA[ i - 1 ];
  248. }
  249. /**
  250. * Removes this node from it's parent.
  251. */
  252. remove() {
  253. this.parent.removeChildren( this.index );
  254. }
  255. /**
  256. * Checks if the node has an attribute with given key.
  257. *
  258. * @param {String} key Key of attribute to check.
  259. * @returns {Boolean} `true` if attribute with given key is set on node, `false` otherwise.
  260. */
  261. hasAttribute( key ) {
  262. return this._attrs.has( key );
  263. }
  264. /**
  265. * Gets an attribute value for given key or `undefined` if that attribute is not set on node.
  266. *
  267. * @param {String} key Key of attribute to look for.
  268. * @returns {*} Attribute value or `undefined`.
  269. */
  270. getAttribute( key ) {
  271. return this._attrs.get( key );
  272. }
  273. /**
  274. * Returns iterator that iterates over this node's attributes.
  275. *
  276. * Attributes are returned as arrays containing two items. First one is attribute key and second is attribute value.
  277. * This format is accepted by native `Map` object and also can be passed in `Node` constructor.
  278. *
  279. * @returns {Iterable.<*>}
  280. */
  281. getAttributes() {
  282. return this._attrs.entries();
  283. }
  284. /**
  285. * Returns iterator that iterates over this node's attribute keys.
  286. *
  287. * @returns {Iterator.<String>}
  288. */
  289. getAttributeKeys() {
  290. return this._attrs.keys();
  291. }
  292. /**
  293. * Sets attribute on the node. If attribute with the same key already is set, it's value is overwritten.
  294. *
  295. * @param {String} key Key of attribute to set.
  296. * @param {*} value Attribute value.
  297. */
  298. setAttribute( key, value ) {
  299. this._attrs.set( key, value );
  300. }
  301. /**
  302. * Removes all attributes from the node and sets given attributes.
  303. *
  304. * @param {Object} [attrs] Attributes to set. See {@link module:utils/tomap~toMap} for a list of accepted values.
  305. */
  306. setAttributesTo( attrs ) {
  307. this._attrs = toMap( attrs );
  308. }
  309. /**
  310. * Removes an attribute with given key from the node.
  311. *
  312. * @param {String} key Key of attribute to remove.
  313. * @returns {Boolean} `true` if the attribute was set on the element, `false` otherwise.
  314. */
  315. removeAttribute( key ) {
  316. return this._attrs.delete( key );
  317. }
  318. /**
  319. * Removes all attributes from the node.
  320. */
  321. clearAttributes() {
  322. this._attrs.clear();
  323. }
  324. /**
  325. * Converts `Node` to plain object and returns it.
  326. *
  327. * @returns {Object} `Node` converted to plain object.
  328. */
  329. toJSON() {
  330. const json = {};
  331. if ( this._attrs.size ) {
  332. json.attributes = [ ...this._attrs ];
  333. }
  334. return json;
  335. }
  336. /**
  337. * Checks whether given model tree object is of given type.
  338. *
  339. * This method is useful when processing model tree objects that are of unknown type. For example, a function
  340. * may return {@link module:engine/model/documentfragment~DocumentFragment} or {@link module:engine/model/node~Node}
  341. * that can be either text node or element. This method can be used to check what kind of object is returned.
  342. *
  343. * obj.is( 'node' ); // true for any node, false for document fragment
  344. * obj.is( 'documentFragment' ); // true for document fragment, false for any node
  345. * obj.is( 'element' ); // true for any element, false for text node or document fragment
  346. * obj.is( 'element', 'paragraph' ); // true only for element which name is 'paragraph'
  347. * obj.is( 'paragraph' ); // shortcut for obj.is( 'element', 'paragraph' )
  348. * obj.is( 'text' ); // true for text node, false for element and document fragment
  349. * obj.is( 'textProxy' ); // true for text proxy object
  350. *
  351. * @method #is
  352. * @param {'element'|'rootElement'|'text'|'textProxy'|'documentFragment'} type
  353. * @returns {Boolean}
  354. */
  355. }
  356. /**
  357. * The node's parent does not contain this node.
  358. *
  359. * This error may be thrown from corrupted trees.
  360. *
  361. * @error model-node-not-found-in-parent
  362. */