Skip to content

Commit

Permalink
Upgrade variable field to use new serialization
Browse files Browse the repository at this point in the history
  • Loading branch information
BeksOmega committed Jul 15, 2021
1 parent 25fbde5 commit 7f74bb7
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
22 changes: 22 additions & 0 deletions core/field_variable.js
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,28 @@ Blockly.FieldVariable.prototype.toXml = function(fieldElement) {
return fieldElement;
};

/**
* Saves this field's value.
* @return {string} The id of the variable referenced by this field.
* @override
* @package
*/
Blockly.FieldVariable.prototype.saveState = function() {
// Make sure the variable is initialized.
this.initModel();
return this.variable_.getId();
};

/**
* Sets the field's value based on the given state.
* @param {*} id The id of the variable to assign to this variable field.
* @override
* @package
*/
Blockly.FieldVariable.prototype.loadState = function(id) {
this.setValue(id);
};

/**
* Attach this field to a block.
* @param {!Blockly.Block} block The block containing this field.
Expand Down
29 changes: 29 additions & 0 deletions tests/mocha/field_variable_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -377,4 +377,33 @@ suite('Variable Fields', function() {
chai.assert.equal(this.variableField.getValue(), 'id2');
});
});

suite('Serialization', function() {
setup(function() {
this.workspace = new Blockly.Workspace();
defineRowBlock();
createGenUidStubWithReturns(new Array(10).fill().map((_, i) => 'id' + i));
});

teardown(function() {
workspaceTeardown.call(this, this.workspace);
});

test('Untyped', function() {
const block = this.workspace.newBlock('row_block');
const field = new Blockly.FieldVariable('x');
block.getInput('INPUT').appendField(field, 'VAR');
const jso = Blockly.serialization.blocks.save(block);
chai.assert.deepEqual(jso['fields'], {'VAR': 'id2'});
});

test('Typed', function() {
const block = this.workspace.newBlock('row_block');
const field =
new Blockly.FieldVariable('x', undefined, undefined, ['String']);
block.getInput('INPUT').appendField(field, 'VAR');
const jso = Blockly.serialization.blocks.save(block);
chai.assert.deepEqual(jso['fields'], {'VAR': 'id2'});
});
});
});

0 comments on commit 7f74bb7

Please sign in to comment.