Skip to content

Grida Canvas - emscripten node target (render without browser) - #505

Merged
softmarshmallow merged 14 commits into
mainfrom
canary
Jan 26, 2026
Merged

softmarshmallow merged 14 commits into
mainfrom
canary

Conversation

@softmarshmallow

@softmarshmallow softmarshmallow commented Jan 20, 2026 •

Copy link
Copy Markdown
Member

This PR aims to provide to support both web,node for emscripten build target,
while preserving the turbopack use on main, production use as web canvas.

on node, it will use CPU for rendering, as allowing node runtime to use gl context seems cumbersome atm.

The prebuild script will change once, emscripten-core/emscripten#26134 is solved.

Summary by CodeRabbit

Release Notes

  • New Features

    • Added dual-environment support: WebGL rendering for browsers and raster export for Node.js.
    • Introduced Canvas class and createCanvas() factory for unified initialization.
    • PNG export capability in Node.js with improved lifecycle management via dispose().
  • Documentation

    • Added browser and Node.js usage examples with code samples.
    • Added bundler compatibility guide for multi-environment packaging.
  • Tests

    • Added comprehensive environment validation and raster export test coverage.

✏️ Tip: You can customize this high-level summary in your review settings.

@vercel

vercel Bot commented Jan 20, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Review Updated (UTC)
backgrounds Ready Ready Preview, Comment Jan 25, 2026 4:38pm
blog Ready Ready Preview, Comment Jan 25, 2026 4:38pm
docs Ready Ready Preview, Comment Jan 25, 2026 4:38pm
grida Ready Ready Preview, Comment Jan 25, 2026 4:38pm
viewer Ready Ready Preview, Comment Jan 25, 2026 4:38pm
2 Skipped Deployments
Project Deployment Review Updated (UTC)
code Ignored Ignored Jan 25, 2026 4:38pm
legacy Ignored Ignored Jan 25, 2026 4:38pm

Request Review

@softmarshmallow softmarshmallow added the cg Core Graphics label Jan 20, 2026
@coderabbitai

coderabbitai Bot commented Jan 20, 2026 •

Copy link
Copy Markdown

Walkthrough

This PR introduces multi-backend support to grida-canvas-wasm, enabling rendering via both WebGL (browser) and Raster (Node.js) backends. Key architectural changes include a backend-agnostic application abstraction, a new public Canvas API layer with factory function, FFI utilities for WASM memory management, test suites for Node.js environments, and corresponding Rust refactoring to abstract over surface types.

Changes

