Browse Source

Added: engine.treeView.Matcher#getElementName.

Szymon Cofalik 9 years ago
parent
commit
dd3108addc

+ 13 - 0
packages/ckeditor5-engine/src/treeview/matcher.js

@@ -195,6 +195,19 @@ export default class Matcher {
 
 		return results.length > 0 ? results : null;
 	}
+
+	/**
+	 * Returns the name of the element to match if there is exactly one pattern added to the matcher instance
+	 * and it matches element name defined by `string` (not `RegExp`). Otherwise, returns `null`.
+	 *
+	 * @returns {String|null} Element name trying to match.
+	 */
+	getElementName() {
+		return this._patterns.length == 1 && this._patterns[ 0 ].name && !( this._patterns[ 0 ].name instanceof RegExp ) ?
+			this._patterns[ 0 ].name :
+			null;
+	}
+
 }
 
 // Returns match information if {@link engine.treeView.Element element} is matching provided pattern.

+ 32 - 0
packages/ckeditor5-engine/tests/treeview/matcher.js

@@ -374,4 +374,36 @@ describe( 'Matcher', () => {
 			expect( matcher.matchAll( el3 ) ).to.be.null;
 		} );
 	} );
+
+	describe( 'getElementName', () => {
+		it( 'should return null if there are no patterns in the matcher instance', () => {
+			const matcher = new Matcher();
+
+			expect( matcher.getElementName() ).to.be.null;
+		} );
+
+		it( 'should return null if pattern has no name property', () => {
+			const matcher = new Matcher( { class: 'foo' } );
+
+			expect( matcher.getElementName() ).to.be.null;
+		} );
+
+		it( 'should return null if pattern has name property specified as RegExp', () => {
+			const matcher = new Matcher( { name: /foo.*/ } );
+
+			expect( matcher.getElementName() ).to.be.null;
+		} );
+
+		it( 'should return element name if matcher has one patter with name property specified as string', () => {
+			const matcher = new Matcher( { name: 'div' } );
+
+			expect( matcher.getElementName() ).to.equal( 'div' );
+		} );
+
+		it( 'should return null if matcher has more than one pattern', () => {
+			const matcher = new Matcher( { name: 'div' }, { class: 'foo' } );
+
+			expect( matcher.getElementName() ).to.be.null;
+		} );
+	} );
 } );