Custom language generator to Blockly

Viewed 3835

I know that I can use

Blockly.JavaScript['my_code'] = function() {  ... }

But how can I add another language support like JSON? I tried ..

Blockly.Json['my_code'] = function() {  ... }

It fails when I try to recover

Blockly.Json.workspaceToCode(this.workspace)

workspaceToCode is not a function.

I need to add a new language to Blockly

I will not display this new language (JSON), it will just be used to send instructions to the robots.


I try to

Blockly.Json = new Blockly.Generator('Json');
Blockly.Json['my_code'] = function() {  ... }

But an error occurs in

Blockly.Json.workspaceToCode(this.workspace)

Error ..

Uncaught TypeError: this.init is not a function
    at js.ou3v.module.exports.Blockly.Generator.workspaceToCode
2 Answers

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>

Related