diff --git a/packages/artifacts/README.md b/packages/artifacts/README.md index 73ad228b68..ca3371a766 100644 --- a/packages/artifacts/README.md +++ b/packages/artifacts/README.md @@ -167,6 +167,36 @@ 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 +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..884f59ef8c --- /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: 140, 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/e2e/canvas-helpers.ts b/packages/artifacts/e2e/canvas-helpers.ts new file mode 100644 index 0000000000..f3a81379da --- /dev/null +++ b/packages/artifacts/e2e/canvas-helpers.ts @@ -0,0 +1,67 @@ +import { expect, type Page } from "@playwright/test"; + +export const SETTLE_MS = 450; + +export type Camera = { x: number; y: number; s: number }; + +export async function camera(page: Page): Promise { + return page.getByTestId("canvas-world").evaluate((element) => { + const match = + /translate\((?[\d.e+-]+)px, (?[\d.e+-]+)px\) scale\((?[\d.e+-]+)\)/u.exec( + element instanceof HTMLElement ? element.style.transform : "", + ); + const groups = match?.groups; + return { + x: Number(groups?.["x"]), + y: Number(groups?.["y"]), + s: Number(groups?.["s"]), + }; + }); +} + +export async function zoomOf(page: Page): Promise { + const { s } = await camera(page); + return s; +} + +export async function cameraOf(page: Page): Promise { + return camera(page); +} + +export async function viewportBox(page: Page) { + const box = await page.getByTestId("canvas-viewport").boundingBox(); + if (box === null) throw new Error("the canvas has no box"); + return box; +} + +/** Dispatches a wheel event on the viewport (Playwright's mouse cannot set both modifiers and integer points). */ +export async function wheel( + page: Page, + init: { dx?: number; dy?: number; ctrl?: boolean; x: number; y: number }, +): Promise { + await page.getByTestId("canvas-viewport").evaluate((element, value) => { + element.dispatchEvent( + new WheelEvent("wheel", { + deltaX: value.dx ?? 0, + deltaY: value.dy ?? 0, + ctrlKey: value.ctrl ?? false, + clientX: value.x, + clientY: value.y, + bubbles: true, + cancelable: true, + }), + ); + }, init); +} + +export async function openBoard(page: Page, slug: string): Promise { + await page.goto(`/b/${slug}`); + await expect(page.getByTestId("canvas-viewport")).toBeVisible(); + await expect(page.getByTestId("canvas-frame").first()).toBeVisible(); + // The first view fits every frame. + await page.waitForTimeout(SETTLE_MS); +} + +export function frame(page: Page, artifactId: string) { + return page.locator(`[data-frame-id="${artifactId}"]`); +} diff --git a/packages/artifacts/e2e/canvas.desktop.spec.ts b/packages/artifacts/e2e/canvas.desktop.spec.ts index 27dada7fab..e1b0aa1b2d 100644 --- a/packages/artifacts/e2e/canvas.desktop.spec.ts +++ b/packages/artifacts/e2e/canvas.desktop.spec.ts @@ -1,5 +1,15 @@ -import { expect, test, type Page } from "@playwright/test"; +import { expect, test } from "@playwright/test"; import { agentApi, resetAndSeed, sharedFixtures } from "./review-setup.ts"; +import { + SETTLE_MS, + camera, + cameraOf, + frame, + openBoard, + viewportBox, + wheel, + zoomOf, +} from "./canvas-helpers.ts"; import { publishFixture, type SeededBoards } from "./seed.ts"; let seeded: SeededBoards; @@ -9,72 +19,6 @@ test.beforeAll(async ({ baseURL }) => { seeded = await resetAndSeed(baseURL); }); -const SETTLE_MS = 450; - -type Camera = { x: number; y: number; s: number }; - -async function camera(page: Page): Promise { - return page.getByTestId("canvas-world").evaluate((element) => { - const match = - /translate\((?[\d.e+-]+)px, (?[\d.e+-]+)px\) scale\((?[\d.e+-]+)\)/u.exec( - element instanceof HTMLElement ? element.style.transform : "", - ); - const groups = match?.groups; - return { - x: Number(groups?.["x"]), - y: Number(groups?.["y"]), - s: Number(groups?.["s"]), - }; - }); -} - -async function zoomOf(page: Page): Promise { - const { s } = await camera(page); - return s; -} - -async function cameraOf(page: Page): Promise { - return camera(page); -} - -async function viewportBox(page: Page) { - const box = await page.getByTestId("canvas-viewport").boundingBox(); - if (box === null) throw new Error("the canvas has no box"); - return box; -} - -/** Dispatches a wheel event on the viewport (Playwright's mouse cannot set both modifiers and integer points). */ -async function wheel( - page: Page, - init: { dx?: number; dy?: number; ctrl?: boolean; x: number; y: number }, -): Promise { - await page.getByTestId("canvas-viewport").evaluate((element, value) => { - element.dispatchEvent( - new WheelEvent("wheel", { - deltaX: value.dx ?? 0, - deltaY: value.dy ?? 0, - ctrlKey: value.ctrl ?? false, - clientX: value.x, - clientY: value.y, - bubbles: true, - cancelable: true, - }), - ); - }, init); -} - -async function openBoard(page: Page, slug: string): Promise { - await page.goto(`/b/${slug}`); - await expect(page.getByTestId("canvas-viewport")).toBeVisible(); - await expect(page.getByTestId("canvas-frame").first()).toBeVisible(); - // The first view fits every frame. - await page.waitForTimeout(SETTLE_MS); -} - -function frame(page: Page, artifactId: string) { - return page.locator(`[data-frame-id="${artifactId}"]`); -} - test.describe("canvas", () => { test("lays frames out from the index and fits them all on first open", async ({ page, @@ -175,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"); @@ -240,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); }); @@ -323,88 +290,6 @@ test.describe("canvas", () => { expect(documents.length).toBe(loaded + 1); }); - test("a board pin is placed on empty canvas, round-trips, and stays glued while panning", async ({ - page, - baseURL, - }) => { - await openBoard(page, "demo"); - await page.keyboard.press("c"); - await expect(page.getByTestId("comment-mode")).toHaveAttribute( - "aria-pressed", - "true", - ); - const view = await viewportBox(page); - const at = { x: view.x + 120, y: view.y + 120 }; - await page.mouse.click(at.x, at.y); - const composer = page.getByTestId("placement-composer"); - await expect(composer).toBeVisible(); - await composer.getByRole("textbox").fill("The spacing here is off"); - await composer.getByRole("button", { name: "Comment" }).click(); - await expect(composer).toBeHidden(); - const pin = page.getByTestId("pin"); - await expect(pin).toHaveCount(1); - const pinBox = await pin.boundingBox(); - if (pinBox === null) throw new Error("no pin box"); - // The pin's tip is where the click was. - expect(Math.abs(pinBox.x + 2 - at.x)).toBeLessThan(3); - expect(Math.abs(pinBox.y + pinBox.height - at.y)).toBeLessThan(3); - - const claim = await agentApi(baseURL).feedback.claim.mutate({ - scope: { type: "board", board: "demo" }, - }); - const anchor = claim.items.at(-1)?.thread.anchor; - expect(anchor?.type).toBe("board"); - - // Panning moves the pin with the world, by exactly the delta. - await wheel(page, { dx: -60, dy: -25, x: 400, y: 400 }); - await page.waitForTimeout(40); - await expect - .poll(async () => { - const box = await pin.boundingBox(); - return box?.x ?? 0; - }) - .toBeCloseTo(pinBox.x + 60, 0); - - // And it is still where it was after a reload (the camera is restored too). - await page.waitForTimeout(SETTLE_MS); - const moved = await pin.boundingBox(); - await page.reload(); - await expect(page.getByTestId("pin")).toHaveCount(1); - await page.waitForTimeout(SETTLE_MS); - const restored = await page.getByTestId("pin").boundingBox(); - expect(Math.abs((restored?.x ?? 0) - (moved?.x ?? 0))).toBeLessThan(1.5); - expect(Math.abs((restored?.y ?? 0) - (moved?.y ?? 0))).toBeLessThan(1.5); - }); - - test("a frame pin is placed on a frame and follows it", async ({ page }) => { - await openBoard(page, "concepts"); - await page.getByRole("button", { name: /^Concept A,/u }).click(); - await page.keyboard.press("2"); - await page.waitForTimeout(SETTLE_MS); - await page.keyboard.press("c"); - const target = frame(page, seeded.concepts[0]?.artifactId ?? ""); - const box = await target.boundingBox(); - if (box === null) throw new Error("no frame box"); - await page.mouse.click(box.x + box.width * 0.5, box.y + box.height * 0.5); - const composer = page.getByTestId("placement-composer"); - await expect(composer).toBeVisible(); - await composer.getByRole("textbox").fill("Heading is too small"); - await composer.getByRole("button", { name: "Comment" }).click(); - await expect(composer).toBeHidden(); - const pin = page.getByTestId("pin"); - await expect(pin).toHaveCount(1); - await expect(page.getByTestId("thread")).toContainText("Concept A"); - const first = await pin.boundingBox(); - const frameBefore = await target.boundingBox(); - if (first === null || frameBefore === null) throw new Error("no boxes"); - await wheel(page, { dx: -90, dy: 0, x: 300, y: 300 }); - await page.waitForTimeout(SETTLE_MS); - const frameAfter = await target.boundingBox(); - const second = await pin.boundingBox(); - if (second === null || frameAfter === null) throw new Error("no boxes"); - expect(second.x - first.x).toBeCloseTo(frameAfter.x - frameBefore.x, 0); - }); - test("reduced motion leaves nothing animating on the canvas", async ({ page, }) => { diff --git a/packages/artifacts/e2e/comment.desktop.spec.ts b/packages/artifacts/e2e/comment.desktop.spec.ts new file mode 100644 index 0000000000..f17095416d --- /dev/null +++ b/packages/artifacts/e2e/comment.desktop.spec.ts @@ -0,0 +1,142 @@ +import { expect, test } from "@playwright/test"; +import { + SETTLE_MS, + frame, + openBoard, + viewportBox, + 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; + +test.beforeAll(async ({ baseURL }) => { + test.setTimeout(120_000); + seeded = await resetAndSeed(baseURL); +}); + +test.describe("comments on the canvas", () => { + test("a board pin is placed on empty canvas, round-trips, and stays glued while panning", async ({ + page, + baseURL, + }) => { + await openBoard(page, "demo"); + await page.keyboard.press("c"); + await expect(page.getByTestId("comment-mode")).toHaveAttribute( + "aria-pressed", + "true", + ); + const view = await viewportBox(page); + const at = { x: view.x + 120, y: view.y + 120 }; + await page.mouse.click(at.x, at.y); + const composer = page.getByTestId("placement-composer"); + await expect(composer).toBeVisible(); + await composer.getByRole("textbox").fill("The spacing here is off"); + await composer.getByRole("button", { name: "Comment" }).click(); + await expect(composer).toBeHidden(); + const pin = page.getByTestId("pin"); + await expect(pin).toHaveCount(1); + 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 + 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" }, + }); + const anchor = claim.items.at(-1)?.thread.anchor; + expect(anchor?.type).toBe("board"); + + // Panning moves the pin with the world, by exactly the delta. + await wheel(page, { dx: -60, dy: -25, x: 400, y: 400 }); + await page.waitForTimeout(40); + await expect + .poll(async () => { + const box = await pin.boundingBox(); + return box?.x ?? 0; + }) + .toBeCloseTo(pinBox.x + 60, 0); + + // And it is still where it was after a reload (the camera is restored too). + await page.waitForTimeout(SETTLE_MS); + const moved = await pin.boundingBox(); + await page.reload(); + await expect(page.getByTestId("pin")).toHaveCount(1); + await page.waitForTimeout(SETTLE_MS); + const restored = await page.getByTestId("pin").boundingBox(); + expect(Math.abs((restored?.x ?? 0) - (moved?.x ?? 0))).toBeLessThan(1.5); + expect(Math.abs((restored?.y ?? 0) - (moved?.y ?? 0))).toBeLessThan(1.5); + }); + + test("a frame pin is placed on a frame and follows it", async ({ page }) => { + await openBoard(page, "concepts"); + await page.getByRole("button", { name: /^Concept A,/u }).click(); + await page.keyboard.press("2"); + await page.waitForTimeout(SETTLE_MS); + await page.keyboard.press("c"); + const target = frame(page, seeded.concepts[0]?.artifactId ?? ""); + const box = await target.boundingBox(); + if (box === null) throw new Error("no frame box"); + await page.mouse.click(box.x + box.width * 0.5, box.y + box.height * 0.5); + const composer = page.getByTestId("placement-composer"); + await expect(composer).toBeVisible(); + await composer.getByRole("textbox").fill("Heading is too small"); + await composer.getByRole("button", { name: "Comment" }).click(); + await expect(composer).toBeHidden(); + const pin = page.getByTestId("pin"); + await expect(pin).toHaveCount(1); + await expect(page.getByTestId("thread")).toContainText("Concept A"); + const first = await pin.boundingBox(); + const frameBefore = await target.boundingBox(); + if (first === null || frameBefore === null) throw new Error("no boxes"); + await wheel(page, { dx: -90, dy: 0, x: 300, y: 300 }); + await page.waitForTimeout(SETTLE_MS); + const frameAfter = await target.boundingBox(); + const second = await pin.boundingBox(); + if (second === null || frameAfter === null) throw new Error("no boxes"); + expect(second.x - first.x).toBeCloseTo(frameAfter.x - frameBefore.x, 0); + }); + + test("comment mode shows the MessageCircle cursor on the canvas and in the focused view", async ({ + page, + }) => { + const cursorOf = (selector: string) => + page + .locator(selector) + .first() + .evaluate((element) => getComputedStyle(element).cursor); + await openBoard(page, "concepts"); + expect(await cursorOf('[data-testid="canvas-viewport"]')).not.toContain( + "url(", + ); + await page.keyboard.press("c"); + await expect(page.getByTestId("comment-mode")).toHaveAttribute( + "aria-pressed", + "true", + ); + // Over the world and a frame the bubble; over the toolbar the normal cursor. + expect(await cursorOf('[data-testid="canvas-viewport"]')).toContain("url("); + expect(await cursorOf('[data-testid="canvas-frame"]')).toContain("url("); + expect(await cursorOf('[role="toolbar"]')).not.toContain("url("); + await page.keyboard.press("Escape"); + expect(await cursorOf('[data-testid="canvas-viewport"]')).not.toContain( + "url(", + ); + + await openFocused(page, seeded.demo.htmlV2.artifactId); + expect(await cursorOf(".ar-stage")).not.toContain("url("); + await page.keyboard.press("c"); + await expect(page.getByTestId("comment-mode")).toHaveAttribute( + "aria-pressed", + "true", + ); + expect(await cursorOf(".ar-stage")).toContain("url("); + // The overlay over the inert frame carries it: iframe content cannot. + expect(await cursorOf('[data-testid="comment-catcher"]')).toContain("url("); + await page.keyboard.press("Escape"); + expect(await cursorOf(".ar-stage")).not.toContain("url("); + }); +}); 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/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/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 ( +
Nothing on this board yet.

) : null} + {arrange.status === "idle" ? null : ( +

+ {SAVE_TEXT[arrange.status]} +

+ )} + +

