diff --git a/apps/web/e2e/keyboard.spec.ts b/apps/web/e2e/keyboard.spec.ts new file mode 100644 index 0000000..2120c66 --- /dev/null +++ b/apps/web/e2e/keyboard.spec.ts @@ -0,0 +1,377 @@ +/** + * Keyboard shortcuts and the command menu (roadmap Track C, decision 028). One test per group of + * shortcuts in the keymap. GitHub is not reachable in E2E: the cache rows are written directly and + * PATCH is answered by a stub that applies the change to the snapshot's task. + */ +import { type Page, type Route, expect, test } from "@playwright/test"; +import { ghIssues, ghProjectFields, ghProjectItems, ghProjects, ghRepos, workspaceGithub, workspaceRepos } from "@gitwork/db"; +import { openSqlite } from "@gitwork/db/node"; +import { emailCount, lastEmail, signInCode } from "./outbox"; + +const N = 8; +const STATUS = [ + { id: "k-todo", name: "Todo" }, + { id: "k-doing", name: "Doing" }, + { id: "k-done", name: "Done" }, +]; +const PRIORITY = [ + { id: "k-high", name: "High" }, + { id: "k-low", name: "Low" }, +]; +const SPRINTS = { iterations: [{ id: "k-it2", title: "Sprint 2", startDate: "2026-11-16", duration: 14 }], completedIterations: [{ id: "k-it1", title: "Sprint 1", startDate: "2026-11-02", duration: 14 }] }; + +async function signIn(page: Page, email: string) { + const before = emailCount(email); + await page.goto("/sign-in"); + await page.getByLabel("Email").fill(email); + await page.getByRole("button", { name: "Email me a sign-in code" }).click(); + await page.getByLabel("Code").fill(await signInCode(email, before)); + await page.getByRole("button", { name: "Sign in" }).click(); + await expect(page.getByRole("button", { name: "Sign out" })).toBeVisible(); +} + +async function seed(workspaceId: string) { + const { db } = openSqlite("file:.data/e2e.sqlite"); + const now = new Date(); + const at = new Date("2026-05-01T00:00:00Z"); + const ns = Array.from({ length: N }, (_, i) => i + 1); + await db.batch([ + db.insert(ghRepos).values({ nodeId: "R_kb", githubId: 601, installationId: 97, owner: "kbco", name: "web", fullName: "kbco/web", private: true, htmlUrl: "https://github.com/kbco/web", syncedAt: now }), + db.insert(ghProjects).values({ nodeId: "PVT_kb", installationId: 97, ownerLogin: "kbco", number: 3, title: "Keys", url: "https://github.com/orgs/kbco/projects/3", syncedAt: now }), + db.insert(ghProjectFields).values([ + { nodeId: "F_kstatus", projectNodeId: "PVT_kb", name: "Status", dataType: "SINGLE_SELECT", config: STATUS, syncedAt: now }, + { nodeId: "F_kprio", projectNodeId: "PVT_kb", name: "Priority", dataType: "SINGLE_SELECT", config: PRIORITY, syncedAt: now }, + { nodeId: "F_kest", projectNodeId: "PVT_kb", name: "Estimate", dataType: "NUMBER", config: null, syncedAt: now }, + { nodeId: "F_ktarget", projectNodeId: "PVT_kb", name: "Target date", dataType: "DATE", config: null, syncedAt: now }, + { nodeId: "F_ksprint", projectNodeId: "PVT_kb", name: "Sprint", dataType: "ITERATION", config: SPRINTS, syncedAt: now }, + ]), + db.insert(ghIssues).values( + ns.map((n) => ({ + nodeId: `I_kb#${n}`, + repoNodeId: "R_kb", + number: n, + title: `Key task ${n}`, + body: `Body ${n}`, + state: "open", + labels: [], + assignees: [], + htmlUrl: `https://github.com/kbco/web/issues/${n}`, + createdAtGh: at, + githubUpdatedAt: at, + syncedAt: now, + })), + ), + db.insert(ghProjectItems).values( + ns.map((n) => ({ + nodeId: `PVTI_kb${n}`, + projectNodeId: "PVT_kb", + contentType: "ISSUE", + contentNodeId: `I_kb#${n}`, + fieldValues: { F_kstatus: { type: "single_select", optionId: "k-todo", name: "Todo" } } as never, + githubUpdatedAt: at, + syncedAt: now, + })), + ), + db.insert(workspaceGithub).values({ workspaceId, installationId: 97, projectNodeId: "PVT_kb", linkedAt: now }), + db.insert(workspaceRepos).values({ workspaceId, repoNodeId: "R_kb" }), + ]); +} + +type Task = { id: string; title: string; state: string; stateReason: string | null; fields: Record }; +type Field = { id: string; dataType: string; options?: { id: string; name: string }[]; iterations?: { id: string; title: string; startDate: string; duration: number }[] }; + +/** Answers PATCH /tasks/:id like the server would, from the current snapshot. Records each call. */ +async function stubWrites(page: Page, workspaceId: string) { + const res = await page.request.get(`/api/v1/workspaces/${workspaceId}/sync`); + const snap = (await res.json()) as { board: { tasks: Task[]; fields: Field[] } }; + const tasks = new Map(snap.board.tasks.map((t) => [t.id, structuredClone(t)])); + const calls: { id: string; body: Record }[] = []; + await page.route(`**/api/v1/workspaces/${workspaceId}/tasks/*`, async (route: Route) => { + if (route.request().method() !== "PATCH") return route.fallback(); + const id = decodeURIComponent(route.request().url().split("/").pop()!); + const body = route.request().postDataJSON() as { fields?: Record | null>; state?: string }; + calls.push({ id, body }); + const task = tasks.get(id)!; + for (const [fieldId, input] of Object.entries(body.fields ?? {})) { + const field = snap.board.fields.find((f) => f.id === fieldId)!; + if (!input) delete task.fields[fieldId]; + else if (input.type === "single_select") task.fields[fieldId] = { ...input, name: field.options!.find((o) => o.id === input.optionId)!.name }; + else if (input.type === "iteration") { + const it = field.iterations!.find((i) => i.id === input.iterationId)!; + task.fields[fieldId] = { type: "iteration", iterationId: it.id, title: it.title, startDate: it.startDate, duration: it.duration }; + } else task.fields[fieldId] = input; + } + if (body.state) { + task.state = body.state; + task.stateReason = body.state === "closed" ? "completed" : null; + } + await route.fulfill({ json: { task } }); + }); + return calls; +} + +const row = (page: Page, n: number) => page.locator(`[data-testid="task-row"][data-task-id="PVTI_kb${n}"]`); +const focusedId = (page: Page) => page.locator('[data-focused="true"]').getAttribute("data-task-id"); + +let workspaceId = ""; + +test.describe.configure({ mode: "serial" }); + +test.beforeAll(async ({ browser }) => { + const ctx = await browser.newContext({ storageState: { cookies: [], origins: [] } }); + const owner = await ctx.newPage(); + await signIn(owner, "keys-owner@example.com"); + await owner.getByLabel("Account name").fill("Keys Agency"); + await owner.getByLabel("First workspace").fill("Keys Board"); + await owner.getByRole("button", { name: "Create" }).click(); + await expect(owner.getByRole("heading", { name: "Keys Board" })).toBeVisible(); + workspaceId = /\/w\/([^/?#]+)/.exec(owner.url())![1]!; + await seed(workspaceId); + await ctx.storageState({ path: ".data/keys-owner.json" }); + + // A Read Only member, for the "cannot edit" check. + await owner.goto(`/w/${workspaceId}/members`); + await owner.getByLabel("Email").fill("keys-reader@example.com"); + await owner.getByLabel("Role").selectOption("read_only"); + await owner.getByRole("button", { name: "Send invite" }).click(); + const [, invitePath] = await lastEmail("keys-reader@example.com", /http:\/\/localhost:\d+(\/invite\/[A-Za-z0-9_-]+)/); + const rctx = await browser.newContext({ storageState: { cookies: [], origins: [] } }); + const reader = await rctx.newPage(); + await signIn(reader, "keys-reader@example.com"); + await reader.goto(invitePath!); + await reader.getByRole("button", { name: "Accept invite" }).click(); + await expect(reader.getByText("Your role: Read Only")).toBeVisible(); + await rctx.storageState({ path: ".data/keys-reader.json" }); + await rctx.close(); + await ctx.close(); +}); + +test.use({ storageState: ".data/keys-owner.json", permissions: ["clipboard-read", "clipboard-write"] }); + +async function open(page: Page, view = "list") { + await page.goto(`/w/${workspaceId}?view=${view}`); + await expect(page.getByTestId(view === "board" ? "task-card" : view === "timeline" ? "timeline-row" : "task-row")).toHaveCount(N); +} + +test("? shows every shortcut; Escape closes it", async ({ page }) => { + await open(page); + await page.keyboard.press("?"); + const sheet = page.getByTestId("shortcut-sheet"); + await expect(sheet).toBeVisible(); + for (const label of ["Open command menu", "Go to settings", "Switch list ↔ board", "Move down", "Set status", "Copy branch name"]) { + await expect(sheet.getByText(label, { exact: true })).toBeVisible(); + } + await page.keyboard.press("Escape"); + await expect(sheet).toHaveCount(0); +}); + +test("J / K / arrows move focus; Space opens the panel, which follows focus; Escape steps back", async ({ page }) => { + await open(page); + await page.keyboard.press("j"); + expect(await focusedId(page)).toBe("PVTI_kb1"); + await page.keyboard.press("j"); + await page.keyboard.press("ArrowDown"); + expect(await focusedId(page)).toBe("PVTI_kb3"); + await page.keyboard.press("k"); + expect(await focusedId(page)).toBe("PVTI_kb2"); + await page.keyboard.press(" "); + const panel = page.getByTestId("peek-panel"); + await expect(panel.getByRole("heading", { name: "Key task 2" })).toBeVisible(); + await page.keyboard.press("j"); + await expect(panel.getByRole("heading", { name: "Key task 3" })).toBeVisible(); + await page.keyboard.press("Escape"); + await expect(panel).toHaveCount(0); + expect(await focusedId(page)).toBe("PVTI_kb3"); + await page.keyboard.press("Escape"); + await expect(page.locator('[data-focused="true"]')).toHaveCount(0); +}); + +test("Enter opens the focused task's page", async ({ page }) => { + await open(page); + await page.keyboard.press("j"); + await page.keyboard.press("Enter"); + await expect(page).toHaveURL(new RegExp(`/w/${workspaceId}/tasks/PVTI_kb1$`)); +}); + +test("X selects, Shift+J extends, mod+A selects all, Escape clears", async ({ page }) => { + await open(page); + await page.keyboard.press("j"); + await page.keyboard.press("x"); + await expect(page.getByTestId("selection-bar")).toContainText("1 selected"); + await page.keyboard.press("Shift+J"); + await page.keyboard.press("Shift+ArrowDown"); + await expect(page.getByTestId("selection-bar")).toContainText("3 selected"); + await page.keyboard.press("ControlOrMeta+a"); + await expect(page.getByTestId("selection-bar")).toContainText(`${N} selected`); + await page.keyboard.press("Escape"); + await expect(page.getByTestId("selection-bar")).toHaveCount(0); +}); + +test("S sets status on the focused task, optimistically", async ({ page }) => { + await open(page); + const calls = await stubWrites(page, workspaceId); + await page.keyboard.press("j"); + await page.keyboard.press("s"); + await page.getByRole("option", { name: "Doing" }).click(); + await expect(row(page, 1)).toContainText("Doing"); + expect(calls).toEqual([{ id: "PVTI_kb1", body: { fields: { F_kstatus: { type: "single_select", optionId: "k-doing" } } } }]); +}); + +test("S on a selection edits every selected task; mod+Z undoes them as one step", async ({ page }) => { + await open(page); + const calls = await stubWrites(page, workspaceId); + for (const _ of [1, 2, 3]) { + await page.keyboard.press("j"); + await page.keyboard.press("x"); + } + await page.keyboard.press("s"); + await page.getByRole("dialog").getByPlaceholder(/Set Status for 3 tasks/).fill("done"); + await page.keyboard.press("Enter"); + for (const n of [1, 2, 3]) await expect(row(page, n)).toContainText("Done"); + await expect(row(page, 4)).toContainText("Todo"); + await expect(page.getByRole("status")).toContainText("Updated Status on 3 tasks"); + expect(calls.map((c) => c.id)).toEqual(["PVTI_kb1", "PVTI_kb2", "PVTI_kb3"]); + + await page.keyboard.press("Escape"); // clear the selection first: Escape never undoes + await page.keyboard.press("ControlOrMeta+z"); + for (const n of [1, 2, 3]) await expect(row(page, n)).toContainText("Todo"); + await expect(page.getByRole("status")).toContainText("Undone: Status change on 3 tasks"); + expect(calls).toHaveLength(6); +}); + +test("P, E, Shift+D, Shift+C edit priority, estimate, due date, and cycle", async ({ page }) => { + await open(page); + const calls = await stubWrites(page, workspaceId); + await page.keyboard.press("j"); + await page.keyboard.press("p"); + await page.getByRole("option", { name: "High" }).click(); + await page.keyboard.press("e"); + await page.getByRole("dialog").getByLabel("Estimate").fill("5"); + await page.keyboard.press("Enter"); + await page.keyboard.press("Shift+D"); + await page.getByRole("dialog").getByLabel("Target date").fill("2026-12-24"); + await page.keyboard.press("Enter"); + await page.keyboard.press("Shift+C"); + await page.getByRole("option", { name: "Sprint 2" }).click(); + await expect.poll(() => calls.length).toBe(4); + expect(calls.map((c) => c.body.fields)).toEqual([ + { F_kprio: { type: "single_select", optionId: "k-high" } }, + { F_kest: { type: "number", number: 5 } }, + { F_ktarget: { type: "date", date: "2026-12-24" } }, + { F_ksprint: { type: "iteration", iterationId: "k-it2" } }, + ]); + await expect(row(page, 1)).toContainText("2026-12-24"); +}); + +test("mod+Shift+X closes and reopens the focused task", async ({ page }) => { + await open(page); + const calls = await stubWrites(page, workspaceId); + await page.keyboard.press("j"); + await page.keyboard.press("ControlOrMeta+Shift+X"); + await expect(row(page, 1)).toContainText("Closed"); + await page.keyboard.press("ControlOrMeta+Shift+X"); + await expect(row(page, 1)).not.toContainText("Closed"); + expect(calls.map((c) => c.body.state)).toEqual(["closed", "open"]); +}); + +test("mod+. copies the ID, mod+Shift+, the URL, mod+Shift+. a branch name", async ({ page }) => { + await open(page); + await page.keyboard.press("j"); + const clip = () => page.evaluate(() => navigator.clipboard.readText()); + await page.keyboard.press("ControlOrMeta+."); + await expect.poll(clip).toBe("kbco/web#1"); + await page.keyboard.press("ControlOrMeta+Shift+Comma"); + await expect.poll(clip).toBe(`${new URL(page.url()).origin}/w/${workspaceId}/tasks/PVTI_kb1`); + await page.keyboard.press("ControlOrMeta+Shift+Period"); + await expect.poll(clip).toBe("1-key-task-1"); +}); + +test("mod+K runs commands and finds tasks; / searches tasks", async ({ page }) => { + await open(page); + await page.keyboard.press("ControlOrMeta+k"); + const menu = page.getByRole("dialog"); + await expect(menu.getByRole("option", { name: /New task/ })).toBeVisible(); + await menu.getByRole("combobox").fill("timeline"); + await page.keyboard.press("Enter"); + // The seeded tasks have no dates: the timeline lists them as unscheduled. + await expect(page.getByRole("heading", { name: "Unscheduled" })).toBeVisible(); + expect(new URL(page.url()).searchParams.get("view")).toBe("timeline"); + + await page.keyboard.press("/"); + await page.getByRole("dialog").getByRole("combobox").fill("Key task 6"); + await page.keyboard.press("Enter"); + await expect(page.getByTestId("peek-panel").getByRole("heading", { name: "Key task 6" })).toBeVisible(); +}); + +test("mod+B toggles list and board; V then T shows the timeline", async ({ page }) => { + await open(page); + await page.keyboard.press("ControlOrMeta+b"); + await expect(page.getByTestId("task-card")).toHaveCount(N); + await page.keyboard.press("ControlOrMeta+b"); + await expect(page.getByTestId("task-row")).toHaveCount(N); + await page.keyboard.press("v"); + await page.keyboard.press("t"); + await expect(page.getByRole("heading", { name: "Unscheduled" })).toBeVisible(); +}); + +test("G then S opens settings; members is in the command menu; G then M stays free for My tasks", async ({ page }) => { + await open(page); + await page.keyboard.press("g"); + await page.keyboard.press("m"); // reserved (Linear: My tasks): does nothing yet + await expect(page).toHaveURL(new RegExp(`/w/${workspaceId}\\?view=list$`)); + await page.keyboard.press("g"); + await page.keyboard.press("s"); + await expect(page).toHaveURL(new RegExp(`/w/${workspaceId}/settings$`)); + await open(page); + await page.keyboard.press("ControlOrMeta+k"); + await page.getByRole("dialog").getByRole("combobox").fill("go to members"); + await page.keyboard.press("Enter"); + await expect(page).toHaveURL(new RegExp(`/w/${workspaceId}/members$`)); +}); + +test("C opens the new-task dialog", async ({ page }) => { + await open(page); + await page.keyboard.press("c"); + await expect(page.getByRole("dialog").getByRole("heading", { name: "New task" })).toBeVisible(); + // Typing in the dialog's fields never triggers shortcuts. + await page.getByLabel("Title").fill("s j x"); + await expect(page.getByRole("dialog").getByRole("heading", { name: "New task" })).toBeVisible(); + await expect(page.getByLabel("Title")).toHaveValue("s j x"); +}); + +test("keys typed in a field stay in the field", async ({ page }) => { + await open(page); + await page.keyboard.press("j"); + await page.keyboard.press(" "); + const est = page.getByTestId("peek-panel").getByLabel("Estimate"); + await est.click(); + await page.keyboard.type("3"); + await page.keyboard.press("s"); // would open the status picker outside a field + await expect(page.getByRole("dialog")).toHaveCount(0); + // Positive control: the same key outside the field opens the picker. + await page.keyboard.press("Escape"); // drops the draft, keeps the panel + await page.locator("body").click({ position: { x: 5, y: 5 } }); + await page.keyboard.press("s"); + await expect(page.getByRole("dialog")).toBeVisible(); +}); + +test.describe("as Read Only", () => { + test.use({ storageState: ".data/keys-reader.json" }); + + test("edit keys explain the role and send nothing; reading keys work", async ({ page }) => { + await open(page); + let writes = 0; + page.on("request", (r) => { + if (r.method() === "PATCH") writes++; + }); + await page.keyboard.press("j"); + await page.keyboard.press("s"); + await expect(page.getByRole("status")).toContainText("Your role cannot edit tasks."); + await page.keyboard.press("c"); + await expect(page.getByRole("dialog")).toHaveCount(0); + await page.keyboard.press(" "); + await expect(page.getByTestId("peek-panel").getByRole("heading", { name: "Key task 1" })).toBeVisible(); + expect(writes).toBe(0); + }); +}); + diff --git a/apps/web/package.json b/apps/web/package.json index d953b46..d29d691 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -24,6 +24,7 @@ "@opennextjs/cloudflare": "1.20.11", "better-auth": "1.7.8", "class-variance-authority": "0.7.1", + "cmdk": "1.1.1", "cn": "0.4.0", "drizzle-orm": "0.45.4", "lucide-react": "1.57.0", diff --git a/apps/web/src/app/w/[workspaceId]/board-context.tsx b/apps/web/src/app/w/[workspaceId]/board-context.tsx index 62e9dff..c77e5ea 100644 --- a/apps/web/src/app/w/[workspaceId]/board-context.tsx +++ b/apps/web/src/app/w/[workspaceId]/board-context.tsx @@ -31,6 +31,16 @@ interface BoardContextValue { loadDetail: (task: TaskView) => Promise; notice: string | null; notify: (message: string) => void; + /** Keyboard focus in the current view, and the multi-selection (ids). */ + focusedId: string | null; + setFocusedId: (id: string | null) => void; + selected: ReadonlySet; + setSelected: (next: ReadonlySet) => void; + /** The task ids in on-screen order. The visible view sets it after each render. */ + setOrder: (ids: string[]) => void; + getOrder: () => string[]; + newTaskOpen: boolean; + setNewTaskOpen: (open: boolean) => void; } const BoardContext = createContext(null); @@ -39,6 +49,10 @@ export function BoardProvider({ workspaceId, initial, etag, children }: { worksp const [store] = useState(() => new BoardStore(initial, etag, { fetchSnapshot: (e) => fetchSnapshot(workspaceId, e) })); const [peekId, setPeekId] = useState(null); const [notice, setNotice] = useState(null); + const [focusedId, setFocusedId] = useState(null); + const [selected, setSelected] = useState>(() => new Set()); + const [newTaskOpen, setNewTaskOpen] = useState(false); + const order = useRef([]); const details = useRef(new Map>()); const noticeTimer = useRef | undefined>(undefined); @@ -65,8 +79,27 @@ export function BoardProvider({ workspaceId, initial, etag, children }: { worksp }, []); const value = useMemo( - () => ({ workspaceId, store, peekId, openPeek: setPeekId, closePeek: () => setPeekId(null), loadDetail, notice, notify }), - [workspaceId, store, peekId, loadDetail, notice, notify], + () => ({ + workspaceId, + store, + peekId, + openPeek: setPeekId, + closePeek: () => setPeekId(null), + loadDetail, + notice, + notify, + focusedId, + setFocusedId, + selected, + setSelected, + setOrder: (ids: string[]) => { + order.current = ids; + }, + getOrder: () => order.current, + newTaskOpen, + setNewTaskOpen, + }), + [workspaceId, store, peekId, loadDetail, notice, notify, focusedId, selected, newTaskOpen], ); return {children}; } @@ -132,6 +165,32 @@ function taskActions(workspaceId: string, store: BoardStore, notify: (message: s } } + /** One field on many tasks, one after another (GitHub rate limits). One undo step for all. */ + async function setFieldMany(tasks: TaskView[], field: FieldView, input: FieldInput | null): Promise { + if (tasks.length === 1) return setField(tasks[0]!, field, input); + const done: { task: TaskView; previous: FieldInput | null }[] = []; + for (const [i, task] of tasks.entries()) { + notify(`Updating ${field.name}: ${i + 1} of ${tasks.length}…`); + const previous = currentInput(field, task); + try { + await store.mutate(task.id, withField(field, input), () => patch(task.id, { fields: { [field.id]: input } })); + done.push({ task, previous }); + } catch (error) { + notify(`Stopped after ${done.length} of ${tasks.length}: ${(error as Error).message}`); + break; + } + } + if (done.length === tasks.length) notify(`Updated ${field.name} on ${tasks.length} tasks.`); + if (done.length > 0) { + store.pushUndo({ + label: `${field.name} change on ${done.length} tasks`, + run: async () => { + for (const { task, previous } of done) await setField(task, field, previous, false); + }, + }); + } + } + async function undo(): Promise { try { const label = await store.undo(); @@ -141,5 +200,5 @@ function taskActions(workspaceId: string, store: BoardStore, notify: (message: s } } - return { setField, setState, undo, upsert: (task: TaskView) => store.upsert(task) }; + return { setField, setFieldMany, setState, undo, upsert: (task: TaskView) => store.upsert(task) }; } diff --git a/apps/web/src/app/w/[workspaceId]/command-layer.tsx b/apps/web/src/app/w/[workspaceId]/command-layer.tsx new file mode 100644 index 0000000..553cea7 --- /dev/null +++ b/apps/web/src/app/w/[workspaceId]/command-layer.tsx @@ -0,0 +1,368 @@ +"use client"; +/** + * Keyboard shortcuts and the command menu for a workspace's tasks (roadmap Track C, decision 028). + * Every action here is also a command-menu item, so a person who knows no keys can still find it. + */ +import { COMMANDS, type Command as KeyCommand, type CommandId, commandById, displayBinding } from "@gitwork/core"; +import type { FieldView, TaskView } from "@gitwork/server"; +import { useRouter } from "next/navigation"; +import { useMemo, useState } from "react"; +import { Button, Input } from "@/components/kit"; +import { Command, CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandShortcut } from "@/components/ui/command"; +import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"; +import { fromInputValue, toInputValue } from "@/lib/field-values"; +import { type Handlers, isMac, useShortcuts } from "@/lib/keyboard"; +import { useBoard, useBoardContext, useSnapshot, useTaskActions } from "./board-context"; +import type { ViewId } from "./views"; + +type FieldRole = "status" | "priority" | "estimate" | "due" | "cycle"; + +type Mode = { kind: "root" } | { kind: "search" } | { kind: "pick"; role: FieldRole } | { kind: "value"; role: FieldRole }; + +/** The board field each task command edits, if the board has one. */ +function useRoleFields(): Partial> { + const { fields, mapping } = useBoard(); + return useMemo(() => { + const byId = (id: string | null) => fields.find((f) => f.id === id); + const byName = (type: string, pattern: RegExp) => fields.find((f) => f.dataType === type && pattern.test(f.name)); + return { + status: byId(mapping.kanbanFieldId), + priority: byName("SINGLE_SELECT", /^priority$/i), + estimate: byName("NUMBER", /^(estimate|points|story points)$/i), + due: byId(mapping.targetFieldId), + cycle: byId(mapping.iterationFieldId), + }; + }, [fields, mapping]); +} + +const slug = (title: string) => + title + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, "") + .slice(0, 40); + +export function CommandLayer({ view, setView }: { view: ViewId; setView: (v: ViewId) => void }) { + const router = useRouter(); + const ctx = useBoardContext(); + const { workspaceId, peekId, openPeek, closePeek, focusedId, setFocusedId, selected, setSelected, getOrder, notify, setNewTaskOpen } = ctx; + const board = useBoard(); + const { canWrite } = useSnapshot(); + const actions = useTaskActions(); + const roles = useRoleFields(); + const [mode, setMode] = useState(null); + const [helpOpen, setHelpOpen] = useState(false); + const mac = isMac(); + + const byId = useMemo(() => new Map(board.tasks.map((t) => [t.id, t])), [board.tasks]); + /** What a task command acts on: the selection, else the task in focus, else the open panel. */ + const targets: TaskView[] = useMemo(() => { + if (selected.size > 0) return [...selected].flatMap((id) => byId.get(id) ?? []); + const one = (focusedId && byId.get(focusedId)) || (peekId && byId.get(peekId)); + return one ? [one] : []; + }, [selected, focusedId, peekId, byId]); + const single = targets.length === 1 ? targets[0]! : null; + + function moveFocus(step: 1 | -1, extend = false) { + const ids = getOrder(); + if (ids.length === 0) return; + const at = focusedId ? ids.indexOf(focusedId) : -1; + const next = ids[Math.max(0, Math.min(ids.length - 1, at === -1 ? 0 : at + step))]!; + if (extend) { + const from = focusedId ?? next; + setSelected(new Set([...selected, from, next])); + } + setFocusedId(next); + if (peekId) openPeek(next); // the panel follows the focus, as in Linear + document.querySelector(`[data-task-id="${CSS.escape(next)}"]`)?.scrollIntoView({ block: "nearest" }); + } + + async function copy(text: string, what: string) { + try { + await navigator.clipboard.writeText(text); + notify(`Copied ${what}: ${text}`); + } catch { + notify(`Could not copy the ${what}.`); + } + } + + const ref = (t: TaskView) => (t.repo && t.number !== null ? `${t.repo.fullName}#${t.number}` : t.title); + const appUrl = (t: TaskView) => `${window.location.origin}/w/${workspaceId}/tasks/${encodeURIComponent(t.id)}`; + + const edit = (role: FieldRole) => () => { + if (!canWrite) return notify("Your role cannot edit tasks."); + if (!roles[role]) return notify(`This board has no ${role === "due" ? "due date" : role} field.`); + if (targets.length === 0) return notify("Move to a task first (J / K), or select some (X)."); + setMode({ kind: roles[role]!.dataType === "SINGLE_SELECT" || roles[role]!.dataType === "ITERATION" ? "pick" : "value", role }); + }; + + const handlers: Handlers = { + "menu.open": () => setMode((m) => (m ? null : { kind: "root" })), + "search.open": () => setMode({ kind: "search" }), + "help.shortcuts": () => setHelpOpen(true), + "task.create": canWrite && board.board.available && board.repos.length > 0 ? () => setNewTaskOpen(true) : undefined, + "edit.undo": () => void actions.undo(), + escape: () => { + if (peekId) closePeek(); + else if (selected.size > 0) setSelected(new Set()); + else setFocusedId(null); + }, + "go.tasks": () => router.push(`/w/${workspaceId}`), + "go.members": () => router.push(`/w/${workspaceId}/members`), + "go.settings": () => router.push(`/w/${workspaceId}/settings`), + "view.toggle": () => setView(view === "list" ? "board" : "list"), + "view.list": () => setView("list"), + "view.board": () => setView("board"), + "view.timeline": () => setView("timeline"), + "list.down": () => moveFocus(1), + "list.up": () => moveFocus(-1), + "list.extendDown": () => moveFocus(1, true), + "list.extendUp": () => moveFocus(-1, true), + "list.select": () => { + if (!focusedId) return; + const next = new Set(selected); + if (next.has(focusedId)) next.delete(focusedId); + else next.add(focusedId); + setSelected(next); + }, + "list.selectAll": () => setSelected(new Set(getOrder())), + "list.peek": () => focusedId && (peekId === focusedId ? closePeek() : openPeek(focusedId)), + "list.open": () => focusedId && router.push(`/w/${workspaceId}/tasks/${encodeURIComponent(focusedId)}`), + "task.status": edit("status"), + "task.priority": edit("priority"), + "task.estimate": edit("estimate"), + "task.dueDate": edit("due"), + "task.cycle": edit("cycle"), + "task.close": () => { + if (!canWrite || !single || single.kind !== "issue") return; + void actions.setState(single, single.state === "closed" ? "open" : "closed"); + }, + "task.copyId": () => single && void copy(ref(single), "ID"), + "task.copyUrl": () => single && void copy(appUrl(single), "URL"), + "task.copyBranch": () => single && single.number !== null && void copy(`${single.number}-${slug(single.title)}`, "branch name"), + }; + + const scopes: ("global" | "list" | "task")[] = ["global", "list", ...(targets.length > 0 ? (["task"] as const) : [])]; + useShortcuts(handlers, scopes); + + // ---- Menu content ------------------------------------------------------------------------- + + const [query, setQuery] = useState(""); + const close = () => { + setMode(null); + setQuery(""); + // The menu animates out with its input still focused; shortcuts must work at once. + if (document.activeElement instanceof HTMLElement && document.activeElement.closest('[role="dialog"]')) document.activeElement.blur(); + }; + const run = (id: CommandId) => { + close(); + handlers[id]?.(); + }; + const matches = useMemo(() => { + if (!mode || (mode.kind !== "root" && mode.kind !== "search")) return []; + const q = query.trim().toLowerCase(); + if (!q) return mode.kind === "search" ? board.tasks.slice(0, 20) : []; + const out: TaskView[] = []; + for (const t of board.tasks) { + if (t.title.toLowerCase().includes(q) || (t.number !== null && `#${t.number}`.includes(q)) || ref(t).toLowerCase().includes(q)) out.push(t); + if (out.length === 30) break; + } + return out; + }, [mode, query, board.tasks]); + + const available = (COMMANDS as readonly KeyCommand[]).filter( + (c) => handlers[c.id] && c.id !== "menu.open" && c.id !== "escape" && (c.scope !== "task" || targets.length > 0) && !c.id.startsWith("list."), + ); + const keysOf = (c: KeyCommand) => displayBinding(c.keys[0], mac); + + const pickField = mode?.kind === "pick" || mode?.kind === "value" ? roles[mode.role] : undefined; + const targetLabel = targets.length === 1 ? `“${targets[0]!.title}”` : `${targets.length} tasks`; + + return ( + <> + !open && close()} + title={mode?.kind === "pick" ? `Set ${pickField?.name}` : "Command menu"} + description={mode?.kind === "pick" ? `For ${targetLabel}` : "Search tasks or run a command"} + > + + + + No results. + {mode?.kind === "pick" && pickField && ( + + {(pickField.dataType === "SINGLE_SELECT" + ? (pickField.options ?? []).map((o) => ({ id: o.id, name: o.name })) + : (pickField.iterations ?? []).map((i) => ({ id: i.id, name: i.title })) + ).map((o) => ( + { + close(); + void actions.setFieldMany(targets, pickField, fromInputValue(pickField, o.id)); + }} + > + {o.name} + {single && toInputValue(single.fields[pickField.id]) === o.id && current} + + ))} + { + close(); + void actions.setFieldMany(targets, pickField, null); + }} + > + No {pickField.name} + + + )} + {(mode?.kind === "root" || mode?.kind === "search") && matches.length > 0 && ( + + {matches.map((t) => ( + { + close(); + setFocusedId(t.id); + openPeek(t.id); + }} + > + {t.title || "(untitled)"} + {t.repo ? `${t.repo.fullName.split("/")[1]}#${t.number}` : "Draft"} + + ))} + + )} + {mode?.kind === "root" && + (["General", "Task", "Views", "Navigation"] as const).map((group) => { + const items = available.filter((c) => c.group === group); + if (items.length === 0) return null; + return ( + + {items.map((c) => ( + run(c.id)}> + {c.label} + {keysOf(c)} + + ))} + + ); + })} + + + + + {mode?.kind === "value" && pickField && ( + { + close(); + void actions.setFieldMany(targets, pickField, fromInputValue(pickField, value)); + }} + /> + )} + + + setSelected(new Set())} onStatus={canWrite && roles.status ? edit("status") : undefined} mac={mac} /> + + ); +} + +function ValueDialog(props: { field: FieldView; initial: string; targetLabel: string; onClose: () => void; onSave: (value: string) => void }) { + const [value, setValue] = useState(props.initial); + return ( + !open && props.onClose()}> + + + Set {props.field.name} + For {props.targetLabel}. Leave it empty to clear. + +
{ + e.preventDefault(); + props.onSave(value); + }} + > + setValue(e.target.value)} + /> + +
+
+
+ ); +} + +function ShortcutSheet({ open, onOpenChange, mac }: { open: boolean; onOpenChange: (open: boolean) => void; mac: boolean }) { + const groups = ["General", "Navigation", "Views", "List", "Task"] as const; + return ( + + + + Keyboard shortcuts + The same keys as Linear. Press ? anywhere to see this again. + +
+ {groups.map((g) => ( +
+

{g}

+
+ {(COMMANDS as readonly KeyCommand[]) + .filter((c) => c.group === g) + .map((c) => ( +
+
{c.label}
+
+ {c.keys.length === 0 && Command menu} + {c.keys.map((k) => ( + + {displayBinding(k, mac)} + + ))} +
+
+ ))} +
+
+ ))} +
+
+
+ ); +} + +function SelectionBar({ count, onClear, onStatus, mac }: { count: number; onClear: () => void; onStatus?: () => void; mac: boolean }) { + if (count === 0) return null; + return ( +
+
+ {count} selected + {onStatus && ( + + )} + +
+
+ ); +} diff --git a/apps/web/src/app/w/[workspaceId]/tasks/new-task.tsx b/apps/web/src/app/w/[workspaceId]/tasks/new-task.tsx index 0806c82..ba4c9da 100644 --- a/apps/web/src/app/w/[workspaceId]/tasks/new-task.tsx +++ b/apps/web/src/app/w/[workspaceId]/tasks/new-task.tsx @@ -8,7 +8,7 @@ import { useBoard, useBoardContext, useTaskActions } from "../board-context"; export function NewTaskButton() { const board = useBoard(); - const { workspaceId, openPeek } = useBoardContext(); + const { workspaceId, openPeek, newTaskOpen: open, setNewTaskOpen: setOpen, setFocusedId } = useBoardContext(); const { upsert } = useTaskActions(); const props = { workspaceId, @@ -16,7 +16,6 @@ export function NewTaskButton() { defaultRepo: board.lastRepoNodeId, statusField: board.fields.find((f) => f.id === board.mapping.kanbanFieldId) ?? null, }; - const [open, setOpen] = useState(false); const [repo, setRepo] = useState(props.defaultRepo ?? props.repos[0]?.nodeId ?? ""); const [title, setTitle] = useState(""); const [body, setBody] = useState(""); @@ -40,6 +39,7 @@ export function NewTaskButton() { setBody(""); // The new task joins the store and opens beside the list: no page load. upsert(task); + setFocusedId(task.id); openPeek(task.id); } catch (err) { setError((err as Error).message); @@ -51,7 +51,9 @@ export function NewTaskButton() { return ( - + diff --git a/apps/web/src/app/w/[workspaceId]/tasks/peek-panel.tsx b/apps/web/src/app/w/[workspaceId]/tasks/peek-panel.tsx index b83c20f..6d72ff8 100644 --- a/apps/web/src/app/w/[workspaceId]/tasks/peek-panel.tsx +++ b/apps/web/src/app/w/[workspaceId]/tasks/peek-panel.tsx @@ -18,15 +18,7 @@ export function PeekPanel() { const { tasks } = useBoard(); const task = peekId ? tasks.find((t) => t.id === peekId) : undefined; - useEffect(() => { - if (!peekId) return; - const onKey = (e: KeyboardEvent) => { - if (e.key === "Escape" && !e.defaultPrevented) closePeek(); - }; - window.addEventListener("keydown", onKey); - return () => window.removeEventListener("keydown", onKey); - }, [peekId, closePeek]); - + // Escape closes the panel through the keymap (command-layer.tsx). if (!peekId) return null; return (