Unique tool for creating personalized coding languages within Blockly

One way I am aware of is to utilize the following code snippet in Blockly for JavaScript:

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

However, I want to include support for another language like JSON. So, I attempted to do so with this code:

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

Unfortunately, when I tried to retrieve the code using:

Blockly.Json.workspaceToCode(this.workspace)

I encountered an error as workspaceToCode is not recognized as a function.

My objective is to integrate a new programming language into Blockly.

This newly added language (JSON) will not be visible on the interface but will be utilized to issue commands to robots.


In my attempt to configure JSON in Blockly, I used the following code:

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

However, I encountered an error while trying to execute:

Blockly.Json.workspaceToCode(this.workspace)

The error message stated:

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

Answer β„–1

Developing a new language generator for Blockly is quite an extensive project, and the available documentation may not provide much assistance in this regard.

Based on my own experience, one effective approach to creating a generator is to examine the existing ones in generators/. For instance, I utilized the JavaScript generator as a reference when working on a project that required generating C++ code.

It's important to mention that the Block Factory generates JSON for usage in other Blockly applications. However, upon inspecting the code, it appears that there is no specific generator defined for it.

The error message you're encountering could be due to the fact that Blockly.Json lacks an init function. This is a feature typically found in existing generator files, such as in the JavaScript generator:

/**
* Initialise the database of variable names.
* @param {!Blockly.Workspace} workspace Workspace to generate code from.
*/
Blockly.JavaScript.init = function(workspace) {
  ....
};

With this in mind, your function should resemble:

/**
* Initialise the database of variable names.
* @param {!Blockly.Workspace} workspace Workspace to generate code from.
*/
Blockly.Json.init = function(workspace) {
 .....
};

The generator file contains additional functions, and referring to the existing code while customizing it to suit your requirements can facilitate your progress.

Answer β„–2

Below is the simplified example that I have created:

I made a custom block called print:

Blockly.defineBlocksWithJsonArray([
  {
    type: 'print',
    message0: 'print %1',
    args0: [
      { type: 'field_input', name: 'EMOJI_CODE' }
    ]
  }
]);

Next, I set up the Blockly editor with this new block:

const ws = Blockly.inject('ide', {
  toolbox: {
    kind: 'flyoutToolbox',
    contents: [
      { kind: 'block', type: 'print' }
    ]
  }
});

After that, I defined the functionality of the block.

In this scenario, we are converting strings to emojis like :-) becoming πŸ™‚. I establish a new language and specify what the print block should accomplish:

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)';
};

Lastly, I monitor changes in the editor to convert blocks into emojis:

ws.addChangeListener(function () {
  document.getElementById('out').innerHTML =
    emojiLang.workspaceToCode(ws);
});

Complete Example in Action

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying and hiding the Angular <object> element

I am faced with a challenge involving managing files of various formats and creating a gallery with preview functionality. Everything works smoothly when clicking through items of the same format, like JPEGs. However, an issue arises when switching from vi ...

Is it possible to switch states in Angular UI Router without altering the URL?

The feature of multiple nested views in the ui-router is quite convenient as it allows for seamless transitions between different states within an application. Sometimes, there may be a need to modify the URL while navigating through states, while at othe ...

Creating a Dynamic Form in Angular 4 with Multiple Components to Easily Submit Data

Just starting to learn angular 4 and I have a question. I've got a page with 3 sections, each section is its own form: Section 1 - Basic info first name last name email Section 2 - Contact info address city state zip Section 3 - Order info Order i ...

How can I pass command line variables into an npm script?

I am facing an issue where I am attempting to pass a command line option (which is not stored in version control) to my main script index.js. This script performs specific actions based on a designated S3 bucket. Here is the relevant section from my packa ...

Output the name of the file while executing the ant process

Currently, I am utilizing YUI compressor within an ant build process to compress CSS and JavaScript files. I would like the compressor to display the name of each file it is processing as it goes along, so that in case of an error, I can easily pinpoint wh ...

Encountering an issue with an Uncaught SyntaxError: Unexpected identifier