+ {arrange.announcement} +

{placement === null ? null : ( ) : null} + { + setConfirmRemove(false); + }} + onConfirm={() => { + arrange.remove(); + setConfirmRemove(false); + }} + /> ); } diff --git a/packages/artifacts/src/client/canvas/gestures.ts b/packages/artifacts/src/client/canvas/gestures.ts index 71c4c356ba..8db40df761 100644 --- a/packages/artifacts/src/client/canvas/gestures.ts +++ b/packages/artifacts/src/client/canvas/gestures.ts @@ -34,6 +34,26 @@ export type Tap = { readonly shiftKey: boolean; }; +/** + * A drag the page runs once a press has moved past the threshold: moving + * frames, a marquee. The gesture layer feeds it pointer positions and ends it. + */ +export type PointerSession = { + readonly move: ( + point: Point, + modifiers: { readonly altKey: boolean }, + ) => void; + readonly end: (cancelled: boolean) => void; +}; + +export type SessionStart = { + /** The frame under the pointer when it went down, or null on empty canvas. */ + readonly frameId: string | null; + /** Viewport-relative. */ + readonly point: Point; + readonly shiftKey: boolean; +}; + export type GestureDeps = { readonly viewport: HTMLElement; readonly blanket: HTMLElement; @@ -42,6 +62,11 @@ export type GestureDeps = { readonly spaceHeld: () => boolean; readonly onTap: (tap: Tap) => void; readonly onDoubleTap: (frameId: string) => void; + /** + * A mouse press with the select tool; the session it returns takes over + * from panning once the pointer moves 4 px. Null pans (or taps) instead. + */ + readonly beginSession?: (start: SessionStart) => PointerSession | null; }; /** A pointer must move this far before a press becomes a drag. */ @@ -50,6 +75,7 @@ const DOUBLE_TAP_MS = 350; const DOUBLE_TAP_DISTANCE_PX = 12; type Tracked = { + session?: PointerSession | null; point: Point; readonly down: Point; readonly frameId: string | null; @@ -84,6 +110,7 @@ export function attachGestures(deps: GestureDeps): () => void { const pointers = new Map(); const pinch = createPinch(); let pan: Pan | null = null; + let session: PointerSession | null = null; let dragged = false; let lastTap: { frameId: string; at: number; point: Point } | null = null; @@ -115,6 +142,23 @@ export function attachGestures(deps: GestureDeps): () => void { return a === undefined || b === undefined ? null : [a.point, b.point]; } + /** A mouse press with the select tool may become the page's own drag. */ + function startSession(event: PointerEvent, point: Point): void { + const tracked = pointers.get(event.pointerId); + const wanted = + event.pointerType === "mouse" && + event.button === 0 && + deps.tool() === "select" && + !deps.spaceHeld(); + if (tracked === undefined || !wanted) return; + tracked.session = + deps.beginSession?.({ + frameId: tracked.frameId, + point, + shiftKey: event.shiftKey, + }) ?? null; + } + function onPointerDown(event: PointerEvent): void { if (inIgnored(event.target)) return; if (event.pointerType === "mouse" && event.button > 1) return; @@ -129,6 +173,7 @@ export function attachGestures(deps: GestureDeps): () => void { }); if (pointers.size === 1) { dragged = false; + startSession(event, point); const immediate = event.button === 1 || (event.pointerType === "mouse" && @@ -160,6 +205,10 @@ export function attachGestures(deps: GestureDeps): () => void { if (next !== null) controller.moveTo(next, "zoom"); return; } + if (session !== null) { + session.move(tracked.point, { altKey: event.altKey }); + return; + } if (pan === null) { const moved = Math.hypot( tracked.point.x - tracked.down.x, @@ -167,6 +216,14 @@ export function attachGestures(deps: GestureDeps): () => void { ); if (moved < DRAG_THRESHOLD_PX) return; capture(event.pointerId); + if (tracked.session !== undefined && tracked.session !== null) { + // The page's drag (move frames, marquee) takes over from panning. + session = tracked.session; + dragged = true; + showBlanket(true); + session.move(tracked.point, { altKey: event.altKey }); + return; + } beginPan(tracked.down); } if (pan === null) return; @@ -197,9 +254,13 @@ export function attachGestures(deps: GestureDeps): () => void { pinch.endPointers(); showBlanket(false); const wasDrag = dragged; + const cancelled = event.type === "pointercancel"; + // A press that never moved still owns a session that must clean up. + (session ?? tracked.session)?.end(cancelled || !wasDrag); + session = null; pan = null; dragged = false; - if (wasDrag || event.type === "pointercancel") return; + if (wasDrag || cancelled) return; tap(tracked, event.type === "pointerup"); } diff --git a/packages/artifacts/src/client/canvas/model.ts b/packages/artifacts/src/client/canvas/model.ts index 1cc53bc4d6..d5087a51be 100644 --- a/packages/artifacts/src/client/canvas/model.ts +++ b/packages/artifacts/src/client/canvas/model.ts @@ -2,12 +2,11 @@ * What the canvas draws, derived from one `boards.get` answer and the board's * threads. Pure, so reading order and pin selection are testable. */ -import type { Anchor } from "@shepherdjerred/artifacts/contract"; +import type { Anchor, BoardIndex } from "@shepherdjerred/artifacts/contract"; import type { ArtifactSummary, ThreadView, } from "@shepherdjerred/artifacts/procedures"; -import type { BoardData } from "#client/data/api.ts"; import { isOtherVersion, isPlaced } from "#client/lib/pins.ts"; import type { WorldRect } from "./camera.ts"; @@ -27,7 +26,10 @@ export const CANVAS_PAGE = 0; * artifacts). The order must not change when a frame moves: the iframes are * rendered from this list, and moving an iframe in the DOM reloads it. */ -export function frameModels(data: BoardData): CanvasFrameModel[] { +export function frameModels(data: { + readonly index: Pick; + readonly artifacts: readonly ArtifactSummary[]; +}): CanvasFrameModel[] { const { index, artifacts } = data; const stacking = new Map(index.order.map((id, position) => [id, position])); return artifacts.flatMap((summary) => { @@ -122,3 +124,35 @@ export function canvasPins( ]; }); } + +/** + * Width over height a resize keeps: the design viewport a frame was published + * at, for kinds that render in a fixed viewport. Responsive frames and the + * other kinds resize freely. + */ +export function fixedAspect(summary: ArtifactSummary): number | null { + const viewport = summary.currentVersion?.viewport ?? null; + const framed = + summary.kind === "html" || + summary.kind === "site" || + summary.kind === "mermaid"; + return framed && viewport !== null ? viewport.width / viewport.height : null; +} + +/** + * The frames with a drag or resize in progress drawn at its live rectangle. + * The draft is not part of the document: a change from elsewhere (an agent + * publishing a frame) arrives underneath it and never disturbs the drag. + */ +export function applyDraft< + T extends { readonly id: string; readonly rect: WorldRect }, +>( + models: readonly T[], + draft: ReadonlyMap | null, +): readonly T[] { + if (draft === null) return models; + return models.map((model) => { + const rect = draft.get(model.id); + return rect === undefined ? model : { ...model, rect }; + }); +} diff --git a/packages/artifacts/src/client/canvas/pins-layer.tsx b/packages/artifacts/src/client/canvas/pins-layer.tsx index 3be46ee020..82e18c627d 100644 --- a/packages/artifacts/src/client/canvas/pins-layer.tsx +++ b/packages/artifacts/src/client/canvas/pins-layer.tsx @@ -10,6 +10,7 @@ import { useCallback, useLayoutEffect, useRef, useState } from "react"; import { clusterPins } from "#client/lib/cluster.ts"; import type { Point } from "#client/lib/geometry.ts"; import { describePin } from "#client/viewers/pins-overlay.tsx"; +import { PinBubble } from "#client/viewers/pin-bubble.tsx"; import type { AnchorAdapter } from "#client/viewers/types.ts"; import { screenToWorld, @@ -142,29 +143,23 @@ function PinMarker({ : first; return (
- + />
); } diff --git a/packages/artifacts/src/client/canvas/toolbar.tsx b/packages/artifacts/src/client/canvas/toolbar.tsx index 86cb20e99b..2a85ac50d1 100644 --- a/packages/artifacts/src/client/canvas/toolbar.tsx +++ b/packages/artifacts/src/client/canvas/toolbar.tsx @@ -1,15 +1,20 @@ import { HandIcon, - MessageSquarePlusIcon, + MaximizeIcon, + MessageCircleIcon, MinusIcon, + MousePointer2Icon, PlusIcon, ScanIcon, - ShrinkIcon, + type LucideIcon, } from "lucide-react"; import { useEffect, useRef } from "react"; import type { CameraController } from "./controller.ts"; import type { Tool } from "./gestures.ts"; +const ICON_STROKE = 1.5; +const ICON_SIZE = 20; + /** The zoom readout follows the camera without a render per frame. */ function ZoomReadout({ controller, @@ -41,39 +46,101 @@ function ZoomReadout({ ); } -export function CanvasToolbar({ +export type ToolButton = { + readonly id: string; + readonly label: string; + readonly shortcut: string; + readonly Icon: LucideIcon; + readonly active: boolean; + readonly onPress: () => 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-camera.ts b/packages/artifacts/src/client/canvas/use-camera.ts index 799f4760d4..c2797c950e 100644 --- a/packages/artifacts/src/client/canvas/use-camera.ts +++ b/packages/artifacts/src/client/canvas/use-camera.ts @@ -78,7 +78,8 @@ export type CanvasCamera = { export function useCanvasCamera( slug: string, frames: readonly CanvasFrameModel[], - selected: CanvasFrameModel | undefined, + 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(() => { @@ -148,14 +158,15 @@ export function useCanvasCamera( }, [size.width, frames.length, fitAll]); const fitSelection = useCallback(() => { - if (selected === undefined || sizeRef.current.width === 0) return; + const bounds = boundsOf(selected.map((frame) => frame.rect)); + if (bounds === null || sizeRef.current.width === 0) return; move( - fitRect(selected.rect, sizeRef.current, { + fitRect(bounds, usable(), { padding: FIT_PADDING, maxScale: FIT_SELECTION_MAX_SCALE, }), ); - }, [selected, move]); + }, [selected, move, usable]); const viewportCentre = useCallback( (): Point => ({ @@ -191,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/canvas/use-canvas-keys.ts b/packages/artifacts/src/client/canvas/use-canvas-keys.ts new file mode 100644 index 0000000000..353c59cd4f --- /dev/null +++ b/packages/artifacts/src/client/canvas/use-canvas-keys.ts @@ -0,0 +1,79 @@ +import { useNavigate } from "react-router"; +import { useShortcuts } from "#client/shell/shortcuts.ts"; +import type { CanvasCamera } from "./use-camera.ts"; +import { ZOOM_STEP } from "./use-camera.ts"; +import type { Tool } from "./gestures.ts"; + +type Keys = { + readonly camera: CanvasCamera; + /** The one selected frame, if exactly one is. */ + readonly onlyId: string | null; + readonly placing: boolean; + readonly activeId: string | null; + readonly commentMode: boolean; + readonly tool: Tool; + readonly selectTool: () => void; + readonly toggleHand: () => void; + readonly toggleComment: () => void; + readonly activate: (id: string) => void; + readonly cancelPlacement: () => void; + readonly deactivate: () => void; + readonly leaveComment: () => void; + readonly clearSelection: () => void; +}; + +/** 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; + useShortcuts([ + { key: "1", run: camera.fitAll }, + { key: "2", run: camera.fitSelection }, + { key: "0", run: camera.reset }, + { + key: "=", + run: () => { + camera.zoomBy(ZOOM_STEP); + }, + }, + { + key: "+", + run: () => { + camera.zoomBy(ZOOM_STEP); + }, + }, + { + key: "-", + run: () => { + camera.zoomBy(1 / ZOOM_STEP); + }, + }, + { key: "v", run: keys.selectTool }, + { key: "h", run: keys.toggleHand }, + { key: "c", run: keys.toggleComment }, + { + key: "f", + run: () => { + if (keys.onlyId !== null) void navigate(`/a/${keys.onlyId}`); + }, + }, + { + key: "Enter", + run: (event) => { + if (keys.onlyId === null) return; + event.preventDefault(); + keys.activate(keys.onlyId); + }, + }, + { + key: "Escape", + run: () => { + if (keys.placing) keys.cancelPlacement(); + else if (keys.activeId !== null) keys.deactivate(); + else if (keys.commentMode) keys.leaveComment(); + else if (keys.tool === "hand") keys.selectTool(); + else keys.clearSelection(); + }, + }, + ]); +} diff --git a/packages/artifacts/src/client/canvas/use-input.ts b/packages/artifacts/src/client/canvas/use-input.ts index 3ee4b9a9da..d31f696a6c 100644 --- a/packages/artifacts/src/client/canvas/use-input.ts +++ b/packages/artifacts/src/client/canvas/use-input.ts @@ -2,7 +2,13 @@ import { useCallback, useEffect, useRef } from "react"; import type { HostInput } from "#client/viewers/types.ts"; import { panBy, wheelZoomFactor, zoomAt } from "./camera.ts"; import type { CameraController } from "./controller.ts"; -import { attachGestures, type Tap, type Tool } from "./gestures.ts"; +import { + attachGestures, + type SessionStart, + type PointerSession, + type Tap, + type Tool, +} from "./gestures.ts"; import { createForwardedGestures } from "./pinch.ts"; /** Elements where Space is a character or a click, not the pan modifier. */ @@ -21,6 +27,7 @@ export function useCanvasInput({ tool, onTap, onDoubleTap, + beginSession, }: { readonly controller: CameraController; readonly viewport: HTMLElement | null; @@ -28,12 +35,13 @@ export function useCanvasInput({ readonly tool: Tool; readonly onTap: (tap: Tap) => void; readonly onDoubleTap: (frameId: string) => void; + readonly beginSession: (start: SessionStart) => PointerSession | null; }): (input: HostInput) => void { const toolRef = useRef(tool); toolRef.current = tool; const spaceHeld = useRef(false); - const handlers = useRef({ onTap, onDoubleTap }); - handlers.current = { onTap, onDoubleTap }; + const handlers = useRef({ onTap, onDoubleTap, beginSession }); + handlers.current = { onTap, onDoubleTap, beginSession }; useEffect(() => { if (viewport === null || blanket === null) return; @@ -49,6 +57,7 @@ export function useCanvasInput({ onDoubleTap: (id) => { handlers.current.onDoubleTap(id); }, + beginSession: (start) => handlers.current.beginSession(start), }); }, [viewport, blanket, controller]); 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/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 new file mode 100644 index 0000000000..12241b78a8 --- /dev/null +++ b/packages/artifacts/src/client/lib/pin-shape.test.ts @@ -0,0 +1,87 @@ +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_SIZE, + PIN_TIP, + PIN_WIDTH, + pinAnchor, + pinOrigin, +} from "./pin-shape.ts"; + +/** 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 }, + { x: 312.4, y: 87.9 }, + { x: -50, y: 1200 }, + ]) { + const origin = pinOrigin(anchor); + const tip = pinAnchor(origin); + expect(Math.abs(tip.x - anchor.x)).toBeLessThan(1e-9); + expect(Math.abs(tip.y - anchor.y)).toBeLessThan(1e-9); + expect(origin.x + PIN_TIP.x).toBeCloseTo(anchor.x, 9); + expect(origin.y + PIN_TIP.y).toBeCloseTo(anchor.y, 9); + } + }); + + 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("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 new file mode 100644 index 0000000000..a08237db3c --- /dev/null +++ b/packages/artifacts/src/client/lib/pin-shape.ts @@ -0,0 +1,81 @@ +/** + * 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"; + +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 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 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 { + return { x: anchor.x - PIN_TIP.x, y: anchor.y - PIN_TIP.y }; +} + +/** The anchor a pin whose top-left corner is at `origin` points at. */ +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 690ddec42d..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/dialog.tsx b/packages/artifacts/src/client/shell/dialog.tsx index fe977be177..b6fcfb597a 100644 --- a/packages/artifacts/src/client/shell/dialog.tsx +++ b/packages/artifacts/src/client/shell/dialog.tsx @@ -17,12 +17,18 @@ export function Dialog({ }): React.JSX.Element { const ref = useRef(null); const titleId = useId(); + // Closing from here fires a native `close` event later; it must not close a + // dialog that was opened again in between. + const closedByUs = useRef(false); useEffect(() => { const dialog = ref.current; if (dialog === null) return; if (open && !dialog.open) dialog.showModal(); - if (!open && dialog.open) dialog.close(); + if (!open && dialog.open) { + closedByUs.current = true; + dialog.close(); + } }, [open]); return ( @@ -30,7 +36,13 @@ export function Dialog({ ref={ref} className="ar-dialog" aria-labelledby={titleId} - onClose={onClose} + onClose={() => { + if (closedByUs.current) { + closedByUs.current = false; + return; + } + onClose(); + }} onClick={(event) => { if (event.target === event.currentTarget) onClose(); }} 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 7ed0fdcf1a..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) => @@ -93,9 +103,14 @@ 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" }, + { 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" }, @@ -103,6 +118,6 @@ export const SHORTCUT_SHEET: readonly { { keys: "J / K", does: "Next and previous thread" }, { keys: "R", does: "Reply to the selected thread" }, { keys: "E", does: "Resolve or reopen the selected thread" }, - { keys: "[ / ]", does: "Previous and next version" }, + { keys: "[ / ]", does: "Focused view: previous and next version" }, { keys: "?", does: "This sheet" }, ]; diff --git a/packages/artifacts/src/client/styles/base.css b/packages/artifacts/src/client/styles/base.css index 4d9a9c8dad..e62b58d16d 100644 --- a/packages/artifacts/src/client/styles/base.css +++ b/packages/artifacts/src/client/styles/base.css @@ -7,6 +7,8 @@ --ar-top: 44px; --ar-pin: var(--ui-accent); --ar-pin-ink: var(--ui-on-accent); + /* 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 71a83d3e74..4d767bd729 100644 --- a/packages/artifacts/src/client/styles/canvas.css +++ b/packages/artifacts/src/client/styles/canvas.css @@ -24,8 +24,17 @@ .ar-cv-viewport[data-pan="true"] { cursor: grab; } -.ar-cv[data-commenting="true"] .ar-cv-viewport { - cursor: crosshair; +/* Comment mode: the speech-bubble cursor wherever a click would place a pin. */ +.ar-cv[data-commenting="true"] .ar-cv-viewport, +.ar-cv[data-commenting="true"] .ar-cf, +.ar-cv[data-commenting="true"] .ar-cf * { + cursor: var(--ar-comment-cursor); +} +.ar-cv [data-cv-ignore] { + cursor: default; +} +.ar-cv [data-cv-ignore] :is(button, a, .ar-pin) { + cursor: pointer; } .ar-cv-blanket { position: absolute; @@ -65,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; @@ -91,8 +103,17 @@ font-size: 12.5px; pointer-events: auto; } +/* One ring only: the frame carries the selection ring, the chip a tint. */ .ar-cv-chip[data-selected="true"] { - border-color: var(--ui-accent); + background: color-mix(in srgb, var(--ui-accent) 12%, var(--ui-panel)); +} +.ar-cv-chip-main:focus-visible { + outline: none; +} +/* Keyboard focus is shown on the whole chip, not as a second ring inside it. */ +.ar-cv-chip:has(.ar-cv-chip-main:focus-visible) { + outline: 2px solid var(--ui-accent); + outline-offset: 1px; } .ar-cv-chip-main { flex: 1; @@ -162,31 +183,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; @@ -196,18 +256,94 @@ .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) { - .ar-cv { - height: 70dvh; - } +/* Arranging */ +.ar-cv-handles { + position: absolute; + top: 0; + left: 0; + pointer-events: none; +} +.ar-cv-handle { + position: absolute; + box-sizing: border-box; + width: 10px; + height: 10px; + border: 2px solid var(--ui-accent); + border-radius: 2px; + background: var(--ui-panel); + transform: translate(-50%, -50%); + pointer-events: auto; +} +/* A larger hit target than the square that is drawn. */ +.ar-cv-handle::after { + position: absolute; + inset: -6px; + content: ""; +} +.ar-cv-marquee { + position: absolute; + top: 0; + left: 0; + box-sizing: border-box; + border: 1px solid var(--ui-accent); + background: color-mix(in srgb, var(--ui-accent) 12%, transparent); + pointer-events: none; +} +.ar-cv-toasts { + position: absolute; + bottom: 12px; + left: 12px; + z-index: 12; + display: grid; + gap: 6px; + max-width: min(360px, calc(100% - 24px)); +} +.ar-cv-toast { + display: flex; + align-items: center; + gap: 10px; + padding: 6px 6px 6px 12px; + border: 1px solid var(--ui-line); + border-radius: 8px; + background: var(--ui-panel); + box-shadow: 0 2px 10px color-mix(in srgb, black 16%, transparent); + font-size: 12.5px; +} +.ar-cv-toast span { + overflow: hidden; + font-weight: 600; + text-overflow: ellipsis; + white-space: nowrap; +} +.ar-cv-save { + position: absolute; + top: 10px; + left: 12px; + z-index: 11; + padding: 3px 10px; + border-radius: 999px; + background: var(--ui-panel); + box-shadow: 0 1px 6px color-mix(in srgb, black 14%, transparent); + color: var(--ui-muted); + font-size: 12px; +} +.ar-cv-save[data-status="error"] { + background: var(--ui-sev-warning-soft); + color: var(--ui-sev-warning-text); } 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 bd8f1b6217..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; @@ -104,13 +53,17 @@ } .ar-stage[data-commenting="true"], .ar-stage[data-commenting="true"] * { - cursor: crosshair; + cursor: var(--ar-comment-cursor); } .ar-stage[data-commenting="true"] .ar-pin { cursor: pointer; } -/* Pins: constant size, never scaled with the content. */ +/* + * 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; inset: 0; @@ -121,37 +74,59 @@ position: absolute; display: grid; place-items: center; - min-width: 22px; - height: 22px; - padding: 0 4px; - border: 2px solid var(--ui-panel); - border-radius: 999px 999px 999px 2px; - background: var(--ar-pin); + width: 28px; + height: 28px; + padding: 0; + border: 0; + background: none; color: var(--ar-pin-ink); font-size: 11px; font-weight: 700; line-height: 1; - box-shadow: 0 1px 4px color-mix(in srgb, black 35%, transparent); - transform: translate(-2px, -100%); + filter: drop-shadow(0 1px 2px color-mix(in srgb, black 40%, transparent)); pointer-events: auto; cursor: pointer; } -.ar-pin[data-hollow="true"] { - background: var(--ui-panel); - border-color: var(--ar-pin); +.ar-pin svg { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + overflow: visible; +} +.ar-pin path { + fill: var(--ar-pin); + stroke: var(--ui-panel); + stroke-width: 1.5; + stroke-linejoin: round; + stroke-linecap: round; +} +.ar-pin-n { + position: relative; +} +/* A thread on another version, or a position that is a guess: not filled. */ +.ar-pin[data-hollow="true"], +.ar-pin[data-approximate="true"] { color: var(--ar-pin); } +.ar-pin[data-hollow="true"] path, +.ar-pin[data-approximate="true"] path { + fill: var(--ui-panel); + stroke: var(--ar-pin); +} +.ar-pin[data-approximate="true"] path { + stroke-dasharray: 3 2; +} .ar-pin[data-resolved="true"] { opacity: 0.55; filter: grayscale(1); } -.ar-pin[data-approximate="true"] { - border-style: dashed; -} .ar-pin[data-selected="true"] { - outline: 3px solid color-mix(in srgb, var(--ar-pin) 45%, transparent); - outline-offset: 1px; z-index: 2; + filter: drop-shadow(0 0 3px var(--ar-pin)); +} +.ar-pin[data-selected="true"] path { + stroke-width: 2.25; } .ar-pin-badge { display: inline-grid; diff --git a/packages/artifacts/src/client/viewers/pin-bubble.tsx b/packages/artifacts/src/client/viewers/pin-bubble.tsx new file mode 100644 index 0000000000..5e8a7e64ec --- /dev/null +++ b/packages/artifacts/src/client/viewers/pin-bubble.tsx @@ -0,0 +1,55 @@ +import { ICON_PATH, PIN_TIP } from "#client/lib/pin-shape.ts"; + +/** + * 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. It is lucide's MessageCircle at 28 px; the box is translated so the tail tip sits at `left`/`top`. + */ +export function PinBubble({ + label, + text, + selected, + hollow, + resolved, + approximate, + boardPin = false, + style, + onClick, +}: { + readonly label: string; + readonly text: string | number; + readonly selected: boolean; + readonly hollow: boolean; + readonly resolved: boolean; + readonly approximate: boolean; + readonly boardPin?: boolean; + readonly style?: React.CSSProperties; + readonly onClick: (event: React.MouseEvent) => void; +}): React.JSX.Element { + return ( + + ); +} diff --git a/packages/artifacts/src/client/viewers/pins-overlay.tsx b/packages/artifacts/src/client/viewers/pins-overlay.tsx index fa2cdb9c89..b34f6e5e22 100644 --- a/packages/artifacts/src/client/viewers/pins-overlay.tsx +++ b/packages/artifacts/src/client/viewers/pins-overlay.tsx @@ -1,6 +1,7 @@ import { useLayoutEffect, useState } from "react"; import { clusterPins, type PinCluster } from "#client/lib/cluster.ts"; import type { Pin } from "#client/lib/pins.ts"; +import { PinBubble } from "./pin-bubble.tsx"; import type { AnchorAdapter } from "./types.ts"; type Placed = { @@ -87,30 +88,24 @@ export function PinsOverlay({ const hollow = members.every((pin) => pin.stale); const resolved = members.every((pin) => pin.state === "resolved"); return ( - + /> ); })} 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)