Procházet zdrojové kódy

Updating command's value after executing.

Szymon Kupś před 9 roky
rodič
revize
d5cb76c846

+ 21 - 11
packages/ckeditor5-heading/src/headingcommand.js

@@ -40,17 +40,7 @@ export default class HeadingCommand extends Command {
 		this.set( 'value', this.defaultFormat );
 
 		// Listen on selection change and set current command's format to format in the current selection.
-		this.listenTo( editor.document.selection, 'change', () => {
-			const position = editor.document.selection.getFirstPosition();
-			const block = findTopmostBlock( position );
-
-			if ( block ) {
-				const format = this._getFormatById( block.name );
-
-				// TODO: What should happen if format is not found?
-				this.value = format;
-			}
-		} );
+		this.listenTo( editor.document.selection, 'change', () => this._updateValue() );
 	}
 
 	/**
@@ -128,6 +118,9 @@ export default class HeadingCommand extends Command {
 			// If range's selection start/end is placed directly in renamed block - we need to restore it's position
 			// after renaming, because renaming puts new element there.
 			doc.selection.setRanges( ranges, isSelectionBackward );
+
+			// Update command's value after change.
+			this._updateValue();
 		} );
 	}
 
@@ -141,6 +134,23 @@ export default class HeadingCommand extends Command {
 	_getFormatById( id ) {
 		return this.formats.find( item => item.id === id ) || this.defaultFormat;
 	}
+
+	/**
+	 * Updates command's {@link heading.HeadingCommand#value value} based on current selection.
+	 *
+	 * @private
+	 */
+	_updateValue() {
+		const position = this.editor.document.selection.getFirstPosition();
+		const block = findTopmostBlock( position );
+
+		if ( block ) {
+			const format = this._getFormatById( block.name );
+
+			// TODO: What should happen if format is not found?
+			this.value = format;
+		}
+	}
 }
 
 // Looks for the topmost element in the position's ancestor (up to an element in the root).

+ 10 - 0
packages/ckeditor5-heading/tests/headingcommand.js

@@ -65,6 +65,16 @@ describe( 'HeadingCommand', () => {
 	} );
 
 	describe( '_doExecute', () => {
+		it( 'should update value after execution', () => {
+			setData( document, '<paragraph>[]</paragraph>' );
+			command._doExecute( { formatId: 'heading1' } );
+
+			expect( getData( document ) ).to.equal( '<heading1>[]</heading1>' );
+			expect( command.value ).to.be.object;
+			expect( command.value.id ).to.equal( 'heading1' );
+			expect( command.value.viewElement ).to.equal( 'h2' );
+		} );
+
 		describe( 'custom options', () => {
 			it( 'should use provided batch', () => {
 				const batch = editor.document.batch();