Kaynağa Gözat

Added treeView.Node.getAncestors methods.

Szymon Kupś 9 yıl önce
ebeveyn
işleme
11d4a5c6b3

+ 19 - 0
packages/ckeditor5-engine/src/treeview/node.js

@@ -106,6 +106,25 @@ export default class Node {
 	}
 
 	/**
+	 * Returns ancestors array of node. Node itself is not included in the array.
+	 *
+	 * @param {Boolean} [parentFirst=false] When set to `true`, array will be sorted from node's parent to root element,
+	 * otherwise root element will be the first item in the array.
+	 * @returns {Array} Array with ancestors. Empty array is returned when node has no ancestors.
+	 */
+	getAncestors( parentFirst ) {
+		const ancestors = [];
+		let parent = this.parent;
+
+		while ( parent !== null ) {
+			ancestors[ parentFirst ? 'push' : 'unshift' ]( parent );
+			parent = parent.parent;
+		}
+
+		return ancestors;
+	}
+
+	/**
 	 * Sets the {@link engine.treeView.TreeView} of the node. Note that not all of nodes need to have {@link engine.treeView.TreeView}
 	 * assigned, see {@link engine.treeView.Node#getTreeView}.
 	 *

+ 22 - 0
packages/ckeditor5-engine/tests/treeview/node.js

@@ -57,6 +57,28 @@ describe( 'Node', () => {
 		} );
 	} );
 
+	describe( 'getAncestors', () => {
+		it( 'should return empty array for node without ancestors', () => {
+			const result = root.getAncestors();
+			expect( result ).to.be.an( 'array' );
+			expect( result.length ).to.equal( 0 );
+		} );
+
+		it( 'should return array of ancestors', () => {
+			const result = charR.getAncestors();
+			expect( result.length ).to.equal( 2 );
+			expect( result[ 0 ] ).to.equal( root );
+			expect( result[ 1 ] ).to.equal( two );
+		} );
+
+		it( 'should return array of ancestors starting from parent', () => {
+			const result = charR.getAncestors( true );
+			expect( result.length ).to.equal( 2 );
+			expect( result[ 0 ] ).to.equal( two );
+			expect( result[ 1 ] ).to.equal( root );
+		} );
+	} );
+
 	describe( 'getIndex', () => {
 		it( 'should return null if the parent is null', () => {
 			expect( root.getIndex() ).to.be.null;