Skip to content

day308 Grida Canvas - UX / Icons Library - #466

Merged
softmarshmallow merged 3 commits into
mainfrom
canary
Dec 11, 2025
Merged

softmarshmallow merged 3 commits into
mainfrom
canary

Conversation

@softmarshmallow

@softmarshmallow softmarshmallow commented Dec 10, 2025 •

Copy link
Copy Markdown
Member
day-308-grida-canvas-ux-icons-browser.mp4

Summary by CodeRabbit

Release Notes

  • New Features
    • Added a floating window system enabling draggable, boundary-constrained windows for managing multiple UI panels simultaneously.
    • Introduced a searchable icons browser with vendor and variant filtering for inserting icons into designs with visual feedback notifications.

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

@vercel

vercel Bot commented Dec 10, 2025 •

Copy link
Copy Markdown

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

Project Deployment Preview Comments Updated (UTC)
docs Ready Ready Preview Comment Dec 11, 2025 6:05pm
grida Ready Ready Preview Comment Dec 11, 2025 6:05pm
5 Skipped Deployments
Project Deployment Preview Comments Updated (UTC)
code Ignored Ignored Dec 11, 2025 6:05pm
legacy Ignored Ignored Dec 11, 2025 6:05pm
backgrounds Skipped Skipped Dec 11, 2025 6:05pm
blog Skipped Skipped Dec 11, 2025 6:05pm
viewer Skipped Skipped Dec 11, 2025 6:05pm

@coderabbitai

coderabbitai Bot commented Dec 10, 2025 •

Copy link
Copy Markdown

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

This pull request introduces a complete floating window system with dragging, boundary constraints, and portal support. It includes wrapper components, a demo page, and a new IconsBrowser component that enables searching, filtering, and inserting icons from multiple vendors into the editor.

Changes

Cohort / File(s) Summary
Floating Window Primitives
editor/components/floating-window/primitives.tsx
Introduces core floating window system with portal rendering, boundary confinement, drag handling via @use-gesture, CSS variable transforms, ResizeObserver for sizing, and a global registry context. Exports FloatingWindowRoot, FloatingWindowBounds, FloatingWindowHost, useFloatingWindowControls hook, and interaction primitives (Trigger, Close, TitleBar, Body). Includes internal utilities for element rect and size tracking.
Floating Window Wrappers
editor/components/floating-window/floating-window.tsx
Provides typed wrapper components that compose primitives with default styles and classNames via cn utility. Exports FloatingWindowHost, FloatingWindowBounds, FloatingWindowRoot, FloatingWindowTitleBar, FloatingWindowBody, FloatingWindowTrigger, FloatingWindowClose, and FloatingWindowPortal alongside their prop types.
Floating Window Exports
editor/components/floating-window/index.ts
Barrel export file with "use client" directive re-exporting all components/hooks from "./floating-window" and primitives namespace as FloatingWindowPrimitive.
Icons Browser Component
editor/grida-canvas-hosted/playground/icons-browser.tsx
New component for browsing and inserting icons with vendor/variant filtering, search, and virtualized grid rendering. Manages API calls to fetch vendors and icons, handles lazy-loaded images with tooltips, and triggers onInsert callback with toast notifications.
Demo & Integration
editor/app/(dev)/ui/floating-window/page.tsx, editor/grida-canvas-hosted/playground/playground.tsx
Demo page showcasing FloatingWindowHost with multiple FloatingWindowRoot instances (Inspector, Console, Icons Browser). Playground updated to replace inline library dialog with FloatingWindowTrigger-based icons browser window and implements icon insertion flow with SVG fetching and node creation.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant UI as UI (Trigger)
    participant Window as FloatingWindowRoot
    participant Browser as IconsBrowser
    participant API as Icons API
    participant Canvas as Canvas/Editor

    User->>UI: Click "Open Icons Browser"
    UI->>Window: trigger open via controls.openWindow()
    Window->>Window: Show window (CSS transform)
    
    User->>Browser: Type search query
    Browser->>API: Fetch icons (vendor + query)
    API-->>Browser: Return icons array
    Browser->>Browser: Render virtualized grid
    
    User->>Browser: Click icon
    Browser->>Browser: Show loading toast
    Browser->>API: Fetch SVG (download URL)
    API-->>Browser: Return SVG blob
    Browser->>Canvas: Call onInsert callback
    Canvas->>Canvas: Fetch SVG, create node, set name
    Canvas->>Browser: Success
    Browser->>Browser: Show success toast
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Areas requiring extra attention:

  • Drag implementation and boundary clamping logic in FloatingWindowRoot with @use-gesture integration
  • ResizeObserver and window event listener cleanup to prevent memory leaks
  • Portal rendering guards against client-server mismatch and proper container mounting
  • Icons API integration, error handling, and state synchronization across vendor/variant filters
  • Virtualized grid rendering and responsive cell sizing calculations
  • CSS custom property updates (--floating-window-x, --floating-window-y) and transition timing

