feat(v2): improve keyboard tab navigation in the gallery

- useGridNav: keep every card in the Tab order (Tab walks card → card)
  while pulling the hidden in-card hover-overlay action buttons out of it
  (tabindex="-1"), applied eagerly on mount and re-synced as virtualised
  rows mount/unmount. Adds tests.
- GalleryShell: opt the virtual scroller out of the tab order
  (tabindex="-1") so Tab no longer lands on the scroll container.
- RBtn: stop the scoped `outline: none` from swallowing the global
  modality-gated focus ring; only clear the native UA outline for
  non-focus-visible (mouse) focus, so keyboard/pad show the branded ring.
- RTabNav: replace the outline focus ring (clipped into vertical slivers
  by the nav's overflow) with a contained, rounded inset focus highlight.

Generated-By: PostHog Code
Task-Id: 2dcae833-1422-499e-bf58-0c555cf5e96e
This commit is contained in:
Georges-Antoine Assi
2026-07-06 11:02:56 -04:00
parent a750e3ee40
commit affc739f7e
5 changed files with 236 additions and 17 deletions

View File

@@ -878,6 +878,7 @@ defineExpose({
:overscan="virtualOverscan"
:min-content-width="layout === 'list' ? listMinWidth : undefined"
class="r-v2-shell__scroller r-v2-scroll-hidden"
:tabindex="-1"
@update:viewport-range="onViewportRangeChange"
>
<!-- HEADER (Section 1) + INFLOW TOOLBAR (Section 2 — first

View File

@@ -0,0 +1,136 @@
import { mount } from "@vue/test-utils";
import { createPinia, setActivePinia } from "pinia";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { defineComponent, h, nextTick, ref, type Ref } from "vue";
import { useGridNav } from "./index";
// useGridNav reads the input modality and the current route; stub both so
// the composable can run outside a real app shell. Modality stays "mouse"
// so the pad-only autofocus never fires and steals focus mid-test.
vi.mock("@/v2/composables/useInputModality", () => ({
useInputModality: () => ({ modality: ref("mouse") }),
}));
vi.mock("vue-router", () => ({
useRoute: () => ({ fullPath: "/test" }),
}));
// Resolve after the composable's coalescing rAF has fired.
const raf = () =>
new Promise<void>((res) => requestAnimationFrame(() => res()));
// A grid host: one row per entry in `shape`, that many cards in it. Each
// card is an <a> wrapping a hidden overlay <button> (mirrors GameCard's
// hover-overlay actions — focusable even while invisible).
function mountGrid(shape: number[]) {
const Host = defineComponent({
setup() {
const root = ref<HTMLElement | null>(null) as Ref<HTMLElement | null>;
useGridNav(root, { rowSelector: ".row" });
return { root };
},
render() {
return h(
"section",
{ ref: "root" },
shape.map((count, r) =>
h(
"div",
{ class: "row" },
Array.from({ length: count }, (_, c) =>
h(
"a",
{ href: "#", class: "card", "data-focus-key": `k-${r}-${c}` },
[h("button", { class: "overlay" }, "action")],
),
),
),
),
);
},
});
return mount(Host, { attachTo: document.body });
}
function cards(root: Element) {
return Array.from(root.querySelectorAll<HTMLElement>(".card"));
}
function overlays(root: Element) {
return Array.from(root.querySelectorAll<HTMLElement>(".overlay"));
}
beforeEach(() => {
setActivePinia(createPinia());
// happy-dom doesn't implement scrollIntoView on elements.
Element.prototype.scrollIntoView = vi.fn();
});
afterEach(() => {
document.body.innerHTML = "";
});
describe("useGridNav tab order", () => {
it("keeps every card in the tab order but drops the in-card overlay buttons", async () => {
const wrapper = mountGrid([3, 3]);
await nextTick();
await raf();
const root = wrapper.element as HTMLElement;
// Every one of the 6 cards is tabbable, so Tab walks card → card.
for (const card of cards(root)) {
expect(card.getAttribute("tabindex")).toBe("0");
}
// ...and none of the hidden overlay buttons are (Tab skips them).
for (const overlay of overlays(root)) {
expect(overlay.getAttribute("tabindex")).toBe("-1");
}
wrapper.unmount();
});
it("moves focus to the adjacent card with arrow keys", async () => {
const wrapper = mountGrid([3, 3]);
await nextTick();
await raf();
const root = wrapper.element as HTMLElement;
const firstCard = root.querySelector<HTMLElement>(
'[data-focus-key="k-0-0"]',
)!;
firstCard.focus();
window.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight" }));
await nextTick();
const active = document.activeElement as HTMLElement;
expect(active.getAttribute("data-focus-key")).toBe("k-0-1");
wrapper.unmount();
});
it("keeps overlay buttons out of the tab order after new rows mount", async () => {
const wrapper = mountGrid([2]);
await nextTick();
await raf();
const root = wrapper.element as HTMLElement;
// Append a fresh row straight into the DOM (as the virtualiser does
// when the user scrolls) — its overlay button arrives as a natural
// tab stop until the mutation observer re-syncs.
const newRow = document.createElement("div");
newRow.className = "row";
newRow.innerHTML =
'<a href="#" class="card" data-focus-key="k-9-0"><button class="overlay">action</button></a>';
root.appendChild(newRow);
// One frame for the mutation observer to fire scheduleRefresh, another
// for the refresh's own coalescing rAF to run syncRoving.
await raf();
await raf();
const newCard = root.querySelector<HTMLElement>(
'[data-focus-key="k-9-0"]',
)!;
// The new card joins the tab order; its overlay button stays out.
expect(newCard.getAttribute("tabindex")).toBe("0");
expect(newCard.querySelector(".overlay")!.getAttribute("tabindex")).toBe(
"-1",
);
wrapper.unmount();
});
});

View File

@@ -18,6 +18,14 @@
// * On autofocus we remember a "preferred column" and restore it when
// moving up/down through rows of different lengths — common media-UI
// pattern so row switching doesn't permanently lose horizontal place.
// * Tab order — every cell's primary focusable (the card link / row
// anchor) stays in the natural Tab sequence, so Tab walks card → card
// and only leaves the grid past the last rendered cell. What does NOT
// stay are the nested in-card action buttons (the hover overlay's
// play / download / favorite / more — focusable even while invisible):
// they're set to tabindex="-1" so Tab never detours through them.
// Applied eagerly on mount and re-synced as virtualised rows mount /
// unmount, so it holds before the first arrow / gamepad move too.
//
// Integration:
// * Input modality flipping to `"pad"` (gamepad connected / pressed)
@@ -103,6 +111,37 @@ export function useGridNav(
return inner ?? el;
}
// Every focusable inside a cell: the cell's own focusable (a card
// link / list-row anchor) plus any nested ones. A GameCard nests its
// hidden hover-overlay actions (play / download / favorite / more /
// platform icon) here — all natural tab stops even while invisible,
// so they must be swept out of the tab order alongside the card link.
function cellFocusables(cell: HTMLElement): HTMLElement[] {
const out: HTMLElement[] = [];
if (cell.matches(FOCUSABLE_SELECTOR)) out.push(cell);
cell
.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)
.forEach((el) => out.push(el));
return out;
}
// Keep every cell's primary focusable (the card link / row anchor) in
// the natural Tab order so Tab walks card → card, but pull the nested
// in-card action buttons (the hidden hover overlay's play / download /
// favorite / more) OUT of it (tabindex="-1") so Tab never detours
// through them. Arrow keys still layer 2D nav on top. Cheap and
// idempotent — safe on mount and on every row mount / unmount.
function syncRoving() {
for (const row of rows()) {
for (const cell of cells(row)) {
const primary = focusableIn(cell);
for (const el of cellFocusables(cell)) {
el.setAttribute("tabindex", el === primary ? "0" : "-1");
}
}
}
}
function current(): { rowIdx: number; colIdx: number } | null {
const active = document.activeElement as HTMLElement | null;
if (!active) return null;
@@ -134,20 +173,6 @@ export function useGridNav(
const cell = cs[clamped];
const target = focusableIn(cell);
// Roving tabindex — only the current cell is a tab stop, every other
// cell sets tabindex="-1". Lets the user land on the last focused
// card via Tab from outside the grid, and keeps Shift+Tab escape
// behaviour clean. Borrowed from the v1 console useRovingDom.
const previous = rootRef.value?.querySelectorAll<HTMLElement>(
"[data-grid-nav-cell]",
);
previous?.forEach((other) => {
other.setAttribute("tabindex", "-1");
other.removeAttribute("data-grid-nav-cell");
});
target.setAttribute("data-grid-nav-cell", "");
target.setAttribute("tabindex", "0");
target.focus({ preventScroll: true });
// Jumping rows (up/down): centre the whole section vertically so the
@@ -253,6 +278,18 @@ export function useGridNav(
// land focus on it.
let observer: MutationObserver | null = null;
// Coalesce roving + autofocus into one rAF so a burst of row mounts
// during a fast scroll doesn't sweep the whole grid per mutation.
let refreshRaf = 0;
function scheduleRefresh() {
if (refreshRaf) return;
refreshRaf = requestAnimationFrame(() => {
refreshRaf = 0;
syncRoving();
maybeAutofocus();
});
}
function maybeAutofocus() {
if (modality.value !== "pad") return;
if (!rootRef.value) return;
@@ -276,10 +313,10 @@ export function useGridNav(
window.addEventListener("keydown", onKey);
window.addEventListener("focusin", onFocusIn);
if (rootRef.value) {
observer = new MutationObserver(() => maybeAutofocus());
observer = new MutationObserver(scheduleRefresh);
observer.observe(rootRef.value, { childList: true, subtree: true });
}
requestAnimationFrame(maybeAutofocus);
scheduleRefresh();
});
onBeforeUnmount(() => {
@@ -287,6 +324,8 @@ export function useGridNav(
window.removeEventListener("focusin", onFocusIn);
observer?.disconnect();
observer = null;
if (refreshRaf) cancelAnimationFrame(refreshRaf);
refreshRaf = 0;
});
// Reactively autofocus when modality becomes "pad". Useful when the

View File

@@ -428,7 +428,11 @@ const spinnerSize = computed(() => {
/* Suppress native button defaults. */
background: transparent;
color: inherit;
outline: none;
/* No blanket `outline: none` here — Vue's scope attribute would raise
its specificity above the `:where()`-wrapped global focus ring
(global.css), swallowing the keyboard / pad ring. The focus rules
below defer to that global ring and only clear the native UA outline
for the mouse (non-focus-visible) case. */
/* Smooth tone / theme / state changes — RSwitch motion language. */
transition:
background var(--r-motion-fast) var(--r-motion-ease-out),
@@ -457,6 +461,16 @@ const spinnerSize = computed(() => {
opacity: 0.18;
}
/* ── Focus ─────────────────────────────────────────────────────────
Keyboard / pad focus rings come from the global modality-gated rule
in global.css (branded outline for `key`, outline + bloom for `pad`).
We only need to clear the native UA outline for a pointer focus that
isn't `:focus-visible` (a mouse click), so it doesn't leak a grey
rectangle on press. */
.r-btn:focus:not(:focus-visible) {
outline: none;
}
/* ── Ripple — circular wave from the activation point ─────────── */
.r-btn__ripples {
position: absolute;

View File

@@ -226,6 +226,11 @@ onBeforeUnmount(() => {
border: none;
cursor: pointer;
white-space: nowrap;
/* Anchor + own stacking context for the contained focus highlight
(below), so its `z-index: -1` pseudo stays behind the label but above
the button's own background. The underlined variant raises this to 1. */
position: relative;
z-index: 0;
/* Keep natural width so the horizontal nav scrolls on overflow
(`.r-tab-nav--horizontal { overflow-x: auto }`) instead of squishing
the tabs below their content on narrow viewports. */
@@ -265,6 +270,30 @@ onBeforeUnmount(() => {
text-align: left;
}
/* ---------- Focus ----------
The global modality-gated ring (global.css) is an `outline`, which the
nav's `overflow-y: hidden` clip slices into two vertical slivers on
either side of the focused tab. Suppress it and paint a contained,
rounded highlight that lives INSIDE the button (a pseudo-element, so
nothing can be clipped away). Gated to keyboard / pad exactly like the
global rule. The `::before` sits behind the label (z-index: -1) and
leaves the bottom edge clear so the active tab's underline still reads. */
html[data-input="key"] .r-tab-nav__btn:focus-visible,
html[data-input="pad"] .r-tab-nav__btn:focus-visible {
outline: none;
}
html[data-input="key"] .r-tab-nav__btn:focus-visible::before,
html[data-input="pad"] .r-tab-nav__btn:focus-visible::before {
content: "";
position: absolute;
inset: 3px 3px 5px;
z-index: -1;
border-radius: var(--r-radius-sm);
background: var(--r-color-surface-hover);
box-shadow: inset 0 0 0 2px var(--r-color-focus);
pointer-events: none;
}
/* ---------- Underlined variant (horizontal only) ---------- */
.r-tab-nav--underlined {
border-bottom: 1px solid var(--r-color-border-strong);