8
0

node.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. /**
  2. * @license Copyright (c) 2003-2020, 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. * Returns true if the node is in a tree rooted in the document (is a descendant of one of its roots).
  169. *
  170. * @returns {Boolean}
  171. */
  172. isAttached() {
  173. return this.root.is( 'rootElement' );
  174. }
  175. /**
  176. * Gets path to the node. The path is an array containing starting offsets of consecutive ancestors of this node,
  177. * beginning from {@link module:engine/model/node~Node#root root}, down to this node's starting offset. The path can be used to
  178. * create {@link module:engine/model/position~Position Position} instance.
  179. *
  180. * const abc = new Text( 'abc' );
  181. * const foo = new Text( 'foo' );
  182. * const h1 = new Element( 'h1', null, new Text( 'header' ) );
  183. * const p = new Element( 'p', null, [ abc, foo ] );
  184. * const div = new Element( 'div', null, [ h1, p ] );
  185. * foo.getPath(); // Returns [ 1, 3 ]. `foo` is in `p` which is in `div`. `p` starts at offset 1, while `foo` at 3.
  186. * h1.getPath(); // Returns [ 0 ].
  187. * div.getPath(); // Returns [].
  188. *
  189. * @returns {Array.<Number>} The path.
  190. */
  191. getPath() {
  192. const path = [];
  193. let node = this; // eslint-disable-line consistent-this
  194. while ( node.parent ) {
  195. path.unshift( node.startOffset );
  196. node = node.parent;
  197. }
  198. return path;
  199. }
  200. /**
  201. * Returns ancestors array of this node.
  202. *
  203. * @param {Object} options Options object.
  204. * @param {Boolean} [options.includeSelf=false] When set to `true` this node will be also included in parent's array.
  205. * @param {Boolean} [options.parentFirst=false] When set to `true`, array will be sorted from node's parent to root element,
  206. * otherwise root element will be the first item in the array.
  207. * @returns {Array} Array with ancestors.
  208. */
  209. getAncestors( options = { includeSelf: false, parentFirst: false } ) {
  210. const ancestors = [];
  211. let parent = options.includeSelf ? this : this.parent;
  212. while ( parent ) {
  213. ancestors[ options.parentFirst ? 'push' : 'unshift' ]( parent );
  214. parent = parent.parent;
  215. }
  216. return ancestors;
  217. }
  218. /**
  219. * Returns a {@link module:engine/model/element~Element} or {@link module:engine/model/documentfragment~DocumentFragment}
  220. * which is a common ancestor of both nodes.
  221. *
  222. * @param {module:engine/model/node~Node} node The second node.
  223. * @param {Object} options Options object.
  224. * @param {Boolean} [options.includeSelf=false] When set to `true` both nodes will be considered "ancestors" too.
  225. * Which means that if e.g. node A is inside B, then their common ancestor will be B.
  226. * @returns {module:engine/model/element~Element|module:engine/model/documentfragment~DocumentFragment|null}
  227. */
  228. getCommonAncestor( node, options = {} ) {
  229. const ancestorsA = this.getAncestors( options );
  230. const ancestorsB = node.getAncestors( options );
  231. let i = 0;
  232. while ( ancestorsA[ i ] == ancestorsB[ i ] && ancestorsA[ i ] ) {
  233. i++;
  234. }
  235. return i === 0 ? null : ancestorsA[ i - 1 ];
  236. }
  237. /**
  238. * Returns whether this node is before given node. `false` is returned if nodes are in different trees (for example,
  239. * in different {@link module:engine/model/documentfragment~DocumentFragment}s).
  240. *
  241. * @param {module:engine/model/node~Node} node Node to compare with.
  242. * @returns {Boolean}
  243. */
  244. isBefore( node ) {
  245. // Given node is not before this node if they are same.
  246. if ( this == node ) {
  247. return false;
  248. }
  249. // Return `false` if it is impossible to compare nodes.
  250. if ( this.root !== node.root ) {
  251. return false;
  252. }
  253. const thisPath = this.getPath();
  254. const nodePath = node.getPath();
  255. const result = compareArrays( thisPath, nodePath );
  256. switch ( result ) {
  257. case 'prefix':
  258. return true;
  259. case 'extension':
  260. return false;
  261. default:
  262. return thisPath[ result ] < nodePath[ result ];
  263. }
  264. }
  265. /**
  266. * Returns whether this node is after given node. `false` is returned if nodes are in different trees (for example,
  267. * in different {@link module:engine/model/documentfragment~DocumentFragment}s).
  268. *
  269. * @param {module:engine/model/node~Node} node Node to compare with.
  270. * @returns {Boolean}
  271. */
  272. isAfter( node ) {
  273. // Given node is not before this node if they are same.
  274. if ( this == node ) {
  275. return false;
  276. }
  277. // Return `false` if it is impossible to compare nodes.
  278. if ( this.root !== node.root ) {
  279. return false;
  280. }
  281. // In other cases, just check if the `node` is before, and return the opposite.
  282. return !this.isBefore( node );
  283. }
  284. /**
  285. * Checks if the node has an attribute with given key.
  286. *
  287. * @param {String} key Key of attribute to check.
  288. * @returns {Boolean} `true` if attribute with given key is set on node, `false` otherwise.
  289. */
  290. hasAttribute( key ) {
  291. return this._attrs.has( key );
  292. }
  293. /**
  294. * Gets an attribute value for given key or `undefined` if that attribute is not set on node.
  295. *
  296. * @param {String} key Key of attribute to look for.
  297. * @returns {*} Attribute value or `undefined`.
  298. */
  299. getAttribute( key ) {
  300. return this._attrs.get( key );
  301. }
  302. /**
  303. * Returns iterator that iterates over this node's attributes.
  304. *
  305. * Attributes are returned as arrays containing two items. First one is attribute key and second is attribute value.
  306. * This format is accepted by native `Map` object and also can be passed in `Node` constructor.
  307. *
  308. * @returns {Iterable.<*>}
  309. */
  310. getAttributes() {
  311. return this._attrs.entries();
  312. }
  313. /**
  314. * Returns iterator that iterates over this node's attribute keys.
  315. *
  316. * @returns {Iterable.<String>}
  317. */
  318. getAttributeKeys() {
  319. return this._attrs.keys();
  320. }
  321. /**
  322. * Converts `Node` to plain object and returns it.
  323. *
  324. * @returns {Object} `Node` converted to plain object.
  325. */
  326. toJSON() {
  327. const json = {};
  328. // Serializes attributes to the object.
  329. // attributes = { a: 'foo', b: 1, c: true }.
  330. if ( this._attrs.size ) {
  331. json.attributes = Array.from( this._attrs ).reduce( ( result, attr ) => {
  332. result[ attr[ 0 ] ] = attr[ 1 ];
  333. return result;
  334. }, {} );
  335. }
  336. return json;
  337. }
  338. /**
  339. * Checks whether this object is of the given type.
  340. *
  341. * This method is useful when processing model objects that are of unknown type. For example, a function
  342. * may return a {@link module:engine/model/documentfragment~DocumentFragment} or a {@link module:engine/model/node~Node}
  343. * that can be either a text node or an element. This method can be used to check what kind of object is returned.
  344. *
  345. * someObject.is( 'element' ); // -> true if this is an element
  346. * someObject.is( 'node' ); // -> true if this is a node (a text node or an element)
  347. * someObject.is( 'documentFragment' ); // -> true if this is a document fragment
  348. *
  349. * Since this method is also available on a range of view objects, you can prefix the type of the object with
  350. * `model:` or `view:` to check, for example, if this is the model's or view's element:
  351. *
  352. * modelElement.is( 'model:element' ); // -> true
  353. * modelElement.is( 'view:element' ); // -> false
  354. *
  355. * By using this method it is also possible to check a name of an element:
  356. *
  357. * imageElement.is( 'element', 'image' ); // -> true
  358. * imageElement.is( 'element', 'image' ); // -> same as above
  359. * imageElement.is( 'model:element', 'image' ); // -> same as above, but more precise
  360. *
  361. * The list of model objects which implement the `is()` method:
  362. *
  363. * * {@link module:engine/model/node~Node#is `Node#is()`}
  364. * * {@link module:engine/model/text~Text#is `Text#is()`}
  365. * * {@link module:engine/model/element~Element#is `Element#is()`}
  366. * * {@link module:engine/model/rootelement~RootElement#is `RootElement#is()`}
  367. * * {@link module:engine/model/position~Position#is `Position#is()`}
  368. * * {@link module:engine/model/liveposition~LivePosition#is `LivePosition#is()`}
  369. * * {@link module:engine/model/range~Range#is `Range#is()`}
  370. * * {@link module:engine/model/liverange~LiveRange#is `LiveRange#is()`}
  371. * * {@link module:engine/model/documentfragment~DocumentFragment#is `DocumentFragment#is()`}
  372. * * {@link module:engine/model/selection~Selection#is `Selection#is()`}
  373. * * {@link module:engine/model/documentselection~DocumentSelection#is `DocumentSelection#is()`}
  374. * * {@link module:engine/model/markercollection~Marker#is `Marker#is()`}
  375. * * {@link module:engine/model/textproxy~TextProxy#is `TextProxy#is()`}
  376. *
  377. * @method #is
  378. * @param {String} type Type to check.
  379. * @returns {Boolean}
  380. */
  381. is( type ) {
  382. return type === 'node' || type === 'model:node';
  383. }
  384. /**
  385. * Creates a copy of this node, that is a node with exactly same attributes, and returns it.
  386. *
  387. * @protected
  388. * @returns {module:engine/model/node~Node} Node with same attributes as this node.
  389. */
  390. _clone() {
  391. return new Node( this._attrs );
  392. }
  393. /**
  394. * Removes this node from it's parent.
  395. *
  396. * @see module:engine/model/writer~Writer#remove
  397. * @protected
  398. */
  399. _remove() {
  400. this.parent._removeChildren( this.index );
  401. }
  402. /**
  403. * Sets attribute on the node. If attribute with the same key already is set, it's value is overwritten.
  404. *
  405. * @see module:engine/model/writer~Writer#setAttribute
  406. * @protected
  407. * @param {String} key Key of attribute to set.
  408. * @param {*} value Attribute value.
  409. */
  410. _setAttribute( key, value ) {
  411. this._attrs.set( key, value );
  412. }
  413. /**
  414. * Removes all attributes from the node and sets given attributes.
  415. *
  416. * @see module:engine/model/writer~Writer#setAttributes
  417. * @protected
  418. * @param {Object} [attrs] Attributes to set. See {@link module:utils/tomap~toMap} for a list of accepted values.
  419. */
  420. _setAttributesTo( attrs ) {
  421. this._attrs = toMap( attrs );
  422. }
  423. /**
  424. * Removes an attribute with given key from the node.
  425. *
  426. * @see module:engine/model/writer~Writer#removeAttribute
  427. * @protected
  428. * @param {String} key Key of attribute to remove.
  429. * @returns {Boolean} `true` if the attribute was set on the element, `false` otherwise.
  430. */
  431. _removeAttribute( key ) {
  432. return this._attrs.delete( key );
  433. }
  434. /**
  435. * Removes all attributes from the node.
  436. *
  437. * @see module:engine/model/writer~Writer#clearAttributes
  438. * @protected
  439. */
  440. _clearAttributes() {
  441. this._attrs.clear();
  442. }
  443. }