fix(ui): the palette ranks what you typed, and lib stops leaning on components

Typing "theme" put the channel "The Meltzone Podcast" (matched only through its handle
`@themeltzone`) above every "Theme: …" row, and Enter opened the channel — the palette listed
matches in pure group order and always highlighted the first one.

- CommandPalette ranks each word: label starts with it > elsewhere in the label > only the hint,
  keywords or group name; an item ranks by its worst word, then the sum. The group order stays
  fixed, rows are ranked inside each group, and the best row overall starts highlighted. The
  highlight is held by id and follows the best match until the arrows or the pointer pick a row,
  so a channel list landing mid-typing no longer shifts it.
- A11y: result groups are `role="group"` named by their heading; `aria-expanded` is false with
  nothing to choose; the listbox stays mounted (hidden) so `aria-controls` never names a missing
  element, and "Nothing matches" sits outside it; a polite status announces the count once the
  typing pauses.
- `Column`/`FilterMap`/`filterRows`/`isActive` move from `ui/tableHeader` to `lib/tableColumns`,
  and the player's auto/loop modes from `playerModalControls` to `lib/playerModes` — three lib
  helpers imported the column contract from a ui component, and `playerModalHooks` its types from a
  feature component.
- eslint: `lib/` may not import from `components/` at any depth, type-only and re-exports included;
  the boundary contract test proves it fires. CLAUDE.md and the ui README say so.