Possibly related PRs

  • gridaco/grida#441: Introduces editor/components/ui/spinner.tsx which may be used for loading states within the icons browser component.

Suggested labels

ux

Poem

🐰 A floating window dances free,
Dragging icons, wild with glee,
Boundaries clamped, no scroll to roam,
A rabbit's dream: a windowed home! ✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 3.70% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Title check ❓ Inconclusive The title refers to real components (floating-window and icons library) introduced in this PR, but is vague about the specific changes and uses a non-descriptive format with just the feature names rather than the actual implementation or improvement. Consider using a more descriptive title like 'Add floating window system for icons library UI' or 'Implement draggable floating windows with icons browser component' to clarify the main change.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch canary

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

❤️ Share

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

@vercel
vercel Bot temporarily deployed to Preview – blog December 11, 2025 17:12 Inactive
@vercel
vercel Bot temporarily deployed to Preview – viewer December 11, 2025 17:12 Inactive
@vercel
vercel Bot temporarily deployed to Preview – backgrounds December 11, 2025 17:12 Inactive
@softmarshmallow
softmarshmallow marked this pull request as ready for review December 11, 2025 17:18

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

ℹ️ About Codex in GitHub

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

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

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

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

Comment on lines +286 to +289
});
setVendorsLoaded(true);
} catch (e) {
console.warn("Failed to load icon vendors", e);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Handle vendor fetch failures so icons can load

When the vendors request fails (network or non-2xx), vendorsLoaded is never set and fetchIcons exits early whenever vendorsLoaded is false. That leaves loading stuck true and the icon list never fetches, even if the vendor endpoint recovers later. The catch block should mark vendors as handled or trigger an icon fetch fallback so users aren’t left with a permanent spinner after a transient vendor error.

Useful? React with 👍 / 👎.

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

🧹 Nitpick comments (6)
editor/grida-canvas-hosted/playground/icons-browser.tsx (1)

242-244: Missing cleanup for fetchIcons effect.

The effect at lines 242-244 triggers fetchIcons but doesn't handle component unmount during the async operation. While the hook's internal state updates won't crash, responses from stale requests could update state unexpectedly.

Consider adding an AbortController for request cancellation:

   useEffect(() => {
-    void fetchIcons();
-  }, [fetchIcons, vendorsLoaded]);
+    const controller = new AbortController();
+    void fetchIcons(controller.signal);
+    return () => controller.abort();
+  }, [fetchIcons, vendorsLoaded]);

This would require updating fetchIcons to accept and use the signal. This is a minor concern since React state updates on unmounted components are safe in React 18+, but cleaner for request lifecycle management.

editor/components/floating-window/primitives.tsx (5)

241-255: Optional: Consider reacting to boundary position changes, not just size

useElementRect tracks the boundary’s DOMRect, but the clamping/layout effect here only depends on boundarySize and windowSize. If the boundary moves (e.g., layout shift) without resizing, windows won’t be re-offset to the new location until some other trigger causes applyPosition to run.

If you expect the boundary to move independently of its size, consider including something derived from boundaryRect (e.g., boundaryRect?.left, boundaryRect?.top) in this effect’s dependencies, or adding a small effect that calls applyPosition(positionRef.current) whenever boundaryRect changes. This would keep portalled windows perfectly aligned during layout shifts.


362-377: Ordering of spreads may allow consumer props to override drag handlers

In FloatingWindowTitleBar you spread dragHandleProps before {...rest}:

<div
  {...dragHandleProps}
  {...rest}
  data-floating-window-titlebar
  className={className}
>

This means any event handlers or pointer props passed in rest can override the drag handlers, potentially disabling dragging if a consumer supplies their own onPointerDown, etc.