Cohort / File(s) Summary
Build Configuration & Tooling
crates/grida-canvas-wasm/.cargo/config.toml, tsup.config.ts, justfile, vitest.config.ts, crates/grida-canvas/src/window/state.rs
Expanded Cargo rustflags for environment support (web → web,node); added external module declaration to prevent bundling Emscripten glue; removed module aliases from Vitest config; updated info output for dual-environment support.
Package Metadata & Scripts
crates/grida-canvas-wasm/package.json, package.json, packages/grida-fonts/package.json
Added private: false, files: ["dist"], main entry, prebuild/typecheck scripts; added @types/node devDependency; added new turbo build script filter; bumped tsup version.
Documentation & Examples
crates/grida-canvas-wasm/AGENTS.md, README.md, example/gradient.grida1, packages/grida-canvas-sdk-render-figma/README.md
Added Next.js Turbopack bundler compatibility guide; added browser/Node.js usage examples with complete code snippets; introduced gradient rectangle example document.
WASM Type Bindings
crates/grida-canvas-wasm/lib/modules/canvas-bindings.d.ts
Replaced GridaCanvasWebGlApplicationPtr with GridaCanvasApplicationPtr; added _init_with_backend() and _destroy() lifecycle methods; expanded _set_main_camera_transform() signature to accept 6 numeric parameters.
TypeScript FFI & Memory Management
crates/grida-canvas-wasm/lib/modules/ffi.ts
New module providing WasmModuleLike interface and ffi namespace with string/bytes allocation, deallocation, and length-prefixed data reading utilities for WASM interop.
TypeScript Public API Layer
crates/grida-canvas-wasm/lib/index.ts, grida-canvas-wasm.ts
Introduced Canvas class with backend selection, scene loading, font/image management, node export, and disposal; added createCanvas factory function; exposed BACKEND_ID constants; renamed CreateWebGLCanvasSurfaceOptions to CreateSurfaceOptions with camelCase property names.
Canvas Module Lifecycle
crates/grida-canvas-wasm/lib/modules/canvas.ts
Added dispose() method and _assertAlive() guard; integrated centralized FFI-based memory management (allocString, free, allocBytes); enforced aliveness checks before operations; refactored string/buffer handling to use length-prefixed data.
Node.js Test Suites
crates/grida-canvas-wasm/lib/__test__/*
Added smoke test (basic module loading and exports), API validation test (C exports arity, runtime methods presence, disposal behavior), and raster export test (PNG generation with embedded fonts, signature validation); added .gitignore for test output; removed placeholder API validation test.
Build Preprocessing
crates/grida-canvas-wasm/scripts/prebuild-patch-emscripten-js-glue.cjs, tsconfig.json
New CommonJS script patching Emscripten glue to use node:* protocol for built-ins, applied to vendored and dist files; added skipLibCheck to tsconfig.
Rust Application Core
crates/grida-canvas-wasm/src/wasm_application.rs
Replaced EmscriptenApplication with UnknownTargetApplication across all C exports; added init_with_backend() for backend selection and destroy() for lifecycle management; refactored return values to use length-prefixed buffers via alloc_len_prefixed() instead of CStrings; expanded _set_main_camera_transform() parameter list.
Rust Application Abstraction
crates/grida-canvas/src/window/application.rs
Updated UnknownTargetApplication to use AnySurfaceState; added new_raster() constructor for CPU-only rendering; introduced set_auto_tick(), auto_tick(), request_stop(), running() lifecycle controls; exposed add_font(), add_image() methods; increased visibility of transaction and redraw methods to public.
Rust Emscripten Integration
crates/grida-canvas/src/window/application_emscripten.rs
Added new_webgl_app() factory for WebGL initialization with RAF loop; introduced request_animation_frame_callback_unknown_target() for lifecycle-aware frame scheduling; adapted EmscriptenApplication to pass AnySurfaceState wrapper to UnknownTargetApplication constructor.
Rust Surface State Abstraction
crates/grida-canvas/src/window/state.rs
Introduced RasterSurfaceState for CPU raster surfaces and AnySurfaceState enum abstracting GPU vs. Raster; added factory methods (from_gpu, new_raster) and backend resolution via Backend enum mapping.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Client Code
    participant Factory as createCanvas()
    participant WASM as WASM Module
    participant WebGLBackend as WebGL Backend
    participant RasterBackend as Raster Backend

    rect rgba(100, 150, 255, 0.5)
    Note over Client,RasterBackend: WebGL Path (Browser)
    Client->>Factory: createCanvas({ type: "webgl", canvas })
    Factory->>WASM: _init_with_backend(0, w, h, fonts)
    WASM->>WebGLBackend: init GL context
    WebGLBackend->>WASM: GL state
    WASM->>Factory: ApplicationPtr
    Factory->>Client: Canvas instance
    end

    rect rgba(150, 100, 255, 0.5)
    Note over Client,RasterBackend: Raster Path (Node.js)
    Client->>Factory: createCanvas({ type: "raster", width, height })
    Factory->>WASM: _init_with_backend(1, w, h, fonts)
    WASM->>RasterBackend: create raster surface
    RasterBackend->>WASM: Surface ptr
    WASM->>Factory: ApplicationPtr
    Factory->>Client: Canvas instance
    end

    rect rgba(100, 255, 100, 0.5)
    Note over Client,WASM: Common Operations
    Client->>Canvas: loadScene(json)
    Canvas->>WASM: _load_scene_json(ptr, len)
    WASM->>WASM: parse & render
    Client->>Canvas: exportNodeAs(id, "png")
    Canvas->>WASM: _export_node_as(id_ptr, fmt_ptr)
    WASM->>Client: PNG bytes
    Client->>Canvas: dispose()
    Canvas->>WASM: _destroy(app_ptr)
    WASM->>WASM: cleanup
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • PR #398: Implements the foundational backend-agnostic refactoring (init_with_backend, UnknownTargetApplication, WASM ABI changes) that this PR builds upon and extends.
  • PR #415: Adds grida-canvas-fonts crate and font binding changes to WASM, directly integrated into this PR's font management API.
  • PR #383: Introduces AnySurfaceState and raster surface abstraction concepts that enable the multi-backend architecture in this PR.

Suggested labels

wasm32, canvas, breaking

Poem

🐰 Hops of dual backends, hopping free,
WebGL in browsers, raster by Node's decree,
Canvas now speaks both tongues so fine,
Memory managed, FFI divine!
From web to node, one canvas to bind! ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: adding Emscripten Node target support for rendering without a browser, which aligns with the PR's primary objective.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch canary

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

- Introduced a prebuild script to patch Emscripten-generated JS glue, ensuring Node built-ins are correctly referenced as `node:*` to avoid bundler resolution issues.
- Updated `package.json` to run the new prebuild script before the build process.
- Created a thin wrapper for the Emscripten glue to keep it external and prevent bundling into the main output.
- Adjusted `tsup.config.ts` to maintain the Emscripten glue as a separate file in the distribution.
- Removed the obsolete postbuild patch script as its functionality is now integrated into the prebuild process.
@vercel
vercel Bot temporarily deployed to Preview – blog January 20, 2026 14:16 Inactive
@vercel
vercel Bot temporarily deployed to Preview – viewer January 20, 2026 14:16 Inactive
@vercel
vercel Bot temporarily deployed to Preview – backgrounds January 20, 2026 14:16 Inactive
@softmarshmallow softmarshmallow changed the title Grida Canvas - node target (render without browser) Grida Canvas - emscripten node target (render without browser) Jan 20, 2026
…aster rendering

- Added support for creating applications with either WebGL or raster backends through a unified API.
- Implemented `new_webgl_app` function for WebGL applications, encapsulating GL setup and animation frame handling.
- Enhanced `UnknownTargetApplication` to manage application state and rendering logic for both backends.
- Updated WASM bindings to accommodate the new backend handling, ensuring compatibility with existing functionality.
- Introduced tests for raster export functionality in Node.js environment.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
crates/grida-canvas-wasm/README.md (1)

68-74: Fix missing return in locateFile example.
Line 73 currently returns nothing, so the production path becomes undefined in the snippet.

🐛 Proposed fix
   locateFile: (path) => {
     if (process.env.NODE_ENV === "development") {
       return `http://localhost:4020/dist/${path}`;
     }
-    `https://unpkg.com/@grida/canvas-wasm@latest/${path}`,
+    return `https://unpkg.com/@grida/canvas-wasm@latest/${path}`;
   },
🤖 Fix all issues with AI agents
In `@crates/grida-canvas/src/window/application.rs`:
- Around line 834-837: add_image currently forwards to
self.renderer.add_image(data) but does not trigger the renderer cache
invalidation that the queued image path does, leaving stale renders; after
calling self.renderer.add_image(data) invoke the same cache invalidation routine
used by the queued image path (e.g. call self.invalidate_queued_image_path() or
the equivalent invalidate_render_cache method) so that the renderer's caches are
refreshed immediately; update the add_image method to perform
renderer.add_image(data) then call the cache invalidation helper before
returning.
🧹 Nitpick comments (9)
crates/grida-canvas-wasm/AGENTS.md (1)

19-23: Add a maintenance note for new built-ins emitted by Emscripten.
Consider a brief reminder to update scripts/prebuild-patch-emscripten-js-glue.cjs if future Emscripten glue adds new require(...) built-ins (e.g., zlib, os). This keeps the patch list from silently going stale as Emscripten evolves.

Also applies to: 31-36

crates/grida-canvas/src/window/state.rs (1)

29-48: Consider returning Result instead of panicking on surface creation failure.

The expect("raster surface") calls on lines 32 and 38 will panic if surface creation fails. While raster_n32_premul typically succeeds for reasonable dimensions, invalid or zero dimensions could cause failures. Consider whether returning a Result would be more appropriate for graceful error handling, especially since this may be called from FFI contexts.

♻️ Proposed refactor to return Result
-impl RasterSurfaceState {
-    pub fn new(width: i32, height: i32) -> Self {
-        let surface =
-            skia_safe::surfaces::raster_n32_premul((width, height)).expect("raster surface");
-        Self { surface }
-    }
+impl RasterSurfaceState {
+    pub fn new(width: i32, height: i32) -> Option<Self> {
+        let surface = skia_safe::surfaces::raster_n32_premul((width, height))?;
+        Some(Self { surface })
+    }
 
-    pub fn resize(&mut self, width: i32, height: i32) {
-        self.surface =
-            skia_safe::surfaces::raster_n32_premul((width, height)).expect("raster surface");
+    pub fn resize(&mut self, width: i32, height: i32) -> bool {
+        match skia_safe::surfaces::raster_n32_premul((width, height)) {
+            Some(surface) => {
+                self.surface = surface;
+                true
+            }
+            None => false,
+        }
     }
crates/grida-canvas-wasm/lib/modules/ffi.ts (1)

36-50: Consider adding a null pointer guard.

The readLenPrefixedBytes function assumes outptr is always valid. If the WASM function returns 0 (null) to indicate an error, reading from address 0 could produce unexpected results. Consider adding a defensive check.

♻️ Optional defensive check
 export function readLenPrefixedBytes(
   module: WasmModuleLike,
   outptr: number
 ): Uint8Array {
+  if (outptr === 0) {
+    return new Uint8Array(0);
+  }
   // [u32 len][bytes...]
   const view = new DataView(
     module.HEAPU8.buffer,
crates/grida-canvas-wasm/src/wasm_application.rs (1)

228-240: Reuse alloc_len_prefixed for get_image_bytes.

This keeps length-prefix handling consistent and preserves the u32 length guard introduced by the helper.

♻️ Proposed refactor
-    if let (Some(app), Some(id)) = (app.as_mut(), __str_from_ptr_len(id_ptr, id_len)) {
-        if let Some(bytes) = app.get_image_bytes(&id) {
-            let len = bytes.len();
-            let out = allocate(len + 4) as *mut u8;
-            let len_bytes = (len as u32).to_le_bytes();
-            std::ptr::copy_nonoverlapping(len_bytes.as_ptr(), out, 4);
-            std::ptr::copy_nonoverlapping(bytes.as_ptr(), out.add(4), len);
-            return out;
-        }
-    }
+    if let (Some(app), Some(id)) = (app.as_mut(), __str_from_ptr_len(id_ptr, id_len)) {
+        if let Some(bytes) = app.get_image_bytes(&id) {
+            return alloc_len_prefixed(&bytes);
+        }
+    }
crates/grida-canvas-wasm/lib/__test__/environment-node-raster-export.test.ts (1)

18-21: Gate PNG file writes behind an env flag.
Unconditional writes can dirty the repo/CI; make them opt-in.

♻️ Proposed tweak
 const OUTPUT_DIR = resolve(process.cwd(), "lib/__test__/out");
+const WRITE_OUTPUT = process.env.GRIDA_WASM_TEST_OUTPUT === "1";

 function writePng(name: string, data: Uint8Array) {
+  if (!WRITE_OUTPUT) return;
   mkdirSync(OUTPUT_DIR, { recursive: true });
   writeFileSync(resolve(OUTPUT_DIR, `${name}.png`), Buffer.from(data));
 }
crates/grida-canvas-wasm/package.json (1)

33-36: Minor: Consider pinning TypeScript version range.

Widening from ^5.3.3 to ^5 increases the range of acceptable versions. While this provides flexibility, it could introduce subtle behavior differences across environments.

crates/grida-canvas-wasm/lib/index.ts (3)

209-260: Canvas API provides clean backend abstraction, but limited raster access.

The design is clean with proper encapsulation. However, raster backend users can only access loadScene, addFont, exportNodeAs, and dispose. If advanced operations (e.g., tick, redraw, camera transforms) are needed for raster, they're currently inaccessible since asWebGL() returns null and there's no asRaster() equivalent.

Consider adding an asRaster(): Scene | null method or expanding the Canvas API if raster users need additional Scene capabilities.


267-284: Consider module caching for multiple canvas instances.

Each createCanvas call invokes createGridaCanvas(), loading a fresh WASM module instance. For applications creating multiple canvases, this could be expensive.

Consider allowing an optional pre-loaded module to be passed in, or implementing internal caching:

// Option: Accept pre-loaded bindings
export async function createCanvas(
  opts: CreateCanvasOptions & { bindings?: createGridaCanvas.GridaCanvasWasmBindings }
): Promise<Canvas> {
  const bindings = opts.bindings ?? await createGridaCanvas({ ... });
  // ...
}

127-144: Naming inconsistency between legacy and new API options.

CreateSurfaceOptions uses use_embedded_fonts (snake_case) while the new CreateCanvasOptions uses useEmbeddedFonts (camelCase). Consider aligning to camelCase for consistency with TypeScript conventions.

♻️ Suggested fix
-interface CreateSurfaceOptions {
+interface CreateSurfaceOptions {
   /**
    * when true, embedded fonts will be registered and used for text rendering.
    * `@default` true
    */
