Suraj Narwade
Suraj Narwade

Reputation: 227

How to generate blocks from code in blockly?

I have a blockly application which generates some output code. Now, is it possible to write some function which will take my output code and will put corresponding blocks on workspace. For example, on this page, https://developers.google.com/blockly/

Blocks are connected to generate javascript code, But is there any way, I will give javascript code and blocks will appear on workspace.

Upvotes: 9

Views: 9361

Answers (4)

James Cat
James Cat

Reputation: 502

We are working on a python-to-blocks system here https://www.npmjs.com/package/@pi-top/blockly it's a work in progress but pretty much deals with all of Python and is being built to work with the pi-top project website https://further.pi-top.com/ but you should be able to extract something useful, the main code->blocks functionality is in the src/piBlocks folder. The code is based on this project https://github.com/blockpy-edu/BlockMirror I mainly converted it to typescript, reorganised the code and linted it, with a few additions and bugfixes.

Upvotes: 2

Johnson Carneiro
Johnson Carneiro

Reputation: 109

You can only create javascript from blocks, not blocks from javascript. However, You can export blocks to xml, and import back the xml to blocks. So you can always save your blocks anywhere you wish in xml format, and load those from xml back to your blockly workspace.

function saveBlocks() {
    var xmlDom = Blockly.Xml.workspaceToDom(Blockly.mainWorkspace);
    var xmlText = Blockly.Xml.domToPrettyText(xmlDom);
    // do whatever you want to this xml
}
function loadBlock(xml) { // xml is the same block xml you stored
    if (typeof xml != "string" || xml.length < 5) {
        return false;
    }
    try {
        var dom = Blockly.Xml.textToDom(xml);
        Blockly.mainWorkspace.clear();
        Blockly.Xml.domToWorkspace(Blockly.mainWorkspace, dom);
        return true;
    } catch (e) {
        return false;
    }
}

Upvotes: 5

Nithin Kumar Biliya
Nithin Kumar Biliya

Reputation: 3011

I don't remember seeing this feature in blockly, but it is definitely possible. You will have to write custom parsers for your language code and then build the blocks accordingly.

This was somewhat explored in this answer.

Basically as and when you parse the code, you need to programatically create the blocks and attach them together to create the program in blockly.

Upvotes: 0

AndyS
AndyS

Reputation: 846

It can be done - see https://makecode.microbit.org/. If you create a block then edit as Javascript, you can edit and (if it's valid code) then it will show the correct blocks when you switch back to the block view. The javascript is a bit odd that it's generates - so don't expect it to turn any javascript into blocks...

This isn't part of Blockly - and I'm not sure how this has been done - just that it exists - hope this helps.

Upvotes: 1

Related Questions