Browse Source

Add startsWith method to SchemaContext.

Maciej Gołaszewski 6 years ago
parent
commit
42beccc5ba

+ 17 - 0
packages/ckeditor5-engine/src/model/schema.js

@@ -1268,6 +1268,23 @@ export class SchemaContext {
 	endsWith( query ) {
 		return Array.from( this.getNames() ).join( ' ' ).endsWith( query );
 	}
+
+	/**
+	 * Checks whether the context starts with the given nodes.
+	 *
+	 *		const ctx = new SchemaContext( [ rootElement, paragraphElement, textNode ] );
+	 *
+	 *		ctx.endsWith( '$root' ); // -> true
+	 *		ctx.endsWith( '$root paragraph' ); // -> true
+	 *		ctx.endsWith( '$text' ); // -> false
+	 *		ctx.endsWith( 'paragraph' ); // -> false
+	 *
+	 * @param {String} query
+	 * @returns {Boolean}
+	 */
+	startsWith( query ) {
+		return Array.from( this.getNames() ).join( ' ' ).startsWith( query );
+	}
 }
 
 /**

+ 56 - 0
packages/ckeditor5-engine/tests/model/schema.js

@@ -3249,4 +3249,60 @@ describe( 'SchemaContext', () => {
 			expect( ctx.endsWith( 'bar', 'foo' ) ).to.be.false;
 		} );
 	} );
+
+	describe( 'startsWith()', () => {
+		it( 'returns true if the start of the context matches the query - 1 item', () => {
+			const ctx = new SchemaContext( [ 'foo', 'bar', 'bom', 'dom' ] );
+
+			expect( ctx.startsWith( 'foo' ) ).to.be.true;
+		} );
+
+		it( 'returns true if the start of the context matches the query - 2 items', () => {
+			const ctx = new SchemaContext( [ 'foo', 'bar', 'bom', 'dom' ] );
+
+			expect( ctx.startsWith( 'foo bar' ) ).to.be.true;
+		} );
+
+		it( 'returns true if the start of the context matches the query - full match of 3 items', () => {
+			const ctx = new SchemaContext( [ 'foo', 'bar', 'bom' ] );
+
+			expect( ctx.startsWith( 'foo bar bom' ) ).to.be.true;
+		} );
+
+		it( 'returns true if the start of the context matches the query - full match of 1 items', () => {
+			const ctx = new SchemaContext( [ 'foo' ] );
+
+			expect( ctx.startsWith( 'foo' ) ).to.be.true;
+		} );
+
+		it( 'returns true if not only the start of the context matches the query', () => {
+			const ctx = new SchemaContext( [ 'foo', 'foo', 'foo', 'foo' ] );
+
+			expect( ctx.startsWith( 'foo foo' ) ).to.be.true;
+		} );
+
+		it( 'returns false if query matches the middle of the context', () => {
+			const ctx = new SchemaContext( [ 'foo', 'bar', 'bom', 'dom' ] );
+
+			expect( ctx.startsWith( 'bom' ) ).to.be.false;
+		} );
+
+		it( 'returns false if query matches the end of the context', () => {
+			const ctx = new SchemaContext( [ 'foo', 'bar', 'bom', 'dom' ] );
+
+			expect( ctx.startsWith( 'dom' ) ).to.be.false;
+		} );
+
+		it( 'returns false if query does not match', () => {
+			const ctx = new SchemaContext( [ 'foo', 'bar', 'bom', 'dom' ] );
+
+			expect( ctx.startsWith( 'dom bar' ) ).to.be.false;
+		} );
+
+		it( 'returns false if query is longer than context', () => {
+			const ctx = new SchemaContext( [ 'foo' ] );
+
+			expect( ctx.startsWith( 'bar', 'foo' ) ).to.be.false;
+		} );
+	} );
 } );