- keymap: `dispatch`'s docblock sat stacked on `matchesShortcut`'s; moved onto `dispatch`.
This commit is contained in:
2026-09-13 02:14:07 +02:00
parent 8a50538275
commit 78a9324381
25 changed files with 418 additions and 167 deletions
+147 -68
View File
@@ -40,14 +40,37 @@ function fold(s: string): string {
.replace(/\p{Diacritic}/gu, "");
}
/** Every query word must appear somewhere in the item's text. Word-wise rather than substring so
* "thevr pod" finds "TheVR Podcast" — the way you actually half-remember a name. */
function matchesQuery(item: CommandItem, groupLabel: string, words: string[]): boolean {
if (words.length === 0) return true;
const hay = fold(`${item.label} ${item.hint ?? ""} ${item.keywords ?? ""} ${groupLabel}`);
return words.every((w) => hay.includes(w));
/** How well an item answers the query: `[worst word, sum of words]`, lower is better. */
type Rank = readonly [number, number];
const byRank = (a: Rank, b: Rank) => a[0] - b[0] || a[1] - b[1];
/** Every query word must appear somewhere in the item's text — word-wise rather than substring, so
* "thevr pod" finds "TheVR Podcast", the way you actually half-remember a name. `null` = no match.
*
* Each word scores 0 when the label STARTS with it, 1 when it is elsewhere in the label, 2 when only
* the hint, the hidden keywords or the group name carry it. An item ranks by its worst word first, so
* a row whose label holds every word beats one that needed its handle for any of them. Before this
* the list was pure group order: "theme" put the channel "The Meltzone Podcast" — matched through its
* handle `@themeltzone` alone — above every "Theme: …" row, and Enter opened a channel (E11 S3). */
function rankItem(item: CommandItem, groupLabel: string, words: string[]): Rank | null {
const label = fold(item.label);
const rest = fold(`${item.hint ?? ""} ${item.keywords ?? ""} ${groupLabel}`);
let worst = 0;
let sum = 0;
for (const w of words) {
const score = label.startsWith(w) ? 0 : label.includes(w) ? 1 : rest.includes(w) ? 2 : -1;
if (score < 0) return null;
worst = Math.max(worst, score);
sum += score;
}
return [worst, sum];
}
/** The result count reaches a screen reader only once the typing pauses: a polite region rewritten on
* every keystroke queues one announcement per letter. */
const ANNOUNCE_DELAY_MS = 400;
export default function CommandPalette({
open,
onClose,
@@ -59,8 +82,12 @@ export default function CommandPalette({
}) {
const { t } = useTranslation();
const listId = useId();
const groupId = useId();
const [query, setQuery] = useState("");
const [active, setActive] = useState(0);
// The row the arrows or the pointer picked, by id; `null` follows the best match. An id rather than
// an index because the lists arrive asynchronously (channels, playlists load on open), and an index
// would quietly point at a different row once they land.
const [picked, setPicked] = useState<string | null>(null);
// Ref on the highlighted row rather than a selector lookup: item ids come from domain data
// (playlist names, channel handles) and would need escaping to be safe in a query string.
const activeRef = useRef<HTMLButtonElement | null>(null);
@@ -70,26 +97,58 @@ export default function CommandPalette({
useEffect(() => {
if (open) {
setQuery("");
setActive(0);
setPicked(null);
}
}, [open]);
const visible = useMemo(() => {
// The GROUP order stays fixed — modules, channels, playlists, views, actions read the same every
// time — and the rows are ranked inside each group. The best row overall starts highlighted, so
// Enter takes the best match even when it sits in a later group.
const { visible, bestId } = useMemo(() => {
const words = fold(query.trim()).split(/\s+/).filter(Boolean);
return groups
.map((g) => ({ ...g, items: g.items.filter((i) => matchesQuery(i, g.label, words)) }))
.filter((g) => g.items.length > 0);
const out: CommandGroup[] = [];
let best: { id: string; rank: Rank } | null = null;
for (const g of groups) {
const ranked: { item: CommandItem; rank: Rank }[] = [];
for (const item of g.items) {
const rank = rankItem(item, g.label, words);
if (rank) ranked.push({ item, rank });
}
if (ranked.length === 0) continue;
// `sort` is stable, so equal ranks keep the group's own order (modules in nav-rail order).
ranked.sort((a, b) => byRank(a.rank, b.rank));
const top = ranked[0]!;
if (!best || byRank(top.rank, best.rank) < 0) best = { id: top.item.id, rank: top.rank };
out.push({ ...g, items: ranked.map((r) => r.item) });
}
return { visible: out, bestId: best?.id };
}, [groups, query]);
// One flat list behind the grouped rendering — arrow keys walk results, not sections.
const flat = useMemo(() => visible.flatMap((g) => g.items), [visible]);
const activeId = flat[Math.min(active, flat.length - 1)]?.id;
const activeId = picked !== null && flat.some((i) => i.id === picked) ? picked : bestId;
const activeIndex = flat.findIndex((i) => i.id === activeId);
// Keep the highlighted row in view when the arrows walk past the fold.
useEffect(() => {
activeRef.current?.scrollIntoView({ block: "nearest" });
}, [activeId]);
const summary = !query.trim()
? ""
: flat.length === 0
? t("palette.empty")
: t("palette.results", { count: flat.length });
const [announced, setAnnounced] = useState("");
useEffect(() => {
if (!summary) {
setAnnounced("");
return;
}
const timer = window.setTimeout(() => setAnnounced(summary), ANNOUNCE_DELAY_MS);
return () => window.clearTimeout(timer);
}, [summary]);
if (!open) return null;
// Close, wait for this dialog's own Back-to-close entry to be reclaimed, THEN run: most commands
@@ -105,9 +164,10 @@ export default function CommandPalette({
e.preventDefault();
if (flat.length === 0) return;
const step = e.key === "ArrowDown" ? 1 : -1;
setActive((i) => (Math.min(i, flat.length - 1) + step + flat.length) % flat.length);
const from = Math.max(activeIndex, 0);
setPicked(flat[(from + step + flat.length) % flat.length]!.id);
} else if (e.key === "Enter") {
const item = flat[Math.min(active, flat.length - 1)];
const item = flat[activeIndex];
if (item) {
e.preventDefault();
choose(item);
@@ -124,72 +184,91 @@ export default function CommandPalette({
value={query}
onChange={(e) => {
setQuery(e.target.value);
setActive(0);
setPicked(null);
}}
onKeyDown={onInputKey}
placeholder={t("palette.placeholder")}
aria-label={t("palette.placeholder")}
// A minimal combobox tree: the arrows move a VIRTUAL selection while the caret stays in
// the field, so a screen reader has to be told which row is current.
// the field, so a screen reader has to be told which row is current. `aria-expanded`
// follows the results: with nothing to choose from there is no popup to be in.
role="combobox"
aria-expanded
aria-expanded={flat.length > 0}
aria-controls={listId}
aria-activedescendant={activeId ? `${listId}-${activeId}` : undefined}
className="w-full bg-transparent text-sm outline-hidden placeholder:text-muted"
/>
</div>
<div id={listId} role="listbox" className="mt-3 max-h-[50vh] overflow-y-auto">
{flat.length === 0 ? (
<p className="px-1 py-6 text-center text-sm text-muted">{t("palette.empty")}</p>
) : (
visible.map((g) => (
<div key={g.id} className="mb-2 last:mb-0">
<div
role="presentation"
className="px-1 pb-1 text-xs font-semibold tracking-wide text-muted uppercase"
>
{g.label}
</div>
{g.items.map((item) => (
<button
key={item.id}
id={`${listId}-${item.id}`}
ref={item.id === activeId ? activeRef : undefined}
data-cmd-id={item.id}
role="option"
aria-selected={item.id === activeId}
type="button"
// The combobox input owns the tab stop; the arrows move a VIRTUAL selection over
// these rows. Leaving them tabbable put DOM focus on a row while
// aria-activedescendant named a different one — two competing "current" options —
// and made Tab walk every result (E10 review round 1).
tabIndex={-1}
onClick={() => choose(item)}
onMouseMove={(e) => {
// Only a pointer that actually MOVED may take the selection. After the arrow keys
// scroll a row past the fold, Blink re-dispatches a mousemove at the unchanged
// cursor position to refresh hover — which handed the highlight straight back to
// whatever row slid under a resting cursor (E10 review round 1). The browser
// reports zero movement for exactly that synthetic event, so ask it directly:
// round 1 remembered the last position instead, which could not judge the FIRST
// move of a session and went stale across a close (round 2).
if (e.movementX === 0 && e.movementY === 0) return;
setActive(flat.indexOf(item));
}}
className={`flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left text-sm ${
item.id === activeId ? "bg-card text-fg" : "text-muted hover:text-fg"
}`}
>
{item.icon && <span className="shrink-0">{item.icon}</span>}
<span className="min-w-0 flex-1 truncate">{item.label}</span>
{item.hint && <span className="shrink-0 text-xs text-muted">{item.hint}</span>}
</button>
))}
</div>
))
)}
<div role="status" aria-live="polite" className="sr-only">
{announced}
</div>
{/* Stays mounted (hidden) while empty, so the input's aria-controls never names a missing
element; the "nothing matches" line sits OUTSIDE it, since a listbox may hold only options
and groups. */}
<div
id={listId}
role="listbox"
aria-label={t("palette.title")}
hidden={flat.length === 0}
className="mt-3 max-h-[50vh] overflow-y-auto"
>
{visible.map((g) => (
<div
key={g.id}
role="group"
aria-labelledby={`${groupId}-${g.id}`}
className="mb-2 last:mb-0"
>
<div
id={`${groupId}-${g.id}`}
role="presentation"
className="px-1 pb-1 text-xs font-semibold tracking-wide text-muted uppercase"
>
{g.label}
</div>
{g.items.map((item) => (
<button
key={item.id}
id={`${listId}-${item.id}`}
ref={item.id === activeId ? activeRef : undefined}
data-cmd-id={item.id}
role="option"
aria-selected={item.id === activeId}
type="button"
// The combobox input owns the tab stop; the arrows move a VIRTUAL selection over
// these rows. Leaving them tabbable put DOM focus on a row while
// aria-activedescendant named a different one — two competing "current" options —
// and made Tab walk every result (E10 review round 1).
tabIndex={-1}
onClick={() => choose(item)}
onMouseMove={(e) => {
// Only a pointer that actually MOVED may take the selection. After the arrow keys
// scroll a row past the fold, Blink re-dispatches a mousemove at the unchanged
// cursor position to refresh hover — which handed the highlight straight back to
// whatever row slid under a resting cursor (E10 review round 1). The browser
// reports zero movement for exactly that synthetic event, so ask it directly:
// round 1 remembered the last position instead, which could not judge the FIRST
// move of a session and went stale across a close (round 2).
if (e.movementX === 0 && e.movementY === 0) return;
setPicked(item.id);
}}
className={`flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left text-sm ${
item.id === activeId ? "bg-card text-fg" : "text-muted hover:text-fg"
}`}
>
{item.icon && <span className="shrink-0">{item.icon}</span>}
<span className="min-w-0 flex-1 truncate">{item.label}</span>
{item.hint && <span className="shrink-0 text-xs text-muted">{item.hint}</span>}
</button>
))}
</div>
))}
</div>
{flat.length === 0 && (
<p className="mt-3 px-1 py-6 text-center text-sm text-muted">{t("palette.empty")}</p>
)}
</Modal>
);
}