node.js 15 KB

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