I've been attempting to send data through ajax but keep encountering errors. Here's the code I have: jQuery.ajax({ url : '', type: 'POST', ...

There seems to be a problem with the bundle.js file caused by Uglify

I've just finished a project and now I'm ready to start building it. Utilizing a boilerplate project, I still find myself struggling to comprehend all the npm/webpack intricacies happening behind the scenes. Whenever I try to run "npm start", I k ...

Is a single script tag sufficient for each AngularJS Controller?

Recently started using angularjs and I'm really enjoying it. My goal is to make my app as modular as possible. I have a question: Should each angularjs controller (service, etc) have its own script tag? Is there a way to dynamically load angular contr ...

Getting files from CDN using NuxtJS content module - a beginner's guide

Is there a way to fetch files from an external server, such as a CDN, using the @nuxtjs/content module? This would allow me to manage the .md files independently without relying on Nuxt.js. In my current nuxt.config.js file, I have the following setup: ex ...

Is there a way for a component to render independently of App.vue?

I’m exploring the use of vue-cli for my app, and I'm curious if it's possible to utilize a component without relying on App.vue. In this scenario, the component is displayed in the html, but when I click the button labeled "click here", the tes ...

Troubleshooting problem with Angular Materials' md-datepicker not displaying correctly in wide browser windows

While using the md-datepicker component in my application, I noticed that it does not display properly on larger browser widths. It only seems to work as expected on small and x-small viewports. Please refer to the attached screenshot for reference. This ...

The revalidation feature in Next.js' getStaticProps function does not seem to be

https://i.stack.imgur.com/vnNMQ.png I have a question regarding my use of the getStaticProps function in index.js. I am trying to ensure that my API call runs every 60 seconds when a user visits my page, but I am experiencing issues with revalidate not wo ...

Adjust the JSON array dimensions using JQ for a neat and organized outcome

The JSON data provided in the link (jq play) needs to be converted into a CSV format as shown below: "SO302993",items1,item2,item3.1,item3.2,item3.3, item3.4,... "SO302994",items1,item2,item3.1,item3.2, , ,... "SO302995",items1,item2,item3.1, ...

Using AND and OR operators, regular expressions, and the length of a value

I'm currently working on a feature that restricts users from entering non-numeric characters and limits the input value length to no more than 6. Right now, it successfully blocks any input with more than 6 characters or containing alphabetic characte ...

Struggling with the Nivo slider not loading properly?

Check out my personal website. I'm having an issue with my Nivo slider not displaying properly - it just keeps loading. Any ideas on why this is happening and how I can fix it? Below is the CSS I am using: #slider { position:relative; width: ...

Chromium based browsers are displaying varying values when using canvas.getimagedata()

Update: The solution is to enable willReadFrequently: true on the canvas in Chromium so that getImageData() will consistently return values. Please refer to the answer below for more details. Currently, I am working on a program that selects a pixel from ...

difficulty encountered while sending data to the API

I am facing an issue with my json file where I need to replace the value field with dynamic variables. For example, if my app fetches "9.3", I want it to replace the existing value (2.3) in the json file. I attempted using placeholders but encountere ...

What is the best method for extracting data from JSON and converting it into the SUPER data type

I need to extract data from a JSON object with a date type of SUPER. The reason for defining the data type as SUPER is because the size of the data exceeds what can be stored in a VARCHAR. I attempted to use JSON_EXTRACT_PATH_TEXT and JSON_EXTRACT_ARRAY_E ...

The feature to disable open gesture hiding in Navigation Drawer on React Native seems to be malfunctioning

Our application utilizes a Navigation Drawer to display the side menu. However, there are certain screens where we do not want this navigation drawer to appear when the user performs left or right gestures. We have attempted to hide these particular scree ...

Deleting a JSON element with NODEJS

I am working with a json file and attempting to delete an element using the code below. exports.delete = function(req, res) { var deletearticle = articles[req.params.id]; delete articles[req.params.id]; fs.writeFile('server/article ...