From 96b01b73941e4be7352deb54dce46be5f40cf669 Mon Sep 17 00:00:00 2001 From: Sam Dornan Date: Thu, 29 Oct 2026 16:09:04 +0000 Subject: [PATCH] spike(frontend): rebuild RSelect's list on reka-ui Listbox Trial of a headless UI library for the hardest v2 primitive. RSelect keeps its own panel (floating-ui, teleport, escape stack) and hands keyboard navigation, highlight and option semantics to reka-ui's Listbox. The highlighted option now takes real focus, so pad A (a .click() on the focused element) picks it; before, A clicked the activator and closed the menu without picking. A Gamepad story covers it. RomM's typeahead stays in front of reka's, which buffers named keys and matches disabled rows. A small adapter keeps ListboxFilter's input state off RTextField's wrapper, where axe flagged it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NH5s4hejU8pB4AEAxTT2f9 --- frontend/package-lock.json | 141 ++++- frontend/package.json | 1 + .../src/lib/forms/RSelect/RSelect.stories.ts | 56 +- .../src/lib/forms/RSelect/RSelect.test.ts | 27 +- frontend/src/lib/forms/RSelect/RSelect.vue | 488 ++++++++---------- frontend/vitest.config.ts | 2 +- 6 files changed, 416 insertions(+), 299 deletions(-) diff --git a/frontend/package-lock.json b/frontend/package-lock.json index c0db71762..263da75b0 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -27,6 +27,7 @@ "mitt": "^3.0.1", "pinia": "^4.0.0", "qrcode": "^1.5.4", + "reka-ui": "^2.11.0", "semver": "^7.6.2", "socket.io-client": "^4.7.5", "spark-md5": "^3.0.2", @@ -2817,6 +2818,24 @@ "url": "https://github.com/sponsors/nzakas" } }, + "node_modules/@internationalized/date": { + "version": "3.12.4", + "resolved": "https://registry.npmjs.org/@internationalized/date/-/date-3.12.4.tgz", + "integrity": "sha512-M1dEn4c1U1HsSlaVR8upZtSqvXrTkHDfv18H01uCSJyjVLDxnBR38v/fMxecmlwXKR4i9HeZcmgQAPE6A+aGJQ==", + "license": "Apache-2.0", + "dependencies": { + "@swc/helpers": "^0.5.0" + } + }, + "node_modules/@internationalized/number": { + "version": "3.6.9", + "resolved": "https://registry.npmjs.org/@internationalized/number/-/number-3.6.9.tgz", + "integrity": "sha512-GgWy2caO/+hV9sT/oCTWGHvbjmJMPT9kkXzoKRLnkEq7adghhR7UprhvY9sXrKfrp3NcDfhF6QQHXR1KfQbB8g==", + "license": "Apache-2.0", + "dependencies": { + "@swc/helpers": "^0.5.0" + } + }, "node_modules/@intlify/core-base": { "version": "11.4.16", "resolved": "https://registry.npmjs.org/@intlify/core-base/-/core-base-11.4.16.tgz", @@ -4942,6 +4961,41 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/@swc/helpers": { + "version": "0.5.23", + "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.23.tgz", + "integrity": "sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.8.0" + } + }, + "node_modules/@tanstack/virtual-core": { + "version": "3.19.7", + "resolved": "https://registry.npmjs.org/@tanstack/virtual-core/-/virtual-core-3.19.7.tgz", + "integrity": "sha512-gxy5SvH0mFRJ0YujtrflB/1HAu9Wn1KGvL0bjZfQkYVVMsIpQiwcf1mR06/ViN4NjllUb4HNCjqE9FGwgTvMCQ==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, + "node_modules/@tanstack/vue-virtual": { + "version": "3.13.48", + "resolved": "https://registry.npmjs.org/@tanstack/vue-virtual/-/vue-virtual-3.13.48.tgz", + "integrity": "sha512-exH0/lELoCW9D6x8V1Uq61XY4zrN1AeDH4rDKUMTOJ93ndkeEVIY8zo366IBM13HSjhULpuWPdPhJ+ccidg58A==", + "license": "MIT", + "dependencies": { + "@tanstack/virtual-core": "3.19.7" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "vue": "^2.7.0 || ^3.0.0" + } + }, "node_modules/@testing-library/dom": { "version": "10.4.2", "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.2.tgz", @@ -6616,6 +6670,18 @@ "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", "license": "Python-2.0" }, + "node_modules/aria-hidden": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/aria-hidden/-/aria-hidden-1.2.6.tgz", + "integrity": "sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA==", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/aria-query": { "version": "5.3.2", "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.2.tgz", @@ -7642,6 +7708,12 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/defu": { + "version": "6.1.7", + "resolved": "https://registry.npmjs.org/defu/-/defu-6.1.7.tgz", + "integrity": "sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==", + "license": "MIT" + }, "node_modules/delayed-stream": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", @@ -10505,6 +10577,12 @@ "node": ">=12.20.0" } }, + "node_modules/ohash": { + "version": "2.0.12", + "resolved": "https://registry.npmjs.org/ohash/-/ohash-2.0.12.tgz", + "integrity": "sha512-65S/5gk9YSsaRjcyf7Nfa6h/d3E8/1gslpXfI4W7Dxn/oap8IKRuNT5VXkLQ1YFKIEg4apRY4Pj6aiwFzrDdmw==", + "license": "MIT" + }, "node_modules/open": { "version": "10.2.0", "resolved": "https://registry.npmjs.org/open/-/open-10.2.0.tgz", @@ -11392,6 +11470,68 @@ "regjsparser": "bin/parser" } }, + "node_modules/reka-ui": { + "version": "2.11.0", + "resolved": "https://registry.npmjs.org/reka-ui/-/reka-ui-2.11.0.tgz", + "integrity": "sha512-ilkpm4bIAol4jwzm4tpm3WVcffyGOpqksNZL1k1qO9QmIwAA+q8jroxjkUGLEn/GddfdExFfvofWfQiKZszUeQ==", + "license": "MIT", + "dependencies": { + "@floating-ui/vue": "^2.0.1", + "@internationalized/date": "^3.5.0", + "@internationalized/number": "^3.5.0", + "@tanstack/vue-virtual": "^3.12.0", + "@vueuse/core": "^14.1.0", + "@vueuse/shared": "^14.1.0", + "aria-hidden": "^1.2.4", + "defu": "^6.1.5", + "ohash": "^2.0.11" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/zernonia" + }, + "peerDependencies": { + "vue": ">= 3.4.0" + } + }, + "node_modules/reka-ui/node_modules/@vueuse/core": { + "version": "14.4.0", + "resolved": "https://registry.npmjs.org/@vueuse/core/-/core-14.4.0.tgz", + "integrity": "sha512-X4WHz1HlCzCBoYXesUkifzzWBAcZgXG8Fi5iNPQg/epdzOB3gu8Fawj3hvuwYR1nGcXGnvxwYYcUC/71++svtQ==", + "license": "MIT", + "dependencies": { + "@types/web-bluetooth": "^0.0.21", + "@vueuse/metadata": "14.4.0", + "@vueuse/shared": "14.4.0" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + }, + "peerDependencies": { + "vue": "^3.5.0" + } + }, + "node_modules/reka-ui/node_modules/@vueuse/metadata": { + "version": "14.4.0", + "resolved": "https://registry.npmjs.org/@vueuse/metadata/-/metadata-14.4.0.tgz", + "integrity": "sha512-swx/255R6JyHZFJhx845iz5CRWDZdCfvkZOpACWc5+c5WHcG24mv8gUT1WIdFQaHt6dq79rvILd9QnCWiyVm9g==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/reka-ui/node_modules/@vueuse/shared": { + "version": "14.4.0", + "resolved": "https://registry.npmjs.org/@vueuse/shared/-/shared-14.4.0.tgz", + "integrity": "sha512-JRgY90Sz8DDtPMsaDflvPMp9xYk69JZAmbuDvAquUVXKr2gEjqtzGNTTthLfckH0BzBqvnu31gb4a8TGLRe79g==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/antfu" + }, + "peerDependencies": { + "vue": "^3.5.0" + } + }, "node_modules/require-directory": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", @@ -12421,7 +12561,6 @@ "version": "2.8.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", - "dev": true, "license": "0BSD" }, "node_modules/tsx": { diff --git a/frontend/package.json b/frontend/package.json index 7d8686a39..b8264805e 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -58,6 +58,7 @@ "mitt": "^3.0.1", "pinia": "^4.0.0", "qrcode": "^1.5.4", + "reka-ui": "^2.11.0", "semver": "^7.6.2", "socket.io-client": "^4.7.5", "spark-md5": "^3.0.2", diff --git a/frontend/src/lib/forms/RSelect/RSelect.stories.ts b/frontend/src/lib/forms/RSelect/RSelect.stories.ts index cb8ee0620..b87a485ed 100644 --- a/frontend/src/lib/forms/RSelect/RSelect.stories.ts +++ b/frontend/src/lib/forms/RSelect/RSelect.stories.ts @@ -29,6 +29,11 @@ const PLATFORMS = [ { title: "PC", value: "pc" }, ]; +// The option keyboard navigation is on. The panel teleports to , +// outside the story canvas. +const activeOption = () => + document.querySelector(".r-select__panel [data-highlighted]"); + // Generic components can't fill Storybook's `component` slot, so it's cast; // the instantiation types the stories' args. const meta: Meta> = { @@ -596,10 +601,6 @@ export const KeyboardNavigation: Story = { const field = await within(canvasElement).findByRole("combobox", { name: "Platform", }); - const activeOption = () => - document.getElementById( - field.getAttribute("aria-activedescendant") ?? "", - ); await step("Arrow Down opens the list on the first option", async () => { field.focus(); @@ -701,17 +702,14 @@ export const MultipleKeyboard: Story = { const field = await within(canvasElement).findByRole("combobox", { name: "Pick platforms", }); - const activeOption = () => - document.getElementById( - field.getAttribute("aria-activedescendant") ?? "", - ); - await step("Arrow Up from the first option reaches All", async () => { + await step("Opening lands on All, the current selection", async () => { field.focus(); await userEvent.keyboard("{ArrowDown}"); await waitFor(() => - expect(field).toHaveAttribute("aria-expanded", "true"), + expect(activeOption()).toHaveClass("r-select__item--all"), ); + await userEvent.keyboard("{ArrowDown}"); await expect(activeOption()).toHaveTextContent("Nintendo 64"); await userEvent.keyboard("{ArrowUp}"); await expect(activeOption()).toHaveClass("r-select__item--all"); @@ -767,10 +765,6 @@ export const KeyboardDisabledRows: Story = { const field = await within(canvasElement).findByRole("combobox", { name: "Fruit", }); - const activeOption = () => - document.getElementById( - field.getAttribute("aria-activedescendant") ?? "", - ); await step("Paging backs off a disabled last row", async () => { field.focus(); @@ -808,3 +802,37 @@ export const KeyboardDisabledRows: Story = { }); }, }; + +// `useGamepad` sends the D-pad as arrow keys to the focused element and +// presses A as `.click()` on it, so the play mirrors both. +function padA() { + (document.activeElement as HTMLElement | null)?.click(); +} + +export const GamepadPick: Story = { + name: "Gamepad · pick with A (play)", + render: () => ({ + components: { RSelect }, + setup: () => ({ value: ref(null), items: PLATFORMS }), + template: `
`, + }), + play: async ({ canvasElement, step }) => { + const field = await within(canvasElement).findByRole("combobox", { + name: "Platform", + }); + + await step("A opens the list, Down and A pick the second row", async () => { + field.focus(); + padA(); + await waitFor(() => + expect(field).toHaveAttribute("aria-expanded", "true"), + ); + await userEvent.keyboard("{ArrowDown}"); + padA(); + await waitFor(() => + expect(document.querySelector(".r-select__panel")).toBeNull(), + ); + await expect(field).toHaveTextContent("Super Nintendo"); + }); + }, +}; diff --git a/frontend/src/lib/forms/RSelect/RSelect.test.ts b/frontend/src/lib/forms/RSelect/RSelect.test.ts index 997967457..b77eb562a 100644 --- a/frontend/src/lib/forms/RSelect/RSelect.test.ts +++ b/frontend/src/lib/forms/RSelect/RSelect.test.ts @@ -1,4 +1,4 @@ -import { mount } from "@vue/test-utils"; +import { flushPromises, mount } from "@vue/test-utils"; import { afterEach, describe, expect, it, vi } from "vitest"; import { nextTick } from "vue"; import { useInputModality } from "@/composables/useInputModality"; @@ -394,17 +394,16 @@ describe("RSelect combobox semantics", () => { attachTo: document.body, }); const field = wrapper.get(".r-select__field"); - const active = () => - document - .getElementById(field.attributes("aria-activedescendant") ?? "") - ?.textContent?.trim(); + const highlighted = () => + document.querySelector("[data-highlighted]")?.textContent?.trim(); await field.trigger("keydown", { key: "b" }); + await flushPromises(); await field.trigger("keydown", { key: "Escape" }); - await field.trigger("click"); await field.trigger("keydown", { key: "c" }); + await flushPromises(); - expect(active()).toBe("Cherry"); + expect(highlighted()).toBe("Cherry"); wrapper.unmount(); document.body.innerHTML = ""; }); @@ -432,7 +431,7 @@ describe("RSelect searchable without search autofocus", () => { document.body.innerHTML = ""; }); - it("keeps the active option on the activator while focus stays there", async () => { + it("hands the arrow keys to the search field", async () => { window.matchMedia = vi.fn(() => ({ matches: false })) as never; const wrapper = mount(RSelect, { props: { items: ["Apple", "Banana"], modelValue: null, searchable: true }, @@ -441,13 +440,15 @@ describe("RSelect searchable without search autofocus", () => { const field = wrapper.get(".r-select__field"); await field.trigger("click"); + await flushPromises(); + expect(document.activeElement).not.toBe( + document.querySelector(".r-select__search input"), + ); await field.trigger("keydown", { key: "ArrowDown" }); - expect( - document - .getElementById(field.attributes("aria-activedescendant") ?? "") - ?.textContent?.trim(), - ).toBe("Banana"); + expect(document.activeElement).toBe( + document.querySelector(".r-select__search input"), + ); wrapper.unmount(); }); }); diff --git a/frontend/src/lib/forms/RSelect/RSelect.vue b/frontend/src/lib/forms/RSelect/RSelect.vue index 8a3e4ac56..17c40b888 100644 --- a/frontend/src/lib/forms/RSelect/RSelect.vue +++ b/frontend/src/lib/forms/RSelect/RSelect.vue @@ -2,7 +2,8 @@ // RSelect: combines an RTextField-style activator (variants, // hover/focus halos, labels) with a floating menu panel positioned by // `@floating-ui/vue` and rendered as a teleported surface in the v2 -// glass language. +// glass language. Keyboard navigation, highlight and type-to-select come +// from reka-ui's Listbox. // // Single + multi-select. Items normalise via `itemTitle` / `itemValue` // (string key or function) so any shape (strings, numbers, plain @@ -10,10 +11,10 @@ // sticky search input at the top of the panel. // // Slots `#selection` and `#item`. The `#item` slot's `props` bag is -// spread on any element you want, it carries `class` (including the -// active/selected/disabled state), `role`, `aria-*`, click/hover -// handlers, and the index data attribute. The row default is a `
  • ` -// styled by `.r-select__item`. `dividerAfter` draws a divider below the +// spread on the row element: it carries the selected/disabled `class`, +// and the listbox adds the option role, state and handlers to that +// element. The highlighted row has `data-highlighted`. The row default +// is a `
  • ` styled by `.r-select__item`. `dividerAfter` draws a divider below the // rows it matches. `#append-label` adds a trailing well that mirrors the // inline prefix label; `info` fills it with an info icon and tooltip. import { @@ -26,9 +27,19 @@ import { } from "@floating-ui/vue"; import type { Placement } from "@floating-ui/vue"; import { useElementSize } from "@vueuse/core"; +import { + type AcceptableValue, + ListboxContent, + ListboxFilter, + ListboxItem, + type ListboxItemSelectEvent, + ListboxRoot, +} from "reka-ui"; import { computed, + type FunctionalComponent, getCurrentInstance, + h, nextTick, onBeforeUnmount, ref, @@ -303,7 +314,7 @@ const itemSearchIndex = computed(() => // Either way, `update:search` is always emitted on every keystroke so // parents that care can observe. This means `:searchable` just works // on its own (no v-model needed) and filtering survives unrelated -// re-renders (e.g. `mouseenter` on a row updating `activeIndex`). +// re-renders. const internalSearch = ref(props.search); watch( () => props.search, @@ -681,7 +692,16 @@ const showClear = computed( // ── Open state + floating ─────────────────────────────────────── const isOpen = ref(false); const activatorRef = ref(null); -const panelRef = ref(null); +// The exposed API RSelect calls on its `ListboxRoot`. +interface ListboxApi { + $el: HTMLElement; + highlightSelected: () => Promise; + highlightItem: (value: AcceptableValue) => void; +} +const listboxRef = ref(null); +const panelRef = computed( + () => listboxRef.value?.$el ?? null, +); // Ceiling for the panel; the viewport remainder can shrink it further. const MAX_PANEL_HEIGHT = 360; @@ -725,22 +745,24 @@ const { floatingStyles } = useFloating(activatorRef, panelRef, { ]), }); -function openMenu() { +// Without a search field the highlighted option takes focus, so pad A +// (a `.click()` on the focused element) picks it. `typed` is the key +// that opened the menu, for type-to-select. +function openMenu(typed?: string) { if (props.disabled || props.readonly) return; if (isOpen.value) return; isOpen.value = true; infoOpen.value = false; - activeIndex.value = Math.max( - 0, - filteredItems.value.findIndex((it) => isSelected(it.value)), - ); emit("open"); - // RMenuSearch autofocuses on mount; keys bubble up to the panel-level - // keydown handler. When `searchable` is off, focus stays on the - // activator and the activator-level keydown handler steers nav. + if (props.searchable) return; + void nextTick(async () => { + await listboxRef.value?.highlightSelected(); + if (typed) typeahead(typed); + }); } function closeMenu() { if (!isOpen.value) return; + const focusInPanel = !!panelRef.value?.contains(document.activeElement); isOpen.value = false; emit("close"); resetTypeahead(); @@ -750,6 +772,7 @@ function closeMenu() { // user expectation for "open select → type → pick → close → reopen" // not leaving a stale query that hides most rows. if (props.searchable && internalSearch.value) setSearch(""); + if (focusInPanel) focusFromInput(activatorRef.value); } function toggleMenu() { if (isOpen.value) closeMenu(); @@ -759,96 +782,39 @@ function toggleMenu() { usePopoverDismiss(isOpen, closeMenu, { reference: () => activatorRef.value, panel: () => panelRef.value, - onEscape: () => { - const focusInPanel = !!panelRef.value?.contains(document.activeElement); - closeMenu(); - if (focusInPanel) focusFromInput(activatorRef.value); - }, }); -// Close when search is changed externally? No, keep open while -// editing search. Reset active index to 0 when filter changes so -// keyboard nav stays sensible. -watch(filteredItems, () => { - activeIndex.value = 0; +// ── Listbox (keyboard nav, highlight, type-to-select: reka-ui) ─ +// Stands in for the synthetic "All" row's value in the listbox model. +const ALL_OPTION = Object.freeze({ all: true }); +// Single-select model with nothing picked; matches no option. +const NO_OPTION = Object.freeze({ none: true }); +// Identity, so a `null`-valued item and the sentinel compare as keys. +const sameValue = (a: AcceptableValue, b: AcceptableValue) => a === b; + +// Item values are whatever the caller's items hold; the listbox only +// compares them with `sameValue`. +const asListboxValue = (value: unknown) => value as AcceptableValue; + +const listboxModel = computed(() => { + const keys = selectedItems.value.map((it) => asListboxValue(it.value)); + if (!props.multiple) return keys.length ? keys[0]! : NO_OPTION; + return showAllRow.value && isAllSelected.value ? [ALL_OPTION, ...keys] : keys; }); -// ── Keyboard nav ──────────────────────────────────────────────── -const activeIndex = ref(0); - -// The option keyboard navigation is on, for `aria-activedescendant`. -// Index -1 is the synthetic "All" row. -const activeOptionId = computed(() => { - if (!isOpen.value) return undefined; - if (activeIndex.value === -1) - return showAllRow.value ? allOptionId : undefined; - return filteredItems.value[activeIndex.value] - ? optionId(activeIndex.value) - : undefined; -}); - -// The "All" row sits above the items at index -1. -const firstIndex = computed(() => (showAllRow.value ? -1 : 0)); - -function moveActive(delta: number) { - const list = filteredItems.value; - const lo = firstIndex.value; - if (!list.length && lo === 0) return; - let i = activeIndex.value + delta; - // Wrap + skip disabled. - for (let n = 0; n < list.length - lo; n++) { - if (i < lo) i = list.length - 1; - if (i >= list.length) i = lo; - if (i === -1 || !list[i]!.disabled) break; - i += delta || 1; - } - activeIndex.value = i; - scrollActiveIntoView(); -} - -function activateActive() { - if (activeIndex.value === -1) { - if (showAllRow.value) toggleAllItems(); - return; - } - const item = filteredItems.value[activeIndex.value]; - if (item) selectItem(item); -} -const PAGE_STEP = 10; - -// Jump to the first or last enabled row. -function moveActiveTo(edge: "first" | "last") { - const list = filteredItems.value; - if (edge === "first" && showAllRow.value) { - activeIndex.value = -1; - scrollActiveIntoView(); - return; - } - const order = list.map((_, i) => i); - if (edge === "last") order.reverse(); - const i = order.find((n) => !list[n]!.disabled); - if (i === undefined) return; - activeIndex.value = i; - scrollActiveIntoView(); -} - -// Move a page of rows, stopping at the ends instead of wrapping. A disabled -// target backs off toward the current row. -function movePage(dir: 1 | -1) { - const list = filteredItems.value; - const lo = firstIndex.value; - let i = Math.min( - list.length - 1, - Math.max(lo, activeIndex.value + dir * PAGE_STEP), - ); - while (i !== -1 && list[i]?.disabled) i -= dir; - if (i < lo || i >= list.length) return; - activeIndex.value = i; - scrollActiveIntoView(); +const highlightedValue = ref(undefined); +const highlightedId = ref(undefined); +function onHighlight( + payload: { ref: HTMLElement; value: unknown } | undefined, +) { + highlightedValue.value = payload?.value; + highlightedId.value = payload?.ref.id; } // Type-to-select: a burst of characters matches a title prefix, and // repeating one character cycles through the rows that start with it. +// reka's own typeahead also buffers named keys (Home, End) and matches +// disabled rows, so printable keys stop here, before the listbox sees them. const TYPEAHEAD_RESET_MS = 500; let typeBuffer = ""; let typeTimer: ReturnType | undefined; @@ -860,13 +826,12 @@ function typeahead(char: string) { typeTimer = setTimeout(() => (typeBuffer = ""), TYPEAHEAD_RESET_MS); const cycling = [...typeBuffer].every((c) => c === typeBuffer[0]); const query = cycling ? typeBuffer[0]! : typeBuffer; - const from = activeIndex.value + (cycling || typeBuffer.length === 1 ? 1 : 0); + const current = list.findIndex((it) => it.value === highlightedValue.value); + const from = current + (cycling || typeBuffer.length === 1 ? 1 : 0); for (let n = 0; n < list.length; n++) { - const i = (from + n + list.length) % list.length; - const item = list[i]!; + const item = list[(from + n + list.length) % list.length]!; if (!item.disabled && item.title.toLowerCase().startsWith(query)) { - activeIndex.value = i; - scrollActiveIntoView(); + listboxRef.value?.highlightItem(asListboxValue(item.value)); return; } } @@ -877,88 +842,92 @@ function resetTypeahead() { } onBeforeUnmount(resetTypeahead); -function scrollActiveIntoView() { - void nextTick(() => { - const el = panelRef.value?.querySelector( - `[data-r-select-index="${activeIndex.value}"]`, - ); - el?.scrollIntoView({ block: "nearest" }); - }); +function onPanelKeyCapture(evt: KeyboardEvent) { + if (props.searchable || !isPrintable(evt)) return; + // Within a typing burst a space continues the query ("game boy"). + if (evt.key === " " && !typeBuffer) return; + evt.preventDefault(); + evt.stopPropagation(); + typeahead(evt.key); } +// The listbox's own model handling is left to run (it marks the change as +// the user's, so the list keeps its highlight); RSelect's emits own the model. +function onOptionSelect( + _evt: ListboxItemSelectEvent, + item?: NormalisedItem, +) { + if (item) selectItem(item); + else toggleAllItems(); +} + +const isPrintable = (evt: KeyboardEvent) => + evt.key.length === 1 && !evt.ctrlKey && !evt.metaKey && !evt.altKey; + +// The first or last enabled row, for PageUp / PageDown. +function edgeValue(edge: "first" | "last"): AcceptableValue | undefined { + if (edge === "first" && showAllRow.value) return ALL_OPTION; + const enabled = filteredItems.value.filter((it) => !it.disabled); + const item = edge === "first" ? enabled[0] : enabled.at(-1); + return item && asListboxValue(item.value); +} + +function onPanelKey(evt: KeyboardEvent) { + if (evt.key === "PageUp" || evt.key === "PageDown") { + evt.preventDefault(); + const value = edgeValue(evt.key === "PageUp" ? "first" : "last"); + if (value !== undefined) listboxRef.value?.highlightItem(value); + } else if (evt.key === "Tab") { + // Focus goes back to the field first, so Tab moves on from there. + closeMenu(); + } +} + +// ListboxFilter puts the input's state on the element it renders, which +// for RTextField is the wrapper around its . The field takes that +// state through `popup` instead; the key and input listeners stay, since +// the input's events bubble through the wrapper. +const FILTER_INPUT_ATTRS = [ + "aria-activedescendant", + "aria-disabled", + "data-disabled", + "disabled", + "type", + "value", +]; +const SearchField: FunctionalComponent = (_, { attrs, slots }) => + h( + RTextField, + { + ...Object.fromEntries( + Object.entries(attrs).filter(([k]) => !FILTER_INPUT_ATTRS.includes(k)), + ), + modelValue: internalSearch.value, + }, + { "prefix-label": slots.default }, + ); + function onActivatorKey(evt: KeyboardEvent) { if (props.disabled || props.readonly) return; - // Within a typing burst a space continues the query ("game boy"). - if (evt.key === " " && typeBuffer && !props.searchable) { - evt.preventDefault(); - typeahead(" "); + if (isOpen.value) { + // Focus stays here when the search field skips autofocus (touch); + // the arrows hand it to the search field. + if (evt.key === "ArrowDown" || evt.key === "ArrowUp") { + evt.preventDefault(); + focusFromInput( + panelRef.value?.querySelector(".r-select__search input"), + ); + } else if (evt.key === "Tab") { + closeMenu(); + } return; } - switch (evt.key) { - case "ArrowDown": - evt.preventDefault(); - if (!isOpen.value) openMenu(); - else moveActive(1); - break; - case "ArrowUp": - evt.preventDefault(); - if (!isOpen.value) openMenu(); - else moveActive(-1); - break; - case "Enter": - case " ": - if (!isOpen.value) { - evt.preventDefault(); - openMenu(); - } else { - evt.preventDefault(); - activateActive(); - } - break; - case "Tab": - if (isOpen.value) closeMenu(); - break; - default: - // A searchable field sends typing to its search input instead. - if (props.searchable) break; - if (isOpen.value && (evt.key === "Home" || evt.key === "End")) { - evt.preventDefault(); - moveActiveTo(evt.key === "Home" ? "first" : "last"); - } else if ( - isOpen.value && - (evt.key === "PageUp" || evt.key === "PageDown") - ) { - evt.preventDefault(); - movePage(evt.key === "PageUp" ? -1 : 1); - } else if ( - evt.key.length === 1 && - evt.key !== " " && - !evt.ctrlKey && - !evt.metaKey && - !evt.altKey - ) { - evt.preventDefault(); - if (!isOpen.value) openMenu(); - typeahead(evt.key); - } - } -} - -function onSearchKey(evt: KeyboardEvent) { - switch (evt.key) { - case "ArrowDown": - evt.preventDefault(); - moveActive(1); - break; - case "ArrowUp": - evt.preventDefault(); - moveActive(-1); - break; - case "Enter": { - evt.preventDefault(); - activateActive(); - break; - } + if (["ArrowDown", "ArrowUp", "Enter", " "].includes(evt.key)) { + evt.preventDefault(); + openMenu(); + } else if (!props.searchable && isPrintable(evt)) { + evt.preventDefault(); + openMenu(evt.key); } } @@ -1060,9 +1029,6 @@ const describedBy = computed(() => { :aria-haspopup="'listbox'" :aria-expanded="isOpen" :aria-controls="isOpen ? listboxId : undefined" - :aria-activedescendant=" - searchable && autofocusSearch ? undefined : activeOptionId - " :aria-label="effectiveAriaLabel" :aria-labelledby=" stackedLabelOn @@ -1298,19 +1264,20 @@ const describedBy = computed(() => { contexts. Mounted only when open. --> - -
    - -
      { items and is separated by a divider so it reads as a meta action rather than a list item. --> -
    +
    No options
    -
    +
    @@ -1634,13 +1589,6 @@ const describedBy = computed(() => { .r-select__item--all { font-weight: var(--r-font-weight-semibold); } -/* The All row is hovered via CSS, `activeIndex` is reserved for the - filtered-items list (keyboard navigation), so we can't piggyback on - the `--active` class here. */ -.r-select__item--all:hover { - background: var(--r-color-surface); - color: var(--r-color-fg); -} .r-select__divider { padding: 0; margin: 4px 0; @@ -1925,7 +1873,7 @@ html[data-input="pad"] .r-select__field:focus { .r-select__item:last-child { margin-bottom: 0; } -.r-select__item--active { +.r-select__item[data-highlighted] { background: var(--r-color-surface); color: var(--r-color-fg); } diff --git a/frontend/vitest.config.ts b/frontend/vitest.config.ts index b2ce0e2f5..b650f2b3f 100644 --- a/frontend/vitest.config.ts +++ b/frontend/vitest.config.ts @@ -41,7 +41,7 @@ export default defineConfig({ // A dependency found mid-run reloads the page and silently drops the // tests in flight, so pre-bundle everything stories reach up front. optimizeDeps: { - include: ["country-flag-emoji-polyfill"], + include: ["country-flag-emoji-polyfill", "reka-ui"], }, // Mirrors vite.config.js, which the router's `process.env.BASE_URL` needs. define: { "process.env": {} },