If you’d prefer drag behavior to always be wired and still allow consumers to augment handlers, you could instead:

  • Either spread rest first and dragHandleProps last, or
  • Merge handlers explicitly (e.g., wrap both in a combined handler).

Right now it’s not wrong, but worth being aware of this precedence.


418-464: Improve disabled semantics for Trigger/Close when no controls are available

FloatingWindowTrigger and FloatingWindowClose set aria-disabled={!getControls()}, but they always render an enabled <button> and still attach onClick. If getControls() returns undefined, clicks become no-ops but the element is still focusable and announced as a normal button by some assistive tech.

To tighten this up:

  • Also set the actual disabled attribute when !getControls():
-    <button
-      type="button"
-      onClick={handleClick}
-      aria-disabled={!getControls()}
-      {...rest}
-    >
+    <button
+      type="button"
+      onClick={handleClick}
+      aria-disabled={!getControls()}
+      disabled={!getControls()}
+      {...rest}
+    >

Same for FloatingWindowClose.

This keeps the ARIA state and actual interactivity in sync and improves keyboard / AT behavior.

Also applies to: 466-512


532-552: Optional: Make measurement hooks resilient to ref target changes

Both useElementSize and useElementRect depend on [ref] and capture const el = ref.current once when the effect runs. If the same ref object gets re-attached to a different DOM node later (common with conditional rendering), the observers will continue to track the old node and ignore the new one.

If you expect the referenced elements to change over time, consider:

  • Depending on ref.current instead of ref (with a small guard for null), or
  • Using a callback ref that wires/unwires observers as the element instance changes.

Example tweak for useElementSize:

-  useEffect(() => {
-    const el = ref.current;
-    if (!el) return;
+  useEffect(() => {
+    const el = ref.current;
+    if (!el) return;
@@
-    observer.observe(el);
-    return () => observer.disconnect();
-  }, [ref]);
+    observer.observe(el);
+    return () => observer.disconnect();
+  }, [ref.current]);

(Same idea for useElementRect.) Not mandatory given your current usage, but it makes these hooks more generally robust.

Also applies to: 554-585


380-416: Minor: toggle captures stale state; prefer functional updates for React 19 concurrent rendering

useFloatingWindowControls captures state in the toggle closure, which could behave unexpectedly under concurrent rendering or with rapid successive calls. React 19 best practice recommends using functional updaters when new state depends on prior state.

To implement this properly, setOpen would need to support both boolean and functional updates:

export type FloatingWindowControls = {
  open: boolean;
-  setOpen: (next: boolean) => void;
+  setOpen: (next: boolean | ((prev: boolean) => boolean)) => void;
  toggle: () => void;
  openWindow: () => void;
  closeWindow: () => void;
};

export function useFloatingWindowControls(
  config: FloatingWindowControlsConfig = {}
): FloatingWindowControls {
  const { open, defaultOpen = true, onOpenChange } = config;
  const [uncontrolled, setUncontrolled] = useState(defaultOpen);
  const isControlled = typeof open === "boolean";
  const state = isControlled ? open : uncontrolled;

  const setOpen = (next: boolean | ((prev: boolean) => boolean)) => {
    const nextValue = typeof next === "function" ? next(state) : next;
    if (!isControlled) {
      setUncontrolled(nextValue);
    }
    onOpenChange?.(nextValue);
  };

  return {
    open: state,
    setOpen,
    toggle: () => setOpen((prev) => !prev),
    openWindow: () => setOpen(true),
    closeWindow: () => setOpen(false),
  };
}

This ensures toggle derives the next state from the current value rather than relying on a captured closure, improving robustness under concurrent rendering.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 04d53fa and 0f3c22d.

