From e0552bad2b38fa6391bd0e582cda9f1dcdd7b1ed Mon Sep 17 00:00:00 2001 From: Jerred Shepherd Date: Thu, 26 Nov 2026 11:20:24 -0800 Subject: [PATCH 1/5] feat(artifacts): resize a frame through moveFrames Why Resizing a frame on the canvas has no op: placeFrame sets the size once and moveFrames only moves. A resize must merge under the row lock like a drag, so an agent publish and a resize never refuse each other. What - `moveFrames` entries take optional `w` and `h`; omitted, the size is left alone, so existing callers are unchanged. - The domain merge and the e2e fake apply them. Verification - bun test of src/domain and src/shared (new cases for the resize and for a zero width). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_011u9pQkmfQzZFyzPbpimoiT --- packages/artifacts/e2e/fake-boards.ts | 2 + packages/artifacts/src/domain/board-ops.ts | 9 +++- packages/artifacts/src/domain/domain.test.ts | 13 ++++++ .../integration/publish.integration.test.ts | 44 +++++++++++++++++++ .../artifacts/src/shared/contract.test.ts | 10 +++++ packages/artifacts/src/shared/contract.ts | 3 ++ 6 files changed, 80 insertions(+), 1 deletion(-) diff --git a/packages/artifacts/e2e/fake-boards.ts b/packages/artifacts/e2e/fake-boards.ts index 85a31a2008..3a3c371ed0 100644 --- a/packages/artifacts/e2e/fake-boards.ts +++ b/packages/artifacts/e2e/fake-boards.ts @@ -293,6 +293,8 @@ function moveFrames( if (frame === undefined) continue; frame.x = move.x; frame.y = move.y; + if (move.w !== undefined) frame.w = move.w; + if (move.h !== undefined) frame.h = move.h; if (move.page !== undefined) frame.page = move.page; } } diff --git a/packages/artifacts/src/domain/board-ops.ts b/packages/artifacts/src/domain/board-ops.ts index 25604e1061..db94b87f4f 100644 --- a/packages/artifacts/src/domain/board-ops.ts +++ b/packages/artifacts/src/domain/board-ops.ts @@ -54,7 +54,14 @@ function move(index: BoardIndex, op: Extract) { step.page !== undefined && step.page < index.pages.length ? step.page : frame.page; - frames[step.artifactId] = { ...frame, x: step.x, y: step.y, page }; + frames[step.artifactId] = { + ...frame, + x: step.x, + y: step.y, + page, + w: step.w ?? frame.w, + h: step.h ?? frame.h, + }; } return { ...index, frames }; } diff --git a/packages/artifacts/src/domain/domain.test.ts b/packages/artifacts/src/domain/domain.test.ts index a3497a75e5..7c235785ca 100644 --- a/packages/artifacts/src/domain/domain.test.ts +++ b/packages/artifacts/src/domain/domain.test.ts @@ -317,6 +317,19 @@ describe("board operations", () => { expect(next.frames[A]).toMatchObject({ x: 5, y: 6, page: 0 }); expect(C in next.frames).toBe(false); }); + it("resizes in a move and leaves the size alone otherwise", () => { + const resized = applyBoardOps(placed, [ + { + op: "moveFrames", + moves: [{ artifactId: A, x: 5, y: 6, w: 800, h: 500 }], + }, + ]); + expect(resized.frames[A]).toMatchObject({ x: 5, y: 6, w: 800, h: 500 }); + const moved = applyBoardOps(resized, [ + { op: "moveFrames", moves: [{ artifactId: A, x: 7, y: 8 }] }, + ]); + expect(moved.frames[A]).toMatchObject({ x: 7, y: 8, w: 800, h: 500 }); + }); it("reorders without losing or duplicating ids", () => { const next = applyBoardOps(placed, [ { op: "reorder", order: [B, B, C, "zzz"] }, diff --git a/packages/artifacts/src/integration/publish.integration.test.ts b/packages/artifacts/src/integration/publish.integration.test.ts index 01a35463ef..d7547933dd 100644 --- a/packages/artifacts/src/integration/publish.integration.test.ts +++ b/packages/artifacts/src/integration/publish.integration.test.ts @@ -519,6 +519,50 @@ describe("boards", () => { expect(new Set(frames).size).toBe(8); }); + it("a resize and a concurrent agent placeFrame both survive", async () => { + await human.mutate("boards.create", { slug: "resize", title: "Resize" }); + const [frame, placed] = [crypto.randomUUID(), crypto.randomUUID()]; + await human.mutate("boards.applyOps", { + slug: "resize", + ops: [{ op: "placeFrame", artifactId: frame, w: 640, h: 420 }], + }); + await Promise.all([ + human.mutate("boards.applyOps", { + slug: "resize", + ops: [ + { + op: "moveFrames", + moves: [{ artifactId: frame, x: 96, y: 48, w: 800, h: 500 }], + }, + ], + }), + human.mutate("boards.applyOps", { + slug: "resize", + ops: [{ op: "placeFrame", artifactId: placed, w: 400, h: 300 }], + }), + ]); + const board = z + .object({ index: BoardIndexSchema }) + .parse(await human.query("boards.get", { slug: "resize" })); + expect(board.index.frames[frame]).toMatchObject({ + x: 96, + y: 48, + w: 800, + h: 500, + }); + expect(board.index.frames[placed]).toMatchObject({ w: 400, h: 300 }); + expect(board.index.order).toHaveLength(2); + // A move without a size leaves the resized size alone. + await human.mutate("boards.applyOps", { + slug: "resize", + ops: [{ op: "moveFrames", moves: [{ artifactId: frame, x: 0, y: 0 }] }], + }); + const moved = z + .object({ index: BoardIndexSchema }) + .parse(await human.query("boards.get", { slug: "resize" })); + expect(moved.index.frames[frame]).toMatchObject({ w: 800, h: 500 }); + }); + it("replaces the whole document only against the current revision", async () => { await human.mutate("boards.create", { slug: "replace", title: "Replace" }); const current = z diff --git a/packages/artifacts/src/shared/contract.test.ts b/packages/artifacts/src/shared/contract.test.ts index 6481ca86ae..ca3052ea0a 100644 --- a/packages/artifacts/src/shared/contract.test.ts +++ b/packages/artifacts/src/shared/contract.test.ts @@ -271,6 +271,10 @@ describe("BoardOpSchema", () => { { op: "placeFrame", artifactId: ID, w: 1440, h: 900 }, { op: "placeFrame", artifactId: ID, w: 1, h: 1, rightOf: OTHER_ID }, { op: "moveFrames", moves: [{ artifactId: ID, x: 1, y: 2 }] }, + { + op: "moveFrames", + moves: [{ artifactId: ID, x: 1, y: 2, w: 800, h: 500 }], + }, { op: "reorder", order: [ID, "n1"] }, { op: "putNote", id: "n1", note: board.notes.n1 }, { op: "deleteNote", id: "n1" }, @@ -285,6 +289,12 @@ describe("BoardOpSchema", () => { expect(() => BoardOpSchema.parse({ op: "moveFrames", moves: [] }), ).toThrow(); + expect(() => + BoardOpSchema.parse({ + op: "moveFrames", + moves: [{ artifactId: ID, x: 1, y: 2, w: 0 }], + }), + ).toThrow(); expect(() => BoardOpSchema.parse({ op: "removeFrame", artifactId: "x" }), ).toThrow(); diff --git a/packages/artifacts/src/shared/contract.ts b/packages/artifacts/src/shared/contract.ts index 374076595b..a4bba084ef 100644 --- a/packages/artifacts/src/shared/contract.ts +++ b/packages/artifacts/src/shared/contract.ts @@ -335,6 +335,9 @@ export const BoardOpSchema = z.discriminatedUnion("op", [ x: Coordinate, y: Coordinate, page: PageIndex.optional(), + /** A resize: both optional, so a plain move leaves the size alone. */ + w: Size.optional(), + h: Size.optional(), }), ) .min(1) From f334ff638532b3d4158e4fed81b8df7863c65c4a Mon Sep 17 00:00:00 2001 From: Jerred Shepherd Date: Thu, 26 Nov 2026 11:48:16 -0800 Subject: [PATCH 2/5] feat(artifacts): arrange frames on the canvas Why M2 done-when: layout survives a reload, and an agent publish during a drag loses neither change. What - Select (click, Shift-click, marquee on empty canvas), drag with a 4 px threshold, pointer capture and edge auto-pan, eight resize handles (a fixed-viewport frame keeps its aspect, a responsive one resizes freely), 8 px grid snap (Alt disables), `[` `]` z-order, arrow nudge (Shift 10x), Delete from board behind a confirm (never the artifact), undo and redo (Mod+Z, Shift+Mod+Z) over the applied ops. Esc cancels a drag. - The arrangement is a replicated document: the server's index plus an outbox of `boards.applyOps` ops, drawn as the index with the outbox applied on top. Saves are debounced 400 ms and flushed on `pagehide` (a keepalive request). A change from another actor merges by id, never moves the camera and never disturbs a drag in progress (the draft is drawn over the document). A toast names a new frame, with a jump-to. - Undo entries record before and after for the touched frames and replay as ops against the board as it is now, so another actor's frames are left alone. - `aria-live` announcements for moves, resizes, order and removal. - Dialog: a native `close` event from our own `close()` no longer closes a dialog reopened in between. Verification - bunx turbo run build typecheck test lint --filter=@shepherdjerred/artifacts - bunx turbo run test:extended --filter=@shepherdjerred/artifacts - bun run test:e2e: desktop Chromium, mobile Chromium and WebKit, including the arrange spec (drag, snap, Alt, reload persistence, aspect and free resize, agent publish mid-drag, undo and redo, nudge, z-order, delete and undo, pagehide flush, edge auto-pan, Esc cancel, axe). - Not run: real trackpad and iPad gestures. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_011u9pQkmfQzZFyzPbpimoiT --- packages/artifacts/README.md | 16 + .../artifacts/e2e/arrange.desktop.spec.ts | 469 ++++++++++++++++++ .../src/client/canvas/arrange/autopan.ts | 71 +++ .../client/canvas/arrange/geometry.test.ts | 220 ++++++++ .../src/client/canvas/arrange/geometry.ts | 246 +++++++++ .../src/client/canvas/arrange/handles.tsx | 126 +++++ .../src/client/canvas/arrange/history.ts | 50 ++ .../src/client/canvas/arrange/merge.test.ts | 103 ++++ .../src/client/canvas/arrange/ops.test.ts | 248 +++++++++ .../src/client/canvas/arrange/ops.ts | 197 ++++++++ .../client/canvas/arrange/remove-dialog.tsx | 45 ++ .../src/client/canvas/arrange/sessions.ts | 193 +++++++ .../src/client/canvas/arrange/toasts.tsx | 105 ++++ .../src/client/canvas/arrange/use-arrange.ts | 268 ++++++++++ .../src/client/canvas/arrange/use-keys.ts | 72 +++ .../src/client/canvas/arrange/use-layout.ts | 139 ++++++ .../src/client/canvas/arrange/use-sessions.ts | 135 +++++ .../artifacts/src/client/canvas/canvas.tsx | 227 +++++---- .../artifacts/src/client/canvas/gestures.ts | 63 ++- packages/artifacts/src/client/canvas/model.ts | 40 +- .../artifacts/src/client/canvas/use-camera.ts | 7 +- .../src/client/canvas/use-canvas-keys.ts | 82 +++ .../artifacts/src/client/canvas/use-input.ts | 15 +- packages/artifacts/src/client/pages/board.tsx | 2 +- .../artifacts/src/client/shell/dialog.tsx | 16 +- .../artifacts/src/client/shell/shortcuts.ts | 6 +- .../artifacts/src/client/styles/canvas.css | 76 +++ 27 files changed, 3140 insertions(+), 97 deletions(-) create mode 100644 packages/artifacts/e2e/arrange.desktop.spec.ts create mode 100644 packages/artifacts/src/client/canvas/arrange/autopan.ts create mode 100644 packages/artifacts/src/client/canvas/arrange/geometry.test.ts create mode 100644 packages/artifacts/src/client/canvas/arrange/geometry.ts create mode 100644 packages/artifacts/src/client/canvas/arrange/handles.tsx create mode 100644 packages/artifacts/src/client/canvas/arrange/history.ts create mode 100644 packages/artifacts/src/client/canvas/arrange/merge.test.ts create mode 100644 packages/artifacts/src/client/canvas/arrange/ops.test.ts create mode 100644 packages/artifacts/src/client/canvas/arrange/ops.ts create mode 100644 packages/artifacts/src/client/canvas/arrange/remove-dialog.tsx create mode 100644 packages/artifacts/src/client/canvas/arrange/sessions.ts create mode 100644 packages/artifacts/src/client/canvas/arrange/toasts.tsx create mode 100644 packages/artifacts/src/client/canvas/arrange/use-arrange.ts create mode 100644 packages/artifacts/src/client/canvas/arrange/use-keys.ts create mode 100644 packages/artifacts/src/client/canvas/arrange/use-layout.ts create mode 100644 packages/artifacts/src/client/canvas/arrange/use-sessions.ts create mode 100644 packages/artifacts/src/client/canvas/use-canvas-keys.ts diff --git a/packages/artifacts/README.md b/packages/artifacts/README.md index 73ad228b68..8ccbac36b7 100644 --- a/packages/artifacts/README.md +++ b/packages/artifacts/README.md @@ -167,6 +167,22 @@ the typed placeholder card. Stacking is CSS `z-index` from the index `order`; an iframe is never moved or remounted, because that reloads it. The outline route stays the keyboard and screen-reader path. +**Arranging** (`src/client/canvas/arrange/`). Click selects, Shift-click adds, +a drag on empty canvas draws a marquee, a drag on a frame moves the selection +(4 px threshold, pointer capture, edge auto-pan, 8 px grid, Alt for free +movement, Esc cancels), eight handles resize one frame (a fixed-viewport frame +keeps its aspect), arrows nudge by 1 px (Shift 10), `[` `]` step z-order, Delete +removes from the board after a confirm (never the artifact), Mod+Z and +Shift+Mod+Z undo and redo. The arrangement is a replicated document: +`useBoardLayout` keeps the server's index plus an outbox of +`boards.applyOps` ops (`moveFrames` with optional `w` and `h`, `reorder`, +`removeFrame`), saved 400 ms after the last edit and on `pagehide` (a +`keepalive` request). What is drawn is the index with the outbox applied on +top, and the ops are absolute, so another actor's change (an agent publishing a +frame) merges by id without moving the camera or losing a drag in progress; +a toast names the new frame with a jump-to. Undo entries record before and +after per touched frame and replay as ops against the current board. + Browser support is Baseline Widely Available. `bun run dev:client` serves the UI with Vite against a service on `:7440`. diff --git a/packages/artifacts/e2e/arrange.desktop.spec.ts b/packages/artifacts/e2e/arrange.desktop.spec.ts new file mode 100644 index 0000000000..217e5235a3 --- /dev/null +++ b/packages/artifacts/e2e/arrange.desktop.spec.ts @@ -0,0 +1,469 @@ +import { expect, test, type Page } from "@playwright/test"; +import { agentApi, resetAndSeed, sharedFixtures } from "./review-setup.ts"; +import { publishFixture } from "./seed.ts"; + +test.beforeAll(async ({ baseURL }) => { + test.setTimeout(120_000); + await resetAndSeed(baseURL); +}); + +const SAVED_MS = 6000; +/** The camera every spec opens at: 100 %, so a screen pixel is a world pixel. */ +const CAMERA = { x: 40, y: 80, s: 1 }; + +type Ids = readonly string[]; + +/** A board of `count` HTML frames: a row of 640 x 420 frames 680 apart, from the origin. */ +async function makeBoard( + baseURL: string | undefined, + slug: string, + options: { count?: number; viewport?: boolean } = {}, +): Promise { + const api = agentApi(baseURL); + await api.boards.create.mutate({ slug, title: `Board ${slug}` }); + const fixtures = await sharedFixtures(); + const ids: string[] = []; + for (let at = 0; at < (options.count ?? 3); at += 1) { + const published = await publishFixture(String(baseURL), { + board: slug, + title: `Frame ${String(at + 1)}`, + files: fixtures.htmlV1.files, + entryPath: fixtures.htmlV1.entryPath, + ...(options.viewport === false + ? {} + : { viewport: { width: 1440, height: 900 } }), + }); + ids.push(published.artifactId); + } + return ids; +} + +async function open(page: Page, slug: string): Promise { + await page.addInitScript( + ([key, value]) => { + localStorage.setItem(String(key), String(value)); + }, + [`artifacts.canvas.camera.v1:${slug}`, JSON.stringify(CAMERA)], + ); + await page.goto(`/b/${slug}`); + await expect(page.getByTestId("canvas-frame").first()).toBeVisible(); + await page.waitForTimeout(500); +} + +function frame(page: Page, id: string) { + return page.locator(`[data-frame-id="${id}"]`); +} + +async function centre(page: Page, id: string) { + const box = await frame(page, id).boundingBox(); + if (box === null) throw new Error("frame has no box"); + return { x: box.x + box.width / 2, y: box.y + box.height / 2, box }; +} + +async function drag( + page: Page, + from: { x: number; y: number }, + by: { x: number; y: number }, +): Promise { + await page.mouse.move(from.x, from.y); + await page.mouse.down(); + await page.mouse.move(from.x + by.x / 2, from.y + by.y / 2, { steps: 4 }); + await page.mouse.move(from.x + by.x, from.y + by.y, { steps: 4 }); + await page.mouse.up(); +} + +async function serverFrame( + baseURL: string | undefined, + slug: string, + id: string, +) { + const board = await agentApi(baseURL).boards.get.query({ slug }); + return board.index.frames[id]; +} + +async function serverOrder(baseURL: string | undefined, slug: string) { + const board = await agentApi(baseURL).boards.get.query({ slug }); + return board.index.order; +} + +async function cameraTransform(page: Page): Promise { + return page + .getByTestId("canvas-world") + .evaluate((element) => + element instanceof HTMLElement ? element.style.transform : "", + ); +} + +test.describe("arranging", () => { + test("click selects, Shift-click adds, a marquee selects what it touches", async ({ + page, + baseURL, + }) => { + const [a = "", b = "", c = ""] = await makeBoard(baseURL, "select"); + await open(page, "select"); + const rings = page.getByTestId("selection-ring"); + await expect(rings).toHaveCount(0); + const first = await centre(page, a); + await page.mouse.click(first.x, first.y); + await expect(rings).toHaveCount(1); + const second = await centre(page, b); + await page.keyboard.down("Shift"); + await page.mouse.click(second.x, second.y); + await page.keyboard.up("Shift"); + await expect(rings).toHaveCount(2); + // A click on empty canvas clears. + const view = await page.getByTestId("canvas-viewport").boundingBox(); + if (view === null) throw new Error("no viewport"); + await page.mouse.click(view.x + 10, view.y + 10); + await expect(rings).toHaveCount(0); + + // A marquee from empty canvas across the first two frames and not the third. + await page.mouse.move(view.x + 10, view.y + 10); + await page.mouse.down(); + await page.mouse.move(view.x + 780, view.y + 300, { steps: 6 }); + await expect(page.getByTestId("marquee")).toBeVisible(); + await expect(rings).toHaveCount(2); + await page.mouse.up(); + await expect(page.getByTestId("marquee")).toHaveCount(0); + await expect(rings).toHaveCount(2); + await expect( + page.getByRole("button", { name: /^Frame 3,/u }), + ).toHaveAttribute("aria-pressed", "false"); + expect(c).toBeDefined(); + }); + + test("dragging moves a frame on the 8 px grid, Alt moves it freely, and it persists", async ({ + page, + baseURL, + }) => { + const [a = ""] = await makeBoard(baseURL, "drag"); + await open(page, "drag"); + const start = await centre(page, a); + await drag(page, start, { x: 101, y: 53 }); + await expect + .poll(() => serverFrame(baseURL, "drag", a), { timeout: SAVED_MS }) + .toMatchObject({ x: 104, y: 56 }); + + await page.keyboard.down("Alt"); + const next = await centre(page, a); + await drag(page, next, { x: 13, y: 9 }); + await page.keyboard.up("Alt"); + await expect + .poll(() => serverFrame(baseURL, "drag", a), { timeout: SAVED_MS }) + .toMatchObject({ x: 117, y: 65 }); + + await page.reload(); + await expect(page.getByTestId("canvas-frame").first()).toBeVisible(); + await page.waitForTimeout(500); + const box = await frame(page, a).boundingBox(); + const view = await page.getByTestId("canvas-viewport").boundingBox(); + if (box === null || view === null) throw new Error("no boxes"); + expect(box.x - view.x).toBeCloseTo(CAMERA.x + 117, 0); + expect(box.y - view.y).toBeCloseTo(CAMERA.y + 65, 0); + }); + + test("a fixed-viewport frame keeps its aspect on resize, a responsive one resizes freely", async ({ + page, + baseURL, + }) => { + const [fixed = ""] = await makeBoard(baseURL, "resize-fixed", { count: 1 }); + await open(page, "resize-fixed"); + await page.getByRole("button", { name: /^Frame 1,/u }).click(); + await expect(page.locator("[data-handle]")).toHaveCount(8); + const handle = await page.locator('[data-handle="se"]').boundingBox(); + if (handle === null) throw new Error("no handle"); + await drag( + page, + { x: handle.x + handle.width / 2, y: handle.y + handle.height / 2 }, + { x: 160, y: 10 }, + ); + await expect + .poll(() => serverFrame(baseURL, "resize-fixed", fixed), { + timeout: SAVED_MS, + }) + .toMatchObject({ w: 800, h: 500 }); + + const [free = ""] = await makeBoard(baseURL, "resize-free", { + count: 1, + viewport: false, + }); + await open(page, "resize-free"); + await page.getByRole("button", { name: /^Frame 1,/u }).click(); + const corner = await page.locator('[data-handle="se"]').boundingBox(); + if (corner === null) throw new Error("no handle"); + await drag( + page, + { x: corner.x + corner.width / 2, y: corner.y + corner.height / 2 }, + { x: 160, y: 10 }, + ); + await expect + .poll(() => serverFrame(baseURL, "resize-free", free), { + timeout: SAVED_MS, + }) + .toMatchObject({ w: 800, h: 432 }); + }); + + test("an agent publish during a drag keeps both changes and does not move the camera", async ({ + page, + baseURL, + }) => { + const [a = ""] = await makeBoard(baseURL, "midair"); + await open(page, "midair"); + const cameraBefore = await cameraTransform(page); + const start = await centre(page, a); + await page.mouse.move(start.x, start.y); + await page.mouse.down(); + await page.mouse.move(start.x + 40, start.y + 24, { steps: 4 }); + await page.mouse.move(start.x + 64, start.y + 40, { steps: 2 }); + + // The agent publishes while the drag is held. + const fixtures = await sharedFixtures(); + await publishFixture(String(baseURL), { + board: "midair", + title: "Agent frame", + files: fixtures.htmlV1.files, + entryPath: fixtures.htmlV1.entryPath, + viewport: { width: 1440, height: 900 }, + }); + await expect(page.getByTestId("canvas-frame")).toHaveCount(4); + // The dragged frame is still under the pointer after the refetch. + const during = await frame(page, a).boundingBox(); + expect(during?.x).toBeGreaterThan(start.box.x + 50); + await page.mouse.move(start.x + 80, start.y + 56, { steps: 3 }); + await page.mouse.up(); + + await expect + .poll(() => serverFrame(baseURL, "midair", a), { + timeout: SAVED_MS, + }) + .toMatchObject({ x: 80, y: 56 }); + const board = await agentApi(baseURL).boards.get.query({ slug: "midair" }); + expect(Object.keys(board.index.frames)).toHaveLength(4); + expect(await cameraTransform(page)).toBe(cameraBefore); + + const toast = page.getByTestId("new-frame-toast"); + await expect(toast).toContainText("New frame: Agent frame"); + await toast.getByRole("button", { name: "Jump to" }).click(); + await expect(page.getByTestId("selection-ring")).toHaveCount(1); + await expect( + page.getByRole("button", { name: /^Agent frame,/u }), + ).toHaveAttribute("aria-pressed", "true"); + await expect(toast).toHaveCount(0); + }); + + test("undo and redo walk the applied ops", async ({ page, baseURL }) => { + const [a = ""] = await makeBoard(baseURL, "history"); + await open(page, "history"); + const start = await centre(page, a); + await drag(page, start, { x: 96, y: 48 }); + await expect + .poll(() => serverFrame(baseURL, "history", a), { + timeout: SAVED_MS, + }) + .toMatchObject({ x: 96, y: 48 }); + await page.keyboard.press("Control+z"); + await expect + .poll(() => serverFrame(baseURL, "history", a), { + timeout: SAVED_MS, + }) + .toMatchObject({ x: 0, y: 0 }); + const undone = await frame(page, a).boundingBox(); + expect(undone?.x).toBeCloseTo(start.box.x, 0); + await page.keyboard.press("Control+Shift+z"); + await expect + .poll(() => serverFrame(baseURL, "history", a), { + timeout: SAVED_MS, + }) + .toMatchObject({ x: 96, y: 48 }); + }); + + test("arrows nudge by 1 px and Shift by 10, and a run is one undo", async ({ + page, + baseURL, + }) => { + const [a = ""] = await makeBoard(baseURL, "nudge"); + await open(page, "nudge"); + await page.getByRole("button", { name: /^Frame 1,/u }).click(); + for (let press = 0; press < 3; press += 1) + await page.keyboard.press("ArrowRight"); + await page.keyboard.press("Shift+ArrowDown"); + await expect + .poll(() => serverFrame(baseURL, "nudge", a), { timeout: SAVED_MS }) + .toMatchObject({ x: 3, y: 10 }); + await expect( + page.getByRole("status").filter({ hasText: "Moved" }), + ).toBeVisible(); + await page.keyboard.press("Control+z"); + await expect + .poll(() => serverFrame(baseURL, "nudge", a), { timeout: SAVED_MS }) + .toMatchObject({ x: 0, y: 0 }); + }); + + test("[ and ] change z-order and the stacking follows without moving iframes", async ({ + page, + baseURL, + }) => { + const [a = "", b = "", c = ""] = await makeBoard(baseURL, "order"); + await open(page, "order"); + const iframes = await page + .locator("iframe") + .evaluateAll((all) => + all.map((element) => element.getAttribute("title")), + ); + await page.getByRole("button", { name: /^Frame 1,/u }).click(); + await page.keyboard.press("]"); + await expect + .poll(() => serverOrder(baseURL, "order"), { timeout: SAVED_MS }) + .toEqual([b, a, c]); + await expect(frame(page, a)).toHaveCSS("z-index", "2"); + await page.keyboard.press("}"); + await expect + .poll(() => serverOrder(baseURL, "order"), { timeout: SAVED_MS }) + .toEqual([b, c, a]); + await page.keyboard.press("["); + await expect + .poll(() => serverOrder(baseURL, "order"), { timeout: SAVED_MS }) + .toEqual([b, a, c]); + // The iframes are in the same DOM order: nothing was moved, so nothing reloaded. + expect( + await page + .locator("iframe") + .evaluateAll((all) => + all.map((element) => element.getAttribute("title")), + ), + ).toEqual(iframes); + }); + + test("delete asks first, removes only from the board, and undo brings it back", async ({ + page, + baseURL, + }) => { + const [, b = ""] = await makeBoard(baseURL, "remove"); + await open(page, "remove"); + await page.getByRole("button", { name: /^Frame 2,/u }).click(); + await page.keyboard.press("Delete"); + const dialog = page.getByRole("dialog"); + await expect(dialog).toContainText("Remove “Frame 2” from the board?"); + await dialog.getByRole("button", { name: "Cancel" }).click(); + await expect(dialog).toBeHidden(); + await expect(page.getByTestId("canvas-frame")).toHaveCount(3); + + await page.keyboard.press("Delete"); + await page.getByTestId("confirm-remove").click(); + await expect(page.getByTestId("canvas-frame")).toHaveCount(2); + await expect + .poll(() => serverFrame(baseURL, "remove", b), { + timeout: SAVED_MS, + }) + .toBeUndefined(); + // The artifact itself is untouched. + const artifact = await agentApi(baseURL).artifacts.get.query({ + id: b, + }); + expect(artifact.title).toBe("Frame 2"); + + await page.keyboard.press("Control+z"); + await expect(page.getByTestId("canvas-frame")).toHaveCount(3); + await expect + .poll(() => serverFrame(baseURL, "remove", b), { + timeout: SAVED_MS, + }) + .toMatchObject({ x: 680, y: 0, w: 640, h: 420 }); + }); + + test("hiding the page flushes the save at once", async ({ + page, + baseURL, + }) => { + const [a = ""] = await makeBoard(baseURL, "flush"); + await open(page, "flush"); + const requests: string[] = []; + page.on("request", (request) => { + if (request.url().includes("boards.applyOps")) + requests.push(request.url()); + }); + await page.getByRole("button", { name: /^Frame 1,/u }).click(); + await page.keyboard.press("ArrowRight"); + await page.evaluate(() => { + globalThis.dispatchEvent(new globalThis.Event("pagehide")); + }); + // The beacon is not a batch call; the debounced save would be. + await expect + .poll(() => requests.some((url) => !url.includes("batch=1")), { + timeout: 2000, + }) + .toBe(true); + await expect + .poll(() => serverFrame(baseURL, "flush", a), { timeout: SAVED_MS }) + .toMatchObject({ x: 1 }); + }); + + test("dragging to the edge pans the camera and the frame follows", async ({ + page, + baseURL, + }) => { + const [a = ""] = await makeBoard(baseURL, "edge"); + await open(page, "edge"); + const view = await page.getByTestId("canvas-viewport").boundingBox(); + if (view === null) throw new Error("no viewport"); + const start = await centre(page, a); + await page.mouse.move(start.x, start.y); + await page.mouse.down(); + await page.mouse.move(start.x + 20, start.y, { steps: 2 }); + await page.mouse.move(view.x + view.width - 6, start.y, { steps: 6 }); + const before = await cameraTransform(page); + await page.waitForTimeout(600); + expect(await cameraTransform(page)).not.toBe(before); + await page.mouse.up(); + const pointerTravel = view.width - 6 - (start.x - view.x); + await expect + .poll( + async () => { + const moved = await serverFrame(baseURL, "edge", a); + return moved?.x ?? 0; + }, + { timeout: SAVED_MS }, + ) + .toBeGreaterThan(pointerTravel + 40); + }); + + test("Escape cancels a drag", async ({ page, baseURL }) => { + const [a = ""] = await makeBoard(baseURL, "cancel", { count: 1 }); + await open(page, "cancel"); + const start = await centre(page, a); + await page.mouse.move(start.x, start.y); + await page.mouse.down(); + await page.mouse.move(start.x + 120, start.y + 80, { steps: 5 }); + await page.keyboard.press("Escape"); + await page.mouse.up(); + await page.waitForTimeout(800); + const box = await frame(page, a).boundingBox(); + expect(box?.x).toBeCloseTo(start.box.x, 0); + expect(await serverFrame(baseURL, "cancel", a)).toMatchObject({ + x: 0, + y: 0, + }); + }); + + test("the arranged canvas has no axe violations", async ({ + page, + baseURL, + }) => { + const { default: AxeBuilder } = await import("@axe-core/playwright"); + await makeBoard(baseURL, "axe"); + await open(page, "axe"); + await page.getByRole("button", { name: /^Frame 1,/u }).click(); + await page.keyboard.press("ArrowRight"); + await expect(page.locator("[data-handle]")).toHaveCount(8); + const results = await new AxeBuilder({ page }) + .exclude("iframe") + .withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"]) + .analyze(); + expect( + results.violations.map( + (violation) => + `${violation.id}: ${violation.nodes.map((node) => node.target.join(" ")).join(", ")}`, + ), + ).toEqual([]); + }); +}); diff --git a/packages/artifacts/src/client/canvas/arrange/autopan.ts b/packages/artifacts/src/client/canvas/arrange/autopan.ts new file mode 100644 index 0000000000..229a0d5976 --- /dev/null +++ b/packages/artifacts/src/client/canvas/arrange/autopan.ts @@ -0,0 +1,71 @@ +import { panBy } from "#client/canvas/camera.ts"; +import type { CameraController } from "#client/canvas/controller.ts"; +import type { Point } from "#client/lib/geometry.ts"; + +/** The camera pans when a dragged pointer is this close to the viewport's edge. */ +export const EDGE_PX = 48; +/** The most it pans per frame, in screen pixels. */ +export const MAX_PAN_PX = 18; + +/** Pan per frame along one axis for a pointer `value` px from the start of a `length` px axis. */ +function axisVelocity(value: number, length: number): number { + if (value < EDGE_PX) + return Math.min(1, (EDGE_PX - value) / EDGE_PX) * MAX_PAN_PX; + return value > length - EDGE_PX + ? -Math.min(1, (value - (length - EDGE_PX)) / EDGE_PX) * MAX_PAN_PX + : 0; +} + +/** How far, and which way, the camera pans for a pointer at `point` in a viewport of `size`. */ +export function edgeVelocity( + point: Point, + size: { readonly width: number; readonly height: number }, +): Point { + return { + x: axisVelocity(point.x, size.width), + y: axisVelocity(point.y, size.height), + }; +} + +export type AutoPan = { + /** Tells it where the pointer is (viewport-relative); null stops it. */ + readonly update: (point: Point | null) => void; + readonly stop: () => void; +}; + +/** + * Pans the camera while a drag is held near an edge, once per animation frame, + * and calls `onTick` after each pan so the drag can recompute from the new camera. + */ +export function createAutoPan( + controller: CameraController, + size: () => { readonly width: number; readonly height: number }, + onTick: () => void, +): AutoPan { + let point: Point | null = null; + let handle: number | null = null; + + function tick(): void { + handle = null; + if (point === null) return; + const velocity = edgeVelocity(point, size()); + if (velocity.x !== 0 || velocity.y !== 0) { + controller.moveTo(panBy(controller.get(), velocity.x, velocity.y), "pan"); + onTick(); + } + handle = requestAnimationFrame(tick); + } + + return { + update(next) { + point = next; + if (next !== null && handle === null) + handle = requestAnimationFrame(tick); + }, + stop() { + point = null; + if (handle !== null) cancelAnimationFrame(handle); + handle = null; + }, + }; +} diff --git a/packages/artifacts/src/client/canvas/arrange/geometry.test.ts b/packages/artifacts/src/client/canvas/arrange/geometry.test.ts new file mode 100644 index 0000000000..5883082870 --- /dev/null +++ b/packages/artifacts/src/client/canvas/arrange/geometry.test.ts @@ -0,0 +1,220 @@ +import { describe, expect, test } from "vitest"; +import { + clickSelection, + framesInMarquee, + marqueeSelection, + MIN_HEIGHT, + MIN_WIDTH, + rectBetween, + resizeRect, + snap, + snapDelta, + stepOrder, +} from "./geometry.ts"; + +const start = { x: 100, y: 100, w: 400, h: 300 }; + +describe("snapping", () => { + test("rounds to the 8 px grid", () => { + expect(snap(0)).toBe(0); + expect(snap(3)).toBe(0); + expect(snap(4)).toBe(8); + expect(snap(-5)).toBe(-8); + expect(snap(13)).toBe(16); + }); + + test("the lead frame lands on the grid and the others keep their offsets", () => { + const lead = { x: 101, y: 203, w: 100, h: 100 }; + const delta = snapDelta(lead, { x: 22, y: -9 }, true); + expect(lead.x + delta.x).toBe(120); + expect(lead.y + delta.y).toBe(192); + // Another frame 7 px right of the lead stays 7 px right of it. + expect(108 + delta.x - (lead.x + delta.x)).toBe(7); + }); + + test("Alt moves freely", () => { + expect(snapDelta(start, { x: 3, y: 5 }, false)).toEqual({ x: 3, y: 5 }); + }); +}); + +describe("marquee", () => { + const frames = [ + { id: "a", rect: { x: 0, y: 0, w: 100, h: 100 } }, + { id: "b", rect: { x: 200, y: 0, w: 100, h: 100 } }, + { id: "c", rect: { x: 0, y: 300, w: 100, h: 100 } }, + ]; + + test("builds the rectangle whichever way the drag went", () => { + expect(rectBetween({ x: 50, y: 80 }, { x: 10, y: 20 })).toEqual({ + x: 10, + y: 20, + w: 40, + h: 60, + }); + }); + + test("hits every frame it touches, even by a corner", () => { + expect(framesInMarquee(frames, { x: 90, y: 90, w: 120, h: 5 })).toEqual([ + "a", + "b", + ]); + expect(framesInMarquee(frames, { x: 500, y: 500, w: 5, h: 5 })).toEqual([]); + }); + + test("a frame it only borders is not hit", () => { + expect(framesInMarquee(frames, { x: 100, y: 0, w: 50, h: 50 })).toEqual([]); + }); + + test("Shift adds to the selection, otherwise the marquee replaces it", () => { + expect([...marqueeSelection(new Set(["c"]), ["a"], true)]).toEqual([ + "c", + "a", + ]); + expect([...marqueeSelection(new Set(["c"]), ["a"], false)]).toEqual(["a"]); + }); + + test("click selects one, Shift-click toggles", () => { + expect([...clickSelection(new Set(["a"]), "b", false)]).toEqual(["b"]); + expect([...clickSelection(new Set(["a"]), "b", true)]).toEqual(["a", "b"]); + expect([...clickSelection(new Set(["a", "b"]), "b", true)]).toEqual(["a"]); + }); +}); + +describe("resizing", () => { + const free = { aspect: null, snap: false } as const; + + test("the east handle moves only the right edge", () => { + expect(resizeRect(start, "e", { x: 50, y: 99 }, free)).toEqual({ + x: 100, + y: 100, + w: 450, + h: 300, + }); + }); + + test("the north-west handle keeps the south-east corner fixed", () => { + const next = resizeRect(start, "nw", { x: 40, y: 30 }, free); + expect(next.x + next.w).toBe(500); + expect(next.y + next.h).toBe(400); + expect(next).toEqual({ x: 140, y: 130, w: 360, h: 270 }); + }); + + test("never shrinks below the minimum", () => { + const next = resizeRect(start, "se", { x: -1000, y: -1000 }, free); + expect(next.w).toBe(MIN_WIDTH); + expect(next.h).toBe(MIN_HEIGHT); + const west = resizeRect(start, "w", { x: 1000, y: 0 }, free); + expect(west.x + west.w).toBe(500); + expect(west.w).toBe(MIN_WIDTH); + }); + + test("a fixed-viewport frame keeps its aspect from a corner", () => { + const aspect = 1440 / 900; + const next = resizeRect( + { x: 0, y: 0, w: 320, h: 200 }, + "se", + { x: 160, y: 10 }, + { aspect, snap: false }, + ); + expect(next.w / next.h).toBeCloseTo(aspect, 10); + expect(next.w).toBeCloseTo(480, 10); + }); + + test("and from an edge, the other dimension follows", () => { + const aspect = 2; + const east = resizeRect( + { x: 0, y: 0, w: 200, h: 100 }, + "e", + { x: 100, y: 0 }, + { aspect, snap: false }, + ); + expect(east).toEqual({ x: 0, y: 0, w: 300, h: 150 }); + const north = resizeRect( + { x: 0, y: 0, w: 200, h: 100 }, + "n", + { x: 0, y: -50 }, + { aspect, snap: false }, + ); + expect(north.h).toBe(150); + expect(north.w).toBe(300); + // The south edge is the anchor. + expect(north.y + north.h).toBe(100); + }); + + test("with an aspect and the minimum the ratio still holds", () => { + const next = resizeRect( + { x: 0, y: 0, w: 320, h: 200 }, + "se", + { x: -900, y: -900 }, + { aspect: 1.6, snap: false }, + ); + expect(next.w / next.h).toBeCloseTo(1.6, 10); + expect(next.w).toBeGreaterThanOrEqual(MIN_WIDTH); + expect(next.h).toBeGreaterThanOrEqual(MIN_HEIGHT); + }); + + test("snaps the dragged edges to the grid", () => { + const next = resizeRect( + start, + "se", + { x: 13, y: 21 }, + { aspect: null, snap: true }, + ); + expect((next.x + next.w) % 8).toBe(0); + expect((next.y + next.h) % 8).toBe(0); + }); +}); + +describe("z-order", () => { + const order = ["a", "b", "c", "d"]; + + test("forward moves past the next unselected neighbour", () => { + expect(stepOrder(order, new Set(["b"]), "forward")).toEqual([ + "a", + "c", + "b", + "d", + ]); + expect(stepOrder(order, new Set(["d"]), "forward")).toEqual(order); + }); + + test("backward mirrors it", () => { + expect(stepOrder(order, new Set(["c"]), "backward")).toEqual([ + "a", + "c", + "b", + "d", + ]); + expect(stepOrder(order, new Set(["a"]), "backward")).toEqual(order); + }); + + test("a selection keeps its internal order and never swaps within itself", () => { + expect(stepOrder(order, new Set(["a", "b"]), "forward")).toEqual([ + "c", + "a", + "b", + "d", + ]); + expect(stepOrder(order, new Set(["c", "d"]), "backward")).toEqual([ + "a", + "c", + "d", + "b", + ]); + }); + + test("front and back go to the ends", () => { + expect(stepOrder(order, new Set(["b"]), "front")).toEqual([ + "a", + "c", + "d", + "b", + ]); + expect(stepOrder(order, new Set(["c", "b"]), "back")).toEqual([ + "b", + "c", + "a", + "d", + ]); + }); +}); diff --git a/packages/artifacts/src/client/canvas/arrange/geometry.ts b/packages/artifacts/src/client/canvas/arrange/geometry.ts new file mode 100644 index 0000000000..cb14f0713e --- /dev/null +++ b/packages/artifacts/src/client/canvas/arrange/geometry.ts @@ -0,0 +1,246 @@ +/** + * Pure geometry of arranging frames: grid snapping, marquee hit-testing, + * the eight resize handles and z-order steps. Nothing here knows about the DOM. + */ +import { clamp, type Point } from "#client/lib/geometry.ts"; +import { intersects, type WorldRect } from "#client/canvas/camera.ts"; + +/** Frames snap to this grid, in world pixels; Alt disables it. */ +export const GRID = 8; +/** No frame is resized below this. */ +export const MIN_WIDTH = 96; +export const MIN_HEIGHT = 64; +/** A step of the arrow keys, and of Shift+arrow. */ +export const NUDGE = 1; +export const NUDGE_FAST = 10; + +export function snap(value: number, grid = GRID): number { + return Math.round(value / grid) * grid; +} + +/** + * The delta that moves `lead` by `delta` and lands its corner on the grid. + * Every frame of a multi-selection takes the same delta, so they keep their + * relative positions. + */ +export function snapDelta( + lead: WorldRect, + delta: Point, + enabled: boolean, +): Point { + if (!enabled) return delta; + return { + x: snap(lead.x + delta.x) - lead.x, + y: snap(lead.y + delta.y) - lead.y, + }; +} + +export function moveRect(rect: WorldRect, delta: Point): WorldRect { + return { ...rect, x: rect.x + delta.x, y: rect.y + delta.y }; +} + +// ── Marquee ───────────────────────────────────────────────────────────────── + +/** The rectangle between two world points, whichever way the drag went. */ +export function rectBetween(a: Point, b: Point): WorldRect { + return { + x: Math.min(a.x, b.x), + y: Math.min(a.y, b.y), + w: Math.abs(a.x - b.x), + h: Math.abs(a.y - b.y), + }; +} + +/** The ids of the frames a marquee touches. */ +export function framesInMarquee( + frames: readonly { readonly id: string; readonly rect: WorldRect }[], + marquee: WorldRect, +): string[] { + return frames + .filter((frame) => intersects(frame.rect, marquee)) + .map((frame) => frame.id); +} + +/** Shift adds the marquee's frames to the selection; without it they replace it. */ +export function marqueeSelection( + base: ReadonlySet, + hits: readonly string[], + additive: boolean, +): Set { + return additive ? new Set([...base, ...hits]) : new Set(hits); +} + +/** A click with Shift toggles a frame; a plain click selects only it. */ +export function clickSelection( + current: ReadonlySet, + id: string, + additive: boolean, +): Set { + if (!additive) return new Set([id]); + const next = new Set(current); + if (next.has(id)) next.delete(id); + else next.add(id); + return next; +} + +// ── Resize ────────────────────────────────────────────────────────────────── + +export const HANDLES = ["nw", "n", "ne", "e", "se", "s", "sw", "w"] as const; +export type Handle = (typeof HANDLES)[number]; + +type Edges = { + readonly left: boolean; + readonly right: boolean; + readonly top: boolean; + readonly bottom: boolean; +}; + +function edgesOf(handle: Handle): Edges { + return { + left: handle.includes("w"), + right: handle.includes("e"), + top: handle.includes("n"), + bottom: handle.includes("s"), + }; +} + +type Size2 = { readonly width: number; readonly height: number }; + +/** `size` forced to `aspect` (when there is one), then lifted to the minimum while holding it. */ +function withAspect( + size: Size2, + context: { + readonly edges: Edges; + readonly start: WorldRect; + readonly aspect: number | null; + }, +): Size2 { + const { edges, start, aspect } = context; + if (aspect === null) return size; + const horizontal = edges.left || edges.right; + const vertical = edges.top || edges.bottom; + let { width, height } = size; + if (horizontal && vertical) { + // A corner: whichever dimension grew more (relative to the start) leads. + if (width / start.w >= height / start.h) height = width / aspect; + else width = height * aspect; + } else if (horizontal) height = width / aspect; + else width = height * aspect; + if (width < MIN_WIDTH) { + width = MIN_WIDTH; + height = width / aspect; + } + if (height < MIN_HEIGHT) { + height = MIN_HEIGHT; + width = height * aspect; + } + return { width, height }; +} + +export type ResizeOptions = { + /** Width over height to keep (a fixed-viewport frame), or null to resize freely. */ + readonly aspect: number | null; + readonly snap: boolean; +}; + +/** + * `start` resized by dragging `handle` by `delta`. The opposite edge or corner + * stays put. With an aspect the frame keeps it: a corner follows the larger + * of the two moves, an edge drives the other dimension from the frame's + * anchored side. + */ +export function resizeRect( + start: WorldRect, + handle: Handle, + delta: Point, + options: ResizeOptions, +): WorldRect { + const edges = edgesOf(handle); + const grid = (value: number): number => (options.snap ? snap(value) : value); + let left = start.x; + let top = start.y; + let right = start.x + start.w; + let bottom = start.y + start.h; + if (edges.left) left = grid(start.x + delta.x); + if (edges.right) right = grid(start.x + start.w + delta.x); + if (edges.top) top = grid(start.y + delta.y); + if (edges.bottom) bottom = grid(start.y + start.h + delta.y); + + const sized = withAspect( + { + width: Math.max(MIN_WIDTH, right - left), + height: Math.max(MIN_HEIGHT, bottom - top), + }, + { edges, start, aspect: options.aspect }, + ); + const { width, height } = sized; + + // The edge opposite the handle is the anchor; a pure vertical or horizontal + // handle keeps the frame's other axis anchored at its start. + const x = edges.left ? start.x + start.w - width : start.x; + const y = edges.top ? start.y + start.h - height : start.y; + return { x, y, w: width, h: height }; +} + +/** Where a handle sits on a rectangle, as fractions of its size. */ +export function handlePosition(handle: Handle): Point { + const edges = edgesOf(handle); + return { + x: edges.left ? 0 : edges.right ? 1 : 0.5, + y: edges.top ? 0 : edges.bottom ? 1 : 0.5, + }; +} + +export const HANDLE_CURSOR: Readonly> = { + nw: "nwse-resize", + se: "nwse-resize", + ne: "nesw-resize", + sw: "nesw-resize", + n: "ns-resize", + s: "ns-resize", + e: "ew-resize", + w: "ew-resize", +}; + +// ── Z-order ───────────────────────────────────────────────────────────────── + +export type OrderStep = "forward" | "backward" | "front" | "back"; + +/** + * `order` (back to front) after moving the selected entries: one step past the + * nearest unselected neighbour, or to an end. The selected keep their + * relative order. + */ +export function stepOrder( + order: readonly string[], + selected: ReadonlySet, + step: OrderStep, +): string[] { + const picked = order.filter((id) => selected.has(id)); + if (picked.length === 0) return [...order]; + const rest = order.filter((id) => !selected.has(id)); + if (step === "front") return [...rest, ...picked]; + if (step === "back") return [...picked, ...rest]; + const result = [...order]; + const indices = result.flatMap((id, at) => (selected.has(id) ? [at] : [])); + const ordered = step === "forward" ? [...indices].reverse() : indices; + for (const at of ordered) { + const to = at + (step === "forward" ? 1 : -1); + const neighbour = result[to]; + const current = result[at]; + if (neighbour === undefined || current === undefined) continue; + if (selected.has(neighbour)) continue; + result[to] = current; + result[at] = neighbour; + } + return result; +} + +/** A frame size within the limits, for a frame placed or restored with odd values. */ +export function clampSize(rect: WorldRect): WorldRect { + return { + ...rect, + w: clamp(rect.w, MIN_WIDTH, 100_000), + h: clamp(rect.h, MIN_HEIGHT, 100_000), + }; +} diff --git a/packages/artifacts/src/client/canvas/arrange/handles.tsx b/packages/artifacts/src/client/canvas/arrange/handles.tsx new file mode 100644 index 0000000000..356768c615 --- /dev/null +++ b/packages/artifacts/src/client/canvas/arrange/handles.tsx @@ -0,0 +1,126 @@ +import { useCallback, useRef } from "react"; +import type { Camera, WorldRect } from "#client/canvas/camera.ts"; +import type { CameraController } from "#client/canvas/controller.ts"; +import { useFollowCamera } from "#client/canvas/follow.ts"; +import type { PointerSession } from "#client/canvas/gestures.ts"; +import type { Point } from "#client/lib/geometry.ts"; +import { + HANDLE_CURSOR, + HANDLES, + handlePosition, + type Handle, +} from "./geometry.ts"; + +/** The point of a pointer event in the canvas viewport's own coordinates. */ +function inViewport(event: React.PointerEvent): Point { + const box = event.currentTarget + .closest(".ar-cv-viewport") + ?.getBoundingClientRect(); + return { + x: event.clientX - (box?.left ?? 0), + y: event.clientY - (box?.top ?? 0), + }; +} + +/** + * The eight resize handles of the selected frame, on the unscaled overlay. A + * handle captures its own pointer and runs the resize session the page gives + * it. They are a pointer affordance only; the keyboard moves frames with the + * arrow keys. + */ +export function ResizeHandles({ + controller, + rect, + start, +}: { + readonly controller: CameraController; + readonly rect: WorldRect; + readonly start: (handle: Handle, point: Point) => PointerSession | null; +}): React.JSX.Element { + const ref = useRef(null); + const session = useRef(null); + const place = useCallback( + (camera: Camera, element: HTMLElement) => { + element.style.width = `${String(rect.w * camera.s)}px`; + element.style.height = `${String(rect.h * camera.s)}px`; + element.style.transform = `translate(${String(camera.x + rect.x * camera.s)}px, ${String(camera.y + rect.y * camera.s)}px)`; + }, + [rect.x, rect.y, rect.w, rect.h], + ); + useFollowCamera(controller, ref, place); + + return ( + From f96887e9e694ca7cf6ec3c10879eedfb6a022ff4 Mon Sep 17 00:00:00 2001 From: Jerred Shepherd Date: Thu, 26 Nov 2026 12:12:51 -0800 Subject: [PATCH 4/5] feat(artifacts): restyle the canvas toolbar as a floating pill Why The toolbar should read like Claude's canvas toolbar: a white pill floating at the bottom centre with large icon buttons, the active tool soft-tinted. What - Tool pill (bottom centre): select (MousePointer2, V; the arrow is filled in the accent colour while active), hand (H), then comment (MessageCircle, C), in groups separated by thin dividers. A group with no tools is not drawn, so the annotation tools can add theirs. - Zoom out, percent, zoom in, fit all and fit selection move to a small second pill at the bottom right. - lucide-react icons at 20 px and 1.5 px stroke, tooltips with the shortcut, `aria-pressed` on tool buttons, 40 px buttons and 44 px on coarse pointers. - Tool state moves into `useToolModes`: select, hand and comment mode are exclusive, and `V` selects. Verification - bunx turbo run build typecheck test lint test:extended --filter=@shepherdjerred/artifacts - bun run test:e2e: desktop Chromium, mobile Chromium and WebKit (155 tests) plus a new pill spec (V, H, C flip the pressed tool; zoom is in its own pill). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_011u9pQkmfQzZFyzPbpimoiT --- packages/artifacts/e2e/canvas.desktop.spec.ts | 23 ++ .../artifacts/src/client/canvas/canvas.tsx | 69 +++--- .../artifacts/src/client/canvas/toolbar.tsx | 200 +++++++++++++----- .../src/client/canvas/use-canvas-keys.ts | 15 +- .../artifacts/src/client/canvas/use-tools.ts | 48 +++++ .../artifacts/src/client/shell/shortcuts.ts | 4 +- .../artifacts/src/client/styles/canvas.css | 69 ++++-- 7 files changed, 332 insertions(+), 96 deletions(-) create mode 100644 packages/artifacts/src/client/canvas/use-tools.ts diff --git a/packages/artifacts/e2e/canvas.desktop.spec.ts b/packages/artifacts/e2e/canvas.desktop.spec.ts index abcfcea3f0..fad591c75e 100644 --- a/packages/artifacts/e2e/canvas.desktop.spec.ts +++ b/packages/artifacts/e2e/canvas.desktop.spec.ts @@ -119,6 +119,29 @@ test.describe("canvas", () => { expect(dragged.x - moved.x).toBeCloseTo(-50, 0); }); + test("the tool pill shows the active tool: V select, H hand, C comment", async ({ + page, + }) => { + await openBoard(page, "concepts"); + const select = page.getByRole("button", { name: "Select tool" }); + const hand = page.getByRole("button", { name: "Hand tool" }); + const comment = page.getByRole("button", { name: "Comment mode" }); + await expect(select).toHaveAttribute("aria-pressed", "true"); + await page.keyboard.press("h"); + await expect(hand).toHaveAttribute("aria-pressed", "true"); + await expect(select).toHaveAttribute("aria-pressed", "false"); + await page.keyboard.press("c"); + await expect(comment).toHaveAttribute("aria-pressed", "true"); + await expect(hand).toHaveAttribute("aria-pressed", "false"); + await page.keyboard.press("v"); + await expect(select).toHaveAttribute("aria-pressed", "true"); + await expect(comment).toHaveAttribute("aria-pressed", "false"); + // Zoom and fit live in their own pill. + await expect( + page.getByRole("toolbar", { name: "Zoom" }).getByTestId("zoom-readout"), + ).toBeVisible(); + }); + test("1 fits all, 2 fits the selection, 0 is 100 %", async ({ page }) => { await openBoard(page, "concepts"); await page.keyboard.press("0"); diff --git a/packages/artifacts/src/client/canvas/canvas.tsx b/packages/artifacts/src/client/canvas/canvas.tsx index e24712c9a2..a4733e9ad9 100644 --- a/packages/artifacts/src/client/canvas/canvas.tsx +++ b/packages/artifacts/src/client/canvas/canvas.tsx @@ -16,15 +16,16 @@ import { useArrangeKeys } from "./arrange/use-keys.ts"; import { useArrangeSessions } from "./arrange/use-sessions.ts"; import { screenToWorld, type WorldRect } from "./camera.ts"; import { CanvasFrame } from "./canvas-frame.tsx"; -import type { Tap, Tool } from "./gestures.ts"; +import type { Tap } from "./gestures.ts"; import { readingOrder, type CanvasPin } from "./model.ts"; import { ExitChip, FrameChip, SelectionRing } from "./overlay.tsx"; import { PinsLayer } from "./pins-layer.tsx"; -import { CanvasToolbar } from "./toolbar.tsx"; +import { commentTool, pointerTools, ToolPill, ZoomPill } from "./toolbar.tsx"; import { useCanvasCamera } from "./use-camera.ts"; import { useCanvasKeys } from "./use-canvas-keys.ts"; import { useCanvasInput } from "./use-input.ts"; import { useFrameTiers } from "./use-tiers.ts"; +import { useToolModes } from "./use-tools.ts"; /** Rounds a placed pin to a tenth of a pixel so the stored anchor is tidy. */ function tidy(value: number): number { @@ -73,9 +74,22 @@ export function Canvas({ const only = selectedFrames.length === 1 ? selectedFrames[0] : undefined; const [activeId, setActiveId] = useState(null); - const [tool, setTool] = useState("select"); - const [commentMode, setCommentMode] = useState(false); const [placement, setPlacement] = useState(null); + const dropPlacement = useCallback(() => { + setPlacement(null); + }, []); + const dropLive = useCallback(() => { + setActiveId(null); + }, []); + const { + tool, + commentMode, + selectTool, + handTool, + toggleHand, + toggleComment, + leaveComment, + } = useToolModes({ placement: dropPlacement, live: dropLive }); const [marquee, setMarquee] = useState(null); const [confirmRemove, setConfirmRemove] = useState(false); const [tick, setTick] = useState(0); @@ -93,6 +107,8 @@ export function Canvas({ activeId, }); + const leaveCommentRef = useRef(leaveComment); + leaveCommentRef.current = leaveComment; const latest = useRef({ commentMode, activeId, byId }); latest.current = { commentMode, activeId, byId }; @@ -102,7 +118,7 @@ export function Canvas({ if (frame === undefined || frame.summary.kind === "file") return; setSelection(new Set([id])); setActiveId(id); - setCommentMode(false); + leaveCommentRef.current(); setPlacement(null); reveal(frame.rect); // The same iframe element gains focus; nothing remounts. @@ -211,7 +227,7 @@ export function Canvas({ { onSuccess: (thread) => { setPlacement(null); - setCommentMode(false); + leaveComment(); onSelectThread(thread.id); }, }, @@ -250,6 +266,13 @@ export function Canvas({ if (activeId === null && selection.size > 0) setConfirmRemove(true); }, }); + const toolGroups = pointerTools({ + tool, + commenting: commentMode, + onSelect: selectTool, + onHand: handTool, + }); + useCanvasKeys({ camera, onlyId: only?.id ?? null, @@ -257,20 +280,15 @@ export function Canvas({ activeId, commentMode, tool, - setTool, - toggleComment: () => { - setCommentMode((on) => !on); - setActiveId(null); - setPlacement(null); - }, + selectTool, + toggleHand, + toggleComment, activate, cancelPlacement: () => { setPlacement(null); }, deactivate, - leaveComment: () => { - setCommentMode(false); - }, + leaveComment, clearSelection: () => { setSelection(new Set()); }, @@ -356,21 +374,24 @@ export function Canvas({ selectedId={selectedThreadId} onSelect={onSelectThread} /> - + 0} onZoom={camera.zoomBy} onReset={camera.reset} onFitAll={camera.fitAll} onFitSelection={camera.fitSelection} - onTool={setTool} - onComment={(on) => { - setCommentMode(on); - setPlacement(null); - if (on) setActiveId(null); - }} />
void; + readonly testId?: string; + /** Filled in the accent colour while active (the select arrow). */ + readonly filledWhenActive?: boolean; +}; + +function ToolButtonView({ tool }: { readonly tool: ToolButton }) { + const { Icon } = tool; + return ( + + ); +} + +/** + * The tool pill at the bottom centre: pointer tools, then the drawing tools of + * `drawing` (annotations), then comment. A group with no tools is not drawn. + */ +export function ToolPill({ + groups, +}: { + readonly groups: readonly (readonly ToolButton[])[]; +}): React.JSX.Element { + const shown = groups.filter((group) => group.length > 0); + return ( +
+ {shown.map((group, at) => ( +
+ {at === 0 ? null :
+ ))} +
+ ); +} + +/** Zoom and fit, in their own small pill at the bottom right. */ +export function ZoomPill({ controller, - tool, - commenting, hasSelection, onZoom, onReset, onFitAll, onFitSelection, - onTool, - onComment, }: { readonly controller: CameraController; - readonly tool: Tool; - readonly commenting: boolean; readonly hasSelection: boolean; readonly onZoom: (factor: number) => void; readonly onReset: () => void; readonly onFitAll: () => void; readonly onFitSelection: () => void; - readonly onTool: (tool: Tool) => void; - readonly onComment: (on: boolean) => void; }): React.JSX.Element { return (
); } + +/** The tools every board has: select, hand, comment. */ +export function pointerTools(state: { + readonly tool: Tool; + readonly commenting: boolean; + readonly onSelect: () => void; + readonly onHand: () => void; +}): { readonly pointer: readonly ToolButton[] } { + return { + pointer: [ + { + id: "select", + label: "Select tool", + shortcut: "V", + Icon: MousePointer2Icon, + active: state.tool === "select" && !state.commenting, + onPress: state.onSelect, + filledWhenActive: true, + testId: "tool-select", + }, + { + id: "hand", + label: "Hand tool", + shortcut: "H", + Icon: HandIcon, + active: state.tool === "hand" && !state.commenting, + onPress: state.onHand, + testId: "tool-hand", + }, + ], + }; +} + +export function commentTool(state: { + readonly commenting: boolean; + readonly onToggle: () => void; +}): ToolButton { + return { + id: "comment", + label: "Comment mode", + shortcut: "C", + Icon: MessageCircleIcon, + active: state.commenting, + onPress: state.onToggle, + testId: "comment-mode", + }; +} diff --git a/packages/artifacts/src/client/canvas/use-canvas-keys.ts b/packages/artifacts/src/client/canvas/use-canvas-keys.ts index e0ecaa69fc..353c59cd4f 100644 --- a/packages/artifacts/src/client/canvas/use-canvas-keys.ts +++ b/packages/artifacts/src/client/canvas/use-canvas-keys.ts @@ -12,7 +12,8 @@ type Keys = { readonly activeId: string | null; readonly commentMode: boolean; readonly tool: Tool; - readonly setTool: (update: (current: Tool) => Tool) => void; + readonly selectTool: () => void; + readonly toggleHand: () => void; readonly toggleComment: () => void; readonly activate: (id: string) => void; readonly cancelPlacement: () => void; @@ -21,7 +22,7 @@ type Keys = { readonly clearSelection: () => void; }; -/** The canvas's own keys: 1 2 0 + - fit and zoom, H hand, C comment, F focus, Enter live, Esc back out. */ +/** The canvas's own keys: 1 2 0 + - fit and zoom, V select, H hand, C comment, F focus, Enter live, Esc back out. */ export function useCanvasKeys(keys: Keys): void { const navigate = useNavigate(); const { camera } = keys; @@ -47,12 +48,8 @@ export function useCanvasKeys(keys: Keys): void { camera.zoomBy(1 / ZOOM_STEP); }, }, - { - key: "h", - run: () => { - keys.setTool((current) => (current === "hand" ? "select" : "hand")); - }, - }, + { key: "v", run: keys.selectTool }, + { key: "h", run: keys.toggleHand }, { key: "c", run: keys.toggleComment }, { key: "f", @@ -74,7 +71,7 @@ export function useCanvasKeys(keys: Keys): void { if (keys.placing) keys.cancelPlacement(); else if (keys.activeId !== null) keys.deactivate(); else if (keys.commentMode) keys.leaveComment(); - else if (keys.tool === "hand") keys.setTool(() => "select"); + else if (keys.tool === "hand") keys.selectTool(); else keys.clearSelection(); }, }, diff --git a/packages/artifacts/src/client/canvas/use-tools.ts b/packages/artifacts/src/client/canvas/use-tools.ts new file mode 100644 index 0000000000..b31b518acb --- /dev/null +++ b/packages/artifacts/src/client/canvas/use-tools.ts @@ -0,0 +1,48 @@ +import { useCallback, useState } from "react"; +import type { Tool } from "./gestures.ts"; + +/** + * Which tool is active: select, hand, or comment mode (which is exclusive with + * both). Entering a mode drops what belongs to the one before: a half-written + * comment, or the live frame. + */ +export function useToolModes(drop: { + readonly placement: () => void; + readonly live: () => void; +}) { + const [tool, setTool] = useState("select"); + const [commentMode, setCommentMode] = useState(false); + const { placement, live } = drop; + + const selectTool = useCallback(() => { + setTool("select"); + setCommentMode(false); + placement(); + }, [placement]); + const handTool = useCallback(() => { + setTool("hand"); + setCommentMode(false); + placement(); + }, [placement]); + const toggleComment = useCallback(() => { + setCommentMode((on) => !on); + live(); + placement(); + }, [live, placement]); + const toggleHand = useCallback(() => { + if (tool === "hand") selectTool(); + else handTool(); + }, [tool, selectTool, handTool]); + const leaveComment = useCallback(() => { + setCommentMode(false); + }, []); + return { + tool, + commentMode, + selectTool, + handTool, + toggleHand, + toggleComment, + leaveComment, + }; +} diff --git a/packages/artifacts/src/client/shell/shortcuts.ts b/packages/artifacts/src/client/shell/shortcuts.ts index a186b33e2b..4b042de8e6 100644 --- a/packages/artifacts/src/client/shell/shortcuts.ts +++ b/packages/artifacts/src/client/shell/shortcuts.ts @@ -93,8 +93,8 @@ export const SHORTCUT_SHEET: readonly { { keys: "1 / 2 / 0", does: "Canvas: fit all, fit the selection, 100 %" }, { keys: "+ / -", does: "Canvas: zoom in and out" }, { - keys: "H, Space", - does: "Canvas: hand tool, or hold Space and drag to pan", + keys: "V / H / Space", + does: "Canvas: select tool, hand tool, or hold Space and drag to pan", }, { keys: "Arrows", does: "Canvas: nudge the selection 1 px (Shift: 10 px)" }, { keys: "[ / ]", does: "Canvas: send the selection back or forward" }, diff --git a/packages/artifacts/src/client/styles/canvas.css b/packages/artifacts/src/client/styles/canvas.css index 716d274260..ccf5e9b051 100644 --- a/packages/artifacts/src/client/styles/canvas.css +++ b/packages/artifacts/src/client/styles/canvas.css @@ -180,31 +180,70 @@ pointer-events: none; } -.ar-cv-toolbar { +/* Tool pill: a white rounded pill at the bottom centre; zoom has its own at the right. */ +.ar-cv-toolbar, +.ar-cv-zoompill { position: absolute; - bottom: 12px; - left: 50%; + bottom: 14px; + z-index: 11; display: flex; align-items: center; gap: 2px; padding: 4px; border: 1px solid var(--ui-line); - border-radius: 10px; + border-radius: 14px; background: var(--ui-panel); - box-shadow: 0 2px 10px color-mix(in srgb, black 16%, transparent); - transform: translateX(-50%); + box-shadow: 0 2px 12px color-mix(in srgb, black 14%, transparent); pointer-events: auto; } -.ar-cv-toolbar .ar-icon-button[aria-pressed="true"] { - background: color-mix(in srgb, var(--ui-accent) 18%, transparent); +.ar-cv-toolbar { + left: 50%; + transform: translateX(-50%); +} +.ar-cv-zoompill { + right: 14px; +} +.ar-cv-group { + display: flex; + align-items: center; + gap: 2px; +} +.ar-cv-tool { + display: grid; + place-items: center; + width: 40px; + height: 40px; + padding: 0; + border: 0; + border-radius: 10px; + background: transparent; + color: var(--ui-ink); + cursor: pointer; +} +.ar-cv-tool:hover:not(:disabled) { + background: var(--ui-head); +} +.ar-cv-tool:disabled { + color: var(--ui-muted); + cursor: default; + opacity: 0.5; +} +.ar-cv-tool[aria-pressed="true"] { + background: color-mix(in srgb, var(--ui-accent) 16%, transparent); color: var(--ui-accent); } +@media (pointer: coarse) { + .ar-cv-tool { + width: 44px; + height: 44px; + } +} .ar-cv-zoom { min-width: 52px; - height: 28px; + height: 40px; padding: 0 6px; border: 0; - border-radius: 6px; + border-radius: 10px; background: transparent; color: var(--ui-ink); font-size: 12.5px; @@ -214,14 +253,20 @@ .ar-cv-zoom:hover { background: var(--ui-head); } +@media (pointer: coarse) { + .ar-cv-zoom { + min-height: 44px; + } +} .ar-cv-sep { width: 1px; - height: 18px; + height: 22px; margin: 0 4px; background: var(--ui-line); } +/* Above the tool pill. */ .ar-cv .ar-mode-hint { - bottom: 64px; + bottom: 74px; } @media (max-width: 900px) { From 031d6f1d41b2bb8adaf7ad82e196d4f67e979701 Mon Sep 17 00:00:00 2001 From: Jerred Shepherd Date: Thu, 26 Nov 2026 13:48:49 -0800 Subject: [PATCH 5/5] feat(artifacts): MessageCircle cursor and pins, floating comments panel and nav pill Why Comment mode should use the same glyph as the toolbar, the comments should not take a column from the canvas, and the shell bar plus page header waste ~90 px on the two views that need the space. What - Cursor and pins are lucide's `MessageCircle`, with the path read from its icon data (`lib/pin-shape.ts`, a test pins the path so a lucide update re-measures the tail tip). The cursor is the glyph with a white fill, an accent stroke and a white halo, installed as `--ar-comment-cursor` at startup, hotspot on the tail tip, `crosshair` fallback. Pins are the same silhouette at 28 px with the tail tip on the anchor: filled, hollow for another version, dashed for approximate. - Comments are a floating card on the right (a bottom sheet on a phone) that collapses to a pill with the icon, the open count and a waiting dot. Shift+C toggles it (letters with Shift are now a different key in `shortcuts.ts`), the choice is remembered per viewer, and a pin click, J/K or a new comment opens it on the thread. While open, fit-all, fit-selection and reveal aim at what it leaves; the viewer narrows. `aria-expanded`, `aria-controls`, focus moves in and back, nothing animates. - The canvas and the focused view are full-bleed. The shell bar and the page header are one floating pill at the top left (workspace switcher and Inbox, then the title and actions: List view, or board > artifact, the version select and Open raw, then keyboard and theme); a phone keeps the mark, the title and an overflow menu. Inbox and outline keep the shell bar. The focused view's comment-mode and viewport-width controls move to a bottom pill. - An open modal now owns Escape (the global Escape binding used to prevent the dialog from closing on the canvas and focused routes). Verification - bunx turbo run build typecheck test lint test:extended --filter=@shepherdjerred/artifacts - bun run test:e2e on desktop Chromium, mobile Chromium and WebKit, including a new shell spec (panel toggle by button and Shift+C with focus, pill count, persistence, pin click and new comment expand and scroll, fit-all clear of the panel, phone bottom sheet, no shell bar on canvas and focused routes, menus, axe) and updated specs (tail tip within 1.5 px, MessageCircle cursor). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_011u9pQkmfQzZFyzPbpimoiT --- packages/artifacts/README.md | 14 + .../artifacts/e2e/arrange.desktop.spec.ts | 2 +- packages/artifacts/e2e/canvas.desktop.spec.ts | 2 +- .../artifacts/e2e/comment.desktop.spec.ts | 7 +- .../artifacts/e2e/review-keyboard.spec.ts | 13 +- packages/artifacts/e2e/review-setup.ts | 31 +- packages/artifacts/e2e/review.spec.ts | 11 +- packages/artifacts/e2e/shell.spec.ts | 361 ++++++++++++++++++ packages/artifacts/src/client/app.tsx | 79 ++-- .../artifacts/src/client/canvas/canvas.tsx | 5 +- .../artifacts/src/client/canvas/use-camera.ts | 26 +- packages/artifacts/src/client/env.d.ts | 11 + .../src/client/lib/pin-shape.test.ts | 73 +++- .../artifacts/src/client/lib/pin-shape.ts | 73 +++- packages/artifacts/src/client/main.tsx | 4 + packages/artifacts/src/client/pages/board.tsx | 133 ++++--- .../src/client/pages/focused-header.tsx | 204 ++++++---- .../artifacts/src/client/pages/focused.tsx | 202 +++++----- .../artifacts/src/client/shell/app-nav.ts | 14 + .../src/client/shell/comments-panel.tsx | 98 +++++ .../src/client/shell/floating-nav.tsx | 98 +++++ .../artifacts/src/client/shell/panel-state.ts | 79 ++++ .../src/client/shell/shell-context.tsx | 13 + .../src/client/shell/shortcuts.test.ts | 19 + .../artifacts/src/client/shell/shortcuts.ts | 15 +- packages/artifacts/src/client/styles/base.css | 7 +- .../artifacts/src/client/styles/canvas.css | 9 +- .../artifacts/src/client/styles/pages.css | 21 +- .../artifacts/src/client/styles/shell.css | 188 +++++++++ .../artifacts/src/client/styles/viewers.css | 89 +---- .../src/client/viewers/pin-bubble.tsx | 17 +- 31 files changed, 1525 insertions(+), 393 deletions(-) create mode 100644 packages/artifacts/e2e/shell.spec.ts create mode 100644 packages/artifacts/src/client/shell/app-nav.ts create mode 100644 packages/artifacts/src/client/shell/comments-panel.tsx create mode 100644 packages/artifacts/src/client/shell/floating-nav.tsx create mode 100644 packages/artifacts/src/client/shell/panel-state.ts create mode 100644 packages/artifacts/src/client/shell/shell-context.tsx create mode 100644 packages/artifacts/src/client/styles/shell.css diff --git a/packages/artifacts/README.md b/packages/artifacts/README.md index 8ccbac36b7..ca3371a766 100644 --- a/packages/artifacts/README.md +++ b/packages/artifacts/README.md @@ -167,6 +167,20 @@ the typed placeholder card. Stacking is CSS `z-index` from the index `order`; an iframe is never moved or remounted, because that reloads it. The outline route stays the keyboard and screen-reader path. +**Shell.** The canvas and the focused view are full-bleed: the console-ui shell bar +and the page header are one floating pill at the top left (`shell/floating-nav.tsx`: +the workspace switcher and Inbox the bar had, then the page's title and actions; +a phone keeps the mark, the title and an overflow menu). The inbox and the outline +keep the normal bar. The comments are a floating card on the right +(`shell/comments-panel.tsx`; a bottom sheet on a phone) that collapses to a pill +with the `MessageCircle` icon, the open count and a dot while an agent waits. +Shift+C toggles it, the choice is remembered per viewer in `localStorage`, and a +pin click, J/K or a new comment opens it on the thread. While it is open the +canvas fits and reveals into what it leaves, and the viewer narrows (the +`--ar-inset-right` variable). The comment cursor and the pins are lucide's +`MessageCircle` glyph, read from its icon data (`lib/pin-shape.ts`), with the tail +tip as the hotspot and the anchor. + **Arranging** (`src/client/canvas/arrange/`). Click selects, Shift-click adds, a drag on empty canvas draws a marquee, a drag on a frame moves the selection (4 px threshold, pointer capture, edge auto-pan, 8 px grid, Alt for free diff --git a/packages/artifacts/e2e/arrange.desktop.spec.ts b/packages/artifacts/e2e/arrange.desktop.spec.ts index 217e5235a3..884f59ef8c 100644 --- a/packages/artifacts/e2e/arrange.desktop.spec.ts +++ b/packages/artifacts/e2e/arrange.desktop.spec.ts @@ -9,7 +9,7 @@ test.beforeAll(async ({ baseURL }) => { const SAVED_MS = 6000; /** The camera every spec opens at: 100 %, so a screen pixel is a world pixel. */ -const CAMERA = { x: 40, y: 80, s: 1 }; +const CAMERA = { x: 40, y: 140, s: 1 }; type Ids = readonly string[]; diff --git a/packages/artifacts/e2e/canvas.desktop.spec.ts b/packages/artifacts/e2e/canvas.desktop.spec.ts index fad591c75e..e1b0aa1b2d 100644 --- a/packages/artifacts/e2e/canvas.desktop.spec.ts +++ b/packages/artifacts/e2e/canvas.desktop.spec.ts @@ -207,7 +207,7 @@ test.describe("canvas", () => { await frame(page, seeded.concepts[0]?.artifactId ?? "").click(); await page .getByTestId("canvas-viewport") - .click({ position: { x: 20, y: 20 } }); + .click({ position: { x: 20, y: 140 } }); await page.waitForTimeout(500); expect(documents.length).toBe(loaded); }); diff --git a/packages/artifacts/e2e/comment.desktop.spec.ts b/packages/artifacts/e2e/comment.desktop.spec.ts index a611793b45..f17095416d 100644 --- a/packages/artifacts/e2e/comment.desktop.spec.ts +++ b/packages/artifacts/e2e/comment.desktop.spec.ts @@ -7,6 +7,7 @@ import { wheel, } from "./canvas-helpers.ts"; import { agentApi, openFocused, resetAndSeed } from "./review-setup.ts"; +import { PIN_TIP } from "#client/lib/pin-shape.ts"; import type { SeededBoards } from "./seed.ts"; let seeded: SeededBoards; @@ -40,8 +41,8 @@ test.describe("comments on the canvas", () => { const pinBox = await pin.boundingBox(); if (pinBox === null) throw new Error("no pin box"); // The speech bubble's tail tip (1 px in, on the bottom edge) is where the click was. - expect(Math.abs(pinBox.x + 1 - at.x)).toBeLessThan(1.5); - expect(Math.abs(pinBox.y + pinBox.height - at.y)).toBeLessThan(1.5); + expect(Math.abs(pinBox.x + PIN_TIP.x - at.x)).toBeLessThan(1.5); + expect(Math.abs(pinBox.y + PIN_TIP.y - at.y)).toBeLessThan(1.5); const claim = await agentApi(baseURL).feedback.claim.mutate({ scope: { type: "board", board: "demo" }, @@ -99,7 +100,7 @@ test.describe("comments on the canvas", () => { expect(second.x - first.x).toBeCloseTo(frameAfter.x - frameBefore.x, 0); }); - test("comment mode shows the speech-bubble cursor on the canvas and in the focused view", async ({ + test("comment mode shows the MessageCircle cursor on the canvas and in the focused view", async ({ page, }) => { const cursorOf = (selector: string) => diff --git a/packages/artifacts/e2e/review-keyboard.spec.ts b/packages/artifacts/e2e/review-keyboard.spec.ts index aad274abe4..a2a399b1cd 100644 --- a/packages/artifacts/e2e/review-keyboard.spec.ts +++ b/packages/artifacts/e2e/review-keyboard.spec.ts @@ -1,5 +1,5 @@ import { expect, test } from "@playwright/test"; -import { openFocused, resetAndSeed, tabTo } from "./review-setup.ts"; +import { openFocused, openPanel, resetAndSeed, tabTo } from "./review-setup.ts"; import type { SeededBoards } from "./seed.ts"; let seeded: SeededBoards; @@ -26,6 +26,7 @@ test.describe("keyboard", () => { }) => { const artifactId = seeded.demo.htmlV2.artifactId; await openFocused(page, artifactId); + await openPanel(page); for (const text of ["First note", "Second note"]) { await page.getByLabel("General comment").fill(text); await page @@ -65,9 +66,13 @@ test.describe("keyboard", () => { await page.keyboard.press("["); await expect(page).toHaveURL(/v=1/u); - await expect(page.getByRole("combobox", { name: "Version" })).toHaveValue( - "1", - ); + if ((page.viewportSize()?.width ?? 0) > 640) + await expect(page.getByRole("combobox", { name: "Version" })).toHaveValue( + "1", + ); + // The URL changes before the page re-renders with the version it names; the + // next key must reach the handler of the new render, so let it commit. + await page.waitForTimeout(250); await page.keyboard.press("]"); await expect(page).toHaveURL(/v=2/u); }); diff --git a/packages/artifacts/e2e/review-setup.ts b/packages/artifacts/e2e/review-setup.ts index 1795556cf5..de4437d6a9 100644 --- a/packages/artifacts/e2e/review-setup.ts +++ b/packages/artifacts/e2e/review-setup.ts @@ -76,6 +76,15 @@ export async function tabTo( throw new Error("Tab never reached the expected element"); } +/** Opens the comments panel when it is collapsed (a phone starts with it collapsed). */ +export async function openPanel(page: Page): Promise { + const toggle = page.getByTestId("panel-toggle"); + await expect(toggle).toBeVisible(); + if ((await toggle.getAttribute("aria-expanded")) === "false") + await toggle.click(); + await expect(page.getByRole("region", { name: "Comments" })).toBeVisible(); +} + export async function openFocused( page: Page, artifactId: string, @@ -84,9 +93,12 @@ export async function openFocused( await page.goto( `/a/${artifactId}${version === undefined ? "" : `?v=${String(version)}`}`, ); + // A phone's sheet starts collapsed and would cover the viewer; wide screens show the panel. await expect( - page.getByRole("complementary", { name: "Threads" }), + page.getByTestId("floating-nav").getByRole("heading", { level: 1 }), ).toBeVisible(); + const width = page.viewportSize()?.width ?? 0; + if (width > 900) await openPanel(page); } export async function commentWithMode(page: Page, text: string): Promise { @@ -105,3 +117,20 @@ export async function enterCommentMode(page: Page): Promise { "true", ); } + +/** Shows version `number` of the focused artifact: the pill's select, or the overflow menu on a phone. */ +export async function selectVersion(page: Page, number: number): Promise { + const width = page.viewportSize()?.width ?? 0; + if (width > 640) { + await page + .getByRole("combobox", { name: "Version" }) + .selectOption(String(number)); + return; + } + await page.getByRole("button", { name: "More" }).click(); + await page + .getByRole("menuitem", { + name: new RegExp(`^Version v${String(number)}`, "u"), + }) + .click(); +} diff --git a/packages/artifacts/e2e/review.spec.ts b/packages/artifacts/e2e/review.spec.ts index 7f5cd863f3..9c4dd65f56 100644 --- a/packages/artifacts/e2e/review.spec.ts +++ b/packages/artifacts/e2e/review.spec.ts @@ -8,6 +8,8 @@ import { drain, KARPATHY, openFocused, + openPanel, + selectVersion, resetAndSeed, sharedFixtures, } from "./review-setup.ts"; @@ -211,7 +213,7 @@ test.describe("html frames", () => { if (rect === null) throw new Error("frame has no box"); await page.mouse.click( rect.x + rect.width * 0.3, - rect.y + rect.height * 0.2, + rect.y + rect.height * 0.5, ); await commentWithMode(page, "Version one needs a logo"); await expect(page.getByTestId("pin")).toHaveCount(1); @@ -229,7 +231,7 @@ test.describe("html frames", () => { "false", ); - await page.getByRole("combobox", { name: "Version" }).selectOption("2"); + await selectVersion(page, 2); await expect(page).toHaveURL(/v=2/u); const thread = page .getByTestId("thread") @@ -368,6 +370,7 @@ test.describe("board", () => { test("board comments are listed in the sidebar", async ({ page }) => { await page.goto("/b/concepts"); + await openPanel(page); await page .getByLabel("Comment on the board") .fill("Overall direction B looks strongest"); @@ -383,6 +386,7 @@ test.describe("threads", () => { page, }) => { await openFocused(page, seeded.demo.png.artifactId); + await openPanel(page); await page.getByLabel("General comment").fill("Needs a caption"); await page .getByRole("button", { name: "Comment", exact: true }) @@ -424,8 +428,9 @@ test.describe("threads", () => { const api = agentApi(baseURL); const artifactId = seeded.demo.webm.artifactId; await openFocused(page, artifactId); + await openPanel(page); // The breadcrumb names the board by its title, not its slug. - await expect(page.locator(".ar-crumbs")).toHaveText("Demo board"); + await expect(page.locator(".ar-fnav-crumb")).toHaveText("Demo board"); await expect(page.getByTestId("waiting")).toHaveText(/No agent waiting/u); await page.getByLabel("General comment").fill("Audio is missing"); diff --git a/packages/artifacts/e2e/shell.spec.ts b/packages/artifacts/e2e/shell.spec.ts new file mode 100644 index 0000000000..86a5d8d1c8 --- /dev/null +++ b/packages/artifacts/e2e/shell.spec.ts @@ -0,0 +1,361 @@ +import { expect, test, type Page } from "@playwright/test"; +import { + agentApi, + openFocused, + resetAndSeed, + sharedFixtures, +} from "./review-setup.ts"; +import { publishFixture, type SeededBoards } from "./seed.ts"; + +let seeded: SeededBoards; + +test.beforeAll(async ({ baseURL }) => { + test.setTimeout(120_000); + seeded = await resetAndSeed(baseURL); +}); + +const KEY = "artifacts.panel.collapsed.v1"; + +async function setCollapsed( + page: Page, + viewer: "board" | "focused", + collapsed: boolean, +): Promise { + await page.addInitScript( + ([key, value]) => { + localStorage.setItem(String(key), String(value)); + }, + [`${KEY}:${viewer}`, String(collapsed)], + ); +} + +function toggle(page: Page) { + return page.getByTestId("panel-toggle"); +} + +test.describe("floating comments panel", () => { + test("opens by default on a wide screen, toggles by button and Shift+C, and moves focus", async ({ + page, + isMobile, + }) => { + test.skip(isMobile, "the phone layout is its own test"); + await page.goto("/b/concepts"); + const panel = page.getByTestId("comments-panel"); + await expect(panel).toBeVisible(); + await expect(toggle(page)).toHaveAttribute("aria-expanded", "true"); + await expect(toggle(page)).toHaveAttribute("aria-controls", /.+/u); + + // A floating card: not a layout column, inset from the top, right and bottom. + const box = await panel.boundingBox(); + const viewport = page.viewportSize(); + if (box === null || viewport === null) throw new Error("no boxes"); + expect(box.width).toBeCloseTo(360, 0); + expect(viewport.width - (box.x + box.width)).toBeCloseTo(12, 0); + expect(box.y).toBeCloseTo(12, 0); + expect(viewport.height - (box.y + box.height)).toBeCloseTo(12, 0); + // The canvas underneath still uses the full width. + const canvas = await page.getByTestId("canvas-viewport").boundingBox(); + expect(canvas?.width).toBe(viewport.width); + + await toggle(page).click(); + await expect(panel).toHaveCount(0); + await expect(toggle(page)).toHaveAttribute("aria-expanded", "false"); + await expect(toggle(page)).toBeFocused(); + + // Keyboard: expand moves focus into the panel, collapse back to the toggle. + await page.keyboard.press("Shift+C"); + await expect(page.getByTestId("comments-panel")).toBeFocused(); + await page.keyboard.press("Shift+C"); + await expect(toggle(page)).toBeFocused(); + // Shift+C is not comment mode. + await expect( + page.getByRole("button", { name: "Comment mode" }), + ).toHaveAttribute("aria-pressed", "false"); + }); + + test("the collapsed pill shows the open count and who is waiting", async ({ + page, + baseURL, + isMobile, + }) => { + test.skip(isMobile, "desktop layout"); + await agentApi(baseURL).threads.create.mutate({ + board: "concepts", + anchor: { type: "board", page: 0, x: 300, y: -60 }, + body: "Pill count", + }); + await setCollapsed(page, "board", true); + await page.goto("/b/concepts"); + const pill = toggle(page); + await expect(pill).toContainText("1"); + await expect(pill).toHaveAttribute("aria-expanded", "false"); + await expect(pill.locator("svg")).toBeVisible(); + await expect(pill).toContainText(/Show comments, 1 open/u); + }); + + test("the choice persists across a reload, per viewer", async ({ + page, + isMobile, + }) => { + test.skip(isMobile, "desktop layout"); + await page.goto("/b/concepts"); + await toggle(page).click(); + await page.reload(); + await expect(toggle(page)).toHaveAttribute("aria-expanded", "false"); + // The focused view remembers its own. + await openFocused(page, seeded.demo.png.artifactId); + await expect(toggle(page)).toHaveAttribute("aria-expanded", "true"); + await toggle(page).click(); + await page.goto("/b/concepts"); + await expect(toggle(page)).toHaveAttribute("aria-expanded", "false"); + }); + + test("clicking a pin, or placing a comment, expands the panel on the thread", async ({ + page, + baseURL, + isMobile, + }) => { + test.skip(isMobile, "desktop layout"); + const api = agentApi(baseURL); + await api.boards.create.mutate({ slug: "pinboard", title: "Pin board" }); + const fixtures = await sharedFixtures(); + const published = await publishFixture(String(baseURL), { + board: "pinboard", + title: "Only frame", + files: fixtures.htmlV1.files, + entryPath: fixtures.htmlV1.entryPath, + }); + const frameId = published.artifactId; + await api.threads.create.mutate({ + board: "pinboard", + artifactId: frameId, + anchor: { type: "frame", x: 0.5, y: 0.5 }, + body: "Pin on frame A", + }); + await setCollapsed(page, "board", true); + await page.goto("/b/pinboard"); + await expect(page.getByTestId("pin")).toHaveCount(1); + await page.getByTestId("pin").click(); + const panel = page.getByTestId("comments-panel"); + await expect(panel).toBeVisible(); + const thread = page + .getByTestId("thread") + .filter({ hasText: "Pin on frame A" }); + await expect(thread).toBeInViewport(); + await expect(thread).toHaveAttribute("data-selected", "true"); + + // Collapse, then place a new board comment: it opens on the new thread. + await toggle(page).click(); + await expect(panel).toHaveCount(0); + await page.keyboard.press("c"); + const view = await page.getByTestId("canvas-viewport").boundingBox(); + if (view === null) throw new Error("no canvas"); + await page.mouse.click(view.x + 60, view.y + view.height - 120); + const composer = page.getByTestId("placement-composer"); + await composer.getByRole("textbox").fill("A fresh one"); + await composer.getByRole("button", { name: "Comment" }).click(); + await expect(page.getByTestId("comments-panel")).toBeVisible(); + await expect( + page.getByTestId("thread").filter({ hasText: "A fresh one" }), + ).toBeInViewport(); + }); + + test("fit-all with the panel open keeps every frame clear of it", async ({ + page, + baseURL, + isMobile, + }) => { + test.skip(isMobile, "desktop layout"); + const api = agentApi(baseURL); + await api.boards.create.mutate({ slug: "wide", title: "Wide" }); + const fixtures = await sharedFixtures(); + for (let at = 0; at < 6; at += 1) + await publishFixture(String(baseURL), { + board: "wide", + title: `Wide ${String(at + 1)}`, + files: fixtures.htmlV1.files, + entryPath: fixtures.htmlV1.entryPath, + }); + await page.goto("/b/wide"); + await page.waitForTimeout(600); + await page.keyboard.press("1"); + await page.waitForTimeout(500); + const panel = await page.getByTestId("comments-panel").boundingBox(); + if (panel === null) throw new Error("no panel"); + const frames = await page.getByTestId("canvas-frame").all(); + expect(frames).toHaveLength(6); + for (const frame of frames) { + const box = await frame.boundingBox(); + if (box === null) throw new Error("no frame box"); + expect(box.x + box.width).toBeLessThanOrEqual(panel.x); + } + }); + + test("on a phone the panel is a bottom sheet and its pill sits above the tools", async ({ + page, + isMobile, + }) => { + test.skip(!isMobile, "phone layout"); + await page.goto("/b/concepts"); + // Collapsed to start with, as a pill above the toolbar. + await expect(page.getByTestId("comments-panel")).toHaveCount(0); + const pill = await toggle(page).boundingBox(); + const tools = await page + .getByRole("toolbar", { name: "Canvas tools" }) + .boundingBox(); + if (pill === null || tools === null) throw new Error("no boxes"); + expect(pill.y + pill.height).toBeLessThanOrEqual(tools.y); + await toggle(page).click(); + const sheet = await page.getByTestId("comments-panel").boundingBox(); + const viewport = page.viewportSize(); + if (sheet === null || viewport === null) throw new Error("no sheet"); + expect(sheet.width).toBeGreaterThan(viewport.width - 24); + expect(sheet.y + sheet.height).toBeGreaterThan(viewport.height - 16); + expect(sheet.y).toBeGreaterThan(viewport.height * 0.3); + }); +}); + +test.describe("floating nav", () => { + test("the canvas and the focused view have no shell bar, the inbox and outline keep it", async ({ + page, + }) => { + await page.goto("/b/concepts"); + await expect(page.getByTestId("floating-nav")).toBeVisible(); + await expect(page.locator("header.ar-top")).toHaveCount(0); + await openFocused(page, seeded.demo.png.artifactId); + await expect(page.getByTestId("floating-nav")).toBeVisible(); + await expect(page.locator("header.ar-top")).toHaveCount(0); + await page.goto("/"); + await expect(page.locator("header.ar-top")).toHaveCount(1); + await page.goto("/b/concepts/outline"); + await expect(page.locator("header.ar-top")).toHaveCount(1); + }); + + test("the canvas is full-bleed: the viewer starts at the top of the page", async ({ + page, + }) => { + await page.goto("/b/concepts"); + const canvas = await page.getByTestId("canvas-viewport").boundingBox(); + expect(canvas?.y).toBe(0); + await openFocused(page, seeded.demo.png.artifactId); + const pane = await page + .getByRole("region", { name: "Artifact" }) + .boundingBox(); + expect(pane?.y).toBe(0); + }); + + test("the nav pill keeps the workspace switcher and Inbox, and the heading is the board title", async ({ + page, + isMobile, + }) => { + await page.goto("/b/concepts"); + const nav = page.getByTestId("floating-nav"); + await expect( + page.getByRole("heading", { name: "Concepts", level: 1 }), + ).toBeVisible(); + await expect( + nav.getByRole("button", { name: /switch app/u }), + ).toBeVisible(); + if (isMobile) { + // The phone keeps the mark, the title and an overflow button. + await expect(nav.getByRole("link", { name: "Inbox" })).toBeHidden(); + await nav.getByRole("button", { name: "More" }).click(); + const menu = page.getByRole("menu"); + await expect(menu).toBeVisible(); + await expect( + menu.getByRole("menuitem", { name: "List view" }), + ).toBeVisible(); + await page.keyboard.press("Escape"); + await expect(menu).toBeHidden(); + await expect(nav.getByRole("button", { name: "More" })).toBeFocused(); + await nav.getByRole("button", { name: "More" }).click(); + await page.getByRole("menuitem", { name: "Inbox" }).click(); + await expect(page).toHaveURL(/\/$/u); + } else { + await nav.getByRole("link", { name: "List view" }).click(); + await expect(page).toHaveURL(/\/b\/concepts\/outline/u); + await page.goBack(); + await nav.getByRole("link", { name: "Inbox" }).click(); + await expect(page).toHaveURL(/\/$/u); + } + }); + + test("the focused nav shows board › artifact, the version, and Open raw", async ({ + page, + isMobile, + }) => { + test.skip(isMobile, "desktop layout"); + await openFocused(page, seeded.demo.htmlV2.artifactId); + const nav = page.getByTestId("floating-nav"); + await expect(page.getByRole("heading", { level: 1 })).toContainText( + "Concept A", + ); + await expect(nav.getByRole("link", { name: "Demo board" })).toBeVisible(); + await expect(nav.getByLabel("Version")).toBeVisible(); + await expect(nav.getByRole("link", { name: "Open raw" })).toHaveAttribute( + "target", + "_blank", + ); + await nav.getByLabel("Version").selectOption({ label: "v1" }); + await expect(page).toHaveURL(/v=1/u); + }); + + test("the app switcher menu opens with the console links and closes with Escape", async ({ + page, + isMobile, + }) => { + test.skip(isMobile, "desktop layout"); + await page.goto("/b/concepts"); + const nav = page.getByTestId("floating-nav"); + const switcher = nav.getByRole("button", { name: /switch app/u }); + await switcher.click(); + await expect(page.getByRole("menu")).toBeVisible(); + await page.keyboard.press("Escape"); + await expect(page.getByRole("menu")).toBeHidden(); + await expect(switcher).toBeFocused(); + }); + + test("the keyboard-shortcuts button opens the sheet, which lists Shift+C", async ({ + page, + isMobile, + }) => { + test.skip(isMobile, "desktop layout"); + await page.goto("/b/concepts"); + await page + .getByTestId("floating-nav") + .getByRole("button", { name: "Keyboard shortcuts" }) + .click(); + await expect(page.getByRole("dialog")).toContainText("Shift+C"); + await page.keyboard.press("Escape"); + await expect(page.getByRole("dialog")).toBeHidden(); + }); + + test("the floating shell has no axe violations, expanded and collapsed", async ({ + page, + isMobile, + }) => { + const { default: AxeBuilder } = await import("@axe-core/playwright"); + const check = async () => { + const results = await new AxeBuilder({ page }) + .exclude("iframe") + .withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"]) + .analyze(); + expect( + results.violations.map( + (violation) => + `${violation.id}: ${violation.nodes.map((node) => node.target.join(" ")).join(", ")}`, + ), + ).toEqual([]); + }; + await page.goto("/b/concepts"); + await page.waitForTimeout(800); + await check(); + if (!isMobile) { + await toggle(page).click(); + await check(); + } + await openFocused(page, seeded.demo.htmlV2.artifactId); + await page.waitForTimeout(800); + await check(); + }); +}); diff --git a/packages/artifacts/src/client/app.tsx b/packages/artifacts/src/client/app.tsx index 447f9dcba0..d5d294c23f 100644 --- a/packages/artifacts/src/client/app.tsx +++ b/packages/artifacts/src/client/app.tsx @@ -1,30 +1,17 @@ -import { - AppSwitcher, - ThemeToggle, - type AppSwitcherEntry, -} from "@shepherdjerred/console-ui"; -import { CONSOLE_LINKS } from "@shepherdjerred/ops-model/tool-links.ts"; +import { AppSwitcher, ThemeToggle } from "@shepherdjerred/console-ui"; import { KeyboardIcon } from "lucide-react"; -import { useState } from "react"; +import { useMemo, useState } from "react"; import { Link, Route, Routes, useMatch } from "react-router"; import { BoardPage } from "./pages/board.tsx"; import { FocusedPage } from "./pages/focused.tsx"; import { InboxPage } from "./pages/inbox.tsx"; import { OutlinePage } from "./pages/outline.tsx"; +import { CURRENT_APP, SWITCHER_APPS } from "./shell/app-nav.ts"; +import { ShellContext } from "./shell/shell-context.tsx"; import { ShortcutSheet } from "./shell/shortcut-sheet.tsx"; import { useShortcuts } from "./shell/shortcuts.ts"; import { themeStore } from "./shell/theme.ts"; -const CURRENT_APP = { label: "Artifacts", mark: "A" } as const; -const SWITCHER_APPS: readonly AppSwitcherEntry[] = [ - { label: "Artifacts", url: "/", group: "Apps" }, - ...CONSOLE_LINKS.filter((link) => link.label !== "Artifacts").map((link) => ({ - label: link.label, - url: link.url, - group: link.group, - })), -]; - function NotFound(): React.JSX.Element { return (
@@ -40,6 +27,18 @@ function NotFound(): React.JSX.Element { export function App(): React.JSX.Element { const [sheet, setSheet] = useState(false); const board = useMatch("/b/:slug"); + const focused = useMatch("/a/:artifactId"); + // The canvas and the focused view are full-bleed: their own floating nav + // replaces the shell bar. The inbox and the outline keep the bar. + const fullBleed = board !== null || focused !== null; + const shell = useMemo( + () => ({ + openShortcuts: () => { + setSheet(true); + }, + }), + [], + ); useShortcuts([ { key: "?", @@ -50,7 +49,7 @@ export function App(): React.JSX.Element { ]); return ( - <> + {board?.params.slug === undefined ? ( Skip to content @@ -60,26 +59,28 @@ export function App(): React.JSX.Element { Review this board as a list )} -
- - - - - -
+ {fullBleed ? null : ( +
+ + + + + +
+ )} } /> } /> @@ -93,6 +94,6 @@ export function App(): React.JSX.Element { setSheet(false); }} /> - +
); } diff --git a/packages/artifacts/src/client/canvas/canvas.tsx b/packages/artifacts/src/client/canvas/canvas.tsx index a4733e9ad9..4ba364b353 100644 --- a/packages/artifacts/src/client/canvas/canvas.tsx +++ b/packages/artifacts/src/client/canvas/canvas.tsx @@ -40,6 +40,8 @@ export type CanvasProps = { readonly pins: readonly CanvasPin[]; readonly selectedThreadId: string | null; readonly onSelectThread: (threadId: string | null) => void; + /** Pixels on the right that the open comments panel covers. */ + readonly rightInset: number; }; const SAVE_TEXT = { @@ -53,6 +55,7 @@ export function Canvas({ pins, selectedThreadId, onSelectThread, + rightInset, }: CanvasProps): React.JSX.Element { const create = useCreateThread(); const arrange = useArrange(slug, data); @@ -97,7 +100,7 @@ export function Canvas({ const [section, setSection] = useState(null); const activeFrame = activeId === null ? undefined : byId.get(activeId); - const camera = useCanvasCamera(slug, frames, selectedFrames); + const camera = useCanvasCamera(slug, frames, selectedFrames, rightInset); const { controller, viewport, reveal, sizeRef } = camera; const tiers = useFrameTiers({ frames, diff --git a/packages/artifacts/src/client/canvas/use-camera.ts b/packages/artifacts/src/client/canvas/use-camera.ts index 15693a348d..c2797c950e 100644 --- a/packages/artifacts/src/client/canvas/use-camera.ts +++ b/packages/artifacts/src/client/canvas/use-camera.ts @@ -79,6 +79,7 @@ export function useCanvasCamera( slug: string, frames: readonly CanvasFrameModel[], selected: readonly CanvasFrameModel[], + insetRight = 0, ): CanvasCamera { const restored = useRef(storedCamera(slug)); const [controller] = useState(() => @@ -89,6 +90,17 @@ export function useCanvasCamera( const [size, setSize] = useState({ width: 0, height: 0 }); const sizeRef = useRef(size); sizeRef.current = size; + // The part of the viewport something floats over (the open comments panel): + // fitting and revealing aim at what is left. + const insetRef = useRef(insetRight); + insetRef.current = insetRight; + const usable = useCallback( + (): Size => ({ + width: Math.max(1, sizeRef.current.width - insetRef.current), + height: sizeRef.current.height, + }), + [], + ); const [settled, setSettled] = useState({ camera: controller.get(), kind: "pan", @@ -135,10 +147,8 @@ export function useCanvasCamera( const fitAll = useCallback(() => { const bounds = boundsOf(frames.map((frame) => frame.rect)); if (bounds === null || sizeRef.current.width === 0) return; - move( - fitRect(bounds, sizeRef.current, { padding: FIT_PADDING, maxScale: 1 }), - ); - }, [frames, move]); + move(fitRect(bounds, usable(), { padding: FIT_PADDING, maxScale: 1 })); + }, [frames, move, usable]); const initialised = useRef(restored.current !== null); useEffect(() => { @@ -151,12 +161,12 @@ export function useCanvasCamera( const bounds = boundsOf(selected.map((frame) => frame.rect)); if (bounds === null || sizeRef.current.width === 0) return; move( - fitRect(bounds, sizeRef.current, { + fitRect(bounds, usable(), { padding: FIT_PADDING, maxScale: FIT_SELECTION_MAX_SCALE, }), ); - }, [selected, move]); + }, [selected, move, usable]); const viewportCentre = useCallback( (): Point => ({ @@ -192,11 +202,11 @@ export function useCanvasCamera( if (inside) return; move({ s: camera.s, - x: sizeRef.current.width / 2 - (rect.x + rect.w / 2) * camera.s, + x: usable().width / 2 - (rect.x + rect.w / 2) * camera.s, y: sizeRef.current.height / 2 - (rect.y + rect.h / 2) * camera.s, }); }, - [controller, move], + [controller, move, usable], ); return { diff --git a/packages/artifacts/src/client/env.d.ts b/packages/artifacts/src/client/env.d.ts index cc97132f52..1deddba324 100644 --- a/packages/artifacts/src/client/env.d.ts +++ b/packages/artifacts/src/client/env.d.ts @@ -1,2 +1,13 @@ // Side-effect stylesheet imports; Vite bundles them. declare module "*.css"; + +// lucide-react exposes each icon's data at its subpath, but its types only declare +// the component; the comment pin and cursor read the path from here so they cannot drift. +declare module "lucide-react/icons/message-circle" { + const iconData: { + readonly name: string; + readonly size: number; + readonly node: readonly (readonly [string, { readonly d: string }])[]; + }; + export { iconData as "__iconData" }; +} diff --git a/packages/artifacts/src/client/lib/pin-shape.test.ts b/packages/artifacts/src/client/lib/pin-shape.test.ts index 63d7233c75..12241b78a8 100644 --- a/packages/artifacts/src/client/lib/pin-shape.test.ts +++ b/packages/artifacts/src/client/lib/pin-shape.test.ts @@ -1,14 +1,40 @@ +import { __iconData } from "lucide-react/icons/message-circle"; import { describe, expect, test } from "vitest"; import { + commentCursor, + CURSOR_HOTSPOT, + CURSOR_SIZE, + ICON_PATH, + ICON_TIP, PIN_HEIGHT, - PIN_PATH, + PIN_SIZE, PIN_TIP, PIN_WIDTH, pinAnchor, pinOrigin, } from "./pin-shape.ts"; -describe("the speech-bubble pin", () => { +/** lucide's `message-circle` at the version this tail tip was measured on. */ +const MEASURED_PATH = + "M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719"; + +describe("the comment glyph", () => { + test("is lucide's own MessageCircle path, and the tail tip was measured on it", () => { + expect(ICON_PATH).toBe(__iconData.node[0]?.[1].d); + // If lucide redraws the icon, the tail tip below must be measured again. + expect(ICON_PATH).toBe(MEASURED_PATH); + }); + + test("the tail tip sits on the glyph's tail corner, at the bottom-left of its box", () => { + expect(ICON_TIP.x).toBeLessThan(3); + expect(ICON_TIP.y).toBeGreaterThan(21); + // On the radius-1 corner arc between (2.021, 20.799) and (3.257, 21.967): + // its centre is (3.001, 21.0), and the tip is one radius from it. + expect(Math.hypot(ICON_TIP.x - 3.001, ICON_TIP.y - 21)).toBeCloseTo(1, 2); + }); +}); + +describe("the comment pin", () => { test("its tail tip maps to the anchor it was placed at, and back", () => { for (const anchor of [ { x: 0, y: 0 }, @@ -19,22 +45,43 @@ describe("the speech-bubble pin", () => { const tip = pinAnchor(origin); expect(Math.abs(tip.x - anchor.x)).toBeLessThan(1e-9); expect(Math.abs(tip.y - anchor.y)).toBeLessThan(1e-9); - // The tip is inside the box, on its bottom edge. expect(origin.x + PIN_TIP.x).toBeCloseTo(anchor.x, 9); - expect(origin.y + PIN_HEIGHT).toBeCloseTo(anchor.y, 9); + expect(origin.y + PIN_TIP.y).toBeCloseTo(anchor.y, 9); } }); - test("the outline really ends its tail at the tip, inside the box", () => { - expect(PIN_PATH.split("L")).toContain( - `${String(PIN_TIP.x)} ${String(PIN_TIP.y)}`, - ); - expect(PIN_TIP.x).toBeLessThanOrEqual(PIN_WIDTH); - expect(PIN_TIP.y).toBe(PIN_HEIGHT); + test("the tip is inside the box, near its bottom-left, and the target is at least 24 px", () => { + expect(PIN_TIP.x).toBeGreaterThan(0); + expect(PIN_TIP.x).toBeLessThan(PIN_WIDTH / 4); + expect(PIN_TIP.y).toBeGreaterThan((PIN_HEIGHT * 3) / 4); + expect(PIN_TIP.y).toBeLessThanOrEqual(PIN_HEIGHT); + expect(PIN_SIZE).toBeGreaterThanOrEqual(24); + }); +}); + +describe("the comment cursor", () => { + const cursor = commentCursor("#176b4d"); + + test("is the glyph's path, drawn twice (halo and body), with a crosshair fallback", () => { + expect(cursor.startsWith('url("data:image/svg+xml,')).toBe(true); + expect(cursor.endsWith(", crosshair")).toBe(true); + expect(cursor.split(ICON_PATH).length - 1).toBe(2); + expect(cursor).toContain("%23176b4d"); + expect(cursor).toContain("fill='%23fff'"); }); - test("keeps a 24 px hit target", () => { - expect(PIN_WIDTH).toBeGreaterThanOrEqual(24); - expect(PIN_HEIGHT).toBeGreaterThanOrEqual(24); + test("the hotspot is the tail tip within half a pixel", () => { + expect(CURSOR_HOTSPOT.x).toBeGreaterThan(0); + expect(Math.abs(CURSOR_HOTSPOT.x - (ICON_TIP.x + 3))).toBeLessThanOrEqual( + 0.5, + ); + expect(Math.abs(CURSOR_HOTSPOT.y - (ICON_TIP.y + 3))).toBeLessThanOrEqual( + 0.5, + ); + expect(cursor).toContain( + `") ${String(CURSOR_HOTSPOT.x)} ${String(CURSOR_HOTSPOT.y)}, crosshair`, + ); + expect(CURSOR_HOTSPOT.x).toBeLessThan(CURSOR_SIZE); + expect(CURSOR_HOTSPOT.y).toBeLessThan(CURSOR_SIZE); }); }); diff --git a/packages/artifacts/src/client/lib/pin-shape.ts b/packages/artifacts/src/client/lib/pin-shape.ts index d2393191d6..a08237db3c 100644 --- a/packages/artifacts/src/client/lib/pin-shape.ts +++ b/packages/artifacts/src/client/lib/pin-shape.ts @@ -1,21 +1,36 @@ /** - * The comment pin is a speech bubble with its tail pointing at the anchor. - * The stored anchor is the tail's tip, not the bubble's centre, so everything + * The comment pin and the comment cursor are the toolbar's lucide + * `MessageCircle` glyph, with its path read from lucide's own icon data so + * nothing is hand-drawn and nothing can drift. The glyph's tail is the point: + * the stored anchor is the tail's tip, not the bubble's centre, so everything * that positions a pin places the *tip* at the anchor point. */ +import { __iconData } from "lucide-react/icons/message-circle"; import type { Point } from "./geometry.ts"; -export const PIN_WIDTH = 26; -export const PIN_HEIGHT = 30; -/** The tail tip inside the pin's box, in CSS pixels from its top-left corner. */ -export const PIN_TIP: Point = { x: 1, y: 30 }; +const [firstNode] = __iconData.node; +/** The glyph's outline in its own 24 x 24 box. */ +export const ICON_PATH = firstNode?.[1].d ?? ""; +export const ICON_SIZE = __iconData.size; /** - * The bubble and its tail in a 26 x 30 box. The path ends its tail at - * `PIN_TIP`; the cursor uses the same outline so the pointer and the pin agree. + * The tail tip in the glyph's box: the point of the tail's rounded corner + * nearest the bottom-left of the box (the middle of its radius-1 arc from + * (2.021, 20.799) to (3.257, 21.967)). `pin-shape.test.ts` pins the path, so a + * lucide update that moves the tail fails there and this is revisited. */ -export const PIN_PATH = - "M13 .75C19.9 .75 25.25 5.4 25.25 11C25.25 16.6 19.9 21.25 13 21.25H11L1 30L4.6 20.2C2.2 18.4 .75 15.1 .75 11C.75 5.4 6.1 .75 13 .75Z"; +export const ICON_TIP: Point = { x: 2.314, y: 21.727 }; + +/** The pin is the glyph at 28 px: a 28 x 28 box (a 24 px or larger target). */ +export const PIN_SIZE = 28; +const PIN_SCALE = PIN_SIZE / ICON_SIZE; +export const PIN_WIDTH = PIN_SIZE; +export const PIN_HEIGHT = PIN_SIZE; +/** The tail tip inside the pin's box, in CSS pixels from its top-left corner. */ +export const PIN_TIP: Point = { + x: ICON_TIP.x * PIN_SCALE, + y: ICON_TIP.y * PIN_SCALE, +}; /** Where the pin's top-left corner goes so its tail tip lands on `anchor`. */ export function pinOrigin(anchor: Point): Point { @@ -26,3 +41,41 @@ export function pinOrigin(anchor: Point): Point { export function pinAnchor(origin: Point): Point { return { x: origin.x + PIN_TIP.x, y: origin.y + PIN_TIP.y }; } + +/** The cursor image is the glyph with this much room around it for its halo. */ +const CURSOR_MARGIN = 3; +export const CURSOR_SIZE = ICON_SIZE + 2 * CURSOR_MARGIN; +/** The cursor's hotspot: the tail tip, to the nearest pixel (the image is 1:1). */ +export const CURSOR_HOTSPOT: Point = { + x: Math.round(ICON_TIP.x + CURSOR_MARGIN), + y: Math.round(ICON_TIP.y + CURSOR_MARGIN), +}; + +/** + * The `cursor` value for comment mode: the glyph with a white fill, an accent + * stroke and a white halo (so it reads on white and on dark artifacts), the + * hotspot on the tail tip, and `crosshair` where cursor images are unsupported. + */ +export function commentCursor(accent: string): string { + const path = `` + + `${path} fill='none' stroke='#fff' stroke-opacity='.85' stroke-width='5' stroke-linejoin='round' stroke-linecap='round'/>` + + `${path} fill='#fff' stroke='${accent}' stroke-width='2' stroke-linejoin='round' stroke-linecap='round'/>` + + ""; + const encoded = svg + .replaceAll("#", "%23") + .replaceAll("<", "%3C") + .replaceAll(">", "%3E"); + return `url("data:image/svg+xml,${encoded}") ${String(CURSOR_HOTSPOT.x)} ${String(CURSOR_HOTSPOT.y)}, crosshair`; +} + +/** The accent used for the cursor: the app's light-theme accent, which the white halo keeps legible anywhere. */ +export const CURSOR_ACCENT = "#176b4d"; + +/** Makes comment mode's cursor available to the stylesheets as `--ar-comment-cursor`. */ +export function installCommentCursor( + root: HTMLElement = document.documentElement, +): void { + root.style.setProperty("--ar-comment-cursor", commentCursor(CURSOR_ACCENT)); +} diff --git a/packages/artifacts/src/client/main.tsx b/packages/artifacts/src/client/main.tsx index febf72cc71..1a4de72381 100644 --- a/packages/artifacts/src/client/main.tsx +++ b/packages/artifacts/src/client/main.tsx @@ -5,14 +5,18 @@ import "./styles/viewers.css"; import "./styles/review.css"; import "./styles/pages.css"; import "./styles/canvas.css"; +import "./styles/shell.css"; import { QueryClientProvider } from "@tanstack/react-query"; import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; import { BrowserRouter } from "react-router"; import { App } from "./app.tsx"; +import { installCommentCursor } from "./lib/pin-shape.ts"; import { queryClient } from "./data/api.ts"; +installCommentCursor(); + const root = document.querySelector("#root"); if (root === null) { throw new Error("Artifacts client is missing #root element"); diff --git a/packages/artifacts/src/client/pages/board.tsx b/packages/artifacts/src/client/pages/board.tsx index ad15dd9616..55294dbdf7 100644 --- a/packages/artifacts/src/client/pages/board.tsx +++ b/packages/artifacts/src/client/pages/board.tsx @@ -1,10 +1,19 @@ -import { useMemo, useState } from "react"; +import { ListIcon } from "lucide-react"; +import { useCallback, useMemo, useState } from "react"; import { Link, Navigate, useParams, useSearchParams } from "react-router"; import { useCreateThread } from "#client/data/mutations.ts"; import { useLiveUpdates } from "#client/data/live.ts"; import { useBoard, useBoardThreads } from "#client/data/queries.ts"; import { Canvas } from "#client/canvas/canvas.tsx"; import { canvasPins, frameModels } from "#client/canvas/model.ts"; +import { CommentsPanel } from "#client/shell/comments-panel.tsx"; +import { FloatingNav } from "#client/shell/floating-nav.tsx"; +import { + NARROW_QUERY, + PANEL_CLEARANCE, + usePanelInset, + usePanelState, +} from "#client/shell/panel-state.ts"; import { Composer } from "#client/threads/composer.tsx"; import { ThreadList, @@ -39,6 +48,27 @@ export function BoardPage(): React.JSX.Element { () => new Map(frames.map((frame) => [frame.id, frame.summary.title])), [frames], ); + const panel = usePanelState("board"); + const openCount = all.filter((thread) => thread.state === "open").length; + // A wide screen keeps the open panel's strip clear; a narrow one overlays a sheet. + const wide = !globalThis.matchMedia(NARROW_QUERY).matches; + const inset = wide && !panel.collapsed ? PANEL_CLEARANCE : 0; + usePanelInset(inset); + const { expand } = panel; + const selectThread = useCallback( + (id: string | null) => { + setSelectedThreadId(id); + if (id === null) return; + // Selecting a thread (a pin, J/K, a new comment) opens the panel on it. + expand(); + requestAnimationFrame(() => { + document + .querySelector(`[id="thread-${id}"]`) + ?.scrollIntoView({ block: "nearest" }); + }); + }, + [expand], + ); const pinNumber = useMemo( () => new Map(pins.map((pin) => [pin.id, pin.index])), [pins], @@ -73,53 +103,62 @@ export function BoardPage(): React.JSX.Element { return (
{`${board.data.board.title} · Artifacts`} -
-

{board.data.board.title}

- - - List view - -
-
- + {board.data.board.title}} + actions={ + +
+
); } diff --git a/packages/artifacts/src/client/pages/focused-header.tsx b/packages/artifacts/src/client/pages/focused-header.tsx index 81b19d0691..76e1c49c90 100644 --- a/packages/artifacts/src/client/pages/focused-header.tsx +++ b/packages/artifacts/src/client/pages/focused-header.tsx @@ -1,10 +1,11 @@ import { Segmented } from "@shepherdjerred/console-ui"; -import { ExternalLinkIcon, MessageSquarePlusIcon } from "lucide-react"; +import { ExternalLinkIcon, MessageCircleIcon } from "lucide-react"; import { Link } from "react-router"; import type { VersionSummary, VersionView, } from "@shepherdjerred/artifacts/procedures"; +import { FloatingNav } from "#client/shell/floating-nav.tsx"; import { formatAge } from "#client/lib/format.ts"; import type { PresetId } from "#client/viewers/types.ts"; @@ -21,18 +22,14 @@ export function defaultPreset(viewport: VersionSummary["viewport"]): PresetId { return viewport.width >= 700 ? "tablet" : "mobile"; } -export function FocusedHeader({ +/** The floating nav for one artifact: board › title, the version, and Open raw. */ +export function FocusedNav({ title, boardSlug, boardTitle, versions, shown, version, - framed, - preset, - onPreset, - commentMode, - onCommentMode, onVersion, }: { readonly title: string; @@ -41,81 +38,148 @@ export function FocusedHeader({ readonly versions: readonly VersionSummary[]; readonly shown: VersionSummary; readonly version: VersionView | undefined; + readonly onVersion: (number: number) => void; +}): React.JSX.Element { + const latest = versions[0]?.number; + const raw = + version?.contentUrl == null + ? null + : new URL(encodeURI(version.entryPath), version.contentUrl).href; + return ( + + + {boardTitle} + + +

{title}

+ + } + actions={ + <> + + {raw === null ? null : ( +
+ + )} + + } + menu={[ + ...versions.map((candidate) => ({ + key: `v${String(candidate.number)}`, + label: `Version v${String(candidate.number)}${candidate.number === latest ? " (latest)" : ""}${candidate.number === shown.number ? ", shown" : ""}`, + onSelect: () => { + onVersion(candidate.number); + }, + })), + { + key: "board", + label: `Board: ${boardTitle}`, + to: `/b/${boardSlug}?view=canvas`, + }, + ...(raw === null + ? [] + : [ + { + key: "raw", + label: "Open raw", + onSelect: () => { + globalThis.open(raw, "_blank", "noopener,noreferrer"); + }, + }, + ]), + ]} + /> + ); +} + +/** Who published the version shown, and their note; it leads the comments panel. */ +export function VersionMeta({ + shown, +}: { + readonly shown: VersionSummary; +}): React.JSX.Element { + return ( +

+ {shown.publisher.name} published {formatAge(shown.createdAt)} + {shown.note === "" ? null : ( + {shown.note} + )} +

+ ); +} + +/** The bottom pill of the focused view: comment mode, and the viewport width of a frame. */ +export function FocusedTools({ + framed, + preset, + onPreset, + commentMode, + onCommentMode, +}: { readonly framed: boolean; readonly preset: PresetId; readonly onPreset: (preset: PresetId) => void; readonly commentMode: boolean; readonly onCommentMode: (on: boolean) => void; - readonly onVersion: (number: number) => void; }): React.JSX.Element { - const latest = versions[0]?.number; return ( -
-
-

- {boardTitle} -

-

{title}

-

- {shown.publisher.name} published {formatAge(shown.createdAt)} - {shown.note === "" ? null : ( - {shown.note} - )} -

-
-
- - {framed ? ( +
+ {framed ? ( + <> - ) : null} - - {version?.contentUrl == null ? null : ( - - - )} -
-
+
); } diff --git a/packages/artifacts/src/client/pages/focused.tsx b/packages/artifacts/src/client/pages/focused.tsx index 4f6f5f0865..f1a74ebd6c 100644 --- a/packages/artifacts/src/client/pages/focused.tsx +++ b/packages/artifacts/src/client/pages/focused.tsx @@ -14,7 +14,19 @@ import { import { ArtifactViewer } from "#client/viewers/artifact-viewer.tsx"; import type { AnchorAdapter, PresetId } from "#client/viewers/types.ts"; import { useFocusedData } from "./focused-data.ts"; -import { defaultPreset, FocusedHeader } from "./focused-header.tsx"; +import { + defaultPreset, + FocusedNav, + FocusedTools, + VersionMeta, +} from "./focused-header.tsx"; +import { CommentsPanel } from "#client/shell/comments-panel.tsx"; +import { + NARROW_QUERY, + PANEL_CLEARANCE, + usePanelInset, + usePanelState, +} from "#client/shell/panel-state.ts"; import { useReviewKeys } from "./focused-shortcuts.ts"; import { PlacementComposer, type Placement } from "./placement-composer.tsx"; @@ -47,6 +59,10 @@ export function FocusedPage(): React.JSX.Element { const [pane, setPane] = useState(null); const create = useCreateThread(); const resolve = useSetResolved(); + const panel = usePanelState("focused"); + const wide = !globalThis.matchMedia(NARROW_QUERY).matches; + usePanelInset(wide && !panel.collapsed ? PANEL_CLEARANCE : 0); + const { expand } = panel; const numbered = useMemo( () => new Map(all.map((thread, position) => [thread.id, position + 1])), @@ -67,11 +83,15 @@ export function FocusedPage(): React.JSX.Element { setSelectedId(threadId); const thread = all.find((candidate) => candidate.id === threadId); if (thread !== undefined) adapterRef.current?.reveal?.(thread.anchor); - document - .querySelector(`[id="thread-${threadId}"]`) - ?.scrollIntoView({ block: "nearest" }); + // A pin, J/K or a new comment opens the panel on the thread. + expand(); + requestAnimationFrame(() => { + document + .querySelector(`[id="thread-${threadId}"]`) + ?.scrollIntoView({ block: "nearest" }); + }); }, - [all], + [all, expand], ); const showVersion = useCallback( @@ -153,22 +173,74 @@ export function FocusedPage(): React.JSX.Element { setPlacement(null); setCommentMode(false); setSelectedId(thread.id); + expand(); setFilter("open"); }, }, ); } + const openCount = all.filter((thread) => thread.state === "open").length; + return (
{`${detail.title} · Artifacts`} - + {version === undefined ? ( +

+ Loading version… +

+ ) : ( + { + setPlacement({ anchor, at }); + }, + }} + /> + )} + {placement === null ? null : ( + { + setPlacement(null); + }} + /> + )} + {commentMode && placement === null ? ( +

+ Comment mode: click where the comment belongs. Esc to leave. +

+ ) : null} + + + -
-
- {version === undefined ? ( -

- Loading version… -

- ) : ( - { - setPlacement({ anchor, at }); - }, - }} - /> - )} - {placement === null ? null : ( - { - setPlacement(null); - }} - /> - )} - {commentMode && placement === null ? ( -

- Comment mode: click where the comment belongs. Esc to leave. -

- ) : null} -
- -
+ + + + numbered.get(thread.id) ?? null} + onViewVersion={showVersion} + empty={ + filter === "open" + ? "No open threads. Press C and click to comment." + : "No threads here." + } + /> + { + create.mutate({ + board: detail.boardSlug, + artifactId: detail.id, + versionId: shown.id, + anchor: { type: "general" }, + body, + }); + }} + /> +
); } diff --git a/packages/artifacts/src/client/shell/app-nav.ts b/packages/artifacts/src/client/shell/app-nav.ts new file mode 100644 index 0000000000..4dd9855f10 --- /dev/null +++ b/packages/artifacts/src/client/shell/app-nav.ts @@ -0,0 +1,14 @@ +import type { AppSwitcherEntry } from "@shepherdjerred/console-ui"; +import { CONSOLE_LINKS } from "@shepherdjerred/ops-model/tool-links.ts"; + +/** The workspace button and the console links the shell bar and the floating nav share. */ +export const CURRENT_APP = { label: "Artifacts", mark: "A" } as const; + +export const SWITCHER_APPS: readonly AppSwitcherEntry[] = [ + { label: "Artifacts", url: "/", group: "Apps" }, + ...CONSOLE_LINKS.filter((link) => link.label !== "Artifacts").map((link) => ({ + label: link.label, + url: link.url, + group: link.group, + })), +]; diff --git a/packages/artifacts/src/client/shell/comments-panel.tsx b/packages/artifacts/src/client/shell/comments-panel.tsx new file mode 100644 index 0000000000..db6a7b4264 --- /dev/null +++ b/packages/artifacts/src/client/shell/comments-panel.tsx @@ -0,0 +1,98 @@ +import { MessageCircleIcon, PanelRightCloseIcon } from "lucide-react"; +import { useEffect, useId, useRef } from "react"; +import { useWaiters } from "#client/data/queries.ts"; +import { useShortcuts } from "./shortcuts.ts"; +import type { PanelState } from "./panel-state.ts"; + +/** + * The comments as a floating card over the right of the canvas or viewer + * (a bottom sheet on a narrow screen), collapsible to a small pill with the + * `MessageCircle` icon, the open-thread count and a dot while an agent waits. + * Shift+C toggles it. Expanding moves focus into the card and collapsing moves + * it back to the toggle; there is no animation, so nothing to reduce. + */ +export function CommentsPanel({ + state, + scope, + openCount, + children, +}: { + readonly state: PanelState; + readonly scope: { readonly board: string } | { readonly artifactId: string }; + readonly openCount: number; + readonly children: React.ReactNode; +}): React.JSX.Element { + const id = useId(); + const waiters = useWaiters(scope); + const waiting = (waiters.data?.waiters.length ?? 0) > 0; + const cardRef = useRef(null); + const toggleRef = useRef(null); + const moved = useRef(false); + const { collapsed, toggle } = state; + + useShortcuts([{ key: "c", shift: true, run: toggle }]); + + // After the first render, a change of state moves focus with it. + useEffect(() => { + if (!moved.current) { + moved.current = true; + return; + } + if (collapsed) toggleRef.current?.focus(); + else cardRef.current?.focus(); + }, [collapsed]); + + const summary = `${String(openCount)} open${waiting ? ", an agent is waiting" : ""}`; + if (collapsed) + return ( + + ); + return ( +
+
+

Comments

+ {summary} + + +
+
{children}
+
+ ); +} diff --git a/packages/artifacts/src/client/shell/floating-nav.tsx b/packages/artifacts/src/client/shell/floating-nav.tsx new file mode 100644 index 0000000000..a9fc9d36e6 --- /dev/null +++ b/packages/artifacts/src/client/shell/floating-nav.tsx @@ -0,0 +1,98 @@ +import { Menu } from "@base-ui/react/menu"; +import { AppSwitcher, ThemeToggle } from "@shepherdjerred/console-ui"; +import { KeyboardIcon, MoreHorizontalIcon } from "lucide-react"; +import { Link, useNavigate } from "react-router"; +import { CURRENT_APP, SWITCHER_APPS } from "./app-nav.ts"; +import { useShell } from "./shell-context.tsx"; +import { themeStore } from "./theme.ts"; + +export type NavMenuItem = { + readonly key: string; + readonly label: string; + /** An in-app route; the menu navigates to it. */ + readonly to?: string; + readonly onSelect?: () => void; +}; + +/** + * The shell's top bar and the page's own header as one floating pill at the + * top left: the workspace switcher and Inbox the bar had, then the page's + * title and actions, then the keyboard and theme buttons. On a phone it keeps + * the app mark and the title and moves the rest into an overflow menu. + */ +export function FloatingNav({ + lead, + actions, + menu, +}: { + /** The page's title (and crumbs): the one place a heading lives. */ + readonly lead: React.ReactNode; + /** Page actions shown inline: List view, the version select, Open raw. */ + readonly actions?: React.ReactNode; + /** The same actions as overflow menu items for a narrow screen. */ + readonly menu: readonly NavMenuItem[]; +}): React.JSX.Element { + const { openShortcuts } = useShell(); + const navigate = useNavigate(); + return ( +
+ + +
+ ); +} diff --git a/packages/artifacts/src/client/shell/panel-state.ts b/packages/artifacts/src/client/shell/panel-state.ts new file mode 100644 index 0000000000..c560f2edb3 --- /dev/null +++ b/packages/artifacts/src/client/shell/panel-state.ts @@ -0,0 +1,79 @@ +import { useCallback, useEffect, useState } from "react"; + +const KEY = "artifacts.panel.collapsed.v1"; +/** At and below this width the panel is a bottom sheet, collapsed to start with. */ +export const NARROW_QUERY = "(max-width: 900px)"; + +function read(viewer: string): boolean | null { + try { + const value = localStorage.getItem(`${KEY}:${viewer}`); + return value === null ? null : value === "true"; + } catch { + return null; + } +} + +function write(viewer: string, collapsed: boolean): void { + try { + localStorage.setItem(`${KEY}:${viewer}`, String(collapsed)); + } catch { + // Blocked storage just forgets the choice. + } +} + +export type PanelState = { + readonly collapsed: boolean; + readonly toggle: () => void; + readonly expand: () => void; + readonly collapse: () => void; +}; + +/** + * Whether the comments panel is collapsed, remembered per viewer ("board" or + * "focused"). With nothing stored it starts open, except on a narrow screen + * where it is a bottom sheet and starts collapsed. + */ +export function usePanelState(viewer: string): PanelState { + const [collapsed, setCollapsed] = useState( + () => read(viewer) ?? globalThis.matchMedia(NARROW_QUERY).matches, + ); + const set = useCallback( + (next: boolean) => { + setCollapsed(next); + write(viewer, next); + }, + [viewer], + ); + return { + collapsed, + toggle: useCallback(() => { + set(!collapsed); + }, [set, collapsed]), + expand: useCallback(() => { + set(false); + }, [set]), + collapse: useCallback(() => { + set(true); + }, [set]), + }; +} + +/** The width the open panel takes from the canvas on a wide screen, in pixels. */ +export const PANEL_WIDTH = 360; +export const PANEL_INSET = 12; +/** What a wide screen keeps clear on the right while the panel is open. */ +export const PANEL_CLEARANCE = PANEL_WIDTH + 2 * PANEL_INSET; + +/** + * Publishes the clearance as `--ar-inset-right` so the stylesheets can keep + * pills and the viewer out from under the open panel; cleared on leaving. + */ +export function usePanelInset(inset: number): void { + useEffect(() => { + const root = document.documentElement; + root.style.setProperty("--ar-inset-right", `${String(inset)}px`); + return () => { + root.style.removeProperty("--ar-inset-right"); + }; + }, [inset]); +} diff --git a/packages/artifacts/src/client/shell/shell-context.tsx b/packages/artifacts/src/client/shell/shell-context.tsx new file mode 100644 index 0000000000..b2a7a14d14 --- /dev/null +++ b/packages/artifacts/src/client/shell/shell-context.tsx @@ -0,0 +1,13 @@ +import { noop } from "#client/lib/noop.ts"; +import { createContext, useContext } from "react"; + +/** What a page may ask of the shell it sits in. */ +export type ShellActions = { readonly openShortcuts: () => void }; + +export const ShellContext = createContext({ + openShortcuts: noop, +}); + +export function useShell(): ShellActions { + return useContext(ShellContext); +} diff --git a/packages/artifacts/src/client/shell/shortcuts.test.ts b/packages/artifacts/src/client/shell/shortcuts.test.ts index 6227937c98..723dd488fa 100644 --- a/packages/artifacts/src/client/shell/shortcuts.test.ts +++ b/packages/artifacts/src/client/shell/shortcuts.test.ts @@ -11,6 +11,25 @@ describe("matches", () => { expect(matches({ key: "c", run: noop }, key({ key: "C" }))).toBe(true); }); + test("Shift makes a letter a different key", () => { + expect( + matches({ key: "c", run: noop }, key({ key: "C", shiftKey: true })), + ).toBe(false); + expect( + matches( + { key: "c", shift: true, run: noop }, + key({ key: "C", shiftKey: true }), + ), + ).toBe(true); + expect( + matches({ key: "c", shift: true, run: noop }, key({ key: "c" })), + ).toBe(false); + // Symbols are unaffected: `?` needs Shift on most keyboards. + expect( + matches({ key: "?", run: noop }, key({ key: "?", shiftKey: true })), + ).toBe(true); + }); + test("named keys compare exactly", () => { expect(matches({ key: "Escape", run: noop }, key({ key: "Escape" }))).toBe( true, diff --git a/packages/artifacts/src/client/shell/shortcuts.ts b/packages/artifacts/src/client/shell/shortcuts.ts index 4b042de8e6..3803064820 100644 --- a/packages/artifacts/src/client/shell/shortcuts.ts +++ b/packages/artifacts/src/client/shell/shortcuts.ts @@ -3,6 +3,11 @@ import { useEffect, useRef } from "react"; export type Binding = { /** `KeyboardEvent.key`; letters compare case-insensitively. */ readonly key: string; + /** + * A letter with Shift held is a different key: a binding fires for it only + * when it says `shift: true`, and a plain letter binding does not fire for it. + */ + readonly shift?: boolean; readonly run: (event: KeyboardEvent) => void; }; @@ -28,10 +33,14 @@ function isActivatable(target: EventTarget | null): boolean { export type KeyInput = Pick< KeyboardEvent, "key" | "metaKey" | "ctrlKey" | "altKey" ->; +> & + Partial>; export function matches(binding: Binding, event: KeyInput): boolean { if (event.metaKey || event.ctrlKey || event.altKey) return false; + const letter = /^[a-z]$/iu.test(binding.key); + if (letter && (event.shiftKey === true) !== (binding.shift === true)) + return false; return binding.key.length === 1 ? event.key.toLowerCase() === binding.key.toLowerCase() : event.key === binding.key; @@ -46,7 +55,8 @@ function onKeyDown(event: KeyboardEvent): void { // the page when a field has focus (to leave comment mode). if (!escape && isTypingTarget(event.target)) return; if (event.key === "Enter" && isActivatable(event.target)) return; - if (!escape && document.querySelector("dialog[open]") !== null) return; + // An open modal owns every key, Escape included: it closes itself. + if (document.querySelector("dialog[open]") !== null) return; for (let index = stack.length - 1; index >= 0; index -= 1) { const entry = stack[index]; const binding = entry?.current.find((candidate) => @@ -100,6 +110,7 @@ export const SHORTCUT_SHEET: readonly { { keys: "[ / ]", does: "Canvas: send the selection back or forward" }, { keys: "Delete", does: "Canvas: remove the selection from the board" }, { keys: "Ctrl/⌘ Z", does: "Canvas: undo (Shift to redo)" }, + { keys: "Shift+C", does: "Show or hide the comments panel" }, { keys: "C", does: "Comment mode: click to place a pin" }, { keys: "Enter", does: "Interact with the selected frame" }, { keys: "Esc", does: "Leave the frame, comment mode, or a draft" }, diff --git a/packages/artifacts/src/client/styles/base.css b/packages/artifacts/src/client/styles/base.css index 35de543a3a..e62b58d16d 100644 --- a/packages/artifacts/src/client/styles/base.css +++ b/packages/artifacts/src/client/styles/base.css @@ -7,11 +7,8 @@ --ar-top: 44px; --ar-pin: var(--ui-accent); --ar-pin-ink: var(--ui-on-accent); - /* The comment cursor: a speech bubble whose tail tip (2, 31) is the hotspot. */ - --ar-comment-cursor: - url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='28' height='32' viewBox='-1 -1 28 32'%3E%3Cpath d='M13 .75C19.9 .75 25.25 5.4 25.25 11C25.25 16.6 19.9 21.25 13 21.25H11L1 30L4.6 20.2C2.2 18.4 .75 15.1 .75 11C.75 5.4 6.1 .75 13 .75Z' fill='none' stroke='%23000' stroke-opacity='.3' stroke-width='4' stroke-linejoin='round'/%3E%3Cpath d='M13 .75C19.9 .75 25.25 5.4 25.25 11C25.25 16.6 19.9 21.25 13 21.25H11L1 30L4.6 20.2C2.2 18.4 .75 15.1 .75 11C.75 5.4 6.1 .75 13 .75Z' fill='%23fff' stroke='%23176b4d' stroke-width='2' stroke-linejoin='round'/%3E%3C/svg%3E") - 2 31, - crosshair; + /* Set at startup from lucide's MessageCircle (lib/pin-shape.ts). */ + --ar-comment-cursor: crosshair; } body { diff --git a/packages/artifacts/src/client/styles/canvas.css b/packages/artifacts/src/client/styles/canvas.css index ccf5e9b051..4d767bd729 100644 --- a/packages/artifacts/src/client/styles/canvas.css +++ b/packages/artifacts/src/client/styles/canvas.css @@ -74,6 +74,9 @@ .ar-cv-overlay { position: absolute; inset: 0; + /* Pills sit in what an open comments panel leaves; the camera origin stays at the left. */ + right: var(--ar-inset-right, 0px); + container-type: inline-size; z-index: 10; overflow: hidden; pointer-events: none; @@ -269,12 +272,6 @@ bottom: 74px; } -@media (max-width: 900px) { - .ar-cv { - height: 70dvh; - } -} - /* Arranging */ .ar-cv-handles { position: absolute; diff --git a/packages/artifacts/src/client/styles/pages.css b/packages/artifacts/src/client/styles/pages.css index 0868f6b607..0a6a31788e 100644 --- a/packages/artifacts/src/client/styles/pages.css +++ b/packages/artifacts/src/client/styles/pages.css @@ -77,22 +77,13 @@ /* Board */ .ar-board { - display: grid; - grid-template-rows: auto 1fr; - height: calc(100dvh - var(--ar-top)); - min-height: 0; -} -@media (max-width: 900px) { - .ar-board { - height: auto; - } + position: relative; + height: 100dvh; + overflow: hidden; } -.ar-board-head { - display: flex; - align-items: center; - gap: 12px; - padding: 10px 16px; - border-bottom: 1px solid var(--ui-line); +.ar-board > .ar-cv { + position: absolute; + inset: 0; } .ar-placeholder { display: grid; diff --git a/packages/artifacts/src/client/styles/shell.css b/packages/artifacts/src/client/styles/shell.css new file mode 100644 index 0000000000..9a638d95b6 --- /dev/null +++ b/packages/artifacts/src/client/styles/shell.css @@ -0,0 +1,188 @@ +/* + * The floating shell of the canvas and the focused view: a nav pill at the top + * left (the shell bar and the page header as one), and the comments as a card + * on the right that collapses to a pill. Nothing animates. + */ +.ar-fnav { + position: absolute; + top: 12px; + left: 12px; + z-index: 25; + display: flex; + align-items: center; + gap: 2px; + max-width: calc(100% - var(--ar-inset-right, 0px) - 24px); + padding: 4px 6px 4px 4px; + border: 1px solid var(--ui-line); + border-radius: 14px; + background: var(--ui-panel); + box-shadow: 0 2px 12px color-mix(in srgb, black 14%, transparent); +} +.ar-fnav-links a { + display: inline-block; + padding: 6px 10px; + border-radius: 8px; + color: var(--ui-ink); + font-weight: 500; + text-decoration: none; +} +.ar-fnav-links a:hover { + background: var(--ui-head); +} +.ar-fnav-sep { + flex: none; + width: 1px; + height: 22px; + margin: 0 6px; + background: var(--ui-line); +} +.ar-fnav-lead { + display: flex; + align-items: center; + gap: 6px; + min-width: 0; + max-width: 420px; + padding: 0 4px; +} +.ar-fnav-title { + min-width: 0; + margin: 0; + overflow: hidden; + font-size: 14px; + font-weight: 600; + text-overflow: ellipsis; + white-space: nowrap; +} +.ar-fnav-crumb { + max-width: 160px; + overflow: hidden; + color: var(--ui-muted); + text-decoration: none; + text-overflow: ellipsis; + white-space: nowrap; +} +.ar-fnav-arrow { + color: var(--ui-muted); +} +.ar-fnav-actions { + display: flex; + align-items: center; + gap: 2px; +} +.ar-fnav-select select { + height: 28px; + padding: 0 6px; + border: 1px solid var(--ui-btn-edge); + border-radius: 8px; + background: var(--ui-panel); + color: var(--ui-ink); + font-size: 12.5px; +} +.ar-fnav .ar-icon-button { + min-width: 32px; + min-height: 32px; +} +.ar-fnav-more { + display: none; +} +@media (max-width: 640px) { + .ar-fnav { + right: 12px; + max-width: none; + } + .ar-fnav .ui-workspace-label, + .ar-fnav-links, + .ar-fnav-actions, + .ar-fnav-end { + display: none; + } + .ar-fnav-lead { + flex: 1; + } + .ar-fnav-more { + display: inline-grid; + margin-left: auto; + } +} + +/* Comments */ +.ar-panel { + position: absolute; + top: 12px; + right: 12px; + bottom: 12px; + z-index: 24; + display: grid; + grid-template-rows: auto minmax(0, 1fr); + width: 360px; + overflow: hidden; + border: 1px solid var(--ui-line); + border-radius: 14px; + background: var(--ui-panel); + box-shadow: 0 2px 12px color-mix(in srgb, black 14%, transparent); +} +.ar-panel-head { + display: flex; + align-items: center; + gap: 8px; + padding: 8px 8px 8px 14px; + border-bottom: 1px solid var(--ui-line); +} +.ar-panel-head h2 { + margin: 0; + font-size: 14px; + font-weight: 600; +} +.ar-panel-body { + display: grid; + align-content: start; + gap: 12px; + padding: 12px; + overflow: auto; +} +.ar-panel-pill { + position: absolute; + top: 12px; + right: 12px; + z-index: 24; + display: inline-flex; + align-items: center; + gap: 6px; + height: 40px; + padding: 0 14px; + border: 1px solid var(--ui-line); + border-radius: 20px; + background: var(--ui-panel); + box-shadow: 0 2px 12px color-mix(in srgb, black 14%, transparent); + color: var(--ui-ink); + cursor: pointer; +} +.ar-panel-count { + font-variant-numeric: tabular-nums; + font-weight: 600; +} +.ar-panel-dot { + background: var(--ui-sev-ok); +} +@media (pointer: coarse) { + .ar-panel-pill { + min-height: 44px; + } +} +/* A narrow screen: the card is a bottom sheet, and its pill sits above the tools. */ +@media (max-width: 900px) { + .ar-panel { + top: auto; + right: 8px; + bottom: 8px; + left: 8px; + width: auto; + height: min(55dvh, 520px); + } + .ar-panel-pill { + top: auto; + right: auto; + bottom: 130px; + left: 10px; + } +} diff --git a/packages/artifacts/src/client/styles/viewers.css b/packages/artifacts/src/client/styles/viewers.css index ff6de06cad..894caef28a 100644 --- a/packages/artifacts/src/client/styles/viewers.css +++ b/packages/artifacts/src/client/styles/viewers.css @@ -1,28 +1,8 @@ /* ── Focused view layout ─────────────────────────────────────────────────── */ .ar-focus { - display: grid; - grid-template-rows: auto 1fr; - height: calc(100dvh - var(--ar-top)); - min-height: 0; -} -.ar-focus-head { - display: flex; - flex-wrap: wrap; - align-items: center; - justify-content: space-between; - gap: 8px 16px; - padding: 8px 16px; - border-bottom: 1px solid var(--ui-line); -} -.ar-focus-title h1 { - font-size: 16px; - font-weight: 600; -} -.ar-crumbs { - font-size: 12px; -} -.ar-crumbs a { - color: var(--ui-muted); + position: relative; + height: 100dvh; + overflow: hidden; } .ar-focus-meta { display: flex; @@ -37,42 +17,23 @@ text-overflow: ellipsis; white-space: nowrap; } -.ar-focus-tools { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: 8px; -} -.ar-select { - display: inline-flex; - align-items: center; - gap: 6px; - color: var(--ui-muted); - font-size: 12.5px; -} -.ar-select select { - height: 28px; - padding: 0 8px; - border: 1px solid var(--ui-btn-edge); - border-radius: 6px; - background: var(--ui-panel); - color: var(--ui-ink); -} -.ar-focus-body { - display: grid; - grid-template-columns: minmax(0, 1fr) 360px; - min-height: 0; -} +/* The viewer fills the page; an open comments panel takes the strip on its right. */ .ar-viewer-pane { - position: relative; + position: absolute; + inset: 0; + right: var(--ar-inset-right, 0px); min-width: 0; min-height: 0; overflow: hidden; background: var(--ui-track); } +/* The viewer tools pill sits at the bottom centre of what the panel leaves. */ +.ar-focus-tools { + left: calc((100% - var(--ar-inset-right, 0px)) / 2); +} .ar-mode-hint { position: absolute; - bottom: 12px; + bottom: 74px; left: 50%; z-index: 20; padding: 6px 12px; @@ -83,18 +44,6 @@ transform: translateX(-50%); pointer-events: none; } -@media (max-width: 900px) { - .ar-focus { - height: auto; - } - .ar-focus-body { - grid-template-columns: 1fr; - } - .ar-viewer-pane { - height: 70dvh; - } -} - /* ── Stage ───────────────────────────────────────────────────────────────── */ .ar-stage { position: relative; @@ -111,9 +60,9 @@ } /* - * Pins: constant size, never scaled with the content. A pin is a 26 x 30 - * speech bubble whose tail tip is the anchor, so the box is shifted left and - * up by the tip's position (see lib/pin-shape.ts). + * Pins: constant size, never scaled with the content. A pin is lucide's + * MessageCircle at 28 px; its box is shifted by the tail tip's position inline + * (see lib/pin-shape.ts) so the tip, not the corner, is on the anchor. */ .ar-pins { position: absolute; @@ -125,9 +74,9 @@ position: absolute; display: grid; place-items: center; - width: 26px; - height: 30px; - padding: 0 0 8px; + width: 28px; + height: 28px; + padding: 0; border: 0; background: none; color: var(--ar-pin-ink); @@ -135,7 +84,6 @@ font-weight: 700; line-height: 1; filter: drop-shadow(0 1px 2px color-mix(in srgb, black 40%, transparent)); - transform: translate(-1px, -30px); pointer-events: auto; cursor: pointer; } @@ -151,6 +99,7 @@ stroke: var(--ui-panel); stroke-width: 1.5; stroke-linejoin: round; + stroke-linecap: round; } .ar-pin-n { position: relative; diff --git a/packages/artifacts/src/client/viewers/pin-bubble.tsx b/packages/artifacts/src/client/viewers/pin-bubble.tsx index 1d21b8e67e..5e8a7e64ec 100644 --- a/packages/artifacts/src/client/viewers/pin-bubble.tsx +++ b/packages/artifacts/src/client/viewers/pin-bubble.tsx @@ -1,10 +1,9 @@ -import { PIN_PATH } from "#client/lib/pin-shape.ts"; +import { ICON_PATH, PIN_TIP } from "#client/lib/pin-shape.ts"; /** - * One comment pin: a speech bubble with the thread number (or a count) inside + * One comment pin: the MessageCircle glyph with the thread number (or a count) inside * and its tail tip on the anchor. Filled for a thread on the version shown, - * hollow for another version, dashed when the position is approximate. The box - * is 26 x 30 and CSS translates it so the tail tip sits at `left`/`top`. + * hollow for another version, dashed when the position is approximate. It is lucide's MessageCircle at 28 px; the box is translated so the tail tip sits at `left`/`top`. */ export function PinBubble({ label, @@ -37,14 +36,18 @@ export function PinBubble({ data-resolved={resolved} data-approximate={approximate} data-board-pin={boardPin} - style={style} + style={{ + ...style, + // The tail tip, not the box's corner, is on the anchor. + transform: `translate(${String(-PIN_TIP.x)}px, ${String(-PIN_TIP.y)}px)`, + }} aria-pressed={selected} aria-label={label} title={approximate ? "Approximate position" : undefined} onClick={onClick} > - {text}