-  use_embedded_fonts?: boolean;
+  useEmbeddedFonts?: boolean;
 }

And update the usage in createWebGLCanvasSurface:

-    options.use_embedded_fonts
+    options.useEmbeddedFonts

Comment on lines +834 to +837
/// Register image bytes with the renderer and return metadata.
pub fn add_image(&mut self, data: &[u8]) -> (String, String, u32, u32, String) {
self.renderer.add_image(data)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Invalidate renderer cache after add_image().

The queued image path invalidates caches, but this direct API doesn’t, which can leave stale render output until another invalidation occurs.

🐛 Proposed fix
 pub fn add_image(&mut self, data: &[u8]) -> (String, String, u32, u32, String) {
-    self.renderer.add_image(data)
+    let result = self.renderer.add_image(data);
+    self.renderer.invalidate_cache();
+    result
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
/// Register image bytes with the renderer and return metadata.
pub fn add_image(&mut self, data: &[u8]) -> (String, String, u32, u32, String) {
self.renderer.add_image(data)
}
/// Register image bytes with the renderer and return metadata.
pub fn add_image(&mut self, data: &[u8]) -> (String, String, u32, u32, String) {
let result = self.renderer.add_image(data);
self.renderer.invalidate_cache();
result
}
🤖 Prompt for AI Agents
In `@crates/grida-canvas/src/window/application.rs` around lines 834 - 837,
add_image currently forwards to self.renderer.add_image(data) but does not
trigger the renderer cache invalidation that the queued image path does, leaving
stale renders; after calling self.renderer.add_image(data) invoke the same cache
invalidation routine used by the queued image path (e.g. call
self.invalidate_queued_image_path() or the equivalent invalidate_render_cache
method) so that the renderer's caches are refreshed immediately; update the
add_image method to perform renderer.add_image(data) then call the cache
invalidation helper before returning.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 896b005c10

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +6 to +9
it("can import dist and initialize wasm module in Node", async () => {
// NOTE: this package is CommonJS (no `"type": "module"`), so avoid `import.meta`.
const pkg = require("../../dist/index.js") as {
default?: (opts?: unknown) => Promise<unknown>;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Ensure tests build dist before requiring it

These new node tests require("../../dist/index.js"), but this package’s test script doesn’t build dist/ and turbo test does not depend on build (see turbo.json). In a clean checkout dist/ is absent, so the tests will fail with a module-not-found error unless a manual build ran first. Consider importing from source in tests, or add a pretest/task dependency to build @grida/canvas-wasm before running vitest.

Useful? React with 👍 / 👎.

This branch was successfully deployed

5 active deployments
Preview – grida — 896b005c Deployed Jan 25, 2026 by vercel[bot]
Preview – backgrounds — 896b005c Deployed Jan 25, 2026 by vercel[bot]
Preview – viewer — 896b005c Deployed Jan 25, 2026 by vercel[bot]
Preview – blog — 896b005c Deployed Jan 25, 2026 by vercel[bot]
Preview – docs — 896b005c Deployed Jan 25, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cg Core Graphics

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant