8
0

node.js 15 KB

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