Skip to content

Commit 96a354b

Browse files
feat: added intermediate event change (#7671)
* feat: added intermediate event change * fix: update prettier format for the code * fix: update comment style * fix: update test statements
1 parent 0a27e1c commit 96a354b

2 files changed

Lines changed: 64 additions & 0 deletions

File tree

core/events/events_block_field_intermediate_change.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,36 @@ export class BlockFieldIntermediateChange extends BlockBase {
122122
override isNull(): boolean {
123123
return this.oldValue === this.newValue;
124124
}
125+
126+
/**
127+
* Run a change event.
128+
*
129+
* @param forward True if run forward, false if run backward (undo).
130+
*/
131+
override run(forward: boolean) {
132+
const workspace = this.getEventWorkspace_();
133+
if (!this.blockId) {
134+
throw new Error(
135+
'The block ID is undefined. Either pass a block to ' +
136+
'the constructor, or call fromJson',
137+
);
138+
}
139+
const block = workspace.getBlockById(this.blockId);
140+
if (!block) {
141+
throw new Error(
142+
'The associated block is undefined. Either pass a ' +
143+
'block to the constructor, or call fromJson',
144+
);
145+
}
146+
147+
const value = forward ? this.newValue : this.oldValue;
148+
const field = block.getField(this.name!);
149+
if (field) {
150+
field.setValue(value);
151+
} else {
152+
console.warn("Can't set non-existent field: " + this.name);
153+
}
154+
}
125155
}
126156

127157
export interface BlockFieldIntermediateChangeJson extends BlockBaseJson {

tests/mocha/event_block_field_intermediate_change_test.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,4 +35,38 @@ suite('Field Intermediate Change Event', function () {
3535
chai.assert.deepEqual(newEvent, origEvent);
3636
});
3737
});
38+
39+
suite('Change Value', function () {
40+
test("running forward changes the block's value to new value", function () {
41+
const block = this.workspace.newBlock('text', 'block_id');
42+
const origEvent = new Blockly.Events.BlockFieldIntermediateChange(
43+
block,
44+
'TEXT',
45+
'old value',
46+
'new value',
47+
);
48+
origEvent.run(true);
49+
50+
chai.assert.deepEqual(
51+
block.getField(origEvent.name).getValue(),
52+
'new value',
53+
);
54+
});
55+
56+
test("running backward changes the block's value to old value", function () {
57+
const block = this.workspace.newBlock('text', 'block_id');
58+
const origEvent = new Blockly.Events.BlockFieldIntermediateChange(
59+
block,
60+
'TEXT',
61+
'old value',
62+
'new value',
63+
);
64+
origEvent.run(false);
65+
66+
chai.assert.deepEqual(
67+
block.getField(origEvent.name).getValue(),
68+
'old value',
69+
);
70+
});
71+
});
3872
});

0 commit comments

Comments
 (0)