From 21ccdda7a727bd30669c745e7fe39fbd4eba802b Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Sun, 27 Sep 2026 14:55:35 -0400 Subject: [PATCH] fix(v2): move focus by arrow key and D-pad between page regions Arrow keys (and the D-pad, which useGamepad turns into arrow keys) only moved focus inside a useGridNav/useWrapGridNav region, so from the game page's action ribbon up/down had no target and the top bar was unreachable by pad. Add useSpatialNav, installed by AppLayout: for arrow keys no grid or widget claimed, it focuses the nearest control in that direction and scrolls it into view when it is off-screen or under the fixed bars. The grids now listen on document so they run first and leave edge moves to it. FOCUSABLE_SELECTOR moves to a shared util. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../src/v2/composables/useGridNav/index.ts | 32 ++-- .../composables/useSpatialNav/index.test.ts | 143 ++++++++++++++++++ .../src/v2/composables/useSpatialNav/index.ts | 129 ++++++++++++++++ .../v2/composables/useWrapGridNav/index.ts | 17 +-- frontend/src/v2/layouts/AppLayout.vue | 21 +-- .../src/v2/lib/InputNavigation.stories.ts | 7 + frontend/src/v2/utils/spatialNav.test.ts | 61 ++++++++ frontend/src/v2/utils/spatialNav.ts | 90 +++++++++++ 8 files changed, 461 insertions(+), 39 deletions(-) create mode 100644 frontend/src/v2/composables/useSpatialNav/index.test.ts create mode 100644 frontend/src/v2/composables/useSpatialNav/index.ts create mode 100644 frontend/src/v2/utils/spatialNav.test.ts create mode 100644 frontend/src/v2/utils/spatialNav.ts diff --git a/frontend/src/v2/composables/useGridNav/index.ts b/frontend/src/v2/composables/useGridNav/index.ts index f3f5cfb4f..dff0514e2 100644 --- a/frontend/src/v2/composables/useGridNav/index.ts +++ b/frontend/src/v2/composables/useGridNav/index.ts @@ -16,32 +16,26 @@ // * ArrowLeft / ArrowRight → prev / next cell in the current row. // * ArrowUp / ArrowDown → same column in the prev / next row (clamped). // * On autofocus we remember a "preferred column" and restore it when -// moving up/down through rows of different lengths — common media-UI +// moving up/down through rows of different lengths, a common media-UI // pattern so row switching doesn't permanently lose horizontal place. // // Integration: // * Input modality flipping to `"pad"` (gamepad connected / pressed) // autofocuses the first cell, so `useGamepad`'s synthetic arrow keys // immediately land somewhere useful. -// * `useGamepad` itself dispatches keydowns — so everything here is +// * A key that would leave the grid (up from the first row, …) is left +// unclaimed, so `useSpatialNav` carries focus to the next region. +// * `useGamepad` itself dispatches keydowns, so everything here is // plain keyboard code; gamepad users transparently benefit. // -// For wrapping CSS grids (PlatformsIndex / CollectionsIndex) — where -// there are no per-row DOM containers — use `useWrapGridNav` instead; +// For wrapping CSS grids (PlatformsIndex / CollectionsIndex), where +// there are no per-row DOM containers, use `useWrapGridNav` instead; // it detects rows spatially from cell rects. import { onBeforeUnmount, onMounted, watch, type Ref } from "vue"; import { useRoute } from "vue-router"; import { useInputModality } from "@/v2/composables/useInputModality"; import storeFocusRestoration from "@/v2/stores/focusRestoration"; - -const FOCUSABLE_SELECTOR = [ - "a[href]", - "button:not([disabled])", - "input:not([disabled])", - "select:not([disabled])", - "textarea:not([disabled])", - "[tabindex]:not([tabindex='-1'])", -].join(","); +import { FOCUSABLE_SELECTOR } from "@/v2/utils/spatialNav"; export interface UseGridNavOptions { /** Selector that resolves to one DOM element per logical row. @@ -50,7 +44,7 @@ export interface UseGridNavOptions { rowSelector?: string; /** Returns the row elements. Overrides `rowSelector`. Useful when * the root element itself IS the only row (single-row toolbars - * like GameDetails' action ribbon) — pass `() => [rootEl.value!]`. */ + * like GameDetails' action ribbon): pass `() => [rootEl.value!]`. */ getRows?: () => HTMLElement[]; /** Returns the cells of a given row. Defaults to the row's direct * children. Pass `(row) => [row]` for list-mode rows where the row @@ -134,7 +128,7 @@ export function useGridNav( const cell = cs[clamped]; const target = focusableIn(cell); - // Roving tabindex — only the current cell is a tab stop, every other + // 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. @@ -210,7 +204,7 @@ export function useGridNav( return; } if (!rootRef.value) return; - // Only steer when focus is already inside the grid — don't hijack + // Only steer when focus is already inside the grid; don't hijack // arrow keys meant for input fields, menus, or other widgets. const active = document.activeElement; if (!(active instanceof Node) || !rootRef.value.contains(active)) return; @@ -249,7 +243,7 @@ export function useGridNav( // Watches card rows for late-arriving children (data fetching finishes // after mount, skeletons swap to real cards). When the first cell shows - // up — and the user is in pad modality without focus in the grid — we + // up (and the user is in pad modality without focus in the grid), we // land focus on it. let observer: MutationObserver | null = null; @@ -273,7 +267,7 @@ export function useGridNav( } onMounted(() => { - window.addEventListener("keydown", onKey); + document.addEventListener("keydown", onKey); window.addEventListener("focusin", onFocusIn); if (rootRef.value) { observer = new MutationObserver(() => maybeAutofocus()); @@ -283,7 +277,7 @@ export function useGridNav( }); onBeforeUnmount(() => { - window.removeEventListener("keydown", onKey); + document.removeEventListener("keydown", onKey); window.removeEventListener("focusin", onFocusIn); observer?.disconnect(); observer = null; diff --git a/frontend/src/v2/composables/useSpatialNav/index.test.ts b/frontend/src/v2/composables/useSpatialNav/index.test.ts new file mode 100644 index 000000000..403afd5c6 --- /dev/null +++ b/frontend/src/v2/composables/useSpatialNav/index.test.ts @@ -0,0 +1,143 @@ +import { mount } from "@vue/test-utils"; +import { createPinia, setActivePinia } from "pinia"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { defineComponent, h, ref } from "vue"; +import storePlaying from "@/stores/playing"; +import { useGridNav } from "@/v2/composables/useGridNav"; +import { useSpatialNav } from "./index"; + +vi.mock("vue-router", () => ({ + useRoute: () => ({ fullPath: "/rom/1" }), +})); + +// Laid out by data attributes since jsdom has no layout engine: a top bar +// link, the game page's action ribbon (a single-row useGridNav) under it, +// and a tab below the ribbon. +const Page = defineComponent({ + setup() { + const ribbon = ref(null); + useGridNav(ribbon, { + getRows: () => (ribbon.value ? [ribbon.value] : []), + }); + useSpatialNav().install(); + const btn = (id: string, x: number, y: number) => + h("button", { id, "data-x": x, "data-y": y }); + return () => + h("div", [ + btn("nav", 0, 0), + h("div", { ref: ribbon }, [btn("play", 0, 300), btn("fav", 100, 300)]), + btn("tab", 0, 500), + ]); + }, +}); + +describe("useSpatialNav", () => { + const scrollIntoView = vi.fn(); + let wrapper: ReturnType | null = null; + const restores: (() => void)[] = []; + + function stub( + key: K, + descriptor: PropertyDescriptor, + ) { + const original = Object.getOwnPropertyDescriptor( + HTMLElement.prototype, + key, + ); + Object.defineProperty(HTMLElement.prototype, key, { + configurable: true, + ...descriptor, + }); + restores.push(() => { + if (original) Object.defineProperty(HTMLElement.prototype, key, original); + else delete (HTMLElement.prototype as Partial)[key]; + }); + } + + function el(id: string): HTMLElement { + return document.getElementById(id)!; + } + + function press(key: string): KeyboardEvent { + const event = new KeyboardEvent("keydown", { + key, + bubbles: true, + cancelable: true, + }); + document.activeElement!.dispatchEvent(event); + return event; + } + + beforeEach(() => { + setActivePinia(createPinia()); + scrollIntoView.mockClear(); + stub("getBoundingClientRect", { + value(this: HTMLElement) { + if (this.dataset.x === undefined) return new DOMRect(0, 0, 0, 0); + return new DOMRect( + Number(this.dataset.x), + Number(this.dataset.y), + 40, + 40, + ); + }, + }); + stub("scrollIntoView", { value: scrollIntoView }); + wrapper = mount(Page, { attachTo: document.body }); + }); + + afterEach(() => { + wrapper?.unmount(); + wrapper = null; + restores.splice(0).forEach((restore) => restore()); + }); + + it("moves up and down off a single-row grid", () => { + el("play").focus(); + + expect(press("ArrowUp").defaultPrevented).toBe(true); + expect(document.activeElement).toBe(el("nav")); + + press("ArrowDown"); + expect(document.activeElement).toBe(el("play")); + + press("ArrowDown"); + expect(document.activeElement).toBe(el("tab")); + }); + + it("leaves moves inside the grid to the grid", () => { + el("play").focus(); + + press("ArrowRight"); + + expect(document.activeElement).toBe(el("fav")); + }); + + it("does nothing when no control lies in the direction", () => { + el("nav").focus(); + + expect(press("ArrowUp").defaultPrevented).toBe(false); + expect(document.activeElement).toBe(el("nav")); + }); + + it("scrolls a target outside the viewport into view", () => { + vi.stubGlobal("innerHeight", 400); + el("play").focus(); + + press("ArrowDown"); + + expect(scrollIntoView).toHaveBeenCalledWith( + expect.objectContaining({ block: "center" }), + ); + vi.unstubAllGlobals(); + }); + + it("stays out of the way while a game is running", () => { + storePlaying().setPlaying(true); + el("play").focus(); + + press("ArrowUp"); + + expect(document.activeElement).toBe(el("play")); + }); +}); diff --git a/frontend/src/v2/composables/useSpatialNav/index.ts b/frontend/src/v2/composables/useSpatialNav/index.ts new file mode 100644 index 000000000..bd9493021 --- /dev/null +++ b/frontend/src/v2/composables/useSpatialNav/index.ts @@ -0,0 +1,129 @@ +// useSpatialNav: moves focus by arrow key (and so by D-pad) for keys no grid +// or widget claimed with preventDefault, such as a move off a grid's edge. +// The grids listen on `document`, which an event reaches before `window`. +import { onBeforeUnmount } from "vue"; +import storePlaying from "@/stores/playing"; +import { hasOpenEscapable } from "@/v2/lib/overlays/RDialog/escapeStack"; +import { + ARROW_DIRECTIONS, + FOCUSABLE_SELECTOR, + pickSpatialTarget, + type SpatialDirection, +} from "@/v2/utils/spatialNav"; + +// Input types whose arrow keys move a caret or change the value. +const BUTTON_LIKE_INPUTS = new Set(["button", "checkbox", "reset", "submit"]); + +// Roles whose arrow keys belong to the widget itself. +const ARROW_OWNING_ROLES = new Set([ + "combobox", + "grid", + "gridcell", + "listbox", + "menuitem", + "menuitemcheckbox", + "menuitemradio", + "option", + "radio", + "slider", + "spinbutton", + "textbox", + "tree", + "treeitem", +]); + +function ownsArrowKeys(el: HTMLElement): boolean { + if (el.isContentEditable) return true; + if (el instanceof HTMLInputElement) return !BUTTON_LIKE_INPUTS.has(el.type); + if (el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement) { + return true; + } + return ARROW_OWNING_ROLES.has(el.getAttribute("role") ?? ""); +} + +function isNavigable(el: HTMLElement): boolean { + if (el.closest("[inert], [aria-hidden='true']")) return false; + const rect = el.getBoundingClientRect(); + if (rect.width === 0 || rect.height === 0) return false; + return getComputedStyle(el).visibility !== "hidden"; +} + +function isFixed(el: HTMLElement): boolean { + for (let node: HTMLElement | null = el; node; node = node.parentElement) { + if (getComputedStyle(node).position === "fixed") return true; + } + return false; +} + +// Visible and not covered by fixed chrome such as the top bar. +function isInView(el: HTMLElement): boolean { + const rect = el.getBoundingClientRect(); + if (rect.top < 0 || rect.bottom > window.innerHeight) return false; + if (rect.left < 0 || rect.right > window.innerWidth) return false; + if (typeof document.elementFromPoint !== "function") return true; + const hit = document.elementFromPoint( + (rect.left + rect.right) / 2, + (rect.top + rect.bottom) / 2, + ); + return !hit || el.contains(hit) || hit.contains(el); +} + +/** Moves focus from `from` to the nearest control in `dir`, if any. */ +export function moveFocus(from: HTMLElement, dir: SpatialDirection): boolean { + const candidates = Array.from( + document.querySelectorAll(FOCUSABLE_SELECTOR), + ) + .filter((el) => el !== from && !el.contains(from) && isNavigable(el)) + .map((el) => ({ item: el, box: el.getBoundingClientRect() })); + const target = pickSpatialTarget( + from.getBoundingClientRect(), + candidates, + dir, + ); + if (!target) return false; + target.focus({ preventScroll: true }); + if (!isFixed(target) && !isInView(target)) { + // Centring vertical moves keeps the target clear of the fixed bars. + const vertical = dir === "up" || dir === "down"; + target.scrollIntoView({ + block: vertical ? "center" : "nearest", + inline: "nearest", + behavior: "smooth", + }); + } + return true; +} + +let installed = false; + +export function useSpatialNav() { + function install() { + if (installed) return; + if (typeof window === "undefined") return; + installed = true; + + const playingStore = storePlaying(); + + function onKey(e: KeyboardEvent) { + const dir = ARROW_DIRECTIONS[e.key]; + if (!dir || e.defaultPrevented) return; + if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) return; + // A running game reads the arrows itself, and an open overlay keeps + // focus inside its own panel. + if (playingStore.playing || hasOpenEscapable()) return; + const active = document.activeElement; + if (!(active instanceof HTMLElement) || active === document.body) return; + if (ownsArrowKeys(active)) return; + if (moveFocus(active, dir)) e.preventDefault(); + } + + window.addEventListener("keydown", onKey); + + onBeforeUnmount(() => { + window.removeEventListener("keydown", onKey); + installed = false; + }); + } + + return { install }; +} diff --git a/frontend/src/v2/composables/useWrapGridNav/index.ts b/frontend/src/v2/composables/useWrapGridNav/index.ts index 2bcc197c5..dca2426ab 100644 --- a/frontend/src/v2/composables/useWrapGridNav/index.ts +++ b/frontend/src/v2/composables/useWrapGridNav/index.ts @@ -24,21 +24,16 @@ // auto-focus while in pad modality, reactivity to modality flipping to // pad mid-session. // +// A key that would leave the grid is left unclaimed, so `useSpatialNav` +// carries focus to the next region (the toolbar, the top bar). +// // Integration: this is plain keyboard code; `useGamepad` dispatches // synthetic Arrow events so gamepad users transparently benefit. import { onBeforeUnmount, onMounted, watch, type Ref } from "vue"; import { useRoute } from "vue-router"; import { useInputModality } from "@/v2/composables/useInputModality"; import storeFocusRestoration from "@/v2/stores/focusRestoration"; - -const FOCUSABLE_SELECTOR = [ - "a[href]", - "button:not([disabled])", - "input:not([disabled])", - "select:not([disabled])", - "textarea:not([disabled])", - "[tabindex]:not([tabindex='-1'])", -].join(","); +import { FOCUSABLE_SELECTOR } from "@/v2/utils/spatialNav"; // Within this many CSS pixels two cells are considered to share a row. // Tile heights are uniform per grid so anything within a couple of px is @@ -257,7 +252,7 @@ export function useWrapGridNav( } onMounted(() => { - window.addEventListener("keydown", onKey); + document.addEventListener("keydown", onKey); window.addEventListener("focusin", onFocusIn); if (rootRef.value) { observer = new MutationObserver(() => maybeAutofocus()); @@ -267,7 +262,7 @@ export function useWrapGridNav( }); onBeforeUnmount(() => { - window.removeEventListener("keydown", onKey); + document.removeEventListener("keydown", onKey); window.removeEventListener("focusin", onFocusIn); observer?.disconnect(); observer = null; diff --git a/frontend/src/v2/layouts/AppLayout.vue b/frontend/src/v2/layouts/AppLayout.vue index 9052509f8..b15c77831 100644 --- a/frontend/src/v2/layouts/AppLayout.vue +++ b/frontend/src/v2/layouts/AppLayout.vue @@ -1,10 +1,10 @@