Here's the minimal viable example I came up with:
I have defined a little custom block print
:
Blockly.defineBlocksWithJsonArray([
{
type: 'print',
message0: 'print %1',
args0: [
{ type: 'field_input', name: 'EMOJI_CODE' }
]
}
]);
Then I initialise the Blockly editor with this new block:
const ws = Blockly.inject('ide', {
toolbox: {
kind: 'flyoutToolbox',
contents: [
{ kind: 'block', type: 'print' }
]
}
});
Then I need to define what the block will generate.
In this example we convert strings to emojis e.g. :-)
becomes
. I define a new language and what the print
block should do:
const emojiLang = new Blockly.Generator('EmojiLang');
emojiLang['print'] = function (block) {
const code = block.getFieldValue('EMOJI_CODE');
if (!code) return 'waiting…';
if (code == ':-)') return '';
if (code == ':-(') return '';
if (code == ':-/') return '';
return '(unknown)';
};
Finally I listen for changes in the editor to translate blocks into emoji:
ws.addChangeListener(function () {
document.getElementById('out').innerHTML =
emojiLang.workspaceToCode(ws);
});
Full Working Example
const emojiLang = new Blockly.Generator('EmojiLang');
emojiLang['print'] = function (block) {
const code = block.getFieldValue('EMOJI_CODE');
if (!code) return 'waiting…';
if (code == ':-)') return '';
if (code == ':-(') return '';
if (code == ':-/') return '';
return '(unknown)';
};
Blockly.defineBlocksWithJsonArray([
{
type: 'print',
message0: 'print %1',
args0: [
{ type: 'field_input', name: 'EMOJI_CODE' }
]
}
]);
const ws = Blockly.inject('ide', {
toolbox: {
kind: 'flyoutToolbox',
contents: [
{ kind: 'block', type: 'print' }
]
}
});
ws.addChangeListener(function () {
document.getElementById('out').innerHTML =
emojiLang.workspaceToCode(ws);
});
<script src="https://unpkg.com/blockly/blockly.min.js"></script>
Emoji: <span id="out"></span>
<div id="ide" style="height:200px;width:400px;"></div>