react-blockly

repository·main·Indexed 43 days ago

https://github.com/nbudin/react-blockly

A React wrapper for the Blockly visual programming editor (version 9.0.0). It provides the BlocklyWorkspace component and the useBlocklyWorkspace hook to manage the Blockly lifecycle, workspace injection, and XML serialization within React applications.

Tokens
2.2K
Snippets
6
Records
8
Agent score
55%

What's inside react-blockly

  1. Embed Blockly using the useBlocklyWorkspace hook

    main

    If you need more control over where and how Blockly is rendered, use the useBlocklyWorkspace hook. You must provide a ref pointing to an HTML element where the workspace should be injected.

    import { useBlocklyWorkspace } from 'react-blockly';
    
    function MyBlocklyHookEmbed() {
      const blocklyRef = useRef(null);
      const { workspace, xml } = useBlocklyWorkspace({
        ref: blocklyRef,
        toolboxConfiguration: MY_TOOLBOX, // Must be a JSON toolbox definition
        initialXml: xml,
      });
    
      return (
        <div ref={blocklyRef} /> // Blockly will be injected here
      )
    }
  2. Embed Blockly using the BlocklyWorkspace component

    main

    The BlocklyWorkspace component is the simplest way to integrate Blockly into your React app. It handles the injection, lifecycle, and XML generation automatically. You must provide a toolboxConfiguration which follows the official Blockly JSON toolbox format.

    Note: You typically need to provide a className to set the height of the editor via CSS, as the component generates <div> elements that need explicit dimensions to be visible.

    import { BlocklyWorkspace } from 'react-blockly';
    
    function MyBlocklyEditor() {
      const [xml, setXml] = useState();
    
      return (
        <BlocklyWorkspace
          className="width-100" // Use CSS to ensure height is set
          toolboxConfiguration={MY_TOOLBOX} // Must be a JSON toolbox definition
          initialXml={xml}
          onXmlChange={setXml}
        />
      )
    }
  3. useBlocklyWorkspace hook API

    main

    The useBlocklyWorkspace(options) hook returns an object containing the workspace and the current xml.

    Options

    All properties are optional except ref.

    OptionTypeDescription
    refReact.RefObjectREQUIRED. A ref pointing to the HTML element for injection.
    initialXmlstringThe XML to initially load.
    workspaceConfigurationobjectOptions passed to Blockly.inject (excluding toolbox).
    toolboxConfigurationobjectJSON toolbox configuration.
    onWorkspaceChangefunctionCalled on workspace changes. Receives the workspace object.
    onImportXmlErrorfunctionCalled if initialXml import fails. Receives the error.
    onInjectfunctionCalled after injection. Receives the workspace object.
    onDisposefunctionCalled after disposal. Receives the workspace object.

    Return Value

    PropertyDescription
    workspaceThe Blockly workspace object.
    xmlThe generated XML string (debounced to max once every 200ms).
  4. BlocklyWorkspace component props

    main

    The BlocklyWorkspace component accepts the following optional props:

    PropDescription
    initialXmlThe XML of the program to initially load in the editor.
    workspaceConfigurationAny configuration options to be passed into Blockly.inject (except for toolbox).
    toolboxConfigurationA JSON toolbox configuration (see Blockly documentation).
    classNameThe value for the class attribute on the generated <div> elements.
    onWorkspaceChangeCallback called on every workspace change. Receives the Blockly workspace object.
    onXmlChangeCallback called when workspace XML changes (debounced to max once every 200ms). Receives the new XML string.
    onImportXmlErrorCallback called if initialXml fails to import. Receives the error object.
    onInjectCallback called after the workspace is injected. Receives the Blockly workspace object.
    onDisposeCallback called after the workspace is disposed. Receives the disposed Blockly workspace object.
  5. Configure the BlocklyWorkspace component

    main

    The BlocklyWorkspaceProps interface defines the configuration for the BlocklyWorkspace component. It extends CommonBlocklyProps with additional event handlers for XML and JSON changes.

    Common Configuration Options

    • initialXml: An optional XML string to initialize the workspace.
    • initialJson: An optional JSON object to initialize the workspace.
    • toolboxConfiguration: The Blockly.utils.toolbox.ToolboxDefinition used to define the blocks available in the toolbox.
    • workspaceConfiguration: A Blockly.BlocklyOptions object required to configure the Blockly instance.

    Event Handlers

    • onWorkspaceChange: Called when the workspace changes.
    • onInject: Called when the workspace is injected.
    • onDispose: Called when the workspace is disposed.
    • onImportXmlError: Called if there is an error importing XML.
    • onImportError: Called if there is a general import error.
    • onXmlChange: (Specific to BlocklyWorkspaceProps) Called when the workspace XML changes.
    • onJsonChange: (Specific to BlocklyWorkspaceProps) Called when the workspace JSON changes.
    import { BlocklyWorkspaceProps } from 'react-blockly';
    
    const props: BlocklyWorkspaceProps = {
      workspaceConfiguration: { /* Blockly.BlocklyOptions */ },
      toolboxConfiguration: { /* ToolboxDefinition */ },
      onXmlChange: (xml) => console.log(xml),
      onJsonChange: (json) => console.log(json),
    };
  6. Use the useBlockly hook

    main

    The useBlockly hook allows you to manually manage a Blockly workspace within a React component. It requires a ref to a DOM element where the workspace will be injected.

    Props

    • ref: A RefObject<Element> pointing to the container element.
    • workspaceConfiguration: A Blockly.BlocklyOptions object.
    • toolboxConfiguration: The Blockly.utils.toolbox.ToolboxDefinition.
    • initialXml / initialJson: Optional initial state.
    • onWorkspaceChange, onInject, onDispose, onImportXmlError, onImportError: Lifecycle and error event handlers.
    import { useRef } from 'react';
    import { useBlockly, UseBlocklyProps } from 'react-blockly';
    
    const MyComponent = () => {
      const containerRef = useRef<HTMLDivElement>(null);
    
      const hookProps: UseBlocklyProps = {
        ref: containerRef,
        workspaceConfiguration: { /* ... */ },
        toolboxConfiguration: { /* ... */ },
      };
    
      useBlockly(hookProps);
    
      return <div ref={containerRef} />;
    };
  7. Import react-blockly components and hooks

    main

    The react-blockly package provides a React component for embedding Blockly workspaces and a custom hook for managing workspace state. You can import the main component, the hook, and the ToolboxDefinition type from the package entrypoint.

    Key exports:

    • BlocklyWorkspace: The primary React component for rendering a Blockly workspace.
    • useBlocklyWorkspace: A React hook for interacting with the underlying Blockly workspace instance.
    • ToolboxDefinition: A type representing the structure of the Blockly toolbox.
    • WorkspaceSvg and Workspace: Types/classes re-exported from the core blockly library for compatibility.
    import { 
      BlocklyWorkspace, 
      useBlocklyWorkspace, 
      ToolboxDefinition 
    } from 'react-blockly';