浏览代码

Make label view removable from the form header if it is not necessary

panr 5 年之前
父节点
当前提交
612207411c

+ 31 - 4
packages/ckeditor5-ui/src/formheader/formheaderview.js

@@ -78,9 +78,15 @@ export default class FormHeaderView extends View {
 			children: this.children
 		} );
 
-		const label = new View( locale );
+		/**
+		 * A label view, which text can be set through `options.label` or {@link #label}.
+		 *
+		 * @readonly
+		 * @member {module:ui/view~View}
+		 */
+		this.labelView = new View( locale );
 
-		label.setTemplate( {
+		this.labelView.setTemplate( {
 			tag: 'span',
 			attributes: {
 				class: [
@@ -93,7 +99,28 @@ export default class FormHeaderView extends View {
 			]
 		} );
 
-		// Append the label view only if label text has been set.
-		this.label && this.children.add( label );
+		this.label && this.children.add( this.labelView );
+
+		this.on( 'set:label', () => {
+			if ( !this.children.has( this.labelView ) ) {
+				this.children.add( this.labelView );
+			}
+		} );
+	}
+
+	render() {
+		super.render();
+
+		this.on( 'change:label', evt => {
+			if ( this.children.has( this.labelView ) ) {
+				if ( !evt.source.label ) {
+					// Remove the label view if it is no longer necessary (eg.: label text is empty).
+					this.children.remove( this.labelView );
+				}
+			} else {
+				// Append label view only if it has not been added while creating the instance, but after render.
+				this.children.add( this.labelView );
+			}
+		} );
 	}
 }

+ 21 - 2
packages/ckeditor5-ui/tests/formheader/formheaderview.js

@@ -17,7 +17,9 @@ describe( 'FormHeaderView', () => {
 	} );
 
 	afterEach( () => {
-		view.element.remove();
+		if ( view.element ) {
+			view.element.remove();
+		}
 	} );
 
 	describe( 'constructor()', () => {
@@ -27,7 +29,24 @@ describe( 'FormHeaderView', () => {
 
 		it( 'should create view#children collection', () => {
 			expect( view.children ).to.be.instanceOf( ViewCollection );
+			expect( view.children ).to.have.length( 0 );
+		} );
+
+		it( 'should contain label view only when view#label is defined', () => {
+			view = new FormHeaderView( locale, {
+				label: 'Foo label'
+			} );
+
+			view.render();
+
+			expect( view.children ).to.be.instanceOf( ViewCollection );
 			expect( view.children ).to.have.length( 1 );
+
+			expect( view.children.first.element.classList.contains( 'ck-form__header__label' ) ).to.be.true;
+
+			view.label = '';
+
+			expect( view.children ).to.have.length( 0 );
 		} );
 
 		it( 'should set view#label', () => {
@@ -89,7 +108,7 @@ describe( 'FormHeaderView', () => {
 
 				view.children.add( child );
 
-				expect( view.element.childNodes[ 1 ] ).to.equal( child.element );
+				expect( view.element.childNodes[ 0 ] ).to.equal( child.element );
 
 				view.destroy();
 			} );