Blockly

Blockly Example

This example demonstrates how to integrate Blockly into your module using useLibraries(). It provides a fully working environment where users can:

  • Initialize a Blockly workspace.

  • Generate JavaScript code from blocks.

  • Execute the generated code.

  • Save and restore workspace state.


Setup

module.exports = ({ useEffect, useRef, api, usePlaceholders, useState, useLibraries }) => {
  const blocklyDiv = useRef(null);
  const workspace = useRef(null);
  const [code, setCode] = useState('');
  const [output, setOutput] = useState('');
  const placeholders = usePlaceholders();
  const { Blockly } = useLibraries();

  // Example initialization code...
};
  • useLibraries() is used to load Blockly.

  • useRef, useEffect, and useState handle React-style state and DOM references.

  • api and usePlaceholders are used for logging and saving workspace state.


Features in This Example

1. Workspace Initialization

The Blockly workspace is injected into a div reference, using a custom dark theme and a predefined toolbox.

👉 See: Blockly Inject Docsarrow-up-right


2. Custom Blocks

The example defines a custom block console_log and a corresponding JavaScript generator.

👉 See: Blockly Custom Blocksarrow-up-right 👉 See: Blockly Code Generatorsarrow-up-right


3. Code Generation

Whenever the workspace changes, JavaScript code is automatically generated.

👉 See: Blockly Generating Codearrow-up-right


4. Code Execution

The generated code can be executed directly, with console output captured and displayed.


5. Saving Workspace

The workspace XML and generated code are saved using api.nexomaker.yaml.write().

👉 See: Blockly Saving and Loadingarrow-up-right


UI Layout

The UI is split into two main panels:

  • Workspace panel (left, 60%) → Blockly editor.

  • Code/Output panel (right, 40%) → Displays generated code and execution output.


Full Example Code

Last updated