Parcourir la source

Added method "DocumentFragment#getNodeByPath()".

Kamil Piechaczek il y a 8 ans
Parent
commit
6579c8406b

+ 21 - 0
packages/ckeditor5-engine/src/model/documentfragment.js

@@ -172,6 +172,27 @@ export default class DocumentFragment {
 	}
 
 	/**
+	 * Returns a descendant node by its path relative to this element.
+	 *
+	 *		// <this>a<b>c</b></this>
+	 *		this.getNodeByPath( [ 0 ] );     // -> "a"
+	 *		this.getNodeByPath( [ 1 ] );     // -> <b>
+	 *		this.getNodeByPath( [ 1, 0 ] );  // -> "c"
+	 *
+	 * @param {Array.<Number>} relativePath Path of the node to find, relative to this element.
+	 * @returns {module:engine/model/node~Node|module:engine/model/documentfragment~DocumentFragment}
+	 */
+	getNodeByPath( relativePath ) {
+		let node = this; // eslint-disable-line consistent-this
+
+		for ( const index of relativePath ) {
+			node = node.getChild( index );
+		}
+
+		return node;
+	}
+
+	/**
 	 * Converts offset "position" to index "position".
 	 *
 	 * Returns index of a node that occupies given offset. If given offset is too low, returns `0`. If given offset is

+ 21 - 0
packages/ckeditor5-engine/tests/model/documentfragment.js

@@ -300,4 +300,25 @@ describe( 'DocumentFragment', () => {
 			expect( deserialized.getChild( 1 ).parent ).to.equal( deserialized );
 		} );
 	} );
+
+	describe( 'getNodeByPath', () => {
+		it( 'should return the whole document fragment if path is empty', () => {
+			const frag = new DocumentFragment();
+
+			expect( frag.getNodeByPath( [] ) ).to.equal( frag );
+		} );
+
+		it( 'should return a descendant of this node', () => {
+			const image = new Element( 'image' );
+			const element = new Element( 'elem', [], [
+				new Element( 'elem', [], [
+					new Text( 'foo' ),
+					image
+				] )
+			] );
+			const frag = new DocumentFragment( element );
+
+			expect( frag.getNodeByPath( [ 0, 0, 1 ] ) ).to.equal( image );
+		} );
+	} );
 } );