📒 Files selected for processing (6)
  • editor/app/(dev)/ui/floating-window/page.tsx (1 hunks)
  • editor/components/floating-window/floating-window.tsx (1 hunks)
  • editor/components/floating-window/index.ts (1 hunks)
  • editor/components/floating-window/primitives.tsx (1 hunks)
  • editor/grida-canvas-hosted/playground/icons-browser.tsx (1 hunks)
  • editor/grida-canvas-hosted/playground/playground.tsx (5 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use TypeScript 5 as the main language for most apps
Use Lucide or Radix Icons for icons

Files:

  • editor/components/floating-window/index.ts
  • editor/app/(dev)/ui/floating-window/page.tsx
  • editor/components/floating-window/floating-window.tsx
  • editor/grida-canvas-hosted/playground/playground.tsx
  • editor/components/floating-window/primitives.tsx
  • editor/grida-canvas-hosted/playground/icons-browser.tsx
**/*.{ts,tsx,css}

📄 CodeRabbit inference engine (AGENTS.md)

Use Tailwind CSS 4 for styling

Files:

  • editor/components/floating-window/index.ts
  • editor/app/(dev)/ui/floating-window/page.tsx
  • editor/components/floating-window/floating-window.tsx
  • editor/grida-canvas-hosted/playground/playground.tsx
  • editor/components/floating-window/primitives.tsx
  • editor/grida-canvas-hosted/playground/icons-browser.tsx
**/components/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Use Shadcn UI for reusable UI components

Files:

  • editor/components/floating-window/index.ts
  • editor/components/floating-window/floating-window.tsx
  • editor/components/floating-window/primitives.tsx
**/*.{tsx,jsx}

📄 CodeRabbit inference engine (AGENTS.md)

Use React.js 19 for web UI development

Files:

  • editor/app/(dev)/ui/floating-window/page.tsx
  • editor/components/floating-window/floating-window.tsx
  • editor/grida-canvas-hosted/playground/playground.tsx
  • editor/components/floating-window/primitives.tsx
  • editor/grida-canvas-hosted/playground/icons-browser.tsx
{editor,apps}/**/app/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Use Next.js 15 as the web framework

Files:

  • editor/app/(dev)/ui/floating-window/page.tsx
🧠 Learnings (6)
📚 Learning: 2025-12-01T00:21:48.564Z
Learnt from: CR
Repo: gridaco/grida PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-01T00:21:48.564Z
Learning: Use DOM as canvas backend for website builder canvas bound with React

Applied to files:

  • editor/app/(dev)/ui/floating-window/page.tsx
  • editor/components/floating-window/primitives.tsx
📚 Learning: 2025-12-01T00:21:48.564Z
Learnt from: CR
Repo: gridaco/grida PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-01T00:21:48.564Z
Learning: Applies to **/components/**/*.{ts,tsx} : Use Shadcn UI for reusable UI components

Applied to files:

  • editor/grida-canvas-hosted/playground/playground.tsx
  • editor/grida-canvas-hosted/playground/icons-browser.tsx
📚 Learning: 2025-12-01T00:22:56.899Z
Learnt from: CR
Repo: gridaco/grida PR: 0
File: editor/app/(tools)/tools/halftone/AGENTS.md:0-0
Timestamp: 2025-12-01T00:22:56.899Z
Learning: Applies to editor/app/(tools)/tools/halftone/app/(tools)/tools/halftone/_page.tsx : Use React hooks for state management (imageSrc, shape, grid, maxRadius, gamma, jitter, opacity, color, customShapeImage, imageDataRef, sizeRef)

Applied to files:

  • editor/grida-canvas-hosted/playground/playground.tsx
📚 Learning: 2025-12-01T00:22:19.083Z
Learnt from: CR
Repo: gridaco/grida PR: 0
File: crates/grida-canvas-wasm/AGENTS.md:0-0
Timestamp: 2025-12-01T00:22:19.083Z
Learning: Applies to crates/grida-canvas-wasm/**/main.rs : Update `grida-canvas-wasm.d.ts` TypeScript definitions file when new APIs are introduced via `main.rs`

Applied to files:

  • editor/grida-canvas-hosted/playground/icons-browser.tsx
📚 Learning: 2025-12-01T00:21:48.564Z
Learnt from: CR
Repo: gridaco/grida PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-01T00:21:48.564Z
Learning: Applies to **/*.{ts,tsx} : Use Lucide or Radix Icons for icons

Applied to files:

  • editor/grida-canvas-hosted/playground/icons-browser.tsx
📚 Learning: 2025-12-01T00:22:56.899Z
Learnt from: CR
Repo: gridaco/grida PR: 0
File: editor/app/(tools)/tools/halftone/AGENTS.md:0-0
Timestamp: 2025-12-01T00:22:56.899Z
Learning: Applies to editor/app/(tools)/tools/halftone/app/(tools)/tools/halftone/_page.tsx : When adding new shape types, update the Shape type union, add cases in drawShape() function, add cases in shapeToSVG() function, and add SelectItem in UI

Applied to files:

  • editor/grida-canvas-hosted/playground/icons-browser.tsx
🧬 Code graph analysis (3)
editor/grida-canvas-hosted/playground/playground.tsx (2)
editor/components/floating-window/floating-window.tsx (7)
  • FloatingWindowHost (31-33)
  • FloatingWindowBounds (35-45)
  • FloatingWindowRoot (47-59)
  • FloatingWindowTitleBar (61-72)
  • FloatingWindowClose (87-89)
  • FloatingWindowBody (74-81)
  • FloatingWindowTrigger (83-85)
editor/grida-canvas-hosted/playground/icons-browser.tsx (2)
  • IconsBrowserItem (43-49)
  • IconsBrowser (491-708)
editor/components/floating-window/primitives.tsx (1)
editor/components/floating-window/floating-window.tsx (13)
  • FloatingWindowBoundsProps (26-26)
  • FloatingWindowPortal (91-95)
  • FloatingWindowBounds (35-45)
  • FloatingWindowHost (31-33)
  • FloatingWindowRootProps (24-24)
  • FloatingWindowRoot (47-59)
  • TitleBarProps (25-25)
  • FloatingWindowTitleBar (61-72)
  • TriggerProps (27-27)
  • FloatingWindowTrigger (83-85)
  • CloseProps (28-28)
  • FloatingWindowClose (87-89)
  • FloatingWindowBody (74-81)
editor/grida-canvas-hosted/playground/icons-browser.tsx (4)
editor/components/ui-editor/popover.tsx (3)
  • Popover (62-62)
  • PopoverTrigger (62-62)
  • PopoverContent (62-62)
editor/components/ui/badge.tsx (1)
  • Badge (46-46)
editor/components/ui/command.tsx (6)
  • Command (175-175)
  • CommandInput (177-177)
  • CommandList (178-178)
  • CommandEmpty (179-179)
  • CommandGroup (180-180)
  • CommandItem (181-181)
editor/components/ui/input-group.tsx (3)
  • InputGroup (164-164)
  • InputGroupAddon (165-165)
  • InputGroupInput (168-168)
🪛 Biome (2.1.2)
editor/app/(dev)/ui/floating-window/page.tsx

[error] 120-120: Wrap comments inside children within braces.

Unsafe fix: Wrap the comments with braces

(lint/suspicious/noCommentText)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: cargo test
🔇 Additional comments (13)
editor/components/floating-window/index.ts (1)

1-4: LGTM!

Clean barrel export pattern with appropriate "use client" directive. The namespace export for primitives provides good flexibility for consumers who need lower-level access.

editor/app/(dev)/ui/floating-window/page.tsx (1)

19-172: Well-structured demo page.

Good use of accessibility patterns (sr-only for screen reader text, aria-hidden on decorative icons). The demo effectively showcases multi-window coordination with drag boundaries.

editor/grida-canvas-hosted/playground/playground.tsx (3)

369-393: Icon insertion flow looks good.

The handleInsertIcon callback properly handles the async flow with toast feedback for loading, success, and error states. The cache: "no-store" ensures fresh icon data.


449-541: Clean floating window integration.

The FloatingWindowHost wrapping and FloatingWindowBounds with boundary ref properly coordinate the UI. The icons browser window is well-configured with appropriate initial position, dimensions, and z-index for overlay behavior.


621-670: Simplified sidebar with floating trigger.

Good refactor from modal dialog to floating window trigger. The asChild pattern with the Button component follows Radix UI conventions correctly.

editor/components/floating-window/floating-window.tsx (1)

47-95: Well-designed wrapper components.

Sensible defaults for transitions, styling, and cursor feedback. The consistent use of cn() for className merging allows consumers to override styles while preserving base behavior.

editor/grida-canvas-hosted/playground/icons-browser.tsx (2)

450-489: Good lazy loading pattern.

The IconGridCell component implements a clean skeleton-to-image transition with appropriate loading state management. The tooltip with icon name and primary tag provides helpful context.


491-708: Well-implemented virtualized icon grid.

The IconsBrowser component effectively combines:

  • Responsive cell sizing via ResizeObserver
  • Row virtualization with @tanstack/react-virtual
  • Vendor/variant filtering with searchable dropdowns
  • Horizontal scrollable vendor pills with fade edges

The overall structure is clean and handles loading/error/empty states appropriately.

editor/components/floating-window/primitives.tsx (5)

26-49: Portal implementation and SSR guard look solid

The client-only mount guard (mounted + typeof document !== "undefined") and portal wrapper with a fixed, pointer-events-none overlay are appropriate for avoiding SSR mismatches and keeping windows above the app chrome. No issues here.


51-80: Bounds container API and render-prop pattern look good

FloatingWindowBounds correctly normalizes its children to either static content or a render-prop with a boundaryRef, and it enforces a relative, overflow-hidden 100%×100% container suitable as a drag boundary. This is a clean primitive for the higher-level wrapper to style.


95-127: Registry / host lifecycle is well-structured

The registry context + FloatingWindowHost implementation with Map<string, FloatingWindowControls> and guarded unregister (identity check) is a good pattern to avoid stale removals when controls objects change between renders, while still cleaning up on unmount.


284-297: Drag bindings and render-prop helpers are well-factored

The useDrag configuration (offset-based, from seeded by positionRef.current, scroll prevention, pointer capture) combined with the memoized helpers object and dragHandleProps looks solid. The render prop / render API flexibility is nice and keeps the primitive unopinionated.

Also applies to: 299-318


514-529: Body primitive is fine as a thin passthrough

FloatingWindowBody is a minimal wrapper adding only a data-floating-window-body attribute and forwarding className/style. That matches the “primitive” intent and lets the higher-level wrapper control Tailwind/shadcn styling. No issues.

Comment on lines +35 to +45
export function FloatingWindowBounds(props: FloatingWindowBoundsProps) {
return (
<PrimitiveBounds
{...props}
className={cn(
"relative w-full h-full overflow-hidden data-[floating-window-bounds]",
props.className
)}
/>
);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Invalid data attribute syntax.

data-[floating-window-bounds] uses Tailwind's conditional selector notation, which expects an existing attribute to apply styles conditionally. To define a data attribute, remove the brackets.

     <PrimitiveBounds
       {...props}
       className={cn(
-        "relative w-full h-full overflow-hidden data-[floating-window-bounds]",
+        "relative w-full h-full overflow-hidden",
         props.className
       )}
+      data-floating-window-bounds=""
     />

Alternatively, if this is meant as a Tailwind variant selector, ensure the primitive sets the attribute and use proper conditional syntax like data-[floating-window-bounds]:some-style.

🤖 Prompt for AI Agents
editor/components/floating-window/floating-window.tsx lines 35-45: the JSX uses
Tailwind's conditional selector syntax `data-[floating-window-bounds]` but you
intended to set a data attribute; change the prop to a normal data attribute
name (e.g., data-floating-window-bounds) on the PrimitiveBounds so Tailwind can
match it, or if you meant to apply Tailwind variant styles instead, leave the
selector in className but ensure the PrimitiveBounds actually renders that data
attribute and use the full variant syntax (e.g.,
data-[floating-window-bounds]:<utility>) in className.

Comment on lines +194 to +201
const applyPosition = (pos: { x: number; y: number }) => {
const el = windowRef.current;
if (!el) return;
const offsetX = boundaryRect?.left ?? 0;
const offsetY = boundaryRect?.top ?? 0;
el.style.setProperty("--floating-window-x", `${pos.x + offsetX}px`);
el.style.setProperty("--floating-window-y", `${pos.y + offsetY}px`);
};

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 | 🟠 Major

Bug: Non-portal windows are mis-positioned due to unconditional boundary offset

applyPosition always adds boundaryRect.left/top to the logical {x, y} position before setting the CSS variables, but the render-time transform always interprets those CSS variables in the local coordinate space of the window’s containing element.

  • For portal={true}, the window is rendered inside a fixed, full-screen portal; adding boundaryRect.left/top is correct to map boundary-relative coords into viewport space.
  • For portal={false}, the window is rendered inside the boundary container; adding boundaryRect.left/top double-applies the offset (once from normal layout of the boundary in the page, once from the transform), so the window ends up shifted too far from the top-left of its bounds.

This means the portal flag does not behave correctly today: non-portal windows won’t align to the expected 0…width / 0…height coordinate system of the boundary.

You can fix this by conditioning the offset on portal so local (non-portal) windows use pure boundary-relative coordinates:

@@
-  const applyPosition = (pos: { x: number; y: number }) => {
-    const el = windowRef.current;
-    if (!el) return;
-    const offsetX = boundaryRect?.left ?? 0;
-    const offsetY = boundaryRect?.top ?? 0;
-    el.style.setProperty("--floating-window-x", `${pos.x + offsetX}px`);
-    el.style.setProperty("--floating-window-y", `${pos.y + offsetY}px`);
-  };
+  const applyPosition = (pos: { x: number; y: number }) => {
+    const el = windowRef.current;
+    if (!el) return;
+
+    // For portalled windows, translate boundary-relative coords into viewport space.
+    // For non-portal windows, stay in the boundary’s local coordinate system.
+    const offsetX = portal ? boundaryRect?.left ?? 0 : 0;
+    const offsetY = portal ? boundaryRect?.top ?? 0 : 0;
+
+    el.style.setProperty("--floating-window-x", `${pos.x + offsetX}px`);
+    el.style.setProperty("--floating-window-y", `${pos.y + offsetY}px`);
+  };

With this change, portal={false} will keep window motion correctly clamped and aligned within the boundary, and portal={true} will continue to align to the viewport overlay.

Also applies to: 324-341

🤖 Prompt for AI Agents
In editor/components/floating-window/primitives.tsx around lines 194-201 (and
likewise update the block at 324-341), applyPosition is always adding
boundaryRect.left/top to the logical pos which double-offsets non-portal
windows; change the logic to only add the boundary offsets when the window is
rendered in a portal (portal === true) and otherwise set the CSS vars to the raw
boundary-relative pos (falling back to 0 if boundaryRect is undefined). Update
both occurrences to branch on the portal flag, keep null-safe reads of
boundaryRect, and set "--floating-window-x" and "--floating-window-y"
accordingly so portal windows map to viewport coordinates and non-portal windows
remain in local boundary coordinates.

Comment on lines +517 to +528
const handleInsert = useCallback(
async (icon: IconsBrowserItem) => {
if (!onInsert) return;
const task = Promise.resolve(onInsert(icon));
toast.promise(task, {
loading: "Loading icon...",
success: "Icon inserted",
error: "Failed to insert icon",
});
},
[onInsert]
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Double toast notifications on icon insert.

Both IconsBrowser.handleInsert (here) and playground.tsx:handleInsertIcon (lines 386-390) wrap the insert operation with toast.promise. This results in duplicate toast messages for each icon insertion.

Remove the toast wrapper here since the parent component already handles user feedback:

   const handleInsert = useCallback(
     async (icon: IconsBrowserItem) => {
       if (!onInsert) return;
-      const task = Promise.resolve(onInsert(icon));
-      toast.promise(task, {
-        loading: "Loading icon...",
-        success: "Icon inserted",
-        error: "Failed to insert icon",
-      });
+      await onInsert(icon);
     },
     [onInsert]
   );

Alternatively, keep toasts here and remove them from the consuming components to centralize the feedback logic.

📝 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
const handleInsert = useCallback(
async (icon: IconsBrowserItem) => {
if (!onInsert) return;
const task = Promise.resolve(onInsert(icon));
toast.promise(task, {
loading: "Loading icon...",
success: "Icon inserted",
error: "Failed to insert icon",
});
},
[onInsert]
);
const handleInsert = useCallback(
async (icon: IconsBrowserItem) => {
if (!onInsert) return;
await onInsert(icon);
},
[onInsert]
);
🤖 Prompt for AI Agents
In editor/grida-canvas-hosted/playground/icons-browser.tsx around lines 517 to
528, this handleInsert callback wraps onInsert(icon) with toast.promise causing
duplicate toasts because the parent already shows feedback; remove the
toast.promise wrapper and simply call (and await if onInsert returns a promise)
onInsert(icon) directly inside the useCallback so only the parent handles user
notifications.

This branch was successfully deployed

2 active and 3 inactive deployments
Preview – grida — 0f3c22dc Deployed Dec 11, 2025 by vercel[bot]
Preview – docs — 0f3c22dc Deployed Dec 11, 2025 by vercel[bot]
Preview – viewer — 0f3c22dc Deployed Dec 11, 2025 by vercel[bot]
Preview – backgrounds — 0f3c22dc Deployed Dec 11, 2025 by vercel[bot]
Preview – blog — 0f3c22dc Deployed Dec 11, 2025 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant