moon-egui

    High-performance, pure MoonBit Immediate-Mode GUI library for WebAssembly, Canvas, and Games.

    gui
    egui
    imgui
    canvas
    wasm
    immediate-mode
    ui
    Download zip
    Author
    Version
    0.5.5
    License
    Apache-2.0
    Last updated
    2 hours ago
    Downloads
    32

    #moon-egui

    A Lightweight Immediate-Mode GUI Library for MoonBit and WebAssembly


    #Overview

    moon-egui is a lightweight immediate-mode GUI (IMGUI) library designed for the MoonBit programming language, targeting WebAssembly and HTML5 Canvas 2D graphics environments.

    Inspired by Rust's egui and C++'s Dear ImGui, moon-egui follows the immediate-mode paradigm: code is UI, and UI is state. By evaluating the interface frame-by-frame declaratively, it delivers a direct developer experience, modest runtime footprint, and stable rendering.

    #Why moon-egui?

    When building interactive user interfaces within WebAssembly and HTML5 Canvas environments, developers typically face several trade-offs:

    • Maintenance burden of raw Canvas code: Manually computing layout coordinates, writing hit-testing routines, and handling z-ordering quickly becomes verbose and error-prone.
    • Performance jitter of DOM / Virtual DOM: In high-frequency 60 FPS graphical canvases, retained-mode UI trees incur cross-boundary overhead and garbage collection (GC) pauses.
    • Toolchain friction of C/C++ bindings: FFI-based GUI wrappers introduce heavy external C toolchains and bloated binaries, breaking MoonBit's clean native package manager workflow.

    #Key Features

    • Immediate-Mode Ergonomics: UI is declared frame-by-frame with zero lifecycle callbacks or two-way synchronization. Handling user interactions is as simple as if @widgets.button(ctx, "Save").clicked { ... }.
    • Zero FFI Dependencies: 100% pure MoonBit with a headless core decoupled from host runtimes. Installable in one command (moon add ling71671/moon-egui).
    • Microsecond Frame Pipeline: Viewport spatial culling and command batching keep per-frame kernel cost at ~0.1ms, maintaining a locked 60 FPS.
    • Production-Ready Widgets: Movable windows with z-ordering and viewport clamping, tab bars, keyboard-driven text inputs, click-outside-dismiss combo boxes, and tooltips.


    #Installation

    # Install the latest stable release moon add LING71671/moon-egui # Or pin to an exact version moon add LING71671/moon-egui@0.5.5

    Import the layers you need in your moon.pkg: src/core is the bare immediate-mode runtime, src/widgets adds the standard controls, and src/composite the advanced components.

    { "import": [ "LING71671/moon-egui/src/core", "LING71671/moon-egui/src/widgets", "LING71671/moon-egui/src/composite", "LING71671/moon-egui/src/draw", "LING71671/moon-egui/src/math", "LING71671/moon-egui/src/color" ] }


    #Live Demos

    Experience the interactive capabilities and rendering performance of moon-egui in any modern browser:

    • Interactive Demo Homepage Immediate-mode widgets showcase, application menu bar, floating inspector window, and lightweight canvas playground.
    • Canvas & Multi-Scale Matrix Benchmark 128² to 1024² (16,384 to 1,048,576 nodes) multi-scale pixel matrix, CAD dual-axis rulers, viewport pan & zoom navigation, and CAD pixel grid lines.


    #Quick Example

    fn update_ui(ctx : @core.UIContext, state : AppState) {
    // 1. Global top-level application menu bar (src/composite)
    @composite.menu_bar(ctx, fn(top) {
    @composite.menu(top, "File", fn(menu) {
    if @composite.menu_item(menu, "New Project").clicked { state.new_project() }
    if @composite.menu_item(menu, "Save Config").clicked { state.save() }
    })
    @composite.menu(top, "View", fn(menu) {
    if @composite.menu_item(menu, "Toggle Theme").clicked { state.toggle_theme() }
    })
    })

    // 2. Floating draggable inspector window (src/widgets)
    @widgets.window(ctx, "Console & Properties", @math.Vec2::new(50.0, 50.0), @math.Vec2::new(300.0, 420.0), fn(win) {
    let _ = win.label("Welcome to moon-egui")

    if @widgets.button(win, "Trigger Action").clicked {
    state.counter 1
    }

    // Blender-style DragValue adjustment
    let (gravity, _) = @widgets.drag_value(win, "Gravity", state.gravity, speed=0.1, min=0.0, max=20.0)
    state.gravity = gravity
    let (collision, _) = @widgets.checkbox(win, "Enable Collision", state.collision_enabled)
    state.collision_enabled = collision

    // Collapsible telemetry panel
    @widgets.collapsing_header(win, "render_monitor", "Runtime Monitor", false, fn(panel) {
    let (_, _) = @composite.sparkline(panel, "fps", state.fps_history)
    @widgets.progress_bar(panel, state.progress)
    })
    }))
    })
    }


    #Architecture

    moon-egui separates UI logic from host rendering via a three-tier unidirectional pipeline:

    [ Input Events ] • Pointer coordinates & button state • Keyboard keys & modifiers • Mouse wheel scroll delta │ ▼ [ moon-egui Core ] • Input state machine (Hover, Active, Focused) • Linear cursor layout & AABB hit-testing • Scissor clip rectangle stack • Immediate-mode widget evaluation │ ▼ [ DrawCmd Stream ] • DrawCmd::Rect(x, y, w, h, color, radius) • DrawCmd::Text(x, y, text, size, color) • DrawCmd::Line(x1, y1, x2, y2, color, width) • DrawCmd::Clip(x, y, w, h) │ ▼ [ Render Backends ] • HTML5 Canvas 2D (Default Wasm bridge) • WebGL / WebGPU (Planned) • Native Windowing (Raylib / SDL / Minifb)


    #Core Capabilities

    #Available Now

    • Core Draw Engine: Pure MoonBit implementation of Vec2, Rect, Color, and platform-agnostic DrawCmd stream, supporting rectangles, lines, circles, text, and nested scissor clip stacks.
    • Layout & Space Allocation: UIContext manages hot_id / active_id state machine and layout scope stacks, supporting vertical and horizontal flow layouts (horizontal). allocate_space() computes geometry bounds and automatic cursor placement.
    • Core Widget Suite (42 Available Widgets):
      • Inputs & Editing: button (with keyboard shortcuts, primary/default variants, and custom sizing), text_edit (single-line porcelain text entry with hidden IME bridge), code_editor (multi-line code editor with line numbers, syntax styling, selection highlight, caret scroll, select-all, and shortcuts), stepper (discrete numeric step adjuster with [+] / [-] buttons, mouse wheel, and Shift/Ctrl acceleration), rating (interactive and read-only star score with 0.5 half-star precision and live hover preview), label / label_colored.
      • Selection & Values: checkbox (precision toggle box), toggle (bistable capsule switch), radio (concentric option button), slider / slider_int (continuous/stepped numeric scrubbers), drag_value (fine-grained numeric drag with arrow navigation), knob (270° arc rotary dial), fader / fader_int (vertical channel fader regulator), combo_box (adaptive upward-flipping dropdown), color_button / color_picker (HSV color picker and palette).
      • Feedback & Notifications: progress_bar (smooth progress indicator), badge (status badges and dot indicators), toast (floating notification toasts with hover occlusion blocking), tooltip (floating bubble hints with boundary clipping prevention), spinner (rotary loading indicator).
      • Data Visualization & Plotting: sparkline (real-time telemetry sparkline), plot (immediate-mode plotting with line, scatter, and area series, dual-axis ticks, and crosshairs), bar_chart (adaptive bar chart).
      • Advanced Navigation & Interactions: steps (process and workflow navigation bar with auto-status derivation, centered vector check/cross icons, and keyboard traversal), pagination (data pagination bar with intelligent ellipsis folding and keyboard shortcuts), node_editor (blueprint node flow graph editor with card dragging, port connections, and smooth cubic Bézier wires), menu_bar (desktop-grade menu bar), context_menu (recursive cascading multi-level right-click menu), command_palette (global fuzzy search palette), tree_view (hierarchical asset tree), segmented_control (pill segmented switcher), breadcrumb (hierarchical breadcrumb).
      • Layout Spacing & Flow: separator (hairline divider), spacer (flexible spacing), horizontal_wrapped (auto-wrapping flow layout).
    • Windows & Container Architecture:
      • Global Application Menu Bar: menu_bar, menu, menu_item, menu_separator featuring isolated foreground layer projection, desktop-grade Hover-to-Switch transitions, and outside-click dismissal;
      • Free-Floating Windows: window supporting title-bar drag repositioning, dynamic Z-Index elevation, local coordinate scoping, and scissor clipping;
      • Advanced Containers: splitter (bidirectional draggable divider), table (high-performance virtualized data table with resizable columns), collapsing_header (tree groupings with persistent open memory), scroll_area (wheel and thumb draggable viewport scrolling), tab_bar (tab navigation), dialog (modal confirmation dialog with focus trap).
    • Headless & Automated Testing: Core logic produces pure DrawCmd streams without browser bindings, backed by 348 automated headless unit and integration tests (100% passing).
    • Canvas 2D Host Driver: Lightweight JavaScript bridge and 60 FPS rendering pipeline, coupled with O(1) viewport spatial culling and adaptive LOD architecture.

    #Planned & In Roadmap

    • Hardware-Accelerated Backends: WebGL / WebGPU batched geometry rasterizers and custom shader pipelines.
    • Cross-Platform Native Desktop: Raylib / SDL3 windowing integration.
    • Vector SVG Exporter: Export active frame command streams into clean, standard .svg vector files.


    #Development Roadmap (Sep 9 – Sep 25, 2026)

    #Phase 1: Core Scaffolding & Foundation Suite (Sep 9 – Sep 11) [All Delivered]

    #Phase 2: Workstation & Industrial Capabilities (Sep 12 – Sep 25)

    For full milestone metrics and acceptance criteria, see ROADMAP.md (English).


    #Architecture & Technical Documentation

    Comprehensive design specifications and technical whitepapers are available in the docs/ directory:

    DocumentDescriptionKey Focus
    Roadmap & Milestones (中文)Timeline & DeliverablesHackathon milestones, acceptance criteria, long-term evolution
    Architecture Whitepaper (中文)Engine InternalsWidget ID hashing, frame lifecycle, cursor layout, clip stack
    API Reference Manual (中文)Developer API DocsUIContext method signatures, layout protocols, Painter API
    Design System & Tokens (中文)Visual TokensColor schemes, typography scales, spacing rules, state styles
    Style Guide (中文)Coding StandardsBlock syntax (///\|), naming, visibility, .mbti contracts
    Contributing Guide (中文)Engineering ProtocolsDevelopment workflow, test guidelines, Conventional Commits
    Changelog (中文)Release HistoryNotable changes and release tracking


    #License

    This project is licensed under the Apache License 2.0.