Skip to content

Grida Canvas WASM Backend - #398

Merged
softmarshmallow merged 89 commits into
mainfrom
canary
Jul 6, 2025
Merged

softmarshmallow merged 89 commits into
mainfrom
canary

Conversation

@softmarshmallow

@softmarshmallow softmarshmallow commented Jul 6, 2025 •

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • New Features

    • Introduced a WebAssembly-based 2D canvas rendering engine with TypeScript/JavaScript bindings, including interactive web examples and developer tools overlays (tiles, FPS, hit testing, ruler, stats).
    • Added comprehensive timer and debounce utilities for event-driven applications.
    • Enhanced scene support with new node types (paths, gradients), flexible hit-testing, and advanced camera controls.
    • Enabled archive-based loading of design documents and images.
  • Bug Fixes

    • Improved error handling and reporting for scene and resource loading.
    • Refined camera and tile cache change detection for more accurate rendering updates.
  • Documentation

    • Added detailed usage guides, API references, and example scenes for the new WASM package.
  • Chores

    • Updated project structure, build scripts, and configuration files for improved maintainability and cross-platform support.

@codesandbox

codesandbox Bot commented Jul 6, 2025

Copy link
Copy Markdown

Review or Edit in CodeSandbox

Open the branch in Web Editor • VS Code • Insiders

Open Preview

@coderabbitai

coderabbitai Bot commented Jul 6, 2025 •

Copy link
Copy Markdown

Walkthrough

This update introduces a comprehensive overhaul and expansion of the Grida Canvas 2D rendering system. It adds a new WebAssembly (WASM) package with TypeScript bindings, developer tooling, and example assets. The Rust core is refactored for modularity, improved timing, resource management, and scene handling. New features include advanced hit testing, camera state tracking, tile caching strategies, and a robust timer/debounce system. Numerous files are reorganized or renamed, and extensive documentation and configuration updates are provided.

Changes

