node.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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/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. * Gets path to the node. The path is an array containing starting offsets of consecutive ancestors of this node,
  181. * beginning from {@link module:engine/model/node~Node#root root}, down to this node's starting offset. The path can be used to
  182. * create {@link module:engine/model/position~Position Position} instance.
  183. *
  184. * const abc = new Text( 'abc' );
  185. * const foo = new Text( 'foo' );
  186. * const h1 = new Element( 'h1', null, new Text( 'header' ) );
  187. * const p = new Element( 'p', null, [ abc, foo ] );
  188. * const div = new Element( 'div', null, [ h1, p ] );
  189. * foo.getPath(); // Returns [ 1, 3 ]. `foo` is in `p` which is in `div`. `p` starts at offset 1, while `foo` at 3.
  190. * h1.getPath(); // Returns [ 0 ].
  191. * div.getPath(); // Returns [].
  192. *
  193. * @returns {Array.<Number>} The path.
  194. */
  195. getPath() {
  196. const path = [];
  197. let node = this; // eslint-disable-line consistent-this
  198. while ( node.parent ) {
  199. path.unshift( node.startOffset );
  200. node = node.parent;
  201. }
  202. return path;
  203. }
  204. /**
  205. * Returns ancestors array of this node.
  206. *
  207. * @param {Object} options Options object.
  208. * @param {Boolean} [options.includeSelf=false] When set to `true` this node will be also included in parent's array.
  209. * @param {Boolean} [options.parentFirst=false] When set to `true`, array will be sorted from node's parent to root element,
  210. * otherwise root element will be the first item in the array.
  211. * @returns {Array} Array with ancestors.
  212. */
  213. getAncestors( options = { includeSelf: false, parentFirst: false } ) {
  214. const ancestors = [];
  215. let parent = options.includeSelf ? this : this.parent;
  216. while ( parent ) {
  217. ancestors[ options.parentFirst ? 'push' : 'unshift' ]( parent );
  218. parent = parent.parent;
  219. }
  220. return ancestors;
  221. }
  222. /**
  223. * Returns a {@link module:engine/model/element~Element} or {@link module:engine/model/documentfragment~DocumentFragment}
  224. * which is a common ancestor of both nodes.
  225. *
  226. * @param {module:engine/model/node~Node} node The second node.
  227. * @param {Object} options Options object.
  228. * @param {Boolean} [options.includeSelf=false] When set to `true` both nodes will be considered "ancestors" too.
  229. * Which means that if e.g. node A is inside B, then their common ancestor will be B.
  230. * @returns {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment|null}
  231. */
  232. getCommonAncestor( node, options = {} ) {
  233. const ancestorsA = this.getAncestors( options );
  234. const ancestorsB = node.getAncestors( options );
  235. let i = 0;
  236. while ( ancestorsA[ i ] == ancestorsB[ i ] && ancestorsA[ i ] ) {
  237. i++;
  238. }
  239. return i === 0 ? null : ancestorsA[ i - 1 ];
  240. }
  241. /**
  242. * Checks if the node has an attribute with given key.
  243. *
  244. * @param {String} key Key of attribute to check.
  245. * @returns {Boolean} `true` if attribute with given key is set on node, `false` otherwise.
  246. */
  247. hasAttribute( key ) {
  248. return this._attrs.has( key );
  249. }
  250. /**
  251. * Gets an attribute value for given key or `undefined` if that attribute is not set on node.
  252. *
  253. * @param {String} key Key of attribute to look for.
  254. * @returns {*} Attribute value or `undefined`.
  255. */
  256. getAttribute( key ) {
  257. return this._attrs.get( key );
  258. }
  259. /**
  260. * Returns iterator that iterates over this node's attributes.
  261. *
  262. * Attributes are returned as arrays containing two items. First one is attribute key and second is attribute value.
  263. * This format is accepted by native `Map` object and also can be passed in `Node` constructor.
  264. *
  265. * @returns {Iterable.<*>}
  266. */
  267. getAttributes() {
  268. return this._attrs.entries();
  269. }
  270. /**
  271. * Returns iterator that iterates over this node's attribute keys.
  272. *
  273. * @returns {Iterable.<String>}
  274. */
  275. getAttributeKeys() {
  276. return this._attrs.keys();
  277. }
  278. /**
  279. * Converts `Node` to plain object and returns it.
  280. *
  281. * @returns {Object} `Node` converted to plain object.
  282. */
  283. toJSON() {
  284. const json = {};
  285. if ( this._attrs.size ) {
  286. json.attributes = [ ...this._attrs ];
  287. }
  288. return json;
  289. }
  290. /**
  291. * Creates a copy of this node, that is a node with exactly same attributes, and returns it.
  292. *
  293. * @protected
  294. * @returns {module:engine/model/node~Node} Node with same attributes as this node.
  295. */
  296. _clone() {
  297. return new Node( this._attrs );
  298. }
  299. /**
  300. * Removes this node from it's parent.
  301. *
  302. * @see module:engine/model/writer~Writer#remove
  303. * @protected
  304. */
  305. _remove() {
  306. this.parent._removeChildren( this.index );
  307. }
  308. /**
  309. * Sets attribute on the node. If attribute with the same key already is set, it's value is overwritten.
  310. *
  311. * @see module:engine/model/writer~Writer#setAttribute
  312. * @protected
  313. * @param {String} key Key of attribute to set.
  314. * @param {*} value Attribute value.
  315. */
  316. _setAttribute( key, value ) {
  317. this._attrs.set( key, value );
  318. }
  319. /**
  320. * Removes all attributes from the node and sets given attributes.
  321. *
  322. * @see module:engine/model/writer~Writer#setAttributes
  323. * @protected
  324. * @param {Object} [attrs] Attributes to set. See {@link module:utils/tomap~toMap} for a list of accepted values.
  325. */
  326. _setAttributesTo( attrs ) {
  327. this._attrs = toMap( attrs );
  328. }
  329. /**
  330. * Removes an attribute with given key from the node.
  331. *
  332. * @see module:engine/model/writer~Writer#removeAttribute
  333. * @protected
  334. * @param {String} key Key of attribute to remove.
  335. * @returns {Boolean} `true` if the attribute was set on the element, `false` otherwise.
  336. */
  337. _removeAttribute( key ) {
  338. return this._attrs.delete( key );
  339. }
  340. /**
  341. * Removes all attributes from the node.
  342. *
  343. * @see module:engine/model/writer~Writer#clearAttributes
  344. * @protected
  345. */
  346. _clearAttributes() {
  347. this._attrs.clear();
  348. }
  349. /**
  350. * Checks whether given model tree object is of given type.
  351. *
  352. * This method is useful when processing model tree objects that are of unknown type. For example, a function
  353. * may return {@link module:engine/model/documentfragment~DocumentFragment} or {@link module:engine/model/node~Node}
  354. * that can be either text node or element. This method can be used to check what kind of object is returned.
  355. *
  356. * obj.is( 'node' ); // true for any node, false for document fragment
  357. * obj.is( 'documentFragment' ); // true for document fragment, false for any node
  358. * obj.is( 'element' ); // true for any element, false for text node or document fragment
  359. * obj.is( 'element', 'paragraph' ); // true only for element which name is 'paragraph'
  360. * obj.is( 'paragraph' ); // shortcut for obj.is( 'element', 'paragraph' )
  361. * obj.is( 'text' ); // true for text node, false for element and document fragment
  362. * obj.is( 'textProxy' ); // true for text proxy object
  363. *
  364. * @method #is
  365. * @param {'element'|'rootElement'|'text'|'textProxy'|'documentFragment'} type
  366. * @returns {Boolean}
  367. */
  368. }
  369. /**
  370. * The node's parent does not contain this node.
  371. *
  372. * This error may be thrown from corrupted trees.
  373. *
  374. * @error model-node-not-found-in-parent
  375. */