// @vitest-environment jsdom // // `lib/listNav` against real DOM: `j`/`k` from item to item and across lists in reading order, the // arrows around a grid, Enter as a click on the item's own "open" element — and the places where the // keys must stay out of the way (a field, an overlay, a control inside the card). import { useRef } from "react"; import { afterEach, describe, expect, it, vi } from "vitest"; import { act, cleanup, render, screen, waitFor } from "@testing-library/react"; import { navItemAttrs, useListNav } from "./listNav"; import { pushLayer, removeLayer } from "./layerStack"; afterEach(cleanup); function List({ id, count, cols = 1, mounted, reveal, measure, onOpen = () => {}, }: { id: string; count: number; cols?: number; /** Mount only the first N items, the way a virtualized grid leaves the rest out of the DOM. */ mounted?: number; reveal?: (index: number) => void; /** Register without a count or columns — a rail or plain grid, measured from the DOM. */ measure?: boolean; onOpen?: (id: string) => void; }) { const ref = useRef(null); useListNav(ref, measure ? { enabled: true } : { enabled: true, count, cols, reveal }); return (
{Array.from({ length: mounted ?? count }, (_, i) => (
{ e.preventDefault(); onOpen(`${id}${i}`); }} > title
))}
); } /** A keydown where a real one starts: on whatever holds focus, bubbling to the window listener. */ function press(key: string): KeyboardEvent { const e = new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }); act(() => { (document.activeElement ?? document.body).dispatchEvent(e); }); return e; } const focused = () => (document.activeElement as HTMLElement | null)?.dataset.testid; describe("useListNav", () => { it("lands the first j on an item, then steps one item at a time", () => { render(); press("j"); expect(focused()).toBe("a0"); press("j"); expect(focused()).toBe("a1"); press("k"); expect(focused()).toBe("a0"); }); // The Tab order is the reader's, not ours: only the item the keyboard is on is focusable, and the // previous one gives its tabindex back. it("roves a single tabindex=-1 and never adds a Tab stop", () => { render(); expect(screen.getByTestId("a0").hasAttribute("tabindex")).toBe(false); press("j"); expect(screen.getByTestId("a0").getAttribute("tabindex")).toBe("-1"); press("j"); expect(screen.getByTestId("a0").hasAttribute("tabindex")).toBe(false); expect(screen.getByTestId("a1").getAttribute("tabindex")).toBe("-1"); }); // The player (E11 S2) restores focus to whatever held it when it opened. If the item gave its // tabindex back on blur, that restore would silently fail and focus would fall to . it("keeps the item focusable after focus leaves it, so a dialog can restore onto it", () => { render( <> , ); press("j"); act(() => screen.getByTestId("outside").focus()); act(() => screen.getByTestId("a0").focus()); expect(focused()).toBe("a0"); }); it("stops at both ends of the page instead of wrapping", () => { render(); press("j"); press("k"); expect(focused()).toBe("a0"); press("j"); press("j"); expect(focused()).toBe("a1"); }); // Owner decision D4: j/k walk every collection on the page in reading order. it("continues into the next list, and back, in document order", () => { render( <> , ); press("j"); press("j"); press("j"); expect(focused()).toBe("b0"); press("k"); expect(focused()).toBe("a1"); }); it("moves around a grid with the arrows, row by row", () => { // 3 columns, 7 items: rows [0 1 2] [3 4 5] [6] render(); press("j"); press("ArrowRight"); expect(focused()).toBe("a1"); press("ArrowDown"); expect(focused()).toBe("a4"); press("ArrowDown"); // the row below is short: land on its last item expect(focused()).toBe("a6"); press("ArrowDown"); // already on the last row expect(focused()).toBe("a6"); press("ArrowUp"); expect(focused()).toBe("a3"); press("ArrowLeft"); // left wraps to the end of the row above — reading order expect(focused()).toBe("a2"); }); it("works the arrows from a control inside the card too", () => { render(); act(() => screen.getByTestId("a0-action").focus()); press("ArrowDown"); expect(focused()).toBe("a2"); }); // Outside a list an arrow scrolls the page; that native meaning must survive. it("leaves the arrows alone when focus is not in a list", () => { render(); expect(press("ArrowDown").defaultPrevented).toBe(false); expect(focused()).toBeUndefined(); }); it("opens the item on Enter by clicking its own open element", () => { const onOpen = vi.fn(); render(); press("j"); press("j"); expect(press("Enter").defaultPrevented).toBe(true); expect(onOpen).toHaveBeenCalledWith("a1"); }); it("leaves Enter to a control inside the card", () => { const onOpen = vi.fn(); render(); act(() => screen.getByTestId("a0-action").focus()); expect(press("Enter").defaultPrevented).toBe(false); expect(onOpen).not.toHaveBeenCalled(); }); it("stays out of a text field", () => { render( <> , ); act(() => screen.getByTestId("field").focus()); press("j"); expect(focused()).toBe("field"); }); it("is quiet under a layer that owns the keyboard, but not under a tooltip", () => { render(); const modal = pushLayer(); press("j"); expect(focused()).toBeUndefined(); removeLayer(modal); const tooltip = pushLayer({ passive: true }); press("j"); expect(focused()).toBe("a0"); removeLayer(tooltip); }); // A virtualized grid only mounts a screen of rows: the next item may not exist yet. it("asks the list to reveal an unmounted item, then focuses it once it renders", async () => { const reveal = vi.fn(); const { rerender } = render(); press("j"); press("j"); press("j"); expect(reveal).toHaveBeenCalledWith(2); expect(focused()).toBe("a1"); rerender(); await waitFor(() => expect(focused()).toBe("a2")); }); it("unbinds when the last list unmounts", () => { const { unmount } = render(); unmount(); expect(press("j").defaultPrevented).toBe(false); }); }); // jsdom lays nothing out, so the tests below give each item a box: `boxes` maps an item's test id // (`a0`, `b3`) to where it sits. Everything else — the list containers — is a zero box at the origin. function withLayout( boxes: (id: string, n: number) => { left: number; top: number } | null, run: () => void, ) { const spy = vi.spyOn(Element.prototype, "getBoundingClientRect").mockImplementation(function ( this: Element, ) { const m = /^([a-z])(\d+)$/.exec((this as HTMLElement).dataset?.testid ?? ""); const at = m ? boxes(m[1]!, Number(m[2])) : null; const { left, top } = at ?? { left: 0, top: 0 }; const size = at ? 90 : 0; return { left, top, right: left + size, bottom: top + size, width: size, height: size, x: left, y: top, } as DOMRect; }); // Restored in `finally`: a spy left behind by a failing assertion would fail every later test. try { run(); } finally { spy.mockRestore(); } } describe("useListNav · measured lists (rails and plain grids)", () => { it("reads the item count and the columns off the DOM when the list does not give them", () => { // Three to a row: [0 1 2] [3 4 5] [6] withLayout( (_, n) => ({ left: (n % 3) * 100, top: Math.floor(n / 3) * 100 }), () => { render(); press("j"); press("ArrowDown"); expect(focused()).toBe("a3"); press("ArrowDown"); expect(focused()).toBe("a6"); press("ArrowRight"); // the last item: nothing past it expect(focused()).toBe("a6"); }, ); }); // Owner decision D4: ↑↓ from a rail go to the rail above or below, not nowhere. it("goes on from a list's bottom row to the next list's nearest item, and back up", () => { withLayout( // Two rails of four; the lower one sits 30px further right. (list, n) => (list === "a" ? { left: n * 100, top: 0 } : { left: n * 100 + 30, top: 200 }), () => { render( <> , ); press("j"); press("ArrowRight"); press("ArrowRight"); expect(focused()).toBe("a2"); press("ArrowDown"); expect(focused()).toBe("b2"); // centre 275 is nearest a2's 45+200 press("ArrowDown"); // the page's last list: stays expect(focused()).toBe("b2"); press("ArrowUp"); expect(focused()).toBe("a2"); press("ArrowRight"); press("ArrowRight"); // ←→ never leave the rail expect(focused()).toBe("a3"); }, ); }); it("lands the first j on the first card a rail shows, not one scrolled out to the left", () => { withLayout( (_, n) => ({ left: (n - 2) * 100, top: 0 }), // a0 and a1 sit left of the rail's edge () => { render(); press("j"); expect(focused()).toBe("a2"); }, ); }); }); describe("useListNav · keys and lists it must leave alone", () => { // DataTable renders its rows twice — a table and a card list, one of them display:none at any width. it("skips a list that is not on screen", () => { render( <> , ); Object.defineProperty(screen.getByTestId("a0").parentElement!, "checkVisibility", { value: () => false, }); press("j"); expect(focused()).toBe("b0"); press("k"); expect(focused()).toBe("b0"); }); // A playlist row's drag handle moves the row with the arrows during a keyboard drag; dnd-kit handles // the key on the document first and prevents its default. Moving focus as well would drop the drag. it("leaves a key that something before it already handled", () => { render(); press("j"); const handled = (e: KeyboardEvent) => e.preventDefault(); document.addEventListener("keydown", handled); try { press("ArrowDown"); press("j"); expect(focused()).toBe("a0"); } finally { document.removeEventListener("keydown", handled); } press("ArrowDown"); expect(focused()).toBe("a1"); }); });