Repository navigation
Grida Canvas - emscripten node target (render without browser) - #505
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughThis 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
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
- 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.
…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.
There was a problem hiding this comment.
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 inlocateFileexample.
Line 73 currently returns nothing, so the production path becomesundefinedin 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 updatescripts/prebuild-patch-emscripten-js-glue.cjsif future Emscripten glue adds newrequire(...)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 returningResultinstead of panicking on surface creation failure.The
expect("raster surface")calls on lines 32 and 38 will panic if surface creation fails. Whileraster_n32_premultypically succeeds for reasonable dimensions, invalid or zero dimensions could cause failures. Consider whether returning aResultwould 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
readLenPrefixedBytesfunction assumesoutptris 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.3to^5increases 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, anddispose. If advanced operations (e.g.,tick,redraw, camera transforms) are needed for raster, they're currently inaccessible sinceasWebGL()returnsnulland there's noasRaster()equivalent.Consider adding an
asRaster(): Scene | nullmethod or expanding the Canvas API if raster users need additional Scene capabilities.
267-284: Consider module caching for multiple canvas instances.Each
createCanvascall invokescreateGridaCanvas(), 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.
CreateSurfaceOptionsusesuse_embedded_fonts(snake_case) while the newCreateCanvasOptionsusesuseEmbeddedFonts(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
| /// 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) | ||
| } |
There was a problem hiding this comment.
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.
| /// 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.
There was a problem hiding this comment.
💡 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".
| 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>; |
There was a problem hiding this comment.
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 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
Canvasclass andcreateCanvas()factory for unified initialization.dispose().Documentation
Tests
✏️ Tip: You can customize this high-level summary in your review settings.