node.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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/view/node
  7. */
  8. import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
  9. import EmitterMixin from '@ckeditor/ckeditor5-utils/src/emittermixin';
  10. import mix from '@ckeditor/ckeditor5-utils/src/mix';
  11. import compareArrays from '@ckeditor/ckeditor5-utils/src/comparearrays';
  12. import { clone } from 'lodash-es';
  13. // To check if component is loaded more than once.
  14. import '@ckeditor/ckeditor5-utils/src/version';
  15. /**
  16. * Abstract tree view node class.
  17. *
  18. * This is an abstract class. Its constructor should not be used directly.
  19. * Use the {@link module:engine/view/element~Element} class to create view elements
  20. * or {@link module:engine/view/text~Text} class to create view text nodes.
  21. *
  22. * @abstract
  23. */
  24. export default class Node {
  25. /**
  26. * Creates a tree view node.
  27. */
  28. constructor() {
  29. /**
  30. * Parent element. Null by default. Set by {@link module:engine/view/element~Element#_insertChild}.
  31. *
  32. * @readonly
  33. * @member {module:engine/view/element~Element|module:engine/view/documentfragment~DocumentFragment|null}
  34. */
  35. this.parent = null;
  36. }
  37. /**
  38. * Index of the node in the parent element or null if the node has no parent.
  39. *
  40. * Accessing this property throws an error if this node's parent element does not contain it.
  41. * This means that view tree got broken.
  42. *
  43. * @readonly
  44. * @type {Number|null}
  45. */
  46. get index() {
  47. let pos;
  48. if ( !this.parent ) {
  49. return null;
  50. }
  51. // No parent or child doesn't exist in parent's children.
  52. if ( ( pos = this.parent.getChildIndex( this ) ) == -1 ) {
  53. /**
  54. * The node's parent does not contain this node. It means that the document tree is corrupted.
  55. *
  56. * @error view-node-not-found-in-parent
  57. */
  58. throw new CKEditorError( 'view-node-not-found-in-parent: The node\'s parent does not contain this node.', this );
  59. }
  60. return pos;
  61. }
  62. /**
  63. * Node's next sibling, or `null` if it is the last child.
  64. *
  65. * @readonly
  66. * @type {module:engine/view/node~Node|null}
  67. */
  68. get nextSibling() {
  69. const index = this.index;
  70. return ( index !== null && this.parent.getChild( index + 1 ) ) || null;
  71. }
  72. /**
  73. * Node's previous sibling, or `null` if it is the first child.
  74. *
  75. * @readonly
  76. * @type {module:engine/view/node~Node|null}
  77. */
  78. get previousSibling() {
  79. const index = this.index;
  80. return ( index !== null && this.parent.getChild( index - 1 ) ) || null;
  81. }
  82. /**
  83. * Top-most ancestor of the node. If the node has no parent it is the root itself.
  84. *
  85. * @readonly
  86. * @type {module:engine/view/node~Node|module:engine/view/documentfragment~DocumentFragment}
  87. */
  88. get root() {
  89. let root = this; // eslint-disable-line consistent-this
  90. while ( root.parent ) {
  91. root = root.parent;
  92. }
  93. return root;
  94. }
  95. /**
  96. * {@link module:engine/view/document~Document View document} that owns this node, or `null` if the node is inside
  97. * {@link module:engine/view/documentfragment~DocumentFragment document fragment}.
  98. *
  99. * @readonly
  100. * @type {module:engine/view/document~Document|null}
  101. */
  102. get document() {
  103. // Parent might be Node, null or DocumentFragment.
  104. if ( this.parent instanceof Node ) {
  105. return this.parent.document;
  106. } else {
  107. return null;
  108. }
  109. }
  110. /**
  111. * Gets a path to the node. The path is an array containing indices of consecutive ancestors of this node,
  112. * beginning from {@link module:engine/view/node~Node#root root}, down to this node's index.
  113. *
  114. * const abc = downcastWriter.createText( 'abc' );
  115. * const foo = downcastWriter.createText( 'foo' );
  116. * const h1 = downcastWriter.createElement( 'h1', null, downcastWriter.createText( 'header' ) );
  117. * const p = downcastWriter.createElement( 'p', null, [ abc, foo ] );
  118. * const div = downcastWriter.createElement( 'div', null, [ h1, p ] );
  119. * foo.getPath(); // Returns [ 1, 3 ]. `foo` is in `p` which is in `div`. `p` starts at offset 1, while `foo` at 3.
  120. * h1.getPath(); // Returns [ 0 ].
  121. * div.getPath(); // Returns [].
  122. *
  123. * @returns {Array.<Number>} The path.
  124. */
  125. getPath() {
  126. const path = [];
  127. let node = this; // eslint-disable-line consistent-this
  128. while ( node.parent ) {
  129. path.unshift( node.index );
  130. node = node.parent;
  131. }
  132. return path;
  133. }
  134. /**
  135. * Returns ancestors array of this node.
  136. *
  137. * @param {Object} options Options object.
  138. * @param {Boolean} [options.includeSelf=false] When set to `true` this node will be also included in parent's array.
  139. * @param {Boolean} [options.parentFirst=false] When set to `true`, array will be sorted from node's parent to root element,
  140. * otherwise root element will be the first item in the array.
  141. * @returns {Array} Array with ancestors.
  142. */
  143. getAncestors( options = { includeSelf: false, parentFirst: false } ) {
  144. const ancestors = [];
  145. let parent = options.includeSelf ? this : this.parent;
  146. while ( parent ) {
  147. ancestors[ options.parentFirst ? 'push' : 'unshift' ]( parent );
  148. parent = parent.parent;
  149. }
  150. return ancestors;
  151. }
  152. /**
  153. * Returns a {@link module:engine/view/element~Element} or {@link module:engine/view/documentfragment~DocumentFragment}
  154. * which is a common ancestor of both nodes.
  155. *
  156. * @param {module:engine/view/node~Node} node The second node.
  157. * @param {Object} options Options object.
  158. * @param {Boolean} [options.includeSelf=false] When set to `true` both nodes will be considered "ancestors" too.
  159. * Which means that if e.g. node A is inside B, then their common ancestor will be B.
  160. * @returns {module:engine/view/element~Element|module:engine/view/documentfragment~DocumentFragment|null}
  161. */
  162. getCommonAncestor( node, options = {} ) {
  163. const ancestorsA = this.getAncestors( options );
  164. const ancestorsB = node.getAncestors( options );
  165. let i = 0;
  166. while ( ancestorsA[ i ] == ancestorsB[ i ] && ancestorsA[ i ] ) {
  167. i++;
  168. }
  169. return i === 0 ? null : ancestorsA[ i - 1 ];
  170. }
  171. /**
  172. * Returns whether this node is before given node. `false` is returned if nodes are in different trees (for example,
  173. * in different {@link module:engine/view/documentfragment~DocumentFragment}s).
  174. *
  175. * @param {module:engine/view/node~Node} node Node to compare with.
  176. * @returns {Boolean}
  177. */
  178. isBefore( node ) {
  179. // Given node is not before this node if they are same.
  180. if ( this == node ) {
  181. return false;
  182. }
  183. // Return `false` if it is impossible to compare nodes.
  184. if ( this.root !== node.root ) {
  185. return false;
  186. }
  187. const thisPath = this.getPath();
  188. const nodePath = node.getPath();
  189. const result = compareArrays( thisPath, nodePath );
  190. switch ( result ) {
  191. case 'prefix':
  192. return true;
  193. case 'extension':
  194. return false;
  195. default:
  196. return thisPath[ result ] < nodePath[ result ];
  197. }
  198. }
  199. /**
  200. * Returns whether this node is after given node. `false` is returned if nodes are in different trees (for example,
  201. * in different {@link module:engine/view/documentfragment~DocumentFragment}s).
  202. *
  203. * @param {module:engine/view/node~Node} node Node to compare with.
  204. * @returns {Boolean}
  205. */
  206. isAfter( node ) {
  207. // Given node is not before this node if they are same.
  208. if ( this == node ) {
  209. return false;
  210. }
  211. // Return `false` if it is impossible to compare nodes.
  212. if ( this.root !== node.root ) {
  213. return false;
  214. }
  215. // In other cases, just check if the `node` is before, and return the opposite.
  216. return !this.isBefore( node );
  217. }
  218. /**
  219. * Removes node from parent.
  220. *
  221. * @protected
  222. */
  223. _remove() {
  224. this.parent._removeChildren( this.index );
  225. }
  226. /**
  227. * @protected
  228. * @param {module:engine/view/document~ChangeType} type Type of the change.
  229. * @param {module:engine/view/node~Node} node Changed node.
  230. * @fires change
  231. */
  232. _fireChange( type, node ) {
  233. this.fire( 'change:' + type, node );
  234. if ( this.parent ) {
  235. this.parent._fireChange( type, node );
  236. }
  237. }
  238. /**
  239. * Custom toJSON method to solve child-parent circular dependencies.
  240. *
  241. * @returns {Object} Clone of this object with the parent property removed.
  242. */
  243. toJSON() {
  244. const json = clone( this );
  245. // Due to circular references we need to remove parent reference.
  246. delete json.parent;
  247. return json;
  248. }
  249. /**
  250. * Checks whether this object is of the given type.
  251. *
  252. * This method is useful when processing view objects that are of unknown type. For example, a function
  253. * may return a {@link module:engine/view/documentfragment~DocumentFragment} or a {@link module:engine/view/node~Node}
  254. * that can be either a text node or an element. This method can be used to check what kind of object is returned.
  255. *
  256. * someObject.is( 'element' ); // -> true if this is an element
  257. * someObject.is( 'node' ); // -> true if this is a node (a text node or an element)
  258. * someObject.is( 'documentFragment' ); // -> true if this is a document fragment
  259. *
  260. * Since this method is also available on a range of model objects, you can prefix the type of the object with
  261. * `model:` or `view:` to check, for example, if this is the model's or view's element:
  262. *
  263. * viewElement.is( 'view:element' ); // -> true
  264. * viewElement.is( 'model:element' ); // -> false
  265. *
  266. * By using this method it is also possible to check a name of an element:
  267. *
  268. * imgElement.is( 'img' ); // -> true
  269. * imgElement.is( 'element', 'img' ); // -> same as above
  270. * imgElement.is( 'view:element', 'img' ); // -> same as above, but more precise
  271. *
  272. * The list of view objects which implement the `is()` method:
  273. *
  274. * * {@link module:engine/view/attributeelement~AttributeElement#is `AttributeElement#is()`}
  275. * * {@link module:engine/view/containerelement~ContainerElement#is `ContainerElement#is()`}
  276. * * {@link module:engine/view/documentfragment~DocumentFragment#is `DocumentFragment#is()`}
  277. * * {@link module:engine/view/documentselection~DocumentSelection#is `DocumentSelection#is()`}
  278. * * {@link module:engine/view/editableelement~EditableElement#is `EditableElement#is()`}
  279. * * {@link module:engine/view/element~Element#is `Element#is()`}
  280. * * {@link module:engine/view/emptyelement~EmptyElement#is `EmptyElement#is()`}
  281. * * {@link module:engine/view/node~Node#is `Node#is()`}
  282. * * {@link module:engine/view/position~Position#is `Position#is()`}
  283. * * {@link module:engine/view/range~Range#is `Range#is()`}
  284. * * {@link module:engine/view/rooteditableelement~RootEditableElement#is `RootEditableElement#is()`}
  285. * * {@link module:engine/view/selection~Selection#is `Selection#is()`}
  286. * * {@link module:engine/view/text~Text#is `Text#is()`}
  287. * * {@link module:engine/view/textproxy~TextProxy#is `TextProxy#is()`}
  288. * * {@link module:engine/view/uielement~UIElement#is `UIElement#is()`}
  289. *
  290. * @method #is
  291. * @param {String} type
  292. * @returns {Boolean}
  293. */
  294. is( type ) {
  295. return type == 'node' || type == 'view:node';
  296. }
  297. /**
  298. * Clones this node.
  299. *
  300. * @protected
  301. * @method #_clone
  302. * @returns {module:engine/view/node~Node} Clone of this node.
  303. */
  304. /**
  305. * Checks if provided node is similar to this node.
  306. *
  307. * @method #isSimilar
  308. * @returns {Boolean} True if nodes are similar.
  309. */
  310. }
  311. /**
  312. * Fired when list of {@link module:engine/view/element~Element elements} children changes.
  313. *
  314. * Change event is bubbled – it is fired on all ancestors.
  315. *
  316. * @event change:children
  317. * @param {module:engine/view/node~Node} changedNode
  318. */
  319. /**
  320. * Fired when list of {@link module:engine/view/element~Element elements} attributes changes.
  321. *
  322. * Change event is bubbled – it is fired on all ancestors.
  323. *
  324. * @event change:attributes
  325. * @param {module:engine/view/node~Node} changedNode
  326. */
  327. /**
  328. * Fired when {@link module:engine/view/text~Text text nodes} data changes.
  329. *
  330. * Change event is bubbled – it is fired on all ancestors.
  331. *
  332. * @event change:text
  333. * @param {module:engine/view/node~Node} changedNode
  334. */
  335. /**
  336. * @event change
  337. */
  338. mix( Node, EmitterMixin );