function blocklyCreateVariableWidget(Blockly) {
const shim = html`<div />`;
const promptBox = html`<div class="box" style="display: none"></div>`;
const input = html`<input class="input" type=text />`;
const createVariableButton = html`<button class="button is-link" style="margin-left:20px" id="createVariablePromptButton">创建变量</button>`;
const promtMessageBox = html`<div id="promptMessage"></div>`;
const alertMessageBox = html`<div id="alertbox"></div>`;
promptBox.appendChild(input);
promptBox.appendChild(createVariableButton);
promptBox.appendChild(promtMessageBox);
promptBox.appendChild(alertMessageBox);
shim.appendChild(promptBox);
window.alert = message => {
const container = document.querySelector('#alertbox');
container.innerHTML = message;
};
window.prompt = (caption, defaultText) => {
const b = document.querySelector('#promptMessage');
b.innerHTML = caption;
return input.value;
};
Blockly.Variables.createVariableButtonHandler = function(
workspace,
opt_callback,
opt_type
) {
let createVariablePromptButton = document.querySelector(
'#createVariablePromptButton'
);
var type = opt_type || '';
var promptAndCheckWithAlert = function(defaultName) {
if (defaultName === input.value && input.value !== undefined) {
console.log("defend recurse");
return "";
}
Blockly.Variables.promptName(
Blockly.Msg['NEW_VARIABLE_TITLE'],
defaultName,
function(text) {
if (text) {
var existing = Blockly.Variables.nameUsedWithAnyType(
text,
workspace
);
if (existing) {
if (existing.type == type) {
var msg = Blockly.Msg['VARIABLE_ALREADY_EXISTS'].replace(
'%1',
existing.name
);
} else {
var msg =
Blockly.Msg['VARIABLE_ALREADY_EXISTS_FOR_ANOTHER_TYPE'];
msg = msg
.replace('%1', existing.name)
.replace('%2', existing.type);
}
Blockly.alert(msg, function() {
promptAndCheckWithAlert(text);
});
} else {
workspace.createVariable(text, type);
if (opt_callback) {
opt_callback(text);
}
promptBox.style.display = 'none';
}
} else {
if (opt_callback) {
opt_callback(null);
}
promptBox.style.display = 'none';
}
}
);
};
createVariablePromptButton.onclick = promptAndCheckWithAlert;
promptBox.style.display = 'block';
};
return shim;
}