8
0

node.js 12 KB

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