Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(issues): keyboard cursor for the issue list, table and board (MUL-10203) (#11593)
Jiayuan Zhang9a2d33658482
diff --git a/packages/core/command-bar/context-store.ts b/packages/core/command-bar/context-store.tsindex 6ffdc6e2ca..0c827e2bc7 100644--- a/packages/core/command-bar/context-store.ts+++ b/packages/core/command-bar/context-store.ts@@ -23,6 +23,11 @@ export type CommandBarContext =issue: Issue;/** Where to land after deleting it when there is no history to go back to. */onDeletedFallbackPath?: string;+ /**+ * The issue under an issue list's keyboard cursor. It yields to every+ * other issue or selection context, whenever either was registered.+ */+ cursor?: boolean;}| { kind: "issues"; issues: Issue[]; clearSelection: () => void }| { kind: "project"; project: Project }diff --git a/packages/views/issues/components/board-card.tsx b/packages/views/issues/components/board-card.tsxindex d43fa90162..4061712d44 100644--- a/packages/views/issues/components/board-card.tsx+++ b/packages/views/issues/components/board-card.tsx@@ -43,6 +43,7 @@ import {useIssuePeekActions,useIssuePeekLinkProps,} from "../surface/peek-context";+import { useIsIssueCursor } from "../surface/issue-cursor";function formatDate(date: string, locale: string): string {return formatDateOnly(date, { month: "short", day: "numeric" }, locale);}@@ -207,7 +208,7 @@ export const BoardCardContent = memo(function BoardCardContent({data-status={issue.status}data-priority={issue.priority}data-assignee-type={issue.assignee_type ?? "none"}- className="rounded-board-card border-[0.5px] border-board-card-border bg-board-card py-[var(--board-card-padding-y,var(--space-sm,0.75rem))] px-[var(--board-card-padding-x,0.625rem)] shadow-[var(--board-card-shadow,var(--surface-shadow))] transition-colors group-hover/card:border-foreground/15 group-hover/card:bg-board-card-hover group-data-[popup-open]/card:border-foreground/15 group-data-[popup-open]/card:bg-board-card-hover group-data-[peeked]/card:ring-2 group-data-[peeked]/card:ring-brand/50">+ className="rounded-board-card border-[0.5px] border-board-card-border bg-board-card py-[var(--board-card-padding-y,var(--space-sm,0.75rem))] px-[var(--board-card-padding-x,0.625rem)] shadow-[var(--board-card-shadow,var(--surface-shadow))] transition-colors group-hover/card:border-foreground/15 group-hover/card:bg-board-card-hover group-data-[popup-open]/card:border-foreground/15 group-data-[popup-open]/card:bg-board-card-hover group-data-[peeked]/card:ring-2 group-data-[peeked]/card:ring-brand/50 group-data-[cursor]/card:border-foreground/15 group-data-[cursor]/card:bg-board-card-hover group-data-[cursor]/card:ring-1 group-data-[cursor]/card:ring-ring/60">{/* Row 1: priority + identifier (left), agent activity + assignee (right) */}<div className="flex items-center justify-between gap-2"><div className="flex items-center gap-1.5 min-w-0">@@ -376,6 +377,7 @@ export const DraggableBoardCard = memo(function DraggableBoardCard({const p = useWorkspacePaths();const peek = useIssuePeekActions();const peeked = useIsIssuePeeked(issue.id);+ const cursor = useIsIssueCursor(issue.id);const peekLinkProps = useIssuePeekLinkProps(issue);const {attributes,@@ -404,6 +406,7 @@ export const DraggableBoardCard = memo(function DraggableBoardCard({data-board-card=""{...{ [PEEK_TARGET_ATTR]: issue.id }}data-peeked={peeked ? "" : undefined}+ data-cursor={cursor ? "" : undefined}{...attributes}{...listeners}className={`group/card transition-opacity duration-150 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none ${isDragging ? "opacity-30" : ""}`}diff --git a/packages/views/issues/components/issue-peek.test.tsx b/packages/views/issues/components/issue-peek.test.tsxindex 7cf725770d..e260126824 100644--- a/packages/views/issues/components/issue-peek.test.tsx+++ b/packages/views/issues/components/issue-peek.test.tsx@@ -339,6 +339,21 @@ describe("IssuePeekHost", () => {expect(screen.getByTestId("detail")).toHaveTextContent("a1");});+ it("keeps H / L at the board's outer columns, but not where there is one column", () => {+ renderHost([["a1"], ["b1"]]);+ openCard("b1");+ expect(fireEvent.keyDown(document.body, { key: "l" })).toBe(false);+ expect(fireEvent.keyDown(document.body, { key: "h" })).toBe(false);+ expect(screen.getByTestId("detail")).toHaveTextContent("a1");+ expect(fireEvent.keyDown(document.body, { key: "h" })).toBe(false);+ });++ it("leaves L to the issue shortcuts in a single-column list", () => {+ renderHost([["i-1", "i-2"]]);+ openCard("i-1");+ expect(fireEvent.keyDown(document.body, { key: "l" })).toBe(true);+ });+it("steps with the arrow keys, unless the reader clicked into the panel", () => {renderHost();openCard("i-1");diff --git a/packages/views/issues/components/issue-peek.tsx b/packages/views/issues/components/issue-peek.tsxindex 55f64bf24d..3be6745f5a 100644--- a/packages/views/issues/components/issue-peek.tsx+++ b/packages/views/issues/components/issue-peek.tsx@@ -34,12 +34,14 @@ import { useT } from "../../i18n";import { IssueDetail } from "./issue-detail";import {IssuePeekActionsContext,+ IssuePeekColumnsContext,IssuePeekIdContext,IssuePeekPositionContext,PEEK_TARGET_ATTR,hasIssueInColumns,locateInColumns,useIssuePeekActions,+ useIssuePeekColumns,useIssuePeekPosition,type IssuePeekActions,type IssuePeekColumns,@@ -156,6 +158,7 @@ export function IssuePeekHost({ children }: { children: ReactNode }) {<IssuePeekActionsContext.Provider value={actions}><IssuePeekIdContext.Provider value={openId}><IssuePeekPositionContext.Provider value={position}>+ <IssuePeekColumnsContext.Provider value={columns}><divdata-peek-open={openId ? "" : undefined}className="group/peek relative flex min-h-0 flex-1 flex-col [--issue-peek-width:520px]"@@ -178,6 +181,7 @@ export function IssuePeekHost({ children }: { children: ReactNode }) {)}</AnimatePresence></div>+ </IssuePeekColumnsContext.Provider></IssuePeekPositionContext.Provider></IssuePeekIdContext.Provider></IssuePeekActionsContext.Provider>@@ -282,6 +286,9 @@ function IssuePeekFollow({// Read through a ref so the listener is bound once, not on every step.const positionRef = useRef(position);positionRef.current = position;+ const columns = useIssuePeekColumns();+ const columnCountRef = useRef(0);+ columnCountRef.current = columns?.length ?? 0;useEffect(() => {// Whether the reader's last click landed in the panel. Clicking panel text@@ -312,7 +319,12 @@ function IssuePeekFollow({step = ARROW_STEPS[event.key];}const target = step ? positionRef.current?.[step] : null;- if (!target) return;+ if (!target) {+ // Where H / L step across columns, the last column keeps them too:+ // L there is not a cue to edit labels.+ if ((step === "leftId" || step === "rightId") && columnCountRef.current > 1) event.preventDefault();+ return;+ }event.preventDefault();actions.open(target);};diff --git a/packages/views/issues/components/list-row.tsx b/packages/views/issues/components/list-row.tsxindex 4b7f4363fb..e47aa94766 100644--- a/packages/views/issues/components/list-row.tsx+++ b/packages/views/issues/components/list-row.tsx@@ -28,6 +28,7 @@ import { IssueDuplicateOfMarker } from "./issue-duplicates";import { IssueAgentActivityIndicator } from "./issue-agent-activity-indicator";import { IssuePullRequestChips, useIssuePullRequestSummaries } from "./pull-request-chips";import { useIssueSurfaceSelection } from "../surface/selection-context";+import { CURSOR_ROW_CLASS, useIsIssueCursor } from "../surface/issue-cursor";import {PEEKED_ROW_CLASS,PEEK_TARGET_ATTR,@@ -76,6 +77,7 @@ function ListRowContent({const locale = useLocale();const selection = useIssueSurfaceSelection();const peeked = useIsIssuePeeked(issue.id);+ const cursor = useIsIssueCursor(issue.id);const peekLinkProps = useIssuePeekLinkProps(issue);const selected = selection.selectedIds.has(issue.id);const toggle = selection.toggle;@@ -111,13 +113,14 @@ function ListRowContent({data-selected={selected ? "true" : "false"}{...{ [PEEK_TARGET_ATTR]: issue.id }}data-peeked={peeked ? "" : undefined}+ data-cursor={cursor ? "" : undefined}style={containerStyle}{...containerProps}className={`group/row flex h-[var(--issue-row-height)] items-center gap-2 px-[var(--issue-row-padding-x,1rem)] text-body transition-[background-color,color,opacity] duration-150 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none ${selected? "bg-issue-row-selected hover:not-data-[popup-open]:bg-issue-row-selected data-[popup-open]:bg-issue-row-selected"- : "hover:not-data-[popup-open]:bg-issue-row-hover data-[popup-open]:bg-issue-row-hover"- } ${PEEKED_ROW_CLASS} ${isDragging ? "opacity-30" : ""}`}+ : "hover:not-data-[popup-open]:bg-issue-row-hover data-[popup-open]:bg-issue-row-hover data-[cursor]:bg-issue-row-hover"+ } ${PEEKED_ROW_CLASS} ${CURSOR_ROW_CLASS} ${isDragging ? "opacity-30" : ""}`}><divclassName="relative flex shrink-0 items-center justify-center w-4 h-4"diff --git a/packages/views/issues/components/table-view.tsx b/packages/views/issues/components/table-view.tsxindex 310455d6cd..0f1ddc8e05 100644--- a/packages/views/issues/components/table-view.tsx+++ b/packages/views/issues/components/table-view.tsx@@ -134,6 +134,7 @@ import { ProjectPicker } from "../../projects/components/project-picker";import { useT } from "../../i18n";import { useIssueSurfaceActionsOptional } from "../surface/actions-context";import { useIssueSurfaceSelection } from "../surface/selection-context";+import { CURSOR_ROW_CLASS, useIssueCursorId } from "../surface/issue-cursor";import {PEEK_TARGET_ATTR,useIssuePeekClick,@@ -2166,6 +2167,7 @@ export function TableView({// Side peek steps through the loaded rows top to bottom.const peek = useIssuePeekActions();const peekedId = useIssuePeekId();+ const cursorId = useIssueCursorId();const handlePeekClick = useIssuePeekClick();useEffect(() => {peek?.publishColumns([visibleIssueIds]);@@ -2584,8 +2586,12 @@ export function TableView({row.original.kind === "issue"? {[PEEK_TARGET_ATTR]: row.original.issue.id,- className:- row.original.issue.id === peekedId ? PEEKED_TABLE_ROW_CLASS : undefined,+ "data-cursor": row.original.issue.id === cursorId ? "" : undefined,+ className: cn(+ row.original.issue.id === peekedId && PEEKED_TABLE_ROW_CLASS,+ CURSOR_ROW_CLASS,+ "data-[cursor]:[&>td]:bg-issue-row-hover",+ ),}: undefined}diff --git a/packages/views/issues/surface/issue-cursor.test.tsx b/packages/views/issues/surface/issue-cursor.test.tsxnew file mode 100644index 0000000000..91d6e4df22--- /dev/null+++ b/packages/views/issues/surface/issue-cursor.test.tsx@@ -0,0 +1,352 @@+/**+ * @vitest-environment jsdom+ */+import { act, fireEvent, render, screen } from "@testing-library/react";+import { useMemo, useState, type ReactNode } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { useCommandBarContextStore } from "@multica/core/command-bar";+import { useIssueOpeningStore } from "@multica/core/issues/stores/issue-opening-store";+import { useModalStore } from "@multica/core/modals";+import type { Issue } from "@multica/core/types";+import { NavigationProvider, type NavigationAdapter } from "../../navigation";+import { IssueCursorProvider, useIsIssueCursor } from "./issue-cursor";+import {+ IssuePeekActionsContext,+ IssuePeekColumnsContext,+ IssuePeekIdContext,+ type IssuePeekActions,+ type IssuePeekColumns,+} from "./peek-context";+import {+ IssueSurfaceSelectionProvider,+ useCreateIssueSurfaceSelection,+ useIssueSurfaceSelection,+} from "./selection-context";++const LIST: IssuePeekColumns = [["i-1", "i-2", "i-3"]];+const BOARD: IssuePeekColumns = [["i-1", "i-2", "i-3"], ["i-4", "i-5"]];++const issueOf = (id: string) => ({ id, identifier: id.toUpperCase() }) as Issue;+const ISSUES = ["i-1", "i-2", "i-3", "i-4", "i-5"].map(issueOf);++vi.mock("@multica/core/paths", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/core/paths")>()),+ useWorkspacePaths: () => ({ issueDetail: (ref: string) => `/acme/issues/${ref}` }),+}));++const onOpen = vi.fn();+const onPullRequest = vi.fn();+const navigation: NavigationAdapter = {+ push: vi.fn(),+ replace: vi.fn(),+ back: vi.fn(),+ pathname: "/acme/issues",+ searchParams: new URLSearchParams(),+ hash: "",+ getShareableUrl: (path) => `https://app.example${path}`,+};++function Row({ id }: { id: string }) {+ const cursor = useIsIssueCursor(id);+ const { selectedIds } = useIssueSurfaceSelection();+ return (+ <div data-peek-target={id} data-testid={id} data-cursor={cursor ? "" : undefined} data-selected={selectedIds.has(id) ? "" : undefined}>+ {/* A table row's first link can be its pull request's. */}+ <a+ href="https://github.com/acme/app/pull/1"+ onClick={(event) => {+ event.preventDefault();+ onPullRequest(id);+ }}+ >+ PR {id}+ </a>+ <a+ href={`/acme/issues/${id}`}+ onClick={(event) => {+ event.preventDefault();+ onOpen(id);+ }}+ >+ {id}+ </a>+ <button type="button">menu {id}</button>+ </div>+ );+}++function Harness({+ columns,+ selectable = true,+ initialPeekId = null,+ children,+}: {+ columns: IssuePeekColumns;+ selectable?: boolean;+ initialPeekId?: string | null;+ children?: ReactNode;+}) {+ const [peekId, setPeekId] = useState<string | null>(initialPeekId);+ const selection = useCreateIssueSurfaceSelection("test");+ const actions = useMemo<IssuePeekActions>(+ () => ({+ open: setPeekId,+ toggle: (id) => setPeekId((current) => (current === id ? null : id)),+ close: () => setPeekId(null),+ publishColumns: () => {},+ }),+ [],+ );+ return (+ <NavigationProvider value={navigation}>+ <IssuePeekActionsContext.Provider value={actions}>+ <IssuePeekIdContext.Provider value={peekId}>+ <IssuePeekColumnsContext.Provider value={columns}>+ <IssueSurfaceSelectionProvider selection={selection}>+ <span data-testid="peek">{peekId ?? ""}</span>+ <button type="button" onClick={actions.close}>+ close peek+ </button>+ <IssueCursorProvider issues={ISSUES} selectable={selectable} enabled>+ {columns.flat().map((id) => (+ <Row key={id} id={id} />+ ))}+ </IssueCursorProvider>+ {children}+ </IssueSurfaceSelectionProvider>+ </IssuePeekColumnsContext.Provider>+ </IssuePeekIdContext.Provider>+ </IssuePeekActionsContext.Provider>+ </NavigationProvider>+ );+}++const press = (key: string, init: KeyboardEventInit = {}, target: Element = document.body) =>+ fireEvent.keyDown(target, { key, ...init });+const cursorId = () => document.querySelector("[data-cursor]")?.getAttribute("data-peek-target") ?? null;+const selectedIds = () =>+ Array.from(document.querySelectorAll("[data-selected]")).map((element) => element.getAttribute("data-peek-target"));+const cursorContexts = () =>+ useCommandBarContextStore+ .getState()+ .entries.map((entry) => entry.context)+ .filter((context) => context.kind === "issue" && context.cursor);++describe("IssueCursorProvider", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ useIssueOpeningStore.setState({ openMode: "page" });+ Element.prototype.scrollIntoView = vi.fn();+ });++ afterEach(() => {+ act(() => useModalStore.getState().close());+ });++ it("moves with J / K and the arrows, starting at the top and stopping at the ends", () => {+ render(<Harness columns={LIST} />);+ expect(cursorId()).toBeNull();++ press("j");+ expect(cursorId()).toBe("i-1");+ press("ArrowDown");+ press("j");+ expect(cursorId()).toBe("i-3");+ press("j");+ expect(cursorId()).toBe("i-3");+ press("k");+ press("ArrowUp");+ expect(cursorId()).toBe("i-1");+ });++ it("starts going up from the bottom", () => {+ render(<Harness columns={LIST} />);+ press("k");+ expect(cursorId()).toBe("i-3");+ });++ it("starts from the row the pointer is over, without showing until a key moves it", () => {+ render(<Harness columns={LIST} />);+ fireEvent.pointerMove(screen.getByTestId("i-2"), { clientX: 5, clientY: 5 });+ expect(cursorId()).toBeNull();++ press("j");+ expect(cursorId()).toBe("i-3");++ fireEvent.pointerMove(screen.getByTestId("i-1"), { clientX: 5, clientY: 50 });+ expect(cursorId()).toBeNull();++ press("j");+ expect(cursorId()).toBe("i-2");+ fireEvent.pointerMove(screen.getByTestId("i-2"), { clientX: 9, clientY: 60 });+ expect(cursorId()).toBeNull();+ });++ it("crosses board columns with ← / →", () => {+ render(<Harness columns={BOARD} />);+ press("j");+ press("j");+ expect(cursorId()).toBe("i-2");+ press("ArrowRight");+ expect(cursorId()).toBe("i-5");+ press("ArrowLeft");+ expect(cursorId()).toBe("i-2");+ });++ it("leaves ← / → alone in a single column", () => {+ render(<Harness columns={LIST} />);+ press("j");+ const event = new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true, cancelable: true });+ document.body.dispatchEvent(event);+ expect(event.defaultPrevented).toBe(false);+ });++ it("opens the issue's page with Enter, never a link inside its row", () => {+ render(<Harness columns={LIST} />);+ press("j");+ press("j");+ press("Enter");+ expect(navigation.push).toHaveBeenCalledWith("/acme/issues/I-2");+ expect(onPullRequest).not.toHaveBeenCalled();+ expect(onOpen).not.toHaveBeenCalled();+ });++ it("peeks with Enter where issues open in the peek, and with Space anywhere", () => {+ useIssueOpeningStore.setState({ openMode: "peek" });+ render(<Harness columns={LIST} />);+ press("j");+ press("Enter");+ expect(screen.getByTestId("peek")).toHaveTextContent("i-1");+ expect(navigation.push).not.toHaveBeenCalled();++ fireEvent.click(screen.getByText("close peek"));+ press("j");+ press(" ");+ expect(screen.getByTestId("peek")).toHaveTextContent("i-2");+ });++ it("does nothing with Enter or Space until the cursor shows", () => {+ render(<Harness columns={LIST} />);+ press("Enter");+ press(" ");+ expect(onOpen).not.toHaveBeenCalled();+ expect(screen.getByTestId("peek")).toHaveTextContent("");+ });++ it("follows an open peek and leaves the keys to it", () => {+ render(<Harness columns={LIST} initialPeekId="i-2" />);+ press("j");+ press("x");+ expect(screen.getByTestId("peek")).toHaveTextContent("i-2");+ expect(cursorId()).toBeNull();+ expect(selectedIds()).toEqual([]);++ fireEvent.click(screen.getByText("close peek"));+ expect(cursorId()).toBe("i-2");+ press("j");+ expect(cursorId()).toBe("i-3");+ });++ it("selects with X, extends with Shift, takes every row with ⌘A and clears with Esc", () => {+ render(<Harness columns={LIST} />);+ press("j");+ press("x");+ expect(selectedIds()).toEqual(["i-1"]);++ press("j", { shiftKey: true });+ press("ArrowDown", { shiftKey: true });+ expect(selectedIds()).toEqual(["i-1", "i-2", "i-3"]);+ press("k", { shiftKey: true });+ expect(selectedIds()).toEqual(["i-1", "i-2", "i-3"]);++ press("Escape");+ expect(selectedIds()).toEqual([]);+ expect(cursorId()).toBe("i-2");++ press("a", { metaKey: true });+ expect(selectedIds()).toEqual(["i-1", "i-2", "i-3"]);+ press("Escape");+ press("Escape");+ expect(cursorId()).toBeNull();+ });++ it("leaves ⌘A to the page until the cursor shows or something is selected", () => {+ render(<Harness columns={LIST} />);+ const event = new KeyboardEvent("keydown", { key: "a", metaKey: true, bubbles: true, cancelable: true });+ document.body.dispatchEvent(event);+ expect(event.defaultPrevented).toBe(false);+ expect(selectedIds()).toEqual([]);+ });++ it("does not select where the view shows no selection", () => {+ render(<Harness columns={BOARD} selectable={false} />);+ press("j");+ press("x");+ press("a", { metaKey: true });+ press("j", { shiftKey: true });+ expect(selectedIds()).toEqual([]);+ expect(cursorId()).toBe("i-2");+ });++ it("works from a focused row link, but leaves fields, buttons and dialogs their keys", () => {+ render(+ <Harness columns={LIST}>+ <input aria-label="field" />+ </Harness>,+ );+ press("j", {}, screen.getByText("i-1"));+ expect(cursorId()).toBe("i-1");++ press("j", {}, screen.getByLabelText("field"));+ press("j", {}, screen.getByText("menu i-1"));+ expect(cursorId()).toBe("i-1");++ act(() => useModalStore.getState().open("create-issue"));+ press("j");+ expect(cursorId()).toBe("i-1");+ });++ it("leaves every key to a modal layer, even with focus on the page behind it", () => {+ render(<Harness columns={LIST} />);+ press("j");+ const inert = document.createElement("div");+ inert.setAttribute("data-base-ui-inert", "");+ document.body.appendChild(inert);+ try {+ for (const key of ["j", "Escape", "Enter", " ", "x"]) {+ const event = new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true });+ document.body.dispatchEvent(event);+ expect(event.defaultPrevented).toBe(false);+ }+ expect(cursorId()).toBe("i-1");+ expect(navigation.push).not.toHaveBeenCalled();+ } finally {+ inert.remove();+ }+ });++ it("gives the command bar the cursor's issue while it shows", () => {+ render(<Harness columns={LIST} />);+ expect(cursorContexts()).toEqual([]);++ press("j");+ expect(cursorContexts()).toEqual([{ kind: "issue", issue: ISSUES[0], cursor: true }]);++ press("Escape");+ expect(cursorContexts()).toEqual([]);+ });++ it("keeps the hover peek's Space while the cursor is hidden", () => {+ const onSpace = vi.fn();+ document.addEventListener("keydown", onSpace);+ render(<Harness columns={LIST} />);+ press(" ");+ expect(onSpace).toHaveBeenCalled();+ onSpace.mockClear();++ press("j");+ press(" ");+ expect(onSpace).not.toHaveBeenCalled();+ document.removeEventListener("keydown", onSpace);+ });+});diff --git a/packages/views/issues/surface/issue-cursor.tsx b/packages/views/issues/surface/issue-cursor.tsxnew file mode 100644index 0000000000..1ea4667d26--- /dev/null+++ b/packages/views/issues/surface/issue-cursor.tsx@@ -0,0 +1,302 @@+"use client";++import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from "react";+import { useModalStore } from "@multica/core/modals";+import { issueRouteRef, useWorkspacePaths } from "@multica/core/paths";+import { isEditableShortcutTarget, isPortalLayerShortcutTarget } from "@multica/core/shortcuts";+import type { Issue } from "@multica/core/types";+import { isImeComposing } from "@multica/core/utils";+import { useIntentNavigate } from "../../navigation";+import { useRegisterCommandBarContext } from "../../search/register-context";+import {+ PEEK_TARGET_ATTR,+ hasIssueInColumns,+ locateInColumns,+ useIssuePeekActions,+ useIssuePeekClick,+ useIssuePeekColumns,+ useIssuePeekId,+ type IssuePeekColumns,+ type IssuePeekPosition,+} from "./peek-context";+import { useIssueSurfaceSelection, type IssueSurfaceSelection } from "./selection-context";++/**+ * The row a list, table or board's keyboard cursor is on, while it shows.+ * Rows and cards paint `data-cursor` from it.+ */+const IssueCursorContext = createContext<string | null>(null);++export function useIsIssueCursor(issueId: string) {+ return useContext(IssueCursorContext) === issueId;+}++/** The cursor's row, for views that mark rows without a per-row hook. */+export function useIssueCursorId() {+ return useContext(IssueCursorContext);+}++/** The cursor on a row (list, table): a ring, over the row's hover or selected background. */+export const CURSOR_ROW_CLASS =+ "data-[cursor]:outline data-[cursor]:outline-1 data-[cursor]:-outline-offset-1 data-[cursor]:outline-ring/60";++type Step = keyof Pick<IssuePeekPosition, "prevId" | "nextId" | "leftId" | "rightId">;++interface Cursor {+ id: string;+ /**+ * False when only the pointer put it there: the row's hover already shows+ * it, and nothing but a key (or the peek) should act on it.+ */+ visible: boolean;+}++/**+ * Keyboard flow over the issues a view publishes to its peek host (see+ * `publishColumns`): J / K or ↑ / ↓ move the cursor, ← / → across board+ * columns, Enter opens the issue as a click would, Space peeks it. In views+ * with a selection, X toggles the row, Shift extends from the last toggled+ * one, ⌘A selects every row and Esc clears the selection, then the cursor.+ *+ * The cursor starts where the pointer last was, and follows the peek while+ * one is open (the peek owns these keys then). Its issue is the command+ * bar's, below a peek or a selection, so the issue verbs (S, A, P, ...) act+ * on it.+ */+export function IssueCursorProvider({+ issues,+ selectable,+ enabled,+ children,+}: {+ /** The issues behind the published ids, for the command bar context. */+ issues: readonly Issue[];+ /** Whether this view shows its selection (list, table). */+ selectable: boolean;+ /** Off for views that paint no cursor (swimlane, gantt). */+ enabled: boolean;+ children: ReactNode;+}) {+ const columns = useIssuePeekColumns();+ const peek = useIssuePeekActions();+ const peekId = useIssuePeekId();+ const selection = useIssueSurfaceSelection();+ const [cursor, setCursor] = useState<Cursor | null>(null);+ const rootRef = useRef<HTMLDivElement>(null);+ const anchorRef = useRef<string | null>(null);++ // A cursor left on an issue the view no longer shows starts over.+ const cursorId = enabled && cursor && hasIssueInColumns(columns, cursor.id) ? cursor.id : null;+ // The peek marks its own issue while it is open.+ const shownId = cursor?.visible && !peekId ? cursorId : null;++ useEffect(() => {+ if (peekId) setCursor({ id: peekId, visible: true });+ }, [peekId]);++ useEffect(() => {+ if (selection.selectedIds.size === 0) anchorRef.current = null;+ }, [selection.selectedIds]);++ useEffect(() => {+ if (!shownId) return;+ rootRef.current+ ?.querySelector(`[${PEEK_TARGET_ATTR}="${CSS.escape(shownId)}"]`)+ ?.scrollIntoView?.({ block: "nearest", inline: "nearest" });+ }, [shownId]);++ const cursorIssue = useMemo(+ () => (shownId ? (issues.find((issue) => issue.id === shownId) ?? null) : null),+ [issues, shownId],+ );+ useRegisterCommandBarContext(+ useMemo(() => (cursorIssue ? { kind: "issue", issue: cursorIssue, cursor: true } : null), [cursorIssue]),+ );++ // Enter opens the issue as a click on it would: peek or page, per the+ // reader's open mode. Not by clicking the row's DOM, where a table row's+ // first link can be a pull request's.+ const peekClick = useIssuePeekClick();+ const intentNavigate = useIntentNavigate();+ const paths = useWorkspacePaths();+ const openIssue = useCallback(+ (issue: Issue) => {+ if (!peekClick(issue)) intentNavigate(paths.issueDetail(issueRouteRef(issue)), "push", issue.identifier);+ },+ [intentNavigate, paths, peekClick],+ );++ // Captured, so a key the cursor takes reaches neither the hover peek's+ // Space, the focused row's own handlers nor its link's native Enter.+ const stateRef = useRef({ enabled, columns, cursorId, shownId, cursorIssue, peekId, peek, selection, selectable, openIssue });+ stateRef.current = { enabled, columns, cursorId, shownId, cursorIssue, peekId, peek, selection, selectable, openIssue };++ useEffect(() => {+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.defaultPrevented || event.altKey || isImeComposing(event)) return;+ if (!isCursorKeyTarget(event.target)) return;+ if (useModalStore.getState().modal) return;+ const state = stateRef.current;+ if (!state.enabled || state.peekId || !state.columns) return;+ const handled = handleKey(event, state, {+ moveTo: (id) => setCursor({ id, visible: true }),+ clear: () => setCursor(null),+ anchorRef,+ });+ if (!handled) return;+ event.preventDefault();+ event.stopPropagation();+ };+ document.addEventListener("keydown", onKeyDown, true);+ return () => document.removeEventListener("keydown", onKeyDown, true);+ }, []);++ const lastPointerRef = useRef<{ x: number; y: number } | null>(null);+ return (+ <IssueCursorContext.Provider value={shownId}>+ <div+ ref={rootRef}+ className="contents"+ onPointerMove={(event) => {+ // Content scrolling under a still pointer is not the user pointing.+ const last = lastPointerRef.current;+ lastPointerRef.current = { x: event.clientX, y: event.clientY };+ if (last && last.x === event.clientX && last.y === event.clientY) return;+ // Pointing takes over from the keys: the cursor moves to the row+ // under the pointer and hides, as the row's hover shows it.+ const id = (event.target as Element).closest(`[${PEEK_TARGET_ATTR}]`)?.getAttribute(PEEK_TARGET_ATTR);+ if (id) {+ if (id !== cursor?.id || cursor?.visible) setCursor({ id, visible: false });+ } else if (cursor?.visible) {+ setCursor({ ...cursor, visible: false });+ }+ }}+ >+ {children}+ </div>+ </IssueCursorContext.Provider>+ );+}++interface KeyState {+ columns: IssuePeekColumns | null;+ cursorId: string | null;+ shownId: string | null;+ cursorIssue: Issue | null;+ peek: ReturnType<typeof useIssuePeekActions>;+ selection: IssueSurfaceSelection;+ selectable: boolean;+ openIssue: (issue: Issue) => void;+}++function handleKey(+ event: KeyboardEvent,+ state: KeyState,+ ops: {+ moveTo: (id: string) => void;+ clear: () => void;+ anchorRef: { current: string | null };+ },+): boolean {+ const columns = state.columns ?? [];+ const mod = event.metaKey || event.ctrlKey;+ const { selection, selectable, shownId } = state;++ const move = (step: Step) => {+ const from = state.cursorId;+ const position = locateInColumns(columns, from);+ const next = position ? (position[step] ?? from) : firstId(columns, step);+ if (!next) return false;+ if (event.shiftKey && selectable && from && (step === "prevId" || step === "nextId")) {+ const anchor = ops.anchorRef.current ?? from;+ ops.anchorRef.current = anchor;+ const range = rangeInColumn(columns, anchor, next);+ if (range) selection.select(range);+ }+ ops.moveTo(next);+ return true;+ };++ if (mod) {+ if (event.key.toLowerCase() !== "a" || event.shiftKey || !selectable) return false;+ if (!shownId && selection.selectedIds.size === 0) return false;+ selection.select(columns.flat());+ return true;+ }++ // Held down, only the moves repeat.+ if (event.repeat && (event.key === "x" || event.key === "X" || event.key === "Enter" || event.key === " ")) {+ return shownId !== null;+ }++ switch (event.key) {+ case "j":+ case "J":+ case "ArrowDown":+ return move("nextId");+ case "k":+ case "K":+ case "ArrowUp":+ return move("prevId");+ case "ArrowLeft":+ case "ArrowRight":+ if (columns.length < 2 || event.shiftKey) return false;+ return move(event.key === "ArrowLeft" ? "leftId" : "rightId");+ case "x":+ case "X":+ if (!selectable || !shownId || event.shiftKey) return false;+ selection.toggle(shownId);+ ops.anchorRef.current = shownId;+ return true;+ case "Enter":+ if (!state.cursorIssue || event.shiftKey) return false;+ state.openIssue(state.cursorIssue);+ return true;+ case " ":+ if (!shownId || !state.peek || event.shiftKey) return false;+ state.peek.toggle(shownId);+ return true;+ case "Escape":+ if (selectable && selection.selectedIds.size > 0) {+ selection.clear();+ ops.anchorRef.current = null;+ return true;+ }+ if (!shownId) return false;+ ops.clear();+ return true;+ default:+ return false;+ }+}++/** Where a first step lands with no cursor yet: the top of the first column, or the bottom going up. */+function firstId(columns: IssuePeekColumns, step: Step): string | null {+ const column = columns.find((ids) => ids.length > 0);+ if (!column) return null;+ return step === "prevId" ? column[column.length - 1]! : column[0]!;+}++function rangeInColumn(columns: IssuePeekColumns, from: string, to: string): string[] | null {+ for (const column of columns) {+ const a = column.indexOf(from);+ const b = column.indexOf(to);+ if (a === -1 || b === -1) continue;+ return column.slice(Math.min(a, b), Math.max(a, b) + 1);+ }+ return null;+}++/**+ * The page itself, or a row's own element or link: a focused button, menu+ * trigger or field keeps its keys.+ */+function isCursorKeyTarget(target: EventTarget | null): boolean {+ // First: with a modal layer open, even the page itself is behind it.+ if (isPortalLayerShortcutTarget(target)) return false;+ if (!(target instanceof Element) || target === document.body) return true;+ if (isEditableShortcutTarget(target)) return false;+ const row = target.closest(`[${PEEK_TARGET_ATTR}]`);+ if (!row || row.closest("[data-issue-peek]")) return false;+ return target === row || target.tagName === "A";+}diff --git a/packages/views/issues/surface/issue-surface.tsx b/packages/views/issues/surface/issue-surface.tsxindex 958cb5f764..00543526a1 100644--- a/packages/views/issues/surface/issue-surface.tsx+++ b/packages/views/issues/surface/issue-surface.tsx@@ -51,6 +51,7 @@ import { useWarmRoute } from "../../navigation";import { IssueContextMenuProvider } from "../actions";import { IssueSurfaceActionsProvider } from "./actions-context";import { IssuePeekHost } from "../components/issue-peek";+import { IssueCursorProvider } from "./issue-cursor";import { IssueSurfaceSelectionProvider } from "./selection-context";import { ColumnStatusesProvider } from "./column-statuses-context";import type { IssueCreateDefaults, IssueSurfaceProps } from "./types";@@ -378,6 +379,11 @@ function IssueSurfaceContent({/>)) : (+ <IssueCursorProvider+ issues={controller.viewMode === "table" ? tableLoadedIssues : issues}+ selectable={shouldShowBatchToolbar && controller.viewMode !== "board"}+ enabled={controller.viewMode === "list" || controller.viewMode === "table" || controller.viewMode === "board"}+ ><div className={cn("flex flex-col flex-1 min-h-0", contentClassName)}>{controller.viewMode === "board" && (<BoardView@@ -434,6 +440,7 @@ function IssueSurfaceContent({/>)}</div>+ </IssueCursorProvider>)}</IssuePeekHost>{shouldShowBatchToolbar && (diff --git a/packages/views/issues/surface/peek-context.tsx b/packages/views/issues/surface/peek-context.tsxindex ac0769dd4d..79a9c46782 100644--- a/packages/views/issues/surface/peek-context.tsx+++ b/packages/views/issues/surface/peek-context.tsx@@ -126,6 +126,7 @@ export function resolveIssueClick(export const IssuePeekActionsContext = createContext<IssuePeekActions | null>(null);export const IssuePeekIdContext = createContext<string | null>(null);export const IssuePeekPositionContext = createContext<IssuePeekPosition | null>(null);+export const IssuePeekColumnsContext = createContext<IssuePeekColumns | null>(null);/** `null` outside a surface that hosts a peek (e.g. a board inside a dialog). */export function useIssuePeekActions() {@@ -149,6 +150,11 @@ export function useIssuePeekPosition() {return useContext(IssuePeekPositionContext);}+/** The current view's published order (see `publishColumns`). */+export function useIssuePeekColumns() {+ return useContext(IssuePeekColumnsContext);+}+type PeekIssue = Pick<Issue, "id" | "identifier">;/**diff --git a/packages/views/search/issue-target.test.tsx b/packages/views/search/issue-target.test.tsxindex 721ae9a1b4..adc93a2309 100644--- a/packages/views/search/issue-target.test.tsx+++ b/packages/views/search/issue-target.test.tsx@@ -6,7 +6,7 @@ import { buildIssueStatusCatalog } from "@multica/core/issue-statuses/queries";import { I18nProvider } from "@multica/core/i18n/react";import type { Issue } from "@multica/core/types";import { RESOURCES } from "../locales";-import { useIssueTargetWriter } from "./issue-target";+import { issueTargetFromContexts, useIssueTargetWriter } from "./issue-target";import type { IssueTarget } from "./types";const { mockUpdateIssue, mockToast, mockOpenModal } = vi.hoisted(() => ({@@ -60,6 +60,32 @@ function renderWriter(target: IssueTarget) {return renderHook(() => useIssueTargetWriter(target), { wrapper });}+describe("issueTargetFromContexts", () => {+ const other = { ...issue, id: "issue-2", identifier: "MUL-2" } as Issue;+ const clearSelection = () => {};++ it("takes the newest issue or selection", () => {+ expect(issueTargetFromContexts([{ kind: "issue", issue: other }, { kind: "issue", issue }])).toEqual({+ kind: "single",+ issue: other,+ });+ expect(+ issueTargetFromContexts([{ kind: "issues", issues: [issue, other], clearSelection }, { kind: "issue", issue }]),+ ).toEqual({ kind: "batch", issues: [issue, other], clearSelection });+ });++ it("puts a list cursor behind a selection or a peeked issue, even a later one", () => {+ const cursor = { kind: "issue", issue: other, cursor: true } as const;+ expect(issueTargetFromContexts([cursor, { kind: "issue", issue }])).toEqual({ kind: "single", issue });+ expect(issueTargetFromContexts([cursor, { kind: "issues", issues: [issue], clearSelection }])).toEqual({+ kind: "batch",+ issues: [issue],+ clearSelection,+ });+ expect(issueTargetFromContexts([cursor])).toEqual({ kind: "single", issue: other });+ });+});+describe("useIssueTargetWriter", () => {beforeEach(() => {mockUpdateIssue.mockReset();diff --git a/packages/views/search/issue-target.ts b/packages/views/search/issue-target.tsindex 2796f94852..d018b43ef6 100644--- a/packages/views/search/issue-target.ts+++ b/packages/views/search/issue-target.ts@@ -19,9 +19,22 @@ export function targetIssues(target: IssueTarget): Issue[] {return target.kind === "single" ? [target.issue] : target.issues;}-/** What issue commands act on: the newest issue or selection a page registered. */+/** `contexts` (newest first) with a list cursor's issue moved behind the rest. */+export function withCursorLast(contexts: readonly CommandBarContext[]): readonly CommandBarContext[] {+ if (!contexts.some(isCursorContext)) return contexts;+ return [...contexts.filter((context) => !isCursorContext(context)), ...contexts.filter(isCursorContext)];+}++function isCursorContext(context: CommandBarContext): boolean {+ return context.kind === "issue" && context.cursor === true;+}++/**+ * What issue commands act on: the newest issue or selection a page+ * registered, and a list cursor's issue only when there is neither.+ */export function issueTargetFromContexts(contexts: readonly CommandBarContext[]): IssueTarget | null {- for (const context of contexts) {+ for (const context of withCursorLast(contexts)) {if (context.kind === "issue") return { kind: "single", issue: context.issue };if (context.kind === "issues") {return { kind: "batch", issues: context.issues, clearSelection: context.clearSelection };diff --git a/packages/views/search/search-command.test.tsx b/packages/views/search/search-command.test.tsxindex 2658c1f366..48bd1b5359 100644--- a/packages/views/search/search-command.test.tsx+++ b/packages/views/search/search-command.test.tsx@@ -1088,6 +1088,13 @@ describe("SearchCommand", () => {expect(input().value).toBe("");});+ it("keeps the page's issue ahead of a list cursor registered after it", () => {+ registerContext({ kind: "issue", issue: makeIssue({ id: "issue-2", identifier: "MUL-7" }), cursor: true });+ renderSearch();++ expect(renderedHeadings()[0]).toContain("MUL-42");+ });+it("opens a submenu from its row, with the issue in the breadcrumb", async () => {const user = userEvent.setup();renderSearch();diff --git a/packages/views/search/use-root-model.ts b/packages/views/search/use-root-model.tsindex 9985770780..773a04d4c9 100644--- a/packages/views/search/use-root-model.ts+++ b/packages/views/search/use-root-model.ts@@ -14,6 +14,7 @@ import { useT } from "../i18n";import { useAgentCommandGroup, useAutopilotCommandGroup, useChatCommandGroup, useInboxCommandGroup, useProjectCommandGroup } from "./commands/context-commands";import { useGlobalCommands } from "./commands/global-commands";import { useIssueCommandGroup } from "./commands/issue-commands";+import { withCursorLast } from "./issue-target";import { parseScope, scoreRow, scoreText, type SearchScope } from "./matching";import type { IssueTarget, PaletteCommand, PaletteCommandGroup } from "./types";import type { AgentEntry } from "./use-actor-directory";@@ -157,9 +158,10 @@ function maxScore(entries: readonly { score: number }[]) {export function useRootModel(rawQuery: string,- contexts: readonly CommandBarContext[],+ registeredContexts: readonly CommandBarContext[],options: { active: boolean },): RootModel {+ const contexts = useMemo(() => withCursorLast(registeredContexts), [registeredContexts]);const { t: tNav } = useT("layout");const { scope, text } = parseScope(rawQuery);const q = text.toLowerCase();