diff --git a/core/events/events_block_field_intermediate_change.ts b/core/events/events_block_field_intermediate_change.ts index 1e19a04a6..264f910a8 100644 --- a/core/events/events_block_field_intermediate_change.ts +++ b/core/events/events_block_field_intermediate_change.ts @@ -122,6 +122,36 @@ export class BlockFieldIntermediateChange extends BlockBase { override isNull(): boolean { return this.oldValue === this.newValue; } + + /** + * Run a change event. + * + * @param forward True if run forward, false if run backward (undo). + */ + override run(forward: boolean) { + const workspace = this.getEventWorkspace_(); + if (!this.blockId) { + throw new Error( + 'The block ID is undefined. Either pass a block to ' + + 'the constructor, or call fromJson', + ); + } + const block = workspace.getBlockById(this.blockId); + if (!block) { + throw new Error( + 'The associated block is undefined. Either pass a ' + + 'block to the constructor, or call fromJson', + ); + } + + const value = forward ? this.newValue : this.oldValue; + const field = block.getField(this.name!); + if (field) { + field.setValue(value); + } else { + console.warn("Can't set non-existent field: " + this.name); + } + } } export interface BlockFieldIntermediateChangeJson extends BlockBaseJson { diff --git a/tests/mocha/event_block_field_intermediate_change_test.js b/tests/mocha/event_block_field_intermediate_change_test.js index e8a71effb..4d441e5d6 100644 --- a/tests/mocha/event_block_field_intermediate_change_test.js +++ b/tests/mocha/event_block_field_intermediate_change_test.js @@ -35,4 +35,38 @@ suite('Field Intermediate Change Event', function () { chai.assert.deepEqual(newEvent, origEvent); }); }); + + suite('Change Value', function () { + test("running forward changes the block's value to new value", function () { + const block = this.workspace.newBlock('text', 'block_id'); + const origEvent = new Blockly.Events.BlockFieldIntermediateChange( + block, + 'TEXT', + 'old value', + 'new value', + ); + origEvent.run(true); + + chai.assert.deepEqual( + block.getField(origEvent.name).getValue(), + 'new value', + ); + }); + + test("running backward changes the block's value to old value", function () { + const block = this.workspace.newBlock('text', 'block_id'); + const origEvent = new Blockly.Events.BlockFieldIntermediateChange( + block, + 'TEXT', + 'old value', + 'new value', + ); + origEvent.run(false); + + chai.assert.deepEqual( + block.getField(origEvent.name).getValue(), + 'old value', + ); + }); + }); });