Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(canvas): add grid card actions menu (#86427)

Adam Leithf8ba937b6f85
diff --git a/products/desktop/packages/ui/src/features/canvas/grid/GridCanvasView.tsx b/products/desktop/packages/ui/src/features/canvas/grid/GridCanvasView.tsx
index 6afbc89f359e..902c1d777b0e 100644
--- a/products/desktop/packages/ui/src/features/canvas/grid/GridCanvasView.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/grid/GridCanvasView.tsx
@@ -1,22 +1,9 @@
-import {
- ChatCircleIcon,
- SidebarSimpleIcon,
- SquaresFourIcon,
-} from "@phosphor-icons/react";
+import { SidebarSimpleIcon } from "@phosphor-icons/react";
import type {
GridPlacement,
LayoutOperation,
} from "@posthog/core/canvas/gridLayoutSchemas";
-import {
- Button,
- Empty,
- EmptyDescription,
- EmptyHeader,
- EmptyMedia,
- EmptyTitle,
- Spinner,
- Text,
-} from "@posthog/quill";
+import { Button, Spinner, Text } from "@posthog/quill";
import { canvasCommentTaskId } from "@posthog/ui/features/canvas/freeform/canvasCommentTask";
import { useChannels } from "@posthog/ui/features/canvas/hooks/useChannels";
import {
@@ -26,57 +13,14 @@ import {
import { useGenerateFreeformCanvas } from "@posthog/ui/features/canvas/hooks/useGenerateFreeformCanvas";
import { useCanvasChatPanelStore } from "@posthog/ui/features/canvas/stores/canvasChatPanelStore";
import { ResizableSidebar } from "@posthog/ui/primitives/ResizableSidebar";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useMemo, useState } from "react";
import { GridChatPanel, type GridChatTarget } from "./GridChatPanel";
-import {
- GridPlacementTile,
- type PlacementTileActions,
-} from "./GridPlacementTile";
-import {
- collides,
- type GridRect,
- rectFromCells,
- surfaceRows,
-} from "./gridGeometry";
-import { type GridDragOutcome, useGridDrag } from "./useGridDrag";
+import { GridSurface } from "./GridSurface";
+import { collides } from "./gridGeometry";
+import type { PlacementActions } from "./placementActions";
+import type { GridDragOutcome } from "./useGridDrag";
import { useGridLayout, usePatchLayout } from "./useGridLayout";
-const DEFAULT_GRID = { columns: 6, rowHeight: 96, gap: 8 };
-
-// Outer radius of a lattice dot's fade (the gradient's transparent stop).
-const DOT_FADE_RADIUS = 4;
-
-function gridItemStyle(rect: GridRect): React.CSSProperties {
- return {
- gridColumn: `${rect.x + 1} / span ${rect.w}`,
- gridRow: `${rect.y + 1} / span ${rect.h}`,
- };
-}
-
-// Where the how-to tile sits on an empty grid: centered, wide enough to read,
-// one row down so it looks placed rather than docked to the top edge.
-function emptyHintRect(columns: number): GridRect {
- const w = Math.min(4, columns);
- return { x: Math.floor((columns - w) / 2), y: 1, w, h: 3 };
-}
-
-// The dot lattice needs the surface's real pixel width: columns are fractional
-// (1fr), so corner positions can't be expressed in pure CSS background math.
-function useMeasuredWidth(element: HTMLDivElement | null): number {
- const [width, setWidth] = useState(0);
- useEffect(() => {
- if (!element) return;
- const observer = new ResizeObserver((entries) => {
- const entry = entries[0];
- if (entry) setWidth(entry.contentRect.width);
- });
- observer.observe(element);
- setWidth(element.clientWidth);
- return () => observer.disconnect();
- }, [element]);
- return width;
-}
-
/**
* A grid canvas: a composition of component widgets on a fixed-column grid.
* Viewing renders each live placement's built artifact in its own sandboxed
@@ -106,15 +50,6 @@ export function GridCanvasView({
);
const { generate } = useGenerateFreeformCanvas({ channelId, channelName });
- const surfaceRef = useRef<HTMLDivElement>(null);
- // The surface mounts only after loading, so a plain ref never retriggers the
- // measurement effect; a state-backed element does.
- const [surfaceEl, setSurfaceEl] = useState<HTMLDivElement | null>(null);
- const setSurfaceRef = useCallback((el: HTMLDivElement | null) => {
- surfaceRef.current = el;
- setSurfaceEl(el);
- }, []);
- const surfaceWidth = useMeasuredWidth(surfaceEl);
const placements = layout?.placements;
// The right-hand dock, sharing the freeform panel's persisted collapse and
@@ -182,23 +117,6 @@ export function GridCanvasView({
[placements, patch],
);
- const {
- drag,
- hover,
- onPointerLeave,
- onSurfacePointerDown,
- onPointerMove,
- onPointerUp,
- onPointerCancel,
- startMove,
- startResize,
- } = useGridDrag({
- surfaceRef,
- grid: layout?.grid ?? DEFAULT_GRID,
- interactive,
- onComplete: onDragComplete,
- });
-
const describe = useCallback(
async (placement: GridPlacement, prompt: string) => {
if (!dashboard) return;
@@ -277,12 +195,10 @@ export function GridCanvasView({
[setCollapsed],
);
- const actions: PlacementTileActions = {
- describe,
- reset,
- remove,
- discuss,
- };
+ const actions = useMemo<PlacementActions>(
+ () => ({ describe, reset, remove, discuss }),
+ [describe, reset, remove, discuss],
+ );
if (isLoading || !layout || !placements || !dashboard) {
return (
@@ -291,16 +207,6 @@ export function GridCanvasView({
</div>
);
}
- const { grid } = layout;
- // Cell pitch in px: cell size plus one gap. Vertical pitch is fixed by the
- // layout; horizontal comes from the measured surface width (1fr columns).
- const pitchX = (surfaceWidth + grid.gap) / grid.columns;
- const pitchY = grid.rowHeight + grid.gap;
- // A cell already under a tile is not free to draw on, so it stays unlit.
- const hoveredRect = hover && rectFromCells(hover, hover);
- const hoveredCell =
- hoveredRect && !collides(hoveredRect, placements) ? hoveredRect : null;
-
return (
<div className="flex h-full">
<div className="flex min-w-0 flex-1 flex-col">
@@ -327,135 +233,14 @@ export function GridCanvasView({
) : null}
</div>
) : null}
- <div className="min-h-0 flex-1 overflow-y-auto p-4">
- <div
- ref={setSurfaceRef}
- className="relative grid"
- style={{
- gridTemplateColumns: `repeat(${grid.columns}, minmax(0, 1fr))`,
- gridAutoRows: `${grid.rowHeight}px`,
- gap: `${grid.gap}px`,
- // Fill the viewport even when the content needs fewer rows, so the
- // whole visible page is drawable (and dotted) rather than a strip.
- minHeight: `max(100%, ${surfaceRows(placements) * pitchY}px)`,
- cursor: interactive ? "crosshair" : undefined,
- }}
- onPointerDown={onSurfacePointerDown}
- onPointerMove={onPointerMove}
- onPointerUp={onPointerUp}
- onPointerCancel={onPointerCancel}
- onPointerLeave={onPointerLeave}
- onLostPointerCapture={onPointerCancel}
- >
- {interactive && surfaceWidth > 0 ? (
- // Edit mode reveals the lattice: a soft dot (the fade to transparent
- // is the blur) on each cell corner, where tiles snap and drawing
- // starts, gently pulsing to invite a drag. The overlay's top edge
- // starts at the first interior corner row so no clipped dots hug the
- // top of the page.
- <div
- aria-hidden
- className="pointer-events-none absolute inset-x-0 bottom-0 animate-pulse opacity-60"
- style={{
- top: pitchY - grid.gap / 2 - DOT_FADE_RADIUS,
- backgroundImage:
- "radial-gradient(circle, var(--gray-7) 1px, transparent 4px)",
- backgroundSize: `${pitchX}px ${pitchY}px`,
- backgroundPosition: `${pitchX / 2 - grid.gap / 2}px ${DOT_FADE_RADIUS - pitchY / 2}px`,
- }}
- />
- ) : null}
- {hoveredCell ? (
- // The cell a click would fill, so the empty surface says it is
- // drawable before the pointer goes down.
- <div
- aria-hidden
- className="pointer-events-none rounded-(--radius-3) bg-fill-hover"
- style={gridItemStyle(hoveredCell)}
- />
- ) : null}
- {placements.length === 0 && !drag ? (
- // How-to placed on the grid as a tile of its own, instead of a
- // full-width overlay that looks like broken chrome. Pointer events
- // pass through so the user can draw right over it.
- <div
- className="pointer-events-none flex items-center justify-center rounded-(--radius-3) border border-(--gray-6) border-dashed bg-(--gray-2)"
- style={gridItemStyle(emptyHintRect(grid.columns))}
- >
- <Empty className="border-0 bg-transparent">
- <EmptyHeader>
- <EmptyMedia variant="icon">
- <SquaresFourIcon size={24} />
- </EmptyMedia>
- <EmptyTitle>
- {interactive
- ? "Draw your first widget"
- : "An empty canvas"}
- </EmptyTitle>
- <EmptyDescription>
- {interactive
- ? "Click and drag on the dotted grid to draw a box, then describe what should go there."
- : "Select Edit to draw your first widget."}
- </EmptyDescription>
- </EmptyHeader>
- </Empty>
- </div>
- ) : null}
- {placements.map((placement) => {
- const dragged =
- drag &&
- drag.kind !== "draw" &&
- drag.placementId === placement.id
- ? drag.rect
- : placement;
- return (
- <div
- key={placement.id}
- className="group relative overflow-hidden rounded-(--radius-3) border border-(--gray-5) bg-(--color-panel-solid)"
- style={gridItemStyle(dragged)}
- >
- {interactive ? (
- <div
- className="absolute inset-x-0 top-0 z-10 h-5 cursor-move bg-(--gray-3) opacity-0 transition-opacity group-hover:opacity-100"
- onPointerDown={startMove(placement)}
- />
- ) : null}
- <GridPlacementTile
- placement={placement}
- interactive={interactive}
- patching={isPatching}
- actions={actions}
- />
- {interactive && placement.generationTaskId ? (
- // Opens the widget's own conversation in the side panel so a
- // broken query or tweak goes straight back to its agent.
- <Button
- variant="outline"
- size="icon"
- className="absolute top-1 right-1 z-20 opacity-0 transition-opacity group-hover:opacity-100"
- onPointerDown={(event) => event.stopPropagation()}
- onClick={() => actions.discuss(placement)}
- >
- <ChatCircleIcon size={14} />
- </Button>
- ) : null}
- {interactive ? (
- <div
- className="absolute right-0 bottom-0 z-10 h-4 w-4 cursor-nwse-resize bg-(--gray-6) opacity-0 transition-opacity group-hover:opacity-100"
- onPointerDown={startResize(placement)}
- />
- ) : null}
- </div>
- );
- })}
- {drag ? (
- <div
- className="pointer-events-none rounded-(--radius-3) border-(--accent-8) border-2 border-dashed bg-(--accent-3) opacity-70"
- style={gridItemStyle(drag.rect)}
- />
- ) : null}
- </div>
- </div>
+ <GridSurface
+ grid={layout.grid}
+ placements={placements}
+ interactive={interactive}
+ patching={isPatching}
+ actions={actions}
+ onDragComplete={onDragComplete}
+ />
</div>
{interactive || widgetTarget || viewOpen ? (
<ResizableSidebar
diff --git a/products/desktop/packages/ui/src/features/canvas/grid/GridCardChrome.tsx b/products/desktop/packages/ui/src/features/canvas/grid/GridCardChrome.tsx
new file mode 100644
index 000000000000..4b747122e6d8
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/grid/GridCardChrome.tsx
@@ -0,0 +1,43 @@
+import type { GridPlacement } from "@posthog/core/canvas/gridLayoutSchemas";
+import type { PointerEvent } from "react";
+import { GridPlacementMenu } from "./GridPlacementMenu";
+import type { PlacementActions } from "./placementActions";
+
+/**
+ * A card's edit affordances: the move strip along its top, the actions menu,
+ * and the resize grip in its corner. Rendered only while the canvas is
+ * editable, so a read-only card is the widget and nothing else.
+ */
+export function GridCardChrome({
+ placement,
+ patching,
+ actions,
+ onMovePointerDown,
+ onResizePointerDown,
+}: {
+ placement: GridPlacement;
+ patching: boolean;
+ actions: PlacementActions;
+ onMovePointerDown: (event: PointerEvent) => void;
+ onResizePointerDown: (event: PointerEvent) => void;
+}) {
+ return (
+ <>
+ {/* Under the menu, which takes the corner this strip would otherwise
+ offer as a drag handle. */}
+ <div
+ className="absolute inset-x-0 top-0 z-10 h-5 cursor-move bg-(--gray-3) opacity-0 transition-opacity group-hover:opacity-100"
+ onPointerDown={onMovePointerDown}
+ />
+ <GridPlacementMenu
+ placement={placement}
+ patching={patching}
+ actions={actions}
+ />
+ <div
+ className="absolute right-0 bottom-0 z-10 h-4 w-4 cursor-nwse-resize bg-(--gray-6) opacity-0 transition-opacity group-hover:opacity-100"
+ onPointerDown={onResizePointerDown}
+ />
+ </>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/grid/GridPlacementMenu.test.tsx b/products/desktop/packages/ui/src/features/canvas/grid/GridPlacementMenu.test.tsx
new file mode 100644
index 000000000000..fded0cbd72ec
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/grid/GridPlacementMenu.test.tsx
@@ -0,0 +1,99 @@
+import type { GridPlacement } from "@posthog/core/canvas/gridLayoutSchemas";
+import { render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { describe, expect, it, vi } from "vitest";
+import { GridPlacementMenu } from "./GridPlacementMenu";
+import type { PlacementActions } from "./placementActions";
+
+const placement: GridPlacement = {
+ id: "placement-1",
+ status: "live",
+ component: "component-1",
+ generationTaskId: "task-1",
+ x: 0,
+ y: 0,
+ w: 2,
+ h: 2,
+};
+
+function actions(): PlacementActions {
+ return {
+ describe: vi.fn(),
+ reset: vi.fn(),
+ remove: vi.fn(),
+ discuss: vi.fn(),
+ };
+}
+
+describe("GridPlacementMenu", () => {
+ it("keeps the text-only delete action last and asks for confirmation", async () => {
+ const cardActions = actions();
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ render(
+ <GridPlacementMenu
+ placement={placement}
+ patching={false}
+ actions={cardActions}
+ />,
+ );
+
+ await user.click(screen.getByRole("button", { name: "Card options" }));
+ const menuItems = await screen.findAllByRole("menuitem");
+
+ expect(menuItems.map((item) => item.textContent)).toEqual([
+ "View conversation",
+ "Delete…",
+ ]);
+ for (const item of menuItems) {
+ expect(item.querySelector("svg")).toBeNull();
+ }
+
+ await user.click(menuItems[1]);
+ expect(cardActions.remove).not.toHaveBeenCalled();
+ expect(
+ await screen.findByRole("alertdialog", { name: "Delete card?" }),
+ ).toBeInTheDocument();
+
+ await user.click(screen.getByRole("button", { name: "Delete" }));
+ expect(cardActions.remove).toHaveBeenCalledExactlyOnceWith(placement);
+ });
+
+ it("opens the placement task from the menu", async () => {
+ const cardActions = actions();
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ render(
+ <GridPlacementMenu
+ placement={{ ...placement, status: "generating" }}
+ patching={false}
+ actions={cardActions}
+ />,
+ );
+
+ await user.click(screen.getByRole("button", { name: "Card options" }));
+ await user.click(
+ await screen.findByRole("menuitem", { name: "View progress" }),
+ );
+
+ expect(cardActions.discuss).toHaveBeenCalledExactlyOnceWith({
+ ...placement,
+ status: "generating",
+ });
+ });
+
+ it("shows only delete when the card has no conversation", async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ render(
+ <GridPlacementMenu
+ placement={{ ...placement, generationTaskId: null }}
+ patching={false}
+ actions={actions()}
+ />,
+ );
+
+ await user.click(screen.getByRole("button", { name: "Card options" }));
+
+ expect(
+ (await screen.findAllByRole("menuitem")).map((item) => item.textContent),
+ ).toEqual(["Delete…"]);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/canvas/grid/GridPlacementMenu.tsx b/products/desktop/packages/ui/src/features/canvas/grid/GridPlacementMenu.tsx
new file mode 100644
index 000000000000..c75cee8d3b6d
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/grid/GridPlacementMenu.tsx
@@ -0,0 +1,109 @@
+import { DotsThreeIcon } from "@phosphor-icons/react";
+import type { GridPlacement } from "@posthog/core/canvas/gridLayoutSchemas";
+import {
+ AlertDialog,
+ AlertDialogClose,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@posthog/quill";
+import { useState } from "react";
+import type { PlacementActions } from "./placementActions";
+
+/**
+ * Actions for one grid card, rendered only while the canvas is editable. The
+ * menu stays in the card's outer chrome so it is available for live component
+ * frames as well as pending and generating cards.
+ */
+export function GridPlacementMenu({
+ placement,
+ patching,
+ actions,
+}: {
+ placement: GridPlacement;
+ patching: boolean;
+ actions: PlacementActions;
+}) {
+ const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
+ const hasConversation = !!placement.generationTaskId;
+
+ const confirmDelete = () => {
+ setConfirmDeleteOpen(false);
+ actions.remove(placement);
+ };
+
+ return (
+ <div
+ // An open menu keeps its trigger visible after the pointer leaves the
+ // card, which the trigger already states as data-popup-open.
+ className="absolute top-1 right-1 z-20 opacity-0 transition-opacity focus-within:opacity-100 group-hover:opacity-100 has-[[data-popup-open]]:opacity-100"
+ onPointerDown={(event) => event.stopPropagation()}
+ >
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button variant="outline" size="icon-sm" aria-label="Card options">
+ <DotsThreeIcon size={16} weight="bold" />
+ </Button>
+ }
+ />
+ <DropdownMenuContent align="end" side="bottom" sideOffset={4}>
+ {hasConversation ? (
+ <>
+ <DropdownMenuItem onClick={() => actions.discuss(placement)}>
+ {placement.status === "generating"
+ ? "View progress"
+ : "View conversation"}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ </>
+ ) : null}
+ <DropdownMenuItem
+ variant="destructive"
+ disabled={patching}
+ onClick={() => setConfirmDeleteOpen(true)}
+ >
+ Delete…
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+
+ <AlertDialog open={confirmDeleteOpen} onOpenChange={setConfirmDeleteOpen}>
+ <AlertDialogContent className="max-w-md">
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete card?</AlertDialogTitle>
+ <AlertDialogDescription>
+ This removes the card from the canvas.
+ {placement.component ? " The reusable component stays." : null}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogClose
+ render={
+ <Button variant="outline" size="sm">
+ Cancel
+ </Button>
+ }
+ />
+ <Button
+ variant="destructive"
+ size="sm"
+ disabled={patching}
+ onClick={confirmDelete}
+ >
+ Delete
+ </Button>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/grid/GridPlacementTile.stories.tsx b/products/desktop/packages/ui/src/features/canvas/grid/GridPlacementTile.stories.tsx
index f126395a452a..8625f3aaa32c 100644
--- a/products/desktop/packages/ui/src/features/canvas/grid/GridPlacementTile.stories.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/grid/GridPlacementTile.stories.tsx
@@ -1,9 +1,6 @@
import type { GridPlacement } from "@posthog/core/canvas/gridLayoutSchemas";
import type { Meta, StoryObj } from "@storybook/react-vite";
-import {
- GridPlacementTile,
- type PlacementTileActions,
-} from "./GridPlacementTile";
+import { GridPlacementTile, type PlacementActions } from "./GridPlacementTile";
const PLACEMENT: GridPlacement = {
id: "p1",
@@ -14,7 +11,7 @@ const PLACEMENT: GridPlacement = {
h: 2,
};
-const actions: PlacementTileActions = {
+const actions: PlacementActions = {
describe: async () => {},
reset: () => {},
remove: () => {},
diff --git a/products/desktop/packages/ui/src/features/canvas/grid/GridPlacementTile.tsx b/products/desktop/packages/ui/src/features/canvas/grid/GridPlacementTile.tsx
index 3cb254d4c154..9f5e0195f380 100644
--- a/products/desktop/packages/ui/src/features/canvas/grid/GridPlacementTile.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/grid/GridPlacementTile.tsx
@@ -7,22 +7,12 @@ import { taskDetailQuery } from "@posthog/ui/features/tasks/queries";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { ComponentFrame } from "./ComponentFrame";
+import type { PlacementActions } from "./placementActions";
// Poll cadence for the fill task's run status while a tile is generating —
// matches the canvas generation poll elsewhere.
const FILL_TASK_POLL_MS = 5_000;
-export interface PlacementTileActions {
- /** Dispatch an agent task to fill this placement with the given ask. */
- describe: (placement: GridPlacement, prompt: string) => Promise<void>;
- /** Put a stalled placement back to pending so it can be re-described. */
- reset: (placement: GridPlacement) => void;
- /** Remove this placement from the layout. */
- remove: (placement: GridPlacement) => void;
- /** Open this placement's task conversation in the canvas's side panel. */
- discuss: (placement: GridPlacement) => void;
-}
-
/**
* One placement on the grid, rendered by lifecycle status: a live widget, a
* drawn box awaiting its description, an agent filling it, or a failed fill
@@ -39,7 +29,7 @@ export function GridPlacementTile({
/** A layout write is in flight; the tile's edit buttons stay disabled until
* it lands, so a second click can't fire a patch against the same head. */
patching: boolean;
- actions: PlacementTileActions;
+ actions: PlacementActions;
}) {
if (placement.status === "live" && placement.component) {
return <ComponentFrame placement={placement} />;
@@ -59,7 +49,6 @@ export function GridPlacementTile({
placement={placement}
failed={placement.status === "failed"}
interactive={interactive}
- patching={patching}
actions={actions}
/>
);
@@ -74,7 +63,7 @@ function GeneratingTile({
placement: GridPlacement;
interactive: boolean;
patching: boolean;
- actions: PlacementTileActions;
+ actions: PlacementActions;
}) {
const taskId = placement.generationTaskId ?? null;
const { data: task } = useQuery({
@@ -146,16 +135,6 @@ function GeneratingTile({
Review request
</Button>
) : null}
- {interactive ? (
- <Button
- variant="default"
- size="sm"
- disabled={patching}
- onClick={() => actions.remove(placement)}
- >
- Remove
- </Button>
- ) : null}
</div>
</div>
);
@@ -167,19 +146,7 @@ function GeneratingTile({
<Text size="sm" className="line-clamp-2">
{placement.prompt ?? "Building this widget…"}
</Text>
- <div className="flex items-center gap-1">
- {viewTask}
- {interactive ? (
- <Button
- variant="destructive"
- size="sm"
- disabled={patching}
- onClick={() => actions.remove(placement)}
- >
- Remove
- </Button>
- ) : null}
- </div>
+ {viewTask}
</div>
);
}
@@ -188,14 +155,12 @@ function DescribeTile({
placement,
failed,
interactive,
- patching,
actions,
}: {
placement: GridPlacement;
failed: boolean;
interactive: boolean;
- patching: boolean;
- actions: PlacementTileActions;
+ actions: PlacementActions;
}) {
const [isSubmitting, setIsSubmitting] = useState(false);
@@ -225,8 +190,8 @@ function DescribeTile({
) : null}
{/* The task composer's editor, as the freeform canvas uses it: markdown
as you type, shift+enter for a new line, @ for files and / for
- skills. Its own toolbar stays hidden — the only control this box
- needs beside send is the one that takes the box away. */}
+ skills. Its own toolbar stays hidden; card actions live in the shared
+ overflow menu above this tile. */}
<PromptInput
sessionId={`grid-placement-${placement.id}`}
placeholder="What should go here?"
@@ -240,16 +205,6 @@ function DescribeTile({
enableBashMode={false}
hideDefaultToolbar
onSubmit={(text) => void submit(text)}
- toolbarEndSlot={
- <Button
- variant="destructive"
- size="sm"
- disabled={patching}
- onClick={() => actions.remove(placement)}
- >
- Remove
- </Button>
- }
/>
</div>
);
diff --git a/products/desktop/packages/ui/src/features/canvas/grid/GridSurface.tsx b/products/desktop/packages/ui/src/features/canvas/grid/GridSurface.tsx
new file mode 100644
index 000000000000..aa46d2aceed9
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/grid/GridSurface.tsx
@@ -0,0 +1,241 @@
+import { SquaresFourIcon } from "@phosphor-icons/react";
+import type {
+ GridDefinition,
+ GridPlacement,
+} from "@posthog/core/canvas/gridLayoutSchemas";
+import {
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyMedia,
+ EmptyTitle,
+} from "@posthog/quill";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { GridCardChrome } from "./GridCardChrome";
+import { GridPlacementTile } from "./GridPlacementTile";
+import {
+ collides,
+ type GridRect,
+ rectFromCells,
+ surfaceRows,
+} from "./gridGeometry";
+import type { PlacementActions } from "./placementActions";
+import { type GridDragOutcome, useGridDrag } from "./useGridDrag";
+
+// Outer radius of a lattice dot's fade (the gradient's transparent stop).
+const DOT_FADE_RADIUS = 4;
+
+function gridItemStyle(rect: GridRect): React.CSSProperties {
+ return {
+ gridColumn: `${rect.x + 1} / span ${rect.w}`,
+ gridRow: `${rect.y + 1} / span ${rect.h}`,
+ };
+}
+
+// Where the how-to tile sits on an empty grid: centered, wide enough to read,
+// one row down so it looks placed rather than docked to the top edge.
+function emptyHintRect(columns: number): GridRect {
+ const w = Math.min(4, columns);
+ return { x: Math.floor((columns - w) / 2), y: 1, w, h: 3 };
+}
+
+// The dot lattice needs the surface's real pixel width: columns are fractional
+// (1fr), so corner positions can't be expressed in pure CSS background math.
+function useMeasuredWidth(element: HTMLDivElement | null): number {
+ const [width, setWidth] = useState(0);
+ useEffect(() => {
+ if (!element) return;
+ const observer = new ResizeObserver((entries) => {
+ const entry = entries[0];
+ if (entry) setWidth(entry.contentRect.width);
+ });
+ observer.observe(element);
+ setWidth(element.clientWidth);
+ return () => observer.disconnect();
+ }, [element]);
+ return width;
+}
+
+/**
+ * The drawable grid itself: the cards, the lattice they snap to, and the
+ * pointer state machine that draws, moves and resizes them. Everything here
+ * needs the surface's own measured geometry, so it stays out of the view that
+ * owns the canvas's data.
+ */
+export function GridSurface({
+ grid,
+ placements,
+ interactive,
+ patching,
+ actions,
+ onDragComplete,
+}: {
+ grid: GridDefinition;
+ placements: GridPlacement[];
+ interactive: boolean;
+ patching: boolean;
+ actions: PlacementActions;
+ onDragComplete: (outcome: GridDragOutcome) => void;
+}) {
+ const surfaceRef = useRef<HTMLDivElement>(null);
+ // The surface mounts only after loading, so a plain ref never retriggers the
+ // measurement effect; a state-backed element does.
+ const [surfaceEl, setSurfaceEl] = useState<HTMLDivElement | null>(null);
+ const setSurfaceRef = useCallback((el: HTMLDivElement | null) => {
+ surfaceRef.current = el;
+ setSurfaceEl(el);
+ }, []);
+ const surfaceWidth = useMeasuredWidth(surfaceEl);
+
+ const {
+ drag,
+ hover,
+ onPointerLeave,
+ onSurfacePointerDown,
+ onPointerMove,
+ onPointerUp,
+ onPointerCancel,
+ startMove,
+ startResize,
+ } = useGridDrag({
+ surfaceRef,
+ grid,
+ interactive,
+ onComplete: onDragComplete,
+ });
+
+ // Cell pitch in px: cell size plus one gap. Vertical pitch is fixed by the
+ // layout; horizontal comes from the measured surface width (1fr columns).
+ const pitchX = (surfaceWidth + grid.gap) / grid.columns;
+ const pitchY = grid.rowHeight + grid.gap;
+ // A cell already under a tile is not free to draw on, so it stays unlit.
+ const hoveredRect = hover && rectFromCells(hover, hover);
+ const hoveredCell =
+ hoveredRect && !collides(hoveredRect, placements) ? hoveredRect : null;
+
+ return (
+ <div className="min-h-0 flex-1 overflow-y-auto p-4">
+ <div
+ ref={setSurfaceRef}
+ className="relative grid"
+ style={{
+ gridTemplateColumns: `repeat(${grid.columns}, minmax(0, 1fr))`,
+ gridAutoRows: `${grid.rowHeight}px`,
+ gap: `${grid.gap}px`,
+ // Fill the viewport even when the content needs fewer rows, so the
+ // whole visible page is drawable (and dotted) rather than a strip.
+ minHeight: `max(100%, ${surfaceRows(placements) * pitchY}px)`,
+ cursor: interactive ? "crosshair" : undefined,
+ }}
+ onPointerDown={onSurfacePointerDown}
+ onPointerMove={onPointerMove}
+ onPointerUp={onPointerUp}
+ onPointerCancel={onPointerCancel}
+ onPointerLeave={onPointerLeave}
+ onLostPointerCapture={onPointerCancel}
+ >
+ {interactive && surfaceWidth > 0 ? (
+ // Edit mode reveals the lattice: a soft dot (the fade to transparent
+ // is the blur) on each cell corner, where tiles snap and drawing
+ // starts, gently pulsing to invite a drag. The overlay's top edge
+ // starts at the first interior corner row so no clipped dots hug the
+ // top of the page.
+ <div
+ aria-hidden
+ className="pointer-events-none absolute inset-x-0 bottom-0 animate-pulse opacity-60"
+ style={{
+ top: pitchY - grid.gap / 2 - DOT_FADE_RADIUS,
+ backgroundImage:
+ "radial-gradient(circle, var(--gray-7) 1px, transparent 4px)",
+ backgroundSize: `${pitchX}px ${pitchY}px`,
+ backgroundPosition: `${pitchX / 2 - grid.gap / 2}px ${DOT_FADE_RADIUS - pitchY / 2}px`,
+ }}
+ />
+ ) : null}
+ {hoveredCell ? (
+ // The cell a click would fill, so the empty surface says it is
+ // drawable before the pointer goes down.
+ <div
+ aria-hidden
+ className="pointer-events-none rounded-(--radius-3) bg-fill-hover"
+ style={gridItemStyle(hoveredCell)}
+ />
+ ) : null}
+ {placements.length === 0 && !drag ? (
+ <EmptyGridHint grid={grid} interactive={interactive} />
+ ) : null}
+ {placements.map((placement) => {
+ const dragged =
+ drag && drag.kind !== "draw" && drag.placementId === placement.id
+ ? drag.rect
+ : placement;
+ return (
+ <div
+ key={placement.id}
+ className="group relative overflow-hidden rounded-(--radius-3) border border-(--gray-5) bg-(--color-panel-solid)"
+ style={gridItemStyle(dragged)}
+ >
+ <GridPlacementTile
+ placement={placement}
+ interactive={interactive}
+ patching={patching}
+ actions={actions}
+ />
+ {interactive ? (
+ <GridCardChrome
+ placement={placement}
+ patching={patching}
+ actions={actions}
+ onMovePointerDown={startMove(placement)}
+ onResizePointerDown={startResize(placement)}
+ />
+ ) : null}
+ </div>
+ );
+ })}
+ {drag ? (
+ <div
+ className="pointer-events-none rounded-(--radius-3) border-(--accent-8) border-2 border-dashed bg-(--accent-3) opacity-70"
+ style={gridItemStyle(drag.rect)}
+ />
+ ) : null}
+ </div>
+ </div>
+ );
+}
+
+/**
+ * How-to placed on the grid as a tile of its own, instead of a full-width
+ * overlay that looks like broken chrome. Pointer events pass through so the
+ * user can draw right over it.
+ */
+function EmptyGridHint({
+ grid,
+ interactive,
+}: {
+ grid: GridDefinition;
+ interactive: boolean;
+}) {
+ return (
+ <div
+ className="pointer-events-none flex items-center justify-center rounded-(--radius-3) border border-(--gray-6) border-dashed bg-(--gray-2)"
+ style={gridItemStyle(emptyHintRect(grid.columns))}
+ >
+ <Empty className="border-0 bg-transparent">
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <SquaresFourIcon size={24} />
+ </EmptyMedia>
+ <EmptyTitle>
+ {interactive ? "Draw your first widget" : "An empty canvas"}
+ </EmptyTitle>
+ <EmptyDescription>
+ {interactive
+ ? "Click and drag on the dotted grid to draw a box, then describe what should go there."
+ : "Select Edit to draw your first widget."}
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/grid/placementActions.ts b/products/desktop/packages/ui/src/features/canvas/grid/placementActions.ts
new file mode 100644
index 000000000000..f412a96dbb24
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/grid/placementActions.ts
@@ -0,0 +1,13 @@
+import type { GridPlacement } from "@posthog/core/canvas/gridLayoutSchemas";
+
+/** What a card's chrome and its tile can do to one placement. */
+export interface PlacementActions {
+ /** Dispatch an agent task to fill this placement with the given ask. */
+ describe: (placement: GridPlacement, prompt: string) => Promise<void>;
+ /** Put a stalled placement back to pending so it can be re-described. */
+ reset: (placement: GridPlacement) => void;
+ /** Remove this placement from the layout. */
+ remove: (placement: GridPlacement) => void;
+ /** Open this placement's task conversation in the canvas's side panel. */
+ discuss: (placement: GridPlacement) => void;
+}