Files / Groups Change Summary
.github/workflows/publish-packages.yml Added a GitHub Actions workflow for building and publishing the Grida Canvas WASM package.
CONTRIBUTING.md Updated setup instructions and added a section for canvas WASM packaging.
Cargo.toml, crates/grida-canvas/Cargo.toml, crates/grida-canvas/AGENTS.md Updated workspace member paths and dependency paths for math2.
crates/.gitignore Updated ignore rules for IDE, local, and report directories.
crates/Dockerfile, crates/Makefile, crates/grida-canvas/Makefile, crates/grida-canvas/resources/.gitignore, crates/grida-canvas/web/README.md, crates/grida-canvas/web/main.js, crates/grida-canvas/src/window/tile_overlay.rs Removed obsolete Dockerfile, Makefiles, and redundant files.
crates/grida-canvas-wasm/* Introduced a new WASM package with TypeScript API, build config, example assets, and developer documentation.
crates/grida-canvas-wasm/src/main.rs Added and extended WASM-exported functions for application lifecycle, hit testing, camera, and devtools.
crates/grida-canvas-wasm/lib/* Added TypeScript API, WASM bindings, and initialization logic.
crates/grida-canvas-wasm/package.json, tsconfig.json, tsup.config.ts, serve.json Added package metadata, TypeScript, and build/server configurations.
crates/grida-canvas-wasm/example/* Added example scenes, HTML, and JS for interactive WASM demo.
crates/grida-canvas/src/* Major refactor: modularization, new devtools overlays, improved camera, hit testing, tile caching, and timer system. Added/renamed modules for helpers, sys, resource, dummy, hittest, devtools.
crates/grida-canvas/examples/* Updated examples for new resource paths, added animation and timer demos, and improved Figma/scene/image/font handling.
crates/grida-canvas/tests/* Updated and expanded tests for new modules, hit testing, and tile visibility logic.
crates/math2/* Added tile visibility logic, new rectangle and transform constructors, reorganized exports, and reordered imports.
crates/math2/tests/* Added and updated tests for tile logic, rectangle, and other math utilities.

Sequence Diagram(s)

WASM Canvas Initialization and Rendering (High-Level)

sequenceDiagram
    participant JS as main.js (Browser)
    participant WASM as GridaCanvas WASM
    participant Canvas as HTMLCanvasElement

    JS->>WASM: init({ locateFile })
    WASM-->>JS: Promise<Grida2DScene>
    JS->>Canvas: Get WebGL2 context
    JS->>WASM: createWebGLCanvasSurface(canvas)
    JS->>WASM: loadScene(demoSceneJson)
    loop Animation Frame
        JS->>WASM: redraw()
    end
    JS->>WASM: pointermove(x, y) / wheel / pan / zoom
    WASM-->>Canvas: Render updated scene
Loading

Application Command Handling (Native/WebGL)

sequenceDiagram
    participant App as ApplicationApi
    participant Renderer
    participant Camera
    participant TimerMgr

    App->>Renderer: loadScene / queue / flush
    App->>Camera: set_transform / set_zoom / translate
    App->>TimerMgr: set_timeout / set_interval / debounce
    TimerMgr-->>App: (on timer) queue_stable_frame
    App->>Renderer: flush (redraw)
Loading

Poem

( )    ( )   /)_
 (\_._/ )  ( . .)   The canvas now leaps from Rust to web,
  (  .  )   (")(")  With WASM and TypeScript, new scenes are spun.
 /|    |\           Tiles and timers, overlays in tow,
 (bunny hops)       Hit tests and gradients, all in a row.
 🥕 Let's draw, let's zoom, let's animate anew!

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 Clippy (1.86.0)
Updating crates.io index

warning: failed to write cache, path: /usr/local/registry/index/index.crates.io-1949cf8c6b5b557f/.cache/as/yn/async-trait, error: Permission denied (os error 13)
Downloading crates ...
Downloaded ab_glyph v0.2.29
error: failed to create directory /usr/local/registry/cache/index.crates.io-1949cf8c6b5b557f

Caused by:
Permission denied (os error 13)

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • 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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@vercel

vercel Bot commented Jul 6, 2025 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
grida ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 6, 2025 6:21am
6 Skipped Deployments
Name Status Preview Comments Updated (UTC)
code ⬜️ Ignored (Inspect) Jul 6, 2025 6:21am
legacy ⬜️ Ignored (Inspect) Jul 6, 2025 6:21am
backgrounds ⬜️ Skipped (Inspect) Jul 6, 2025 6:21am
blog ⬜️ Skipped (Inspect) Jul 6, 2025 6:21am
docs ⬜️ Skipped (Inspect) Jul 6, 2025 6:21am
viewer ⬜️ Skipped (Inspect) Jul 6, 2025 6:21am

@vercel
vercel Bot temporarily deployed to Preview – backgrounds July 6, 2025 06:02 Inactive
@vercel
vercel Bot temporarily deployed to Preview – viewer July 6, 2025 06:02 Inactive
@vercel
vercel Bot temporarily deployed to Preview – blog July 6, 2025 06:02 Inactive
@vercel
vercel Bot temporarily deployed to Preview – docs July 6, 2025 06:02 Inactive
@softmarshmallow
softmarshmallow marked this pull request as ready for review July 6, 2025 07:00

@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: 19

🔭 Outside diff range comments (4)
crates/math2/tests/snap_spacing.rs (1)

21-38: Avoid strict f32 equality in assertions

Comparing floating-point structs with assert_eq! is brittle – a tiny rounding error will panic even when the logic is correct. Consider:

-assert_eq!(result.a[0], vec![SnapProjectionPoint { p: 40.0, o: 30.0, fwd: 0 }]);
+let a0 = &result.a[0][0];
+assert!((a0.p - 40.0).abs() < 1e-4);
+assert!((a0.o - 30.0).abs() < 1e-4);
+assert_eq!(a0.fwd, 0);

A helper such as approx::assert_relative_eq! can make this terse.

crates/grida-canvas/src/painter/geometry.rs (1)

75-84: Validate dash pattern before applying PathEffect::dash

PathEffect::dash returns None when the slice length is odd or zero. A silent None here breaks dashed strokes without warning. Prefer explicit validation:

-if let Some(dashes) = stroke_dash_array {
-    if let Some(pe) = PathEffect::dash(dashes, 0.0) {
+if let Some(dashes) = stroke_dash_array {
+    if dashes.len() >= 2 && dashes.len() % 2 == 0 {
+        if let Some(pe) = PathEffect::dash(dashes, 0.0) {
             ...
         }
+    } else {
+        log::warn!("Ignoring invalid dash array (must be even length ≥2): {:?}", dashes);
+    }
 }
crates/math2/src/bezier.rs (1)

24-34: Handle the degenerate (linear) case in solve_quad to prevent divide-by-zero

When a is ≈ 0 the current implementation panics via 1/0 or returns NaN.
Safely downgrade to a linear equation first.

 fn solve_quad(a: f32, b: f32, c: f32) -> Vec<f32> {
-    let d = b * b - 4.0 * a * c;
-    if d < 0.0 {
-        Vec::new()
-    } else if d == 0.0 {
-        vec![-b / (2.0 * a)]
-    } else {
-        let sqrt_d = d.sqrt();
-        vec![(-b + sqrt_d) / (2.0 * a), (-b - sqrt_d) / (2.0 * a)]
-    }
+    const EPS: f32 = 1e-6;
+    if a.abs() < EPS {
+        // Degenerates to bx + c = 0
+        return if b.abs() < EPS { Vec::new() } else { vec![-c / b] };
+    }
+
+    let d = b * b - 4.0 * a * c;
+    if d < 0.0 {
+        Vec::new()
+    } else if d.abs() < EPS {
+        vec![-b / (2.0 * a)]
+    } else {
+        let sqrt_d = d.sqrt();
+        vec![(-b + sqrt_d) / (2.0 * a), (-b - sqrt_d) / (2.0 * a)]
+    }
 }
crates/grida-canvas/src/runtime/repository.rs (1)

133-142: Instantiate FontMgr once, not per insert

Every call to insert/add spins up a fresh FontMgr, which internally scans all system fonts. That’s expensive and unnecessary. Cache a single FontMgr (or reuse the one from TypefaceFontProvider) inside FontRepository instead.

-pub fn insert(&mut self, family: String, bytes: Vec<u8>) {
-    let family_fonts = self.fonts.entry(family.clone()).or_insert_with(Vec::new);
-
-    if let Some(tf) = FontMgr::new().new_from_data(&bytes, None) {
+pub fn insert(&mut self, family: String, bytes: Vec<u8>) {
+    let family_fonts = self.fonts.entry(family.clone()).or_insert_with(Vec::new);
+    // reuse a shared font manager
+    if let Some(tf) = self.font_mgr.new_from_data(&bytes, None) {

You’d need to add font_mgr: FontMgr to the struct and initialise it in new().

♻️ Duplicate comments (1)
crates/math2/tests/snap_spacing.rs (1)

55-61: Same precision caveat for centre-based points

Lines 55-61 again rely on exact f32 equality (fwd is fine, but not p/o). Apply the same tolerant strategy as above.

🧹 Nitpick comments (36)
crates/math2/tests/snap_spacing.rs (1)

66-69: Guard against index out of bounds in small gaps

When result.a or result.b is unexpectedly empty this test will panic before performing the len() assertion. Safer:

assert!(result.a.get(0).map(|v| v.len()).unwrap_or(0) == 1);
crates/math2/tests/raster.rs (1)

11-13: Prefer tolerant float comparison in raster tests

assert_eq!(res, vec![[0.0, …]]) can fail on some platforms when the algorithm returns -0.0. A small helper:

fn cmp(a: &[ [f32;2] ], b: &[ [f32;2] ]) -> bool {
    a.iter().zip(b).all(|(l,r)| (l[0]-r[0]).abs() < 1e-6 && (l[1]-r[1]).abs() < 1e-6)
}
assert!(cmp(&res, &expected));
crates/.gitignore (1)

21-26: Consider un-commenting .idea/ or removing it entirely

#.idea/ is still commented, meaning JetBrains project files will be committed if a contributor forgets. Either drop the comment char or delete the line to rely on global ignores.

crates/math2/tests/snap_canvas.rs (1)

20-32: Prefer tolerant float assertions to avoid brittle tests

Direct equality on f32 can intermittently fail due to rounding artefacts. A tiny epsilon guard keeps the test robust without obscuring intent.

-    assert_eq!(res.delta, [5.0, 0.0]);
-    assert_eq!(res.translated.x, 10.0);
+    const EPS: f32 = 1e-6;
+    assert!((res.delta[0] - 5.0).abs() < EPS && res.delta[1].abs() < EPS);
+    assert!((res.translated.x - 10.0).abs() < EPS);
crates/math2/tests/range.rs (1)

9-16: Use epsilon-based comparison for float fields in complex structs

UniformGapGroup equality ultimately relies on exact f32 matches; a harmless future refactor (e.g. gap computed via floats) could start failing this test. Consider asserting each float with a tolerance or leveraging assert_approx_eq! from float_cmp.

crates/grida-canvas/src/cache/mipmap.rs (1)

90-101: Minor optimisation: early exit avoids needless loop

best_for_zoom scans all levels even when the very first reversed element matches. A quick return inside the loop saves work, especially for deep chains. Not critical but free.

-        for (scale, image) in self.levels.iter().rev() {
-            if zoom <= *scale {
-                return Some(image);
-            }
-        }
-        Some(&self.levels[0].1)
+        for (scale, image) in self.levels.iter().rev() {
+            if zoom <= *scale {
+                return Some(image);
+            }
+        }
+        // unreachable when levels not empty, but keep explicit:
+        Some(&self.levels[0].1)
crates/math2/src/align.rs (1)

1-1: Import order nitpick – keep alphabetic grouping for clarity

While the re-ordering is harmless functionally, rustfmt’s default grouping is alphabetical (Vector2, distance). Deviating makes future diffs noisier. Consider reverting or adding a #[rustfmt::skip] if an intentional semantic order is required.

crates/grida-canvas/src/cache/vector_path.rs (1)

4-4: Minor style – consolidate std::collections uses

You now import HashMap after DefaultHasher. Grouping the two under a single use std::collections::{hash_map::DefaultHasher, HashMap}; keeps the prelude tidy and avoids churn in future re-orders.

crates/math2/tests/measurement.rs (1)

1-1: Style – consistent alphabetical import order

Tests were previously alphabetised; moving measure ahead of Rectangle maintains that convention:

-use math2::{auxiliary_line_xylr, guide_line_xylr, measure, Rectangle, RectangleSide};
+use math2::{auxiliary_line_xylr, guide_line_xylr, Rectangle, RectangleSide, measure};

Purely cosmetic but keeps diffs clean.

crates/math2/tests/raster_extended.rs (1)

2-3: Import ordering nitpick

Placing the single‐word Bitmap with the other raster_* items avoids split blocks:

-    raster_pascaltriangle, raster_resize, raster_scale, raster_smoothstep, raster_tile, Bitmap,
+    raster_pascaltriangle, raster_resize, raster_scale, raster_smoothstep, raster_tile, Bitmap,

No functional impact; adjust only if you want fully alphabetical listings.

crates/grida-canvas-wasm/Cargo.toml (1)

11-12: Confirm dependency pinning & WASM size impact

  1. serde_json = "1.0.140" pins an exact patch level; consider ^1.0 unless you have a reproducibility requirement.
  2. serde_json adds ~150 KB after wasm-bindgen-strip; if JSON is only needed behind a feature flag (e.g., debug/dev-tools), declare it optional to keep the release WASM smaller:
[dependencies]
serde_json = { version = "1", optional = true }

[features]
default = []
dev = ["serde_json"]

Please verify that the extra footprint is acceptable for your distribution artefacts.

crates/grida-canvas/src/hittest/mod.rs (1)

1-3: Consider exposing hit_tester for public docs or tests.

mod hit_tester; pub use hit_tester::HitTester; keeps the sub-module private, which is fine, but it also hides its docs and makes direct unit-testing of helper fns inside hit_tester harder. If you foresee external crate users, consider pub mod hit_tester; instead (or re-export selected items) so that docs.rs shows them and tests can live in hit_tester itself.

crates/grida-canvas/Cargo.toml (1)

29-35: Duplicate tokio spec – unify to avoid feature drift.

tokio appears in both dependencies (under native target) and dev-dependencies with slightly different feature sets (time missing in dev). Cargo will unify versions but feature mismatches can bite when tests use APIs behind the missing feature.

- tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] }
...
-[dev-dependencies]
-...
-tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
+[dev-dependencies]
+tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] }

Or reference it via workspace = true once you migrate to Cargo-workspace dependencies.

crates/grida-canvas/examples/texts.rs (1)

166-167: Hard-coded relative font paths break when run outside the repo root.

Use CARGO_MANIFEST_DIR (or another runtime config) to build absolute paths so the example works when copied or when cargo run --example texts is executed from the crate directory:

-    let caveat_font_path = "../fixtures/fonts/Caveat-VariableFont_wght.ttf".to_string();
-    let vt323_font_path = "../fixtures/fonts/VT323-Regular.ttf".to_string();
+    let caveat_font_path = format!(
+        "{}/../fixtures/fonts/Caveat-VariableFont_wght.ttf",
+        env!(\"CARGO_MANIFEST_DIR\")
+    );
+    let vt323_font_path = format!(
+        "{}/../fixtures/fonts/VT323-Regular.ttf",
+        env!(\"CARGO_MANIFEST_DIR\")
+    );

This avoids path resolution issues on CI, IDE run-configs, or when the crate is published.

crates/grida-canvas/src/cache/paragraph.rs (1)

3-7: Import rewrite correct – consider cheap hasher

Import now points at runtime::repository::FontRepository, matching the refactor.

While you are touching this area: the cache key uses std::collections::hash_map::DefaultHasher (SipHash). For tight render loops a faster non-cryptographic hasher (e.g. fxhash) can cut CPU. Worth a follow-up.

crates/grida-canvas-wasm/example/rectangle.grida (1)

1-1: Consider formatting JSON for better readability.

While the JSON is valid, the single-line format makes it difficult to read and maintain. For example files, consider pretty-printing the JSON to improve readability for developers studying the format.

-{"version":"0.0.1-beta.1+20250303","document":{"bitmaps":{},"images":{},"properties":{},"nodes":{"25575e75-a544-4fa3-b199-15d1906588b2":{"id":"25575e75-a544-4fa3-b199-15d1906588b2","name":"rectangle","locked":false,"active":true,"position":"absolute","top":0,"left":0,"opacity":1,"zIndex":0,"rotation":0,"fill":{"type":"solid","color":{"r":217,"g":217,"b":217,"a":1}},"width":100,"height":100,"style":{},"type":"rectangle","cornerRadius":0,"effects":[],"strokeWidth":0,"strokeCap":"butt"}},"scenes":{"main":{"type":"scene","guides":[],"edges":[],"constraints":{"children":"multiple"},"children":["25575e75-a544-4fa3-b199-15d1906588b2"],"id":"main","name":"main","backgroundColor":{"r":245,"g":245,"b":245,"a":1}}}}}
+{
+  "version": "0.0.1-beta.1+20250303",
+  "document": {
+    "bitmaps": {},
+    "images": {},
+    "properties": {},
+    "nodes": {
+      "25575e75-a544-4fa3-b199-15d1906588b2": {
+        "id": "25575e75-a544-4fa3-b199-15d1906588b2",
+        "name": "rectangle",
+        "locked": false,
+        "active": true,
+        "position": "absolute",
+        "top": 0,
+        "left": 0,
+        "opacity": 1,
+        "zIndex": 0,
+        "rotation": 0,
+        "fill": {
+          "type": "solid",
+          "color": {
+            "r": 217,
+            "g": 217,
+            "b": 217,
+            "a": 1
+          }
+        },
+        "width": 100,
+        "height": 100,
+        "style": {},
+        "type": "rectangle",
+        "cornerRadius": 0,
+        "effects": [],
+        "strokeWidth": 0,
+        "strokeCap": "butt"
+      }
+    },
+    "scenes": {
+      "main": {
+        "type": "scene",
+        "guides": [],
+        "edges": [],
+        "constraints": {
+          "children": "multiple"
+        },
+        "children": ["25575e75-a544-4fa3-b199-15d1906588b2"],
+        "id": "main",
+        "name": "main",
+        "backgroundColor": {
+          "r": 245,
+          "g": 245,
+          "b": 245,
+          "a": 1
+        }
+      }
+    }
+  }
+}
crates/math2/src/tile.rs (1)

29-40: Consider performance optimization for large datasets.

The algorithm correctly implements Z-buffer-like visibility computation. However, consider these performance optimizations for large datasets:

Optimization 1: Store only visible fragments in seen

 for rect in rects.iter() {
     let visible = region::difference(*rect, &seen);
     result.push(visible.clone());
-    seen.push(*rect);
+    seen.extend(visible);
 }

Optimization 2: Use spatial indexing for large rectangle counts
Consider using a spatial data structure (like R-tree) for the seen collection when dealing with many rectangles to reduce the O(n²) complexity of region difference operations.

.github/workflows/publish-packages.yml (2)

6-6: Fix trailing spaces.

Remove the trailing spaces after the workflow trigger section.

-    
+

47-47: Add missing newline at end of file.

YAML files should end with a newline character for better compatibility and consistency.

         run: pnpm publish-packages
+
crates/grida-canvas/src/sys/timeout.rs (1)

34-36: Consider implementing Default trait.

Since new() creates a default state, implementing the Default trait would be idiomatic Rust.

+impl Default for Timeout {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
 impl Timeout {
     /// Creates a new inactive timeout.
     ///
     /// To activate, call [`start`] with a duration and the current time.
     pub fn new() -> Self {
         Self { deadline: None }
     }
crates/grida-canvas/examples/animation.rs (1)

49-49: High-frequency updates may impact performance.

The 5ms update interval (200 FPS) may be unnecessarily high for smooth animation and could impact performance. Consider using a more reasonable frame rate like 60 FPS (16.67ms interval).

-                std::thread::sleep(std::time::Duration::from_millis(5));
+                std::thread::sleep(std::time::Duration::from_millis(16)); // ~60 FPS
crates/grida-canvas/src/sys/clock.rs (1)

126-131: Consider clamping the frequency calculation for edge cases.

While the zero check prevents division by zero, very small delta values could result in extremely high frequency values that might not be meaningful.

Consider adding an upper bound to prevent unrealistic frequency values:

 pub fn hz(&self) -> f64 {
-    if self.delta.as_secs_f64() > 0.0 {
-        1.0 / self.delta.as_secs_f64()
-    } else {
-        0.0
-    }
+    let delta_secs = self.delta.as_secs_f64();
+    if delta_secs > 0.0 {
+        // Clamp to reasonable max frequency (e.g., 10000 Hz)
+        (1.0 / delta_secs).min(10000.0)
+    } else {
+        0.0
+    }
 }
crates/grida-canvas-wasm/example/main.js (1)

24-24: Remove or conditionally enable console.log statements.

Debug logging should be removed from example code or made conditional.

-  console.log(Factory);
+  // console.log(Factory);
-  console.log(grida);
+  // console.log(grida);

Also applies to: 32-32

crates/grida-canvas/src/dummy/mod.rs (1)

82-82: Consider using a hash function for more varied colors.

The current modulo-based color calculation might create visible patterns.

For more visually diverse colors, consider:

-color: Color(((x * 5) % 255) as u8, ((y * 3) % 255) as u8, 128, 255),
+// Use a simple hash-like function for more color variety
+color: Color(
+    ((x * 137 + y * 149) % 256) as u8,
+    ((x * 163 + y * 173) % 256) as u8,
+    ((x * 179 + y * 191) % 200 + 56) as u8,
+    255
+),
crates/grida-canvas/examples/timer_demo.rs (3)

31-37: Unused counter in timeout callback.

The timeout callback reads the counter value but never modifies it, making the Arc<Mutex<>> wrapper unnecessary for this use case.

Consider either:

  1. Incrementing the counter to demonstrate state modification:
 let timeout_id = timer_system.set_timeout(Duration::from_millis(1000), move || {
+    let mut count = counter_clone.lock().unwrap();
+    *count += 1;
     println!(
         "   ⏰ Timeout fired! Counter: {}",
-        *counter_clone.lock().unwrap()
+        *count
     );
 });
  1. Or remove the shared state if not needed:
-let counter = Arc::new(Mutex::new(0));
-let counter_clone = counter.clone();
-
 // Set a timeout that fires after 1 second
 let timeout_id = timer_system.set_timeout(Duration::from_millis(1000), move || {
-    println!(
-        "   ⏰ Timeout fired! Counter: {}",
-        *counter_clone.lock().unwrap()
-    );
+    println!("   ⏰ Timeout fired!");
 });

48-52: Interval doesn't auto-cancel after reaching limit.

The comment mentions stopping after 5 intervals, but the interval continues running and is only cancelled at the end of the demo.

Consider implementing auto-cancellation within the interval callback:

 let interval_id = timer_system.set_interval(Duration::from_millis(500), move || {
     let mut count = interval_counter_clone.lock().unwrap();
     *count += 1;
     println!("   🔄 Interval fired! Count: {}", *count);
 
     // Stop after 5 intervals
     if *count >= 5 {
         println!("   🛑 Interval limit reached, stopping...");
+        // Note: Would need to pass timer_system reference or use a different pattern
+        // to actually cancel from within the callback
     }
 });

Alternatively, document that the interval continues until manually cancelled.


225-225: Inconsistent time source in test.

The test uses Instant::now() directly instead of using the clock abstraction like in the demos.

Consider using EventLoopClock for consistency:

+let mut clock = EventLoopClock::new();
 thread::sleep(Duration::from_millis(60));
-mgr.tick(Instant::now());
+clock.tick();
+mgr.tick(clock.now());
crates/grida-canvas/src/sys/timer.rs (4)

52-59: Consider using enum for callback storage.

The Timer struct stores both callback and interval_callback as separate Option fields, but only one is ever used based on timer_type.

Consider using an enum to reduce memory usage:

+enum TimerCallbackType {
+    OneShot(TimerCallback),
+    Interval(IntervalCallback),
+}
+
 struct Timer {
-    timer_type: TimerType,
     deadline: Instant,
     interval: Option<Duration>,
-    callback: Option<TimerCallback>,
-    interval_callback: Option<IntervalCallback>,
+    callback: Option<TimerCallbackType>,
     active: bool,
 }

95-95: Remove commented debug prints.

These commented println statements should be removed or converted to proper logging.

-// println!("Timer expired: {:?}, type: {:?}", id, timer.timer_type);

Also applies to: 125-126


119-129: Potential timer drift in interval rescheduling.

The interval rescheduling adds duration to the current deadline, which can cause drift if ticks are delayed.

Consider calculating the next deadline based on the original schedule:

 TimerType::Interval => {
     // Repeating timer, schedule next execution
     if let Some(interval) = timer.interval {
-        timer.deadline += interval;
+        // Calculate next deadline to avoid drift
+        let elapsed_intervals = (now.duration_since(timer.deadline).as_nanos() 
+            / interval.as_nanos()) + 1;
+        timer.deadline = timer.deadline + (interval * elapsed_intervals as u32);
     }
 }

363-366: Remove debug prints from tests.

Debug println statements should be removed from test code.

-println!("Setting up interval...");
 timer_system.set_interval(Duration::from_millis(10), move || {
-    println!("Interval callback executed!");
     *counter_clone.lock().unwrap() += 1;
 });

 // Wait for multiple intervals
-println!("Waiting 35ms for intervals...");
 thread::sleep(Duration::from_millis(35));

 // Tick multiple times to simulate regular updates
 for i in 0..5 {
-    println!("Tick {}", i);
     timer_system.tick(Instant::now());
     thread::sleep(Duration::from_millis(1));
 }

 let count = *counter.lock().unwrap();
-println!("Final count: {}", count);
 assert!(count >= 2, "Expected at least 2 intervals, got {}", count);

Also applies to: 370-371, 375-376, 380-382

crates/grida-canvas-wasm/lib/api.d.ts (1)

34-36: Consider using flat array for Transform2D.

The nested array representation [[a, b, c], [d, e, f]] might be less intuitive than a flat array or object representation.

Consider alternative representations:

// Option 1: Flat array (common in graphics APIs)
export type Transform2D = [number, number, number, number, number, number];

// Option 2: Named properties (more readable)
export type Transform2D = {
  a: number; b: number; tx: number;
  c: number; d: number; ty: number;
};
crates/grida-canvas/src/window/application_native.rs (2)

65-67: Consider adding "+" as an alternative zoom-in key binding.

The current implementation only checks for "=" which might not trigger on keyboard layouts where "+" requires shift. Consider matching both "=" and "+" for better compatibility.

match c.as_str() {
-    "=" => ApplicationCommand::ZoomIn,
+    "=" | "+" => ApplicationCommand::ZoomIn,
    "-" => ApplicationCommand::ZoomOut,

282-285: Consider propagating swap buffer errors.

Currently, swap buffer errors are only logged. Consider whether critical rendering errors should trigger more robust error handling or recovery.

crates/grida-canvas-wasm/src/main.rs (1)

189-206: Document memory management responsibility.

The function allocates memory for the return value that must be freed by the caller. This should be clearly documented.

Add a comment above the function:

/// Returns a pointer to a heap-allocated float array [x, y, width, height].
/// The caller is responsible for freeing this memory using deallocate().
crates/grida-canvas/src/cache/tile.rs (1)

87-92: Consider using a larger epsilon for zoom comparison.

Using f32::EPSILON for floating-point comparison might be too strict for zoom levels. Consider using a domain-specific epsilon like 1e-5 or 1e-6 to account for accumulated floating-point errors in zoom calculations.

 ImageTileCacheResolutionStrategy::Exact => {
     if let Some(tile) = tile_at_zoom {
-        (tile.zoom - current_zoom).abs() < f32::EPSILON
+        (tile.zoom - current_zoom).abs() < 1e-5
     } else {
         false
     }
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bdde1d9 and 3dc32bd.

⛔ Files ignored due to path filters (12)
  • Cargo.lock is excluded by !**/*.lock
  • crates/fixtures/fonts/Bungee-Regular.ttf is excluded by !**/*.ttf
  • crates/fixtures/fonts/Caveat-VariableFont_wght.ttf is excluded by !**/*.ttf
  • crates/fixtures/fonts/Fruktur-Regular.ttf is excluded by !**/*.ttf
  • crates/fixtures/fonts/VT323-Regular.ttf is excluded by !**/*.ttf
  • crates/fixtures/images/1024.jpg is excluded by !**/*.jpg
  • crates/fixtures/images/4k.jpg is excluded by !**/*.jpg
  • crates/fixtures/images/512.jpg is excluded by !**/*.jpg
  • crates/fixtures/images/8k.jpg is excluded by !**/*.jpg
  • crates/grida-canvas-wasm/lib/bin/grida_canvas_wasm.wasm is excluded by !**/*.wasm
  • crates/skia-safe-wasm-example/Cargo.lock is excluded by !**/*.lock
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (107)
  • .github/workflows/publish-packages.yml (1 hunks)
  • CONTRIBUTING.md (2 hunks)
  • Cargo.toml (1 hunks)
  • crates/.gitignore (1 hunks)
  • crates/Dockerfile (0 hunks)
  • crates/Makefile (0 hunks)
  • crates/grida-canvas-wasm/Cargo.toml (1 hunks)
  • crates/grida-canvas-wasm/README.md (1 hunks)
  • crates/grida-canvas-wasm/example/demo.grida (1 hunks)
  • crates/grida-canvas-wasm/example/index.html (1 hunks)
  • crates/grida-canvas-wasm/example/main.js (1 hunks)
  • crates/grida-canvas-wasm/example/rectangle.grida (1 hunks)
  • crates/grida-canvas-wasm/lib/api.d.ts (1 hunks)
  • crates/grida-canvas-wasm/lib/bin/.gitattributes (1 hunks)
  • crates/grida-canvas-wasm/lib/bin/grida-canvas-wasm.d.ts (1 hunks)
  • crates/grida-canvas-wasm/lib/index.ts (1 hunks)
  • crates/grida-canvas-wasm/package.json (1 hunks)
  • crates/grida-canvas-wasm/serve.json (1 hunks)
  • crates/grida-canvas-wasm/src/main.rs (3 hunks)
  • crates/grida-canvas-wasm/tsconfig.json (1 hunks)
  • crates/grida-canvas-wasm/tsup.config.ts (1 hunks)
  • crates/grida-canvas-wasm/web/README.md (0 hunks)
  • crates/grida-canvas-wasm/web/main.js (0 hunks)
  • crates/grida-canvas/AGENTS.md (1 hunks)
  • crates/grida-canvas/Cargo.toml (2 hunks)
  • crates/grida-canvas/Makefile (0 hunks)
  • crates/grida-canvas/benches/bench_mipmap.rs (1 hunks)
  • crates/grida-canvas/benches/bench_rectangles.rs (7 hunks)
  • crates/grida-canvas/examples/animation.rs (1 hunks)
  • crates/grida-canvas/examples/cache_picture.rs (1 hunks)
  • crates/grida-canvas/examples/camera.rs (4 hunks)
  • crates/grida-canvas/examples/figma.rs (6 hunks)
  • crates/grida-canvas/examples/fonts.rs (4 hunks)
  • crates/grida-canvas/examples/image.rs (1 hunks)
  • crates/grida-canvas/examples/srcset.rs (1 hunks)
  • crates/grida-canvas/examples/texts.rs (2 hunks)
  • crates/grida-canvas/examples/timer_demo.rs (1 hunks)
  • crates/grida-canvas/examples/webfonts.rs (1 hunks)
  • crates/grida-canvas/examples/winit_raf.rs (3 hunks)
  • crates/grida-canvas/resources/.gitignore (0 hunks)
  • crates/grida-canvas/src/cache/geometry.rs (1 hunks)
  • crates/grida-canvas/src/cache/mipmap.rs (1 hunks)
  • crates/grida-canvas/src/cache/mod.rs (1 hunks)
  • crates/grida-canvas/src/cache/paragraph.rs (1 hunks)
  • crates/grida-canvas/src/cache/scene.rs (3 hunks)
  • crates/grida-canvas/src/cache/tile.rs (9 hunks)
  • crates/grida-canvas/src/cache/vector_path.rs (1 hunks)
  • crates/grida-canvas/src/devtools/hit_overlay.rs (1 hunks)
  • crates/grida-canvas/src/devtools/mod.rs (1 hunks)
  • crates/grida-canvas/src/devtools/ruler_overlay.rs (1 hunks)
  • crates/grida-canvas/src/devtools/tile_overlay.rs (1 hunks)
  • crates/grida-canvas/src/dummy/mod.rs (1 hunks)
  • crates/grida-canvas/src/helpers/mod.rs (1 hunks)
  • crates/grida-canvas/src/hittest/hit_tester.rs (2 hunks)
  • crates/grida-canvas/src/hittest/mod.rs (1 hunks)
  • crates/grida-canvas/src/io/io_figma.rs (1 hunks)
  • crates/grida-canvas/src/io/io_json.rs (6 hunks)
  • crates/grida-canvas/src/lib.rs (1 hunks)
  • crates/grida-canvas/src/painter/geometry.rs (1 hunks)
  • crates/grida-canvas/src/painter/layer.rs (1 hunks)
  • crates/grida-canvas/src/painter/painter.rs (2 hunks)
  • crates/grida-canvas/src/resource/font_loader.rs (4 hunks)
  • crates/grida-canvas/src/resource/image_loader.rs (4 hunks)
  • crates/grida-canvas/src/resource/mod.rs (1 hunks)
  • crates/grida-canvas/src/runtime/camera.rs (5 hunks)
  • crates/grida-canvas/src/runtime/counter.rs (1 hunks)
  • crates/grida-canvas/src/runtime/mod.rs (1 hunks)
  • crates/grida-canvas/src/runtime/repository.rs (1 hunks)
  • crates/grida-canvas/src/runtime/scene.rs (14 hunks)
  • crates/grida-canvas/src/sys/clock.rs (1 hunks)
  • crates/grida-canvas/src/sys/mod.rs (1 hunks)
  • crates/grida-canvas/src/sys/timeout.rs (1 hunks)
  • crates/grida-canvas/src/sys/timer.rs (1 hunks)
  • crates/grida-canvas/src/window/application.rs (4 hunks)
  • crates/grida-canvas/src/window/application_native.rs (6 hunks)
  • crates/grida-canvas/src/window/application_native_demo.rs (3 hunks)
  • crates/grida-canvas/src/window/application_webgl.rs (3 hunks)
  • crates/grida-canvas/src/window/command.rs (1 hunks)
  • crates/grida-canvas/src/window/mod.rs (1 hunks)
  • crates/grida-canvas/src/window/state.rs (1 hunks)
  • crates/grida-canvas/src/window/tile_overlay.rs (0 hunks)
  • crates/grida-canvas/tests/camera.rs (1 hunks)
  • crates/grida-canvas/tests/hit_test.rs (2 hunks)
  • crates/grida-canvas/tests/mipmap.rs (1 hunks)
  • crates/grida-canvas/tests/resource_loader.rs (3 hunks)
  • crates/math2/src/align.rs (1 hunks)
  • crates/math2/src/bezier.rs (1 hunks)
  • crates/math2/src/layout.rs (2 hunks)
  • crates/math2/src/lib.rs (2 hunks)
  • crates/math2/src/measurement.rs (1 hunks)
  • crates/math2/src/rect.rs (4 hunks)
  • crates/math2/src/tile.rs (1 hunks)
  • crates/math2/src/transform.rs (1 hunks)
  • crates/math2/tests/color.rs (1 hunks)
  • crates/math2/tests/layout.rs (1 hunks)
  • crates/math2/tests/measurement.rs (1 hunks)
  • crates/math2/tests/packing.rs (1 hunks)
  • crates/math2/tests/range.rs (1 hunks)
  • crates/math2/tests/raster.rs (1 hunks)
  • crates/math2/tests/raster_extended.rs (1 hunks)
  • crates/math2/tests/rect.rs (2 hunks)
  • crates/math2/tests/rect_boolean.rs (1 hunks)
  • crates/math2/tests/region.rs (1 hunks)
  • crates/math2/tests/snap_advanced.rs (1 hunks)
  • crates/math2/tests/snap_canvas.rs (1 hunks)
  • crates/math2/tests/snap_spacing.rs (1 hunks)
  • crates/math2/tests/tile.rs (1 hunks)
⛔ Files not processed due to max files limit (45)
  • crates/math2/tests/vector2.rs
  • crates/math2/tests/viewport.rs
  • crates/skia-safe-wasm-example/Cargo.toml
  • crates/skia-safe-wasm-example/Makefile
  • crates/skia-safe-wasm-example/README.md
  • crates/skia-safe-wasm-example/src/main.rs
  • crates/skia-safe-wasm-example/web/index.html
  • crates/skia-safe-wasm-example/web/main.js
  • docker/grida-canvas-wasm.build.dockerfile
  • docs/@coli/index.mdx
  • docs/@design-sdk/index.mdx
  • editor/.env.example
  • editor/app/(dev)/canvas/experimental/skia/page.tsx
  • editor/app/(dev)/canvas/experimental/wasm-test/page.tsx
  • editor/app/(dev)/canvas/experimental/wasm/page.tsx
  • editor/app/(workbench)/[org]/[proj]/[id]/form/start/page.tsx
  • editor/grida-canvas-react/provider.tsx
  • editor/grida-canvas-react/renderer.tsx
  • editor/grida-canvas-react/use-editor.tsx
  • editor/grida-canvas-react/viewport/hooks/use-edge-scrolling.ts
  • editor/grida-canvas-react/viewport/size.tsx
  • editor/grida-canvas-react/viewport/surface-hooks.ts
  • editor/grida-canvas-react/viewport/ui/measurement.tsx
  • editor/grida-canvas-wasm-react/index.tsx
  • editor/grida-canvas-wasm-react/locate-file.ts
  • editor/grida-canvas/backends/dom.ts
  • editor/grida-canvas/backends/index.ts
  • editor/grida-canvas/backends/noop.ts
  • editor/grida-canvas/backends/wasm.ts
  • editor/grida-canvas/editor.ts
  • editor/grida-canvas/index.ts
  • editor/grida-canvas/plugins/follow.ts
  • editor/grida-canvas/reducers/document.reducer.ts
  • editor/grida-canvas/reducers/event-target.reducer.ts
  • editor/grida-canvas/reducers/index.ts
  • editor/grida-canvas/reducers/methods/duplicate.ts
  • editor/grida-canvas/reducers/methods/transform.ts
  • editor/grida-canvas/reducers/surface.reducer.ts
  • editor/next.config.ts
  • editor/package.json
  • editor/scaffolds/editor/action.ts
  • editor/scaffolds/editor/reducer.ts
  • editor/scaffolds/playground-canvas/playground.tsx
  • justfile
  • packages/grida-canvas-io-figma/lib.ts
💤 Files with no reviewable changes (7)
  • crates/grida-canvas-wasm/web/README.md
  • crates/grida-canvas/resources/.gitignore
  • crates/Dockerfile
  • crates/grida-canvas/Makefile
  • crates/grida-canvas/src/window/tile_overlay.rs
  • crates/Makefile
  • crates/grida-canvas-wasm/web/main.js
🧰 Additional context used
🧬 Code Graph Analysis (18)
crates/math2/src/bezier.rs (1)
crates/math2/src/rect.rs (1)
  • from_points (154-180)
crates/math2/tests/snap_spacing.rs (2)
crates/math2/src/snap.rs (1)
  • plot_distribution_geometry (21-112)
packages/grida-cmath/index.ts (1)
  • DistributionGeometry1D (4414-4461)
crates/math2/tests/raster_extended.rs (1)
packages/grida-cmath/index.ts (1)
  • Bitmap (3521-3525)
crates/math2/src/align.rs (1)
crates/math2/src/vector2.rs (1)
  • distance (178-180)
crates/math2/tests/range.rs (1)
crates/math2/src/range.rs (1)
  • group_ranges_by_uniform_gap (56-112)
crates/math2/tests/rect.rs (2)
crates/math2/src/rect.rs (2)
  • intersection (123-139)
  • intersection (268-270)
crates/math2/tests/layout.rs (1)
  • rect (3-10)
crates/math2/src/layout.rs (1)
crates/math2/tests/rect.rs (1)
  • rect (8-15)
crates/math2/tests/color.rs (1)
crates/math2/src/color.rs (4)
  • hex_to_rgba8888 (49-78)
  • rgba8888_to_hex (127-130)
  • rgba_to_unit8_chunk (82-89)
  • rgbaf_to_rgba8888 (102-109)
crates/grida-canvas/examples/winit_raf.rs (2)
crates/grida-canvas/src/window/application.rs (1)
  • new (274-310)
crates/grida-canvas/src/sys/scheduler.rs (1)
  • new (17-25)
crates/grida-canvas/src/painter/geometry.rs (1)
.ref/canvaskit/canvaskit.d.ts (4)
  • PathEffect (3119-3119)
  • PathOp (5010-5010)
  • RRect (4806-4806)
  • Rect (4794-4794)
crates/grida-canvas/examples/webfonts.rs (1)
crates/grida-canvas/src/helpers/webfont_helper.rs (3)
  • find_font_files_by_family (127-156)
  • load_webfonts_metadata (64-76)
  • load_webfonts_metadata (79-82)
crates/math2/src/rect.rs (2)
packages/grida-cmath/index.ts (1)
  • Vector4 (62-62)
crates/math2/src/vector2.rs (1)
  • intersection (134-142)
crates/math2/tests/tile.rs (1)
crates/math2/src/tile.rs (1)
  • z_punch_tiles (29-40)
crates/grida-canvas/src/cache/scene.rs (4)
crates/grida-canvas/src/cache/tile.rs (1)
  • update_tiles (328-400)
crates/grida-canvas-wasm/lib/api.d.ts (1)
  • Camera2D (236-270)
.ref/canvaskit/canvaskit.d.ts (1)
  • Surface (3247-3381)
crates/math2/src/rect.rs (2)
  • intersects (113-120)
  • intersects (263-265)
crates/grida-canvas-wasm/example/main.js (1)
crates/grida-canvas-wasm/lib/index.ts (1)
  • init (12-20)
crates/math2/src/lib.rs (4)
crates/math2/src/rect.rs (4)
  • tile (310-332)
  • is_uniform (695-697)
  • positive (565-572)
  • quantize (554-562)
crates/math2/src/raster.rs (3)
  • tile (123-139)
  • fract (14-16)
  • rectangle (100-112)
crates/math2/src/utils.rs (4)
  • mean (69-73)
  • is_uniform (56-66)
  • quantize (13-17)
  • nearest (26-33)
crates/math2/src/vector4.rs (1)
  • identical (5-7)
crates/grida-canvas/src/cache/geometry.rs (3)
crates/grida-canvas/src/node/schema.rs (2)
  • id (457-457)
  • id (462-478)
crates/grida-canvas/src/node/factory.rs (1)
  • id (13-17)
packages/grida-canvas-cg/lib.ts (1)
  • AffineTransform (65-68)
crates/grida-canvas/src/window/application.rs (14)
crates/grida-canvas/src/runtime/camera.rs (2)
  • rect (188-200)
  • new (48-54)
crates/grida-canvas/src/sys/timer.rs (6)
  • tick (89-137)
  • new (78-83)
  • default (255-257)
  • set_timeout (142-160)
  • set_interval (165-183)
  • debounce (190-213)
crates/grida-canvas/src/sys/clock.rs (3)
  • tick (107-112)
  • new (77-84)
  • now (118-120)
crates/grida-canvas/src/window/state.rs (2)
  • resize (49-52)
  • new (23-25)
crates/grida-canvas/src/io/io_json.rs (1)
  • parse (392-394)
crates/grida-canvas/src/dummy/mod.rs (2)
  • create_dummy_scene (4-58)
  • create_benchmark_scene (61-99)
crates/grida-canvas/src/window/application_native.rs (1)
  • new (223-259)
crates/grida-canvas/src/runtime/scene.rs (5)
  • new (89-105)
  • set_request_redraw (109-111)
  • queue (217-233)
  • frame (294-341)
  • draw (348-448)
crates/grida-canvas/src/hittest/hit_tester.rs (1)
  • new (27-29)
crates/grida-canvas/src/window/input.rs (1)
  • default (13-15)
crates/grida-canvas/src/devtools/tile_overlay.rs (1)
  • draw (10-54)
crates/grida-canvas/src/devtools/fps_overlay.rs (1)
  • draw (33-50)
crates/grida-canvas/src/devtools/stats_overlay.rs (1)
  • draw (33-56)
crates/grida-canvas/src/devtools/hit_overlay.rs (1)
  • draw (59-127)
🪛 LanguageTool
crates/grida-canvas-wasm/README.md

[uncategorized] ~40-~40: Possible missing comma found.
Context: ...nstance, you can use the locally served wasm like below. ```ts await init({ locat...

(AI_HYDRA_LEO_MISSING_COMMA)

🪛 YAMLlint (1.37.1)
.github/workflows/publish-packages.yml

[error] 6-6: trailing spaces

(trailing-spaces)


[error] 47-47: no new line character at the end of file

(new-line-at-end-of-file)

🔇 Additional comments (143)
crates/math2/tests/rect_boolean.rs (1)

1-1: Import-order change is purely cosmetic — all good.

Reordering the items inside the { … } group does not affect compilation or runtime behavior. If the intent is to keep imports alphabetically sorted, consider adding rustfmt/clippy::use_self rules so future diffs don’t capture noise, but otherwise this is fine.

crates/grida-canvas/examples/cache_picture.rs (1)

1-1: cg::sys::scheduler::FrameScheduler path is valid

  • pub mod sys; is declared in crates/grida-canvas/src/lib.rs
  • pub mod scheduler; lives unconditionally in crates/grida-canvas/src/sys/mod.rs
  • No Cargo feature gates sys or scheduler (features: figma-api/client, web, native-clock-tick only)

No changes needed here.

crates/math2/tests/packing.rs (1)

1-1: Import reorder only – looks good

Pure style change; no behavioural impact.

crates/math2/tests/layout.rs (1)

1-1: Import order tweak acknowledged

No functional difference; consistent with other test files.

crates/grida-canvas/AGENTS.md (1)

4-4: Updated link matches crate rename

../math2/README.md reflects the crate move; link should now resolve.

crates/math2/tests/snap_advanced.rs (1)

2-3: Only ordering of use items changed

Change is cosmetic; tests remain unaffected.

crates/math2/tests/snap_spacing.rs (1)

1-1: Import re-ordering is fine, but prefer explicit prelude for clarity

No functional impact; just keep an eye on import wild-growth in tests to avoid masking unnecessary items.

crates/math2/tests/raster.rs (1)

1-1: Import shuffle is harmless

No behaviour change – looks good.

crates/grida-canvas-wasm/lib/bin/.gitattributes (1)

1-1: Git LFS required – document or automate

Committing large .wasm binaries behind LFS is great, but builds will fail for contributors without LFS installed. Add a short note to CONTRIBUTING.md or enforce via CI (git lfs install --skip-smudge).

crates/grida-canvas/src/painter/geometry.rs (1)

7-7: Re-ordering imports only – OK

No functional impact.

crates/grida-canvas/examples/winit_raf.rs (2)

1-1: LGTM: Import path updated for module reorganization.

The import path change from cg::window::scheduler to cg::sys::scheduler correctly reflects the module restructuring.


60-60: LGTM: Improved terminology for frame rate measurement.

The change from "Frames in last second" to "Hz in last second" uses more precise terminology for frequency measurement.

Cargo.toml (1)

6-6: LGTM: Workspace member path updated for reorganization.

The path change from "crates/grida-math2" to "crates/math2" aligns with the workspace reorganization described in the PR.

crates/grida-canvas/tests/mipmap.rs (1)

1-1: LGTM: Import path updated for module reorganization.

The import path change from cg::mipmap to cg::cache::mipmap correctly reflects the restructuring where mipmap functionality was moved under the cache namespace.

crates/grida-canvas/src/painter/layer.rs (1)

2-3: LGTM: Import reordering for consistency.

The reordering of imports within the super::geometry module maintains the same functionality while improving code organization.

crates/math2/tests/region.rs (1)

1-1: LGTM: Import reordering for consistency.

The reordering of imports from math2 maintains the same functionality while improving code organization consistency.

crates/grida-canvas/src/cache/mod.rs (1)

1-3: Module exposure looks good

pub mod mipmap; cleanly exposes the new mip-mapping logic and unblocks downstream imports. No issues spotted.

crates/math2/src/measurement.rs (1)

1-1: Import reorder looks fine – no functional change.

Purely stylistic; nothing to flag.

crates/grida-canvas/src/helpers/mod.rs (1)

1-1: Module addition LGTM.

Centralising helpers under helpers::* improves discoverability.

crates/grida-canvas/Cargo.toml (1)

15-15: Path fix for math2 is correct.

Update aligns with the workspace rename.

crates/grida-canvas/examples/texts.rs (1)

4-4: Import path update matches new module layout – ok.

crates/grida-canvas/src/io/io_figma.rs (1)

1-1: Import path update looks good

webfont_helper is now namespaced under crate::helpers, which matches the new module layout. No further action required.

crates/grida-canvas/src/runtime/repository.rs (1)

1-6: Consistent module paths – OK

The switch to crate::cache::mipmap keeps the file in sync with the new cache hierarchy. The additional FontMgr, Image re-ordering is stylistic only and won’t change behaviour.

crates/grida-canvas/benches/bench_mipmap.rs (1)

1-2: Benchmark still compiles

Path updated to cache::mipmap; imports remain aligned with prod code. No further issues.

crates/math2/tests/color.rs (1)

1-3: Re-ordered imports are harmless

Purely cosmetic reorder; tests continue to assert colour conversions correctly.

crates/grida-canvas/src/devtools/ruler_overlay.rs (1)

64-65: Good encapsulation improvement.

The change from direct field access to getter methods aligns with the Camera2D API refactor. This provides better encapsulation and controlled access to camera properties.

crates/grida-canvas-wasm/serve.json (1)

1-13: CORS configuration looks good for development.

The configuration correctly sets up CORS headers for WASM and JS files, which is essential for proper WASM loading. The wildcard pattern properly matches the target file types.

Note: The Access-Control-Allow-Origin: * is appropriate for development but should be configured with specific origins for production deployments.

crates/grida-canvas/src/runtime/mod.rs (1)

2-3: Good module organization.

The addition of counter and repository modules under runtime is well-structured and aligns with the broader refactor to improve frame counting and resource management capabilities.

crates/grida-canvas/src/devtools/hit_overlay.rs (2)

8-8: Import path updated correctly.

The import path change aligns with the module restructuring where FontRepository moved from crate::repository to crate::runtime::repository.


9-9: Import reordering is consistent.

The reordering of skia_safe imports appears to follow a consistent style, moving textlayout to the front of the import list.

crates/grida-canvas/examples/srcset.rs (2)

141-141: Path standardization is good.

The update from "resources/4k.jpg" to "../fixtures/images/4k.jpg" aligns with the broader resource path standardization across the codebase.


144-144: Error message updated consistently.

The error message correctly reflects the new fixtures directory structure, maintaining consistency with the path change.

crates/grida-canvas/src/painter/painter.rs (3)

8-8: LGTM: Import path updated for module reorganization.

The import path correctly reflects the new module structure where repositories are now under runtime::repository.


10-10: LGTM: Import reordering for better organization.

The reordering of skia_safe imports groups related items together, improving readability.


864-864: LGTM: Consistent import path update in test module.

The test module import path is correctly updated to match the new module structure.

CONTRIBUTING.md (2)

16-17: LGTM: Clear setup instructions for required tool.

The addition of just installation instructions helps contributors set up the required tooling.


43-47: LGTM: Clear documentation for new build process.

The new section provides straightforward instructions for building the canvas WASM package, aligning with the PR's focus on WASM backend integration.

crates/grida-canvas/tests/camera.rs (1)

10-10: LGTM: API method name updated for clarity.

The change from set_position to set_center provides a more descriptive method name while maintaining the same functionality.

crates/grida-canvas-wasm/tsconfig.json (1)

1-6: LGTM: Appropriate TypeScript configuration for WASM package.

The configuration includes essential options for module compatibility, which is crucial for WASM bindings that need to work with different module systems.

crates/grida-canvas-wasm/example/index.html (2)

7-7: LGTM: More descriptive page title.

The title change from "rust-skia Wasm sample" to "WASM Example" is more concise and descriptive.


8-8: LGTM: Modern module loading approach.

The change to use type="module" and load only main.js reflects a cleaner, more modern approach where the main script handles module initialization internally.

crates/grida-canvas/examples/webfonts.rs (1)

1-1: Module imports are valid

Verified that:

  • crates/grida-canvas/src/helpers/webfont_helper.rs publicly exports find_font_files_by_family and load_webfonts_metadata
  • crates/grida-canvas/src/resource/mod.rs re-exports FontLoader

No further changes required.

crates/math2/tests/rect.rs (2)

3-5: Good import organization.

The import statements have been reordered for better readability and consistency.


49-52: Excellent test enhancement for intersection commutativity.

The addition of the commutativity test is a valuable improvement that ensures the intersection function behaves correctly regardless of argument order. This property is mathematically expected for rectangle intersection operations and the test helps prevent regression bugs.

crates/grida-canvas/src/sys/mod.rs (1)

1-4: All declared system submodules verified and properly implemented.

Verified presence and substantial content in each file:

  • crates/grida-canvas/src/sys/clock.rs: 133 lines
  • crates/grida-canvas/src/sys/scheduler.rs: 88 lines
  • crates/grida-canvas/src/sys/timeout.rs: 63 lines
  • crates/grida-canvas/src/sys/timer.rs: 429 lines

No missing or stub modules detected; no further action required.

crates/math2/src/layout.rs (2)

3-3: LGTM: Import ordering improvement

The reordering of imports follows alphabetical ordering conventions, which improves code consistency.


123-128: LGTM: Improved code formatting

The expansion of the single-line if-else to use explicit braces improves readability and follows standard Rust formatting practices.

crates/grida-canvas/tests/resource_loader.rs (4)

1-3: LGTM: Module import updates align with resource restructuring

The import paths have been correctly updated to use the new resource module structure, which improves code organization.


7-13: LGTM: Improved test utility function naming and path structure

The rename from resource_path to fixture_path is more descriptive and the path change to "../fixtures" better reflects the test asset organization.


19-19: LGTM: Better test asset organization

The addition of the fonts/ subdirectory improves test asset organization and clarity.


30-30: LGTM: Consistent test asset organization

The addition of the images/ subdirectory maintains consistency with the font asset organization.

crates/math2/src/transform.rs (1)

24-31: LGTM: Useful constructor method for affine transforms

The new from_acebdf method provides a clean way to construct affine transforms from matrix elements. The documentation clearly explains the parameter order and the implementation correctly maps to the internal matrix structure.

crates/grida-canvas/src/devtools/mod.rs (1)

1-5: LGTM: Well-organized developer tools module structure

The module declaration is clean and provides a logical organization for developer tools overlays. The consistent naming convention and comprehensive coverage of debugging aspects (FPS, hit testing, rulers, stats, and tiles) demonstrates good design.

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

17-17: LGTM: Improved struct naming for clarity

The rename from State to SurfaceState is more descriptive and clearly indicates the struct's purpose in managing the rendering surface state.


22-25: LGTM: Consistent implementation updates

The constructor and impl block have been consistently updated to use the new SurfaceState name.


32-33: LGTM: Documentation updated to reflect new naming

The documentation comment has been properly updated to reference the new SurfaceState name, maintaining consistency.

crates/grida-canvas-wasm/tsup.config.ts (1)

1-11: Configuration looks well-structured for WASM package.

The tsup configuration is properly set up with appropriate entry point, dual format output (ESM/CJS), TypeScript declarations, and clean builds. The publicDir pointing to ./lib/bin correctly handles static WASM assets.

crates/math2/src/rect.rs (2)

39-46: Well-designed constructor for explicit parameter creation.

The from_xywh method provides a clear and explicit way to create rectangles from individual parameters, which is particularly useful for FFI scenarios.


148-150: Appropriate FFI conversion method.

The to_vec4 method correctly converts the Rectangle to a 4-element array format [x, y, width, height] suitable for FFI usage. The comment clearly indicates its purpose.

crates/grida-canvas-wasm/package.json (1)

1-32: Well-structured package configuration.

The package.json follows npm best practices with proper scoping, metadata, build scripts, and dependency management. The version 0.0.5 appropriately indicates early development stage.

crates/grida-canvas/tests/hit_test.rs (2)

2-2: Module import updated correctly.

The import change from cg::hit_test to cg::hittest aligns with the module restructuring mentioned in the AI summary.


91-147: Comprehensive test for intersects functionality.

The new test function intersects_returns_all_nodes_in_rect properly validates the intersects method behavior:

  • Creates appropriate test data with rectangle and container nodes
  • Tests both single and multiple intersections
  • Verifies correct node ordering (deepest to shallowest)
  • Validates node counts and IDs match expectations

The test logic is sound and provides good coverage for the new functionality.

crates/grida-canvas/src/resource/mod.rs (1)

1-7: LGTM! Clean module organization.

The module structure follows Rust conventions with appropriate visibility controls and clean re-exports for a unified resource loading interface.

crates/grida-canvas-wasm/README.md (1)

1-39: LGTM! Comprehensive documentation.

The README provides clear installation instructions, usage examples, and development setup guidance that will help users get started with the WASM package.

crates/grida-canvas/benches/bench_rectangles.rs (3)

3-3: LGTM! Added necessary Camera2D import.

The import addition supports the new renderer initialization requirements.


94-101: LGTM! Consistent renderer initialization pattern.

The updated renderer initialization with explicit backend, callback, and Camera2D follows the new API requirements. The pattern is consistently applied across all benchmark functions.


116-117: LGTM! Updated to explicit queue and flush pattern.

The change from queue() to queue_unstable() + flush() provides more explicit control over the rendering pipeline. This pattern is consistently applied across all benchmarks.

crates/grida-canvas/src/resource/font_loader.rs (3)

1-2: LGTM! Improved imports for typed event system.

The addition of HostEvent import supports the transition to a more type-safe event system.


20-20: LGTM! Enhanced type safety with HostEvent.

The change from EventLoopProxy<()> to EventLoopProxy<HostEvent> provides better type safety and structure for the event system.


110-114: LGTM! Structured event dispatch with typed payload.

The transition from sending unit events to structured HostEvent::FontLoaded events with meaningful payload improves the event system's type safety and usability.

crates/math2/src/tile.rs (1)

1-28: LGTM! Excellent documentation and clear algorithm design.

The function documentation is comprehensive with clear explanations of the Z-buffer simulation approach and usage examples.

crates/grida-canvas/src/hittest/hit_tester.rs (2)

4-4: LGTM: Import consolidation improves readability.

The consolidation of multiple math2 imports into a single line enhances code readability without changing functionality.


153-170: LGTM: Well-implemented rectangle intersection method.

The intersects method correctly follows the established pattern of other hit testing methods in this struct. The implementation properly:

  • Retrieves candidate indices from the cache
  • Sorts indices for consistent ordering
  • Iterates in reverse order to maintain DOM-like event bubbling semantics
  • Uses appropriate rectangle intersection logic

The method complements the existing point-based hit testing capabilities well.

crates/grida-canvas/src/lib.rs (1)

2-13: LGTM: Well-structured module reorganization enhances architecture.

The module reorganization systematically improves the crate's architecture by:

  • Consolidating resource management under the resource module
  • Renaming hit_test to hittest for consistency
  • Adding new functionality modules (devtools, sys, dummy)
  • Better organizing utilities under helpers

This restructuring aligns with the broader refactoring effort mentioned in the AI summary and should improve code maintainability and modularity.

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

2-9: LGTM: Command enum refactoring aligns with architectural shift.

The rename from WindowCommand to ApplicationCommand and the updated variants appropriately reflect the shift to application-level command handling:

  • None variant provides a useful default state
  • ToggleDebugMode aligns with the new devtools functionality
  • Removal of window-specific commands (Close, Redraw, Resize) suggests these are now handled at a more appropriate abstraction level

This change supports the broader refactoring toward unified application command handling mentioned in the AI summary.

crates/grida-canvas/src/cache/scene.rs (1)

156-169: LGTM: Method signature simplification improves API design.

The updated update_tiles method signature effectively:

  • Eliminates redundant width and height parameters by deriving them directly from the surface
  • Introduces the partial parameter to control tile update behavior, which aligns with the tile cache refactoring
  • Maintains the same functional behavior while providing a cleaner API

This change is consistent with the broader tile caching improvements mentioned in the AI summary and reduces parameter redundancy.

crates/grida-canvas/src/resource/image_loader.rs (4)

1-6: LGTM: Import updates support strongly typed event handling.

The addition of HostEvent import and reorganization of existing imports supports the transition to strongly typed event handling while maintaining clean import organization.


22-23: LGTM: Strongly typed event proxy improves type safety.

The change from EventLoopProxy<()> to EventLoopProxy<HostEvent> provides better type safety and aligns with the unified event handling architecture.


63-63: LGTM: Method signature updated for consistent typing.

The new_lifecycle method signature correctly updated to accept the strongly typed EventLoopProxy<HostEvent> parameter.


94-98: LGTM: Event sending upgraded to typed events.

The change from sending unit events to HostEvent::ImageLoaded with ImageMessage payload provides:

  • Better type safety
  • Richer event information
  • Consistency with the unified event handling architecture

This improvement supports better event handling and debugging capabilities.

crates/grida-canvas/examples/camera.rs (2)

254-255: Approve the new queue/flush pattern.

The separation of rendering into queue_unstable() followed by flush() provides better control over the rendering pipeline and aligns with the updated renderer architecture.


234-244: Memory safety of raw pointer usage is safe

The window_ptr closure holds a pointer to the locally scoped window and is invoked within the same main event loop—so window outlives any calls to request_redraw(). No other raw‐pointer patterns were found, and this usage matches the intended example. No changes required.

crates/grida-canvas-wasm/example/demo.grida (1)

1-1: Demo JSON Validated – Approved

The crates/grida-canvas-wasm/example/demo.grida file is well-structured and valid JSON, and it provides comprehensive demo content for the WASM canvas example.

No changes required.

As a best practice, consider adding a CI step to validate this file automatically, for example:

jq . crates/grida-canvas-wasm/example/demo.grida > /dev/null
crates/grida-canvas/src/devtools/tile_overlay.rs (3)

7-17: Good early return for empty tiles.

The early return when tiles are empty prevents unnecessary canvas operations and paint object creation.


20-30: Well-structured paint configuration.

The separation of paint objects for different visual elements (green for tile keys, red for actual tile rectangles) provides clear visual distinction for debugging purposes.


32-53: Stroke width adjustment is correct.

The calculation of adding half the stroke width to both axes and subtracting the full stroke width from width/height properly centers the stroke on the rectangle’s border. No other instances of this pattern were found in the codebase, and it matches standard rendering practice—no changes needed.

crates/grida-canvas/src/sys/timeout.rs (2)

3-25: Excellent documentation and examples.

The comprehensive documentation with usage examples makes this module highly maintainable and user-friendly. The external clock pattern is well-explained.


26-63: Solid timeout implementation.

The implementation is clean and follows good Rust practices:

  • Proper use of Option<Instant> for state management
  • Clear method naming and functionality
  • No unnecessary complexity
crates/math2/tests/tile.rs (5)

1-10: Well-structured helper function and imports.

The helper function rect provides a clean API for creating Rectangle instances in tests, improving readability and maintainability.


12-18: Comprehensive basic test case.

The test correctly validates that non-overlapping rectangles remain unchanged, which is fundamental to the z-punch algorithm.


50-56: Excellent area preservation validation.

The test correctly validates that the total visible area equals the original area minus the overlapping area, demonstrating good understanding of the algorithm's geometric properties.


183-197: Good edge case coverage for degenerate rectangles.

Testing zero-sized rectangles ensures the algorithm handles edge cases gracefully without crashing or producing invalid results.


233-251: Robust area preservation verification.

This test provides comprehensive validation of the core geometric property that total visible area should be preserved across all fragments.

crates/math2/src/lib.rs (2)

15-15: New tile module addition looks good.

The tile module is properly integrated into the crate structure, supporting the new z-punch functionality demonstrated in the test file.


24-82: Module reorganization maintains API consistency.

The reorganization of pub use statements maintains all exported entities while improving organization. The alphabetical ordering and consistent formatting enhance maintainability.

crates/grida-canvas/src/window/mod.rs (2)

1-4: Module reorganization improves structure.

Moving application to the top and introducing the input module suggests a cleaner architectural separation of concerns.


19-19: Ensure application_webgl builds cleanly on all targets

The application_webgl module is now included unconditionally, but its internal code still uses #[cfg(target_arch = "wasm32")] and #[cfg(not(target_arch = "wasm32"))] guards. No unguarded wasm-bindgen or web-sys imports were found.

Points to verify manually:

  • Unconditional imports of gl::types and skia_safe::gpu::gl::FramebufferInfo pull in the gl and skia-safe (with "gpu","gl") crates on every target.
  • Confirm that the gl crate builds and links correctly on your native platforms (and on wasm32 if you ever compile there).
  • Ensure that enabling Skia’s GPU + GL features doesn’t break non-WebGL builds (e.g., missing OpenGL libraries).

Please verify these dependencies compile and link as expected on your target platforms.

crates/grida-canvas/examples/animation.rs (1)

8-37: Well-structured scene creation function.

The create_scene function correctly demonstrates dynamic scene generation with mathematical transformations for position, rotation, and color changes.

crates/grida-canvas/src/runtime/counter.rs (4)

1-12: Well-designed frame counter structure.

The FrameCounter struct with prev and next fields provides a clean abstraction for tracking frame progression with clear semantics.


14-20: Solid queue implementation with edge case handling.

The queue method correctly handles the case where next <= prev by ensuring frame progression, preventing frame number regression.


42-45: Proper use of saturating arithmetic.

Using saturating_sub prevents underflow in the pending_count calculation, ensuring robustness against potential edge cases.


77-109: Comprehensive test coverage for basic functionality.

The test thoroughly validates the core frame counter operations including queuing, flushing, and state tracking.

crates/grida-canvas/src/sys/clock.rs (1)

1-133: Well-designed event loop clock implementation!

The EventLoopClock is well-structured with clear documentation, appropriate for single-threaded event loop integration. The implementation correctly handles timing calculations and irregular tick intervals.

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

1-60: Clean refactoring to use the new application architecture!

The migration to NativeApplication::new and strongly typed HostEvent improves code organization and type safety. The simplified initialization and direct access to renderer and devtools settings make the code more maintainable.

crates/grida-canvas/src/dummy/mod.rs (1)

1-99: Well-structured dummy scene generators!

Both functions provide useful test scenes - a simple one for basic testing and a benchmark scene for performance evaluation. The code is clean and follows good practices with proper use of NodeFactory and NodeRepository.

crates/grida-canvas/src/cache/geometry.rs (1)

265-289: Approve flexible ID handling with &str parameters

Confirmed that NodeId is defined as a type alias for String in
• crates/grida-canvas/src/node/schema.rs:9 (pub type NodeId = String;)

This makes the switch from &NodeId to &str in the following methods safe and ergonomic, as HashMap<String, …>::get(&str) is supported:

• crates/grida-canvas/src/cache/geometry.rs
– get_world_transform
– get_world_bounds
– get_render_bounds
– get_parent
– has

No further changes needed.

crates/grida-canvas/examples/timer_demo.rs (2)

1-23: Well-structured demo organization.

The example provides a clear demonstration of the timer system with three distinct use cases. The imports are minimal and the main function layout is easy to follow.


71-129: Excellent debouncer demonstration.

The demo effectively illustrates debounce behavior with both leading/trailing and trailing-only configurations. The console output clearly shows when operations execute.

crates/grida-canvas/src/sys/timer.rs (3)

4-41: Excellent module documentation.

The documentation clearly explains the timer system's purpose and provides practical usage examples. The integration with EventLoopClock is well-documented.


275-308: Well-implemented debounce logic.

The debounce implementation correctly handles leading/trailing execution, uses weak references to prevent memory leaks, and properly manages concurrent access with Mutex.


139-183: Clean and intuitive timer API.

The public methods provide a comprehensive interface for timer management with appropriate return types and lifetime bounds.

crates/grida-canvas-wasm/lib/bin/grida-canvas-wasm.d.ts (2)

1-14: Proper TypeScript module declaration pattern.

The module uses the correct UMD-compatible export pattern and appropriately references emscripten types.


15-131: Well-organized and comprehensive WASM interface.

The interface is logically organized with clear sections for different functionality. Method signatures are consistent and cover all necessary canvas operations.

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

52-98: Well-structured runtime interface design.

The separation between runtime and scene interfaces is logical. Good use of readonly modifiers for immutable properties.


117-187: Excellent DOM-inspired API design.

The API design cleverly mirrors web standards (Document, Selection, etc.), making it intuitive for web developers. The references to MDN documentation are helpful.


236-270: Complete and intuitive Camera2D interface.

The camera interface provides all necessary 2D camera operations with clear property semantics and appropriate use of readonly modifiers.

crates/grida-canvas/examples/figma.rs (5)

1-22: Excellent documentation and CLI updates.

The documentation clearly explains all three loading methods with practical examples. The CLI structure properly supports the new archive directory option.

Also applies to: 50-52


54-67: Good extraction of configuration logic.

Extracting the Figma API configuration into a helper function reduces duplication and improves maintainability.


78-99: Robust archive directory loading implementation.

The implementation includes comprehensive validation with clear error messages for missing directories and required files.


146-226: Well-structured image loading with multiple source support.

The refactored image loading function cleanly handles all source types (archive, local directory, Figma API) with appropriate logging and error handling.


277-293: Comprehensive image loading conditions.

The updated conditions correctly handle all combinations of flags and source types to determine whether images should be loaded.

crates/grida-canvas/src/window/application_native.rs (4)

78-91: LGTM!

The updated function signature and event loop initialization properly support the new event-driven architecture with typed user events.


253-256: Verify if 240Hz tick rate is intentional.

The tick thread sends events 240 times per second, which is unusually high. Most applications use 60Hz or 120Hz. This high frequency might cause unnecessary CPU usage.

Is this tick rate intentional for smooth animations, or should it be reduced to a more standard rate like 60Hz?


271-273: Good modifier state tracking.

Properly updates the stored modifier state to ensure keyboard shortcuts work correctly.


318-322: Proper scene loading handling.

Good practice to queue an unstable frame and request redraw after loading a new scene.

crates/grida-canvas/src/runtime/camera.rs (4)

21-36: Good encapsulation and change tracking design.

Making the transform private and adding proper change tracking fields improves the API design and enables optimization based on camera state changes.


77-90: Excellent change detection implementation.

Using quantized transform comparison is smart - it prevents unnecessary updates from minor floating-point variations while detecting meaningful visual changes.


226-228: LGTM!

Correctly compares zoom levels between current and previous transforms.


238-287: Good test coverage for change tracking.

The unit tests properly verify that previous transform states are tracked and change detection works as expected.

crates/grida-canvas/src/io/io_json.rs (3)

197-242: Well-designed vector path structures.

The vector network representation with indexed vertices and bezier tangents is memory-efficient and aligns with standard vector graphics formats.


318-336: Excellent fill type design.

The tagged enum approach cleanly supports solid colors and gradients with proper transform support for positioning.


683-696: Improved error handling for unknown nodes.

Creating an ErrorNode with descriptive information is better than silently creating an empty container. This helps with debugging.

crates/grida-canvas-wasm/src/main.rs (2)

32-38: Good addition of tick function.

Essential for animation and time-based updates in the WASM environment.


109-121: Correct affine transform parameter order.

The parameter order (a,c,e,b,d,f) properly matches the column-major matrix format for 2D transforms.

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

29-50: Well-structured WebGL initialization.

Proper WebGL2 context creation with appropriate attributes and good practice of resizing after initialization.


88-97: Good string memory management pattern.

The helper functions properly handle UTF-8 string allocation and deallocation with null terminators.

crates/grida-canvas/src/cache/tile.rs (1)

116-117: LGTM! Blur parameters are well-chosen.

The blur scale of 1.0 provides linear mapping and the max radius of 8.0 prevents excessive blurring while still providing smooth transitions between zoom levels.

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

73-151: LGTM! Clean trait implementation.

The ApplicationApi trait implementation properly delegates all methods to the inner UnknownTargetApplication instance, providing a clean and consistent interface.

crates/grida-canvas/src/runtime/scene.rs (3)

217-219: Incomplete dependency checking implementation.

The TODO comment and commented-out code suggest that dependency checking for frame queuing is not fully implemented. This could lead to unnecessary redraws or missed updates.

Could you clarify if dependency checking is planned for a future iteration or if this was intentionally removed?


163-166: LGTM! Good use of frame stability for optimization.

The implementation correctly uses the stable frame flag to enable tile caching, which helps optimize performance by only updating tiles during stable frames.

Also applies to: 334-334


197-205: LGTM! Safe resource cleanup.

The free method properly handles resource cleanup by safely swapping out the backend and abandoning the GPU context.

crates/grida-canvas/src/window/application.rs (2)

15-51: LGTM! Well-designed application API trait.

The ApplicationApi trait provides a comprehensive and well-organized interface for application control, covering rendering, input, debugging, and scene management.


541-585: LGTM! Clean timer management API.

The timer management methods provide a well-designed API with proper trait bounds and clear documentation.

frame_count: 0,
start_time: now,
scheduler: scheduler::FrameScheduler::new(120).with_max_fps(144),
scheduler: scheduler::FrameScheduler::new(u32::MAX).with_max_fps(u32::MAX),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify the performance impact of uncapped frame scheduling.

The scheduler initialization now uses u32::MAX for both target and max FPS, removing previous caps of 120 and 144 FPS. This allows uncapped frame scheduling which might have performance implications.


🏁 Script executed:

#!/bin/bash
# Description: Verify if there are any performance safeguards or documentation about uncapped frame scheduling
# Expected: Find documentation or code that explains the implications of using u32::MAX for FPS

# Search for comments or documentation about FPS limits and performance
rg -A 5 -B 5 "u32::MAX|uncapped|unlimited.*fps|performance.*fps" --type rust

# Check for any validation or bounds checking in the FrameScheduler implementation
ast-grep --pattern 'impl $_ for FrameScheduler {
  $$$
}'

Length of output: 913


Add safeguards or documentation for uncapped frame scheduling

I didn’t find any existing docs or validation in FrameScheduler for using u32::MAX as target/max FPS. Unbounded frame rates can lead to 100% CPU/GPU usage, overheating, or battery drain. Please address this by:

  • Documenting the intended use-case and impacts of uncapped FPS in the public API/docs.
  • Adding bounds checks or sane defaults in FrameScheduler to prevent runaway frame loops.
  • Or reverting to a configurable cap (e.g. 120/144 FPS) with the option to override.

Affected snippet (crates/grida-canvas/examples/winit_raf.rs:91):

-   scheduler: scheduler::FrameScheduler::new(120).with_max_fps(144),
+   scheduler: scheduler::FrameScheduler::new(u32::MAX).with_max_fps(u32::MAX),

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In crates/grida-canvas/examples/winit_raf.rs at line 91, the FrameScheduler is
initialized with u32::MAX for max FPS, which can cause excessive CPU/GPU usage.
To fix this, add documentation in the FrameScheduler public API explaining the
risks and intended use of uncapped FPS. Implement validation in FrameScheduler
to clamp the max FPS to a reasonable upper limit or provide a configurable cap
like 120 or 144 FPS by default, allowing overrides. Alternatively, revert the
example to use a capped FPS value to prevent runaway frame loops.


// Load the Caveat font from local resources
let font_data = fs::read("resources/Caveat-VariableFont_wght.ttf").unwrap();
let font_data = fs::read("../fixtures/fonts/Caveat-VariableFont_wght.ttf").unwrap();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify that the font files exist at the new fixture paths.

The font file paths have been systematically updated from "resources/..." to "../fixtures/fonts/...". Ensure that all font files are accessible at their new locations to prevent runtime errors.

Also applies to: 34-34, 48-48, 62-62


🏁 Script executed:

#!/bin/bash
# Description: Verify all font files exist at the new fixture paths
# Expected: All font files should be present and accessible

echo "Checking font file existence:"
fonts=(
    "../fixtures/fonts/Caveat-VariableFont_wght.ttf"
    "../fixtures/fonts/Bungee-Regular.ttf"
    "../fixtures/fonts/Fruktur-Regular.ttf"
    "../fixtures/fonts/VT323-Regular.ttf"
)

for font in "${fonts[@]}"; do
    if [ -f "$font" ]; then
        echo "✅ Found: $font"
    else
        echo "❌ Missing: $font"
    fi
done

Length of output: 1006


Fix missing font fixtures at updated paths

The shell verification shows that all four font files are not present under ../fixtures/fonts/, which will lead to runtime errors when running this example. Please either add the missing files to that directory or correct the paths to point at the actual location of the font resources.

Files reported missing:

  • crates/grida-canvas/examples/fonts.rs:23 – ../fixtures/fonts/Caveat-VariableFont_wght.ttf
  • crates/grida-canvas/examples/fonts.rs:34 – ../fixtures/fonts/Bungee-Regular.ttf
  • crates/grida-canvas/examples/fonts.rs:48 – ../fixtures/fonts/Fruktur-Regular.ttf
  • crates/grida-canvas/examples/fonts.rs:62 – ../fixtures/fonts/VT323-Regular.ttf

Ensure the fixtures/fonts directory exists at the expected relative path or update these lines accordingly.

🤖 Prompt for AI Agents
In crates/grida-canvas/examples/fonts.rs around lines 23, 34, 48, and 62, the
font file paths point to ../fixtures/fonts/ but the files are missing there,
causing runtime errors. Verify the actual location of these font files in the
project, then either add the missing font files to the ../fixtures/fonts/
directory or update the file paths in these lines to the correct existing
locations of the font resources.

async fn demo_image() -> Scene {
let nf = NodeFactory::new();
// let image4k = "resources/4k.jpg".to_string();
// let image4k = "../fixtures/images/4k.jpg".to_string();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify that the image files exist at the new fixture paths.

The image file paths have been updated from "resources/..." to "../fixtures/images/...". Ensure that the image files are accessible at their new locations to prevent runtime errors.

Also applies to: 14-14


🏁 Script executed:

#!/bin/bash
# Description: Verify image files exist at the new fixture paths
# Expected: Image files should be present and accessible

echo "Checking image file existence:"
images=(
    "../fixtures/images/4k.jpg"
    "../fixtures/images/8k.jpg"
)

for image in "${images[@]}"; do
    if [ -f "$image" ]; then
        echo "✅ Found: $image"
        # Check file size to ensure it's not empty
        size=$(stat -c%s "$image" 2>/dev/null || stat -f%z "$image" 2>/dev/null || echo "unknown")
        echo "   Size: $size bytes"
    else
        echo "❌ Missing: $image"
    fi
done

Length of output: 441


🏁 Script executed:

#!/bin/bash
# Locate the actual paths of the 4k.jpg and 8k.jpg fixtures in the repo
echo "Locating image fixture paths:"
find . -type f \( -name "4k.jpg" -o -name "8k.jpg" \)

Length of output: 186


Correct relative paths for image fixtures in image.rs

The example’s image paths ../fixtures/images/4k.jpg and ../fixtures/images/8k.jpg don’t match the actual locations (crates/fixtures/images/...). From crates/grida-canvas/examples/image.rs, you need to go up two levels to reach crates/fixtures.

• File to update: crates/grida-canvas/examples/image.rs
• Change lines 9 and 14 as follows:

- let image4k = "../fixtures/images/4k.jpg".to_string();
+ let image4k = "../../fixtures/images/4k.jpg".to_string();

- let image8k = "../fixtures/images/8k.jpg".to_string();
+ let image8k = "../../fixtures/images/8k.jpg".to_string();

This ensures the example loads the 4k and 8k images without runtime errors.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In crates/grida-canvas/examples/image.rs at lines 9 and 14, the relative paths
to the image fixtures are incorrect because they only go up one directory level
instead of two. Update the paths by changing "../fixtures/images/4k.jpg" and
"../fixtures/images/8k.jpg" to "../../fixtures/images/4k.jpg" and
"../../fixtures/images/8k.jpg" respectively to correctly reference the images
from the example file location.

Comment on lines +42 to +51
```ts
await init({
locateFile: (path) => {
if (process.env.NODE_ENV === "development") {
return `http://localhost:4020/dist/${path}`;
}
`https://unpkg.com/@grida/canvas-wasm@latest/${path}`,
},
});
```

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

Fix missing return statement in code example.

The code example has a missing return statement in the else branch of the conditional.

 await init({
   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}`;
   },
 });
📝 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
```ts
await init({
locateFile: (path) => {
if (process.env.NODE_ENV === "development") {
return `http://localhost:4020/dist/${path}`;
}
`https://unpkg.com/@grida/canvas-wasm@latest/${path}`,
},
});
```
🤖 Prompt for AI Agents
In crates/grida-canvas-wasm/README.md around lines 42 to 51, the else branch of
the locateFile function is missing a return statement. Add a return keyword
before the URL string in the else branch to ensure the function returns the
correct path in non-development environments.

unsafe { _ = Box::from_raw(surface_ptr) };
let new_surface_ptr = Box::into_raw(Box::new(surface));
renderer.set_backend(Backend::GL(new_surface_ptr));
renderer.backend = Backend::GL(new_surface_ptr);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify backend reassignment safety.

Direct assignment to renderer.backend during surface recreation should be verified for memory safety. The previous surface should be properly cleaned up before assignment.


🏁 Script executed:

#!/bin/bash
# Description: Check how Backend enum handles GL surface lifecycle and cleanup

# Look for Backend enum definition and Drop implementations
ast-grep --pattern $'enum Backend {
    $$$
}'

# Check for Drop implementations on Backend or related types
rg -A 10 "impl Drop for.*Backend"

Length of output: 83


I’ll search more broadly for the Backend enum, its variants (especially the GL variant), any Drop impls, and how Renderer and new_surface_ptr are defined.


🏁 Script executed:

#!/bin/bash
# Find the Backend enum definition and its GL variant
rg -n "enum Backend" -A10

# Alternatively, look for the GL variant specifically
rg -n "GL(" -A5

# Check for any Drop implementations related to Backend or its fields
rg -n "impl Drop" -A10

# Locate the Renderer struct to see how its backend field is typed
rg -n "struct Renderer" -A20

# Find where new_surface_ptr is declared or its type alias
rg -n "new_surface_ptr" -A5

Length of output: 4178


Ensure previous GL surface is freed before overwriting backend

Directly doing

renderer.backend = Backend::GL(new_surface_ptr);

will leak the old Surface, since Backend holds a raw *mut Surface and neither Backend nor Surface implement Drop. You need to clean up the existing pointer before reassigning.

Suggested fix in crates/grida-canvas/examples/camera.rs (around line 309):

- renderer.backend = Backend::GL(new_surface_ptr);
+ // Clean up the old surface to avoid a leak
+ if let Backend::GL(old_ptr) | Backend::Raster(old_ptr) = renderer.backend {
+     // SAFETY: take back ownership and drop
+     unsafe { Box::from_raw(old_ptr); }
+ }
+ renderer.backend = Backend::GL(new_surface_ptr);

This guarantees the previous Surface is properly dropped.

🤖 Prompt for AI Agents
In crates/grida-canvas/examples/camera.rs at line 309, before assigning a new GL
surface pointer to renderer.backend, explicitly free or drop the existing raw
Surface pointer held by renderer.backend to prevent a memory leak, since neither
Backend nor Surface implement Drop. Add code to safely deallocate or release the
old Surface resource before overwriting renderer.backend with the new
Backend::GL(new_surface_ptr).

Comment on lines +344 to +349
if let Some(prev_zoom) = self.prev_zoom {
if (prev_zoom - zoom).abs() < f32::EPSILON {
self.clear();
}
}
self.prev_zoom = Some(zoom);

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

Fix inverted zoom change detection logic.

The current logic clears tiles when zoom hasn't changed, which appears to be the opposite of the intended behavior. Tiles should be cleared when zoom has changed.

 if let Some(prev_zoom) = self.prev_zoom {
-    if (prev_zoom - zoom).abs() < f32::EPSILON {
+    if (prev_zoom - zoom).abs() > f32::EPSILON {
         self.clear();
     }
 }
📝 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
if let Some(prev_zoom) = self.prev_zoom {
if (prev_zoom - zoom).abs() < f32::EPSILON {
self.clear();
}
}
self.prev_zoom = Some(zoom);
if let Some(prev_zoom) = self.prev_zoom {
if (prev_zoom - zoom).abs() > f32::EPSILON {
self.clear();
}
}
self.prev_zoom = Some(zoom);
🤖 Prompt for AI Agents
In crates/grida-canvas/src/cache/tile.rs around lines 344 to 349, the logic
currently clears tiles when the zoom level has not changed, which is inverted.
Modify the condition to clear tiles only when the zoom level has changed by
checking if the absolute difference between prev_zoom and zoom is greater than
f32::EPSILON, then call self.clear(). Keep updating self.prev_zoom to Some(zoom)
after this check.

Comment on lines +37 to +41
#[cfg(not(target_arch = "wasm32"))]
fn init_gl() {
// no-op
}

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

Make non-wasm32 stub behavior consistent.

The non-wasm32 stubs have inconsistent behavior: init_gl is a no-op while create_gpu_state panics. This could lead to confusing runtime errors.

Either both functions should panic with clear messages indicating WebGL is only supported on wasm32, or both should have proper implementations:

 #[cfg(not(target_arch = "wasm32"))]
 fn init_gl() {
-    // no-op
+    panic!("WebGL is only supported on wasm32 targets");
 }

 #[cfg(not(target_arch = "wasm32"))]
 fn create_gpu_state() -> GpuState {
-    // no-op
-    panic!("create_gpu_state is not supported on native");
+    panic!("WebGL is only supported on wasm32 targets");
 }

Also applies to: 63-67

🤖 Prompt for AI Agents
In crates/grida-canvas/src/window/application_webgl.rs around lines 37 to 41 and
63 to 67, the non-wasm32 stub functions have inconsistent behavior: init_gl is a
no-op while create_gpu_state panics. To fix this, make both functions consistent
by either having both panic with clear messages that WebGL is only supported on
wasm32 or by providing proper implementations for both. Choose one approach and
apply it to both functions to avoid confusing runtime errors.

Comment on lines +318 to +340
fn queue(&mut self) {
self.renderer.queue_unstable();

if let Some(id) = self.queue_stable_timer.take() {
self.timer.cancel(id);
}

let renderer_ptr: *mut Renderer = &mut self.renderer;
self.queue_stable_timer = Some(self.timer.set_timeout(
std::time::Duration::from_millis(self.queue_stable_debounce_millis),
move || unsafe {
(*renderer_ptr).queue_stable();
},
));

// TODO: can't use debounce - let's try this later
// self.debounce(
// std::time::Duration::from_millis(100),
// || self.renderer.queue_stable(),
// false,
// true,
// );
}

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

Critical: Unsafe pointer usage in timer callback.

The current implementation creates a raw mutable pointer to the renderer and uses it in a timer callback. This is unsafe because the renderer could be moved, dropped, or accessed concurrently before the timer fires.

Consider these safer alternatives:

  1. Use a channel to send commands:
let (tx, rx) = mpsc::channel();
self.queue_stable_timer = Some(self.timer.set_timeout(
    Duration::from_millis(self.queue_stable_debounce_millis),
    move || { let _ = tx.send(StableFrameRequest); },
));
// Process rx in tick() or another method
  1. Use Arc<Mutex<>> for shared ownership:
// Store renderer in Arc<Mutex<Renderer>> in the struct
let renderer = self.renderer.clone();
self.queue_stable_timer = Some(self.timer.set_timeout(
    Duration::from_millis(self.queue_stable_debounce_millis),
    move || {
        if let Ok(mut r) = renderer.lock() {
            r.queue_stable();
        }
    },
));
  1. Use the event system to queue a stable frame request that's processed in the main loop.
🤖 Prompt for AI Agents
In crates/grida-canvas/src/window/application.rs lines 318 to 340, the current
use of a raw mutable pointer to self.renderer inside the timer callback is
unsafe because the renderer might be moved, dropped, or accessed concurrently
before the callback executes. To fix this, replace the unsafe pointer usage with
a safer approach such as sending a command through a channel to be processed
later, wrapping the renderer in an Arc<Mutex<>> to allow safe shared access
inside the callback, or using the existing event system to queue a stable frame
request handled in the main loop. Implement one of these alternatives to ensure
safe access to the renderer without unsafe code.

Comment on lines +530 to 534
#[allow(dead_code)]
pub(crate) fn pointer_move(&mut self, x: f32, y: f32) {
self.input.cursor = [x, y];
self.perform_hit_test();
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify if pointer_move is actually unused.

The #[allow(dead_code)] attribute suggests this method might not be used. If it's truly unused, consider removing it. If it's used conditionally, document when it's used.


🏁 Script executed:

#!/bin/bash
# Search for usage of pointer_move method
rg -A 2 "pointer_move" --type rust

Length of output: 960


Remove unnecessary #[allow(dead_code)] on pointer_move

The pointer_move method is invoked in:

  • crates/grida-canvas/src/window/application_webgl.rs
  • crates/grida-canvas-wasm/src/main.rs

Since it’s used in multiple build targets, the #[allow(dead_code)] can be removed to keep the code clean.

Affected location:

  • crates/grida-canvas/src/window/application.rs

Suggested diff:

-    #[allow(dead_code)]
     pub(crate) fn pointer_move(&mut self, x: f32, y: f32) {
         self.input.cursor = [x, y];
         self.perform_hit_test();
     }
📝 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
#[allow(dead_code)]
pub(crate) fn pointer_move(&mut self, x: f32, y: f32) {
self.input.cursor = [x, y];
self.perform_hit_test();
}
pub(crate) fn pointer_move(&mut self, x: f32, y: f32) {
self.input.cursor = [x, y];
self.perform_hit_test();
}
🤖 Prompt for AI Agents
In crates/grida-canvas/src/window/application.rs around lines 530 to 534, remove
the #[allow(dead_code)] attribute from the pointer_move method since it is used
in multiple build targets and is not dead code. This will clean up the code by
eliminating an unnecessary attribute.

Comment on lines +220 to +228
fn load_scene_json(&mut self, json: &str) {
use crate::io::io_json;
use math2::transform::AffineTransform;

let Ok(file) = io_json::parse(json) else {
let err = io_json::parse(json).unwrap_err();
eprintln!("failed to parse scene json: {}", err);
return;
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Simplify JSON parsing to avoid double parsing.

The current code parses the JSON twice when there's an error, which is inefficient.

-let Ok(file) = io_json::parse(json) else {
-    let err = io_json::parse(json).unwrap_err();
-    eprintln!("failed to parse scene json: {}", err);
-    return;
-};
+let file = match io_json::parse(json) {
+    Ok(f) => f,
+    Err(err) => {
+        eprintln!("failed to parse scene json: {}", err);
+        return;
+    }
+};
🤖 Prompt for AI Agents
In crates/grida-canvas/src/window/application.rs around lines 220 to 228, the
JSON parsing is done twice: once in the if-let statement and again to get the
error on failure. Refactor the code to parse the JSON only once by storing the
result in a variable, then match or if-let on that variable to handle success or
error cases, printing the error without re-parsing.

@softmarshmallow
softmarshmallow merged commit 62c206b into main Jul 6, 2025
@coderabbitai coderabbitai Bot mentioned this pull request Oct 13, 2025
4 of 13 tasks
@coderabbitai coderabbitai Bot mentioned this pull request Dec 20, 2025
@coderabbitai coderabbitai Bot mentioned this pull request Jan 16, 2026
@coderabbitai coderabbitai Bot mentioned this pull request Jan 26, 2026
@coderabbitai coderabbitai Bot mentioned this pull request Mar 29, 2026
Closed
@coderabbitai coderabbitai Bot mentioned this pull request Apr 20, 2026
6 of 8 tasks

This branch was successfully deployed

1 active and 4 inactive deployments
Preview – grida — 3dc32bd2 Deployed Jul 6, 2025 by vercel[bot]
Preview – backgrounds — 3dc32bd2 Deployed Jul 6, 2025 by vercel[bot]
Preview – viewer — 3dc32bd2 Deployed Jul 6, 2025 by vercel[bot]
Preview – blog — 3dc32bd2 Deployed Jul 6, 2025 by vercel[bot]
Preview – docs — 3dc32bd2 Deployed Jul 6, 2025 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant