javascriptblocklygoogle-blockly

Only first block works in a series in Blockly


Description I tried making my own custom blocks in google blockly and made them generate C++ code. They work, but only when separated and aren't attached. However, when they are connected together in a series, only the first block generates code and the rest connected to it don't generate any code at all. Script:

const toolbox = {
...
}

const cppGenerator = new Blockly.Generator('cppGenerator');

Blockly.Blocks['start_of_file'] = {
    init: function() {
        this.appendDummyInput()
            .appendField("File name:")
            .appendField(new Blockly.FieldTextInput("main"), "filename");
        this.appendDummyInput()
            .appendField("Description: ")
            .appendField(new Blockly.FieldTextInput("The main file"), "description");
        this.setNextStatement(true, null);
        this.setColour(230);
        this.setTooltip("");
        this.setHelpUrl("");
    }
};

Blockly.Blocks['include'] = {
    init: function() {
        this.appendDummyInput()
            .appendField("use the")
            .appendField(new Blockly.FieldTextInput("iostream"), "header")
            .appendField("header");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(230);
        this.setTooltip("");
        this.setHelpUrl("");
    }
};

cppGenerator.forBlock['start_of_file'] = function(block, generator) {
    var filename = block.getFieldValue('filename');
    if (filename.slice(-4) != ".cpp") {
        filename += ".cpp"
    }

    var description = block.getFieldValue('description');

    console.log(block)

    return `// ${filename}\n// ${description}`;
}

cppGenerator.forBlock['include'] = function(block, generator) {
    var header = block.getFieldValue('header');

    return `#include <${header}>`
}

const workspace = Blockly.inject('blocklyDiv', { toolbox: toolbox });

function updateCode(event) {
    const code = cppGenerator.workspaceToCode(workspace);
    document.getElementById('textarea').value = code;
}
// workspace.addChangeListener(Blockly.Events.disableOrphans);
workspace.addChangeListener(updateCode);

Screenshots:

Current result: image Expected Result: image


Solution

  • I checked the codelab and found out that I had to make a scrub function.

    cppGenerator.scrub_ = function(block, code, thisOnly) {
      const nextBlock =
          block.nextConnection && block.nextConnection.targetBlock();
      if (nextBlock && !thisOnly) {
        return code + ',\n' + jsonGenerator.blockToCode(nextBlock);
      }
      return code;
    };