Blockly

repository·main·Indexed 11 days ago

https://github.com/raspberrypifoundation/blockly

A library for integrating a visual, block-based code editor into web applications, allowing users to program using graphical blocks instead of text syntax. It provides a core engine, default blocks, and JavaScript code generators, and can be installed via npm, unpkg, or create-package.

Tokens
229.9K
Snippets
708
Records
1.1K
Agent score
96%

What's inside Blockly

  1. What is Blockly and how to get started

    main

    Blockly is a library that adds a visual code editor to web applications using interlocking, graphical blocks to represent programming concepts (variables, loops, logic, etc.).

    Learning Resources:

    • Developer Site: docs.blockly.com (Configuration, integration guides, and articles).
    • Live Demos: Blockly Demos.
    • Codelabs: Step-by-step tutorials for getting started and advanced usage.
    • Samples: The blockly-samples repository contains examples, codelabs, and plugins.
  2. What is Blockly?

    main

    Blockly is a web library used by developers to integrate a customizable, blocks-based code editor into applications. It represents programming concepts (variables, logic, loops, etc.) using puzzle-piece-like blocks, allowing users to program visually without managing syntax or command-line interfaces.

    Conceptually, Blockly functions in two primary ways:

    1. A Puzzle-Piece UI: You define the connections (puzzle pieces) and input fields, and Blockly manages the complex rendering, dragging, and connecting logic.
    2. A String Builder: You define the code string (e.g., JavaScript, Python) that each individual block generates, and Blockly handles the concatenation of these strings based on the block arrangement. The resulting code can then be used to drive application logic, such as animations, data analysis, or game mechanics.
  3. Overview of Blockly development tools

    main

    Blockly development relies on several key tools, most of which are managed via npm scripts. While you may not need to run these tools directly, understanding them is helpful for debugging and contributing:

    • Node.js & npm: The runtime and package manager used to install dependencies and execute development scripts.
    • Closure Compiler: Used to optimize JavaScript (combining files) and perform syntax/type checking. It is managed via npm and does not require manual installation.
    • ESLint: A static analyzer for enforcing code style.
    • Mocha: The test framework for browser and Node.js testing.
    • Chai: The assertion library used within Mocha tests (using the assert style).
  4. Understand the Blockly repository structure

    main

    The Blockly source code is primarily located in packages/blockly. For most development tasks, you will interact with the core/ and tests/ directories.

    Key Directories in packages/blockly/

    • blocks/: Definitions for built-in blocks.
    • core/: The heart of Blockly. Contains foundational classes like Block, Workspace, and Connection (located directly in core/), as well as specialized logic in subfolders:
      • bubbles/: Popover UI (e.g., mutators).
      • clipboard/: Copy/paste logic.
      • comments/: Workspace and block comments.
      • dragging/: Dragging mechanics.
      • events/: The Events class and built-in events.
      • inputs/: Input types and connections.
      • renderers/: Visual rendering engines (e.g., thrasos, zelos, geras).
      • serialization/: Saving and loading workspace state.
      • toolbox/: Toolbox configuration and logic.
      • utils/: Core utility functions.
    • generators/: Code generators for built-in languages.
    • msg/: Translated message strings.
    • tests/: Unit tests.
    • typings/: Supplemental type declarations.
  5. Ways to contribute to Blockly

    main

    Blockly welcomes contributions beyond code. You can help the project by:

    • Reporting issues: File bugs or feature requests.
    • Code contributions: Fix existing issues or add unit tests.
    • Documentation & Education: Write codelabs to help others learn.
    • Extensibility: Write plugins to extend Blockly's functionality.
    • Community Support: Answer questions in the developer forum.
  6. Understand the value proposition of Blockly

    main

    Blockly is a library designed to let developers focus on domain-specific logic by abstracting away the complexities of rendering, dragging, and connecting blocks. It is suitable for both educational environments (e.g., teaching computational thinking or physics) and industrial applications (e.g., data analysis, robotics automation, and IoT configuration).

    Key strengths include:

    • Availability: Distributed via NPM as a standard web dependency.
    • Fully featured: Includes common blocks for generating code in JavaScript, Python, Lua, Dart, and PHP, supported by a plugin ecosystem.
    • Customizability: Allows for easy definition of custom blocks, fields, and inputs, and supports swapping out core functionalities.
    • Internationalization: Core blocks are translated into 90+ languages, including support for right-to-left (RTL) languages like Arabic and Hebrew.
    • Open Source: Maintained by the Raspberry Pi Foundation.
  7. Overview of sample application files

    main

    When working with a Blockly sample application, the following files represent the core logic for block definition, generation, and orchestration:

    • src/blocks/text.js: Defines custom blocks using the Blockly JSON API.
    • src/generators/javascript.js: Defines the logic for generating JavaScript code from custom blocks.
    • src/toolbox.js: Configures the toolbox, determining which blocks are available to the user.
    • src/index.js: The main entry point that registers blocks and generators, injects the workspace into the DOM, and handles the execution loop (re-running generated code on workspace changes).
  8. Overview of Blockly fields

    main

    Fields are the interactive components within a block that allow users to input or select data. When defining a custom block, you can use either Built-in fields provided by the core Blockly library or Plugin fields which are external packages designed for specialized input types.

    Built-in Fields

    These are available out-of-the-box without additional dependencies:

    • Checkbox: A boolean toggle.
    • Dropdown: A selection list.
    • Image: Displays an image.
    • Label: Displays non-editable text.
    • Serializable label: A label designed for serialization.
    • Number: An input field for numeric values.
    • Text input: An input field for text strings.
    • Variables: A field to select existing variables.

    Plugin Fields

    For more complex inputs, you can install and use specialized plugins. Common examples include:

    • Angle picker (@blockly/field-angle)
    • Bitmap (@blockly/field-bitmap)
    • Colour picker (@blockly/field-colour)
    • Date (@blockly/field-date)
    • Number slider (@blockly/field-slider)
    • Multiline text input (@blockly/field-multilineinput)

    For a complete list of available plugins and demos, visit the Blockly Samples Fields page.

  9. What is a Renderer in Blockly?

    main

    A Renderer is the abstraction layer that handles how blocks are visually represented in the workspace. It serves as the interface between the custom rendering logic (how shapes, colors, and connections look) and the rest of the Blockly engine.

    Blockly provides a base renderer that includes all required fields set to default usable values. Developers can extend this base renderer to modify visual properties while maintaining compatibility with the core engine.

  10. What is a block definition?

    main

    A block definition is an object that defines a custom block's appearance (text, fields, connections, color, etc.) and its behavior (such as block-level event handlers).

    Block definitions can be implemented in two primary ways:

    1. JSON: Using Blockly.common.defineBlocksWithJsonArray to create definitions from a JSON schema.
    2. JavaScript: Defining the block directly as a property on the Blockly.Blocks object, typically using an init function to configure the block instance.
    // JSON Example
    Blockly.common.defineBlocksWithJsonArray([{ 
      "type": "string_length",
      "message0": 'length of %1',
      "args0": [{ "type": "input_value", "name": "VALUE", "check": "String" }],
      "output": "Number",
      "colour": 160
    }]);
    
    // JavaScript Example
    Blockly.Blocks['string_length'] = {
      init: function() {
        this.appendValueInput('VALUE')
            .setCheck('String')
            .appendField('length of');
        this.setOutput(true, 'Number');
        this.setColour(160);
      }
    };
  11. What is a dragger and when to use a custom one

    main

    A dragger is a controller object that coordinates dragging draggables in response to user interactions. It is responsible for:

    • Calling drag methods on the draggable.
    • Calculating the position the draggable should move to in workspace coordinates.
    • Calling drag target methods on any hovered drag targets.

    Implementing a custom dragger is rare. You should only do so if you need to change how dragging is coordinated, such as adding workspace scrolling at the edges (which requires changing how pixel coordinates are converted to workspace coordinates).