Popovers: extract shared usePopover hook; SettingsPopoverStore becomes PopoverStore

This commit is contained in:
2026-06-12 19:40:35 +03:00
parent 0e225d7d5c
commit 20d593a6a3
8 changed files with 241 additions and 334 deletions
+15 -84
View File
@@ -9,8 +9,8 @@
* primitive as SortControl/SettingsPopover — deliberately NOT an ARIA menu and not
* a combobox; a short list of buttons needs neither's contract.
*
* Behaviour (mirrors SortControl): at most one popover is open app-wide
* (`useSettingsPopoverStore`); Esc closes and refocuses the trigger; an outside
* Behaviour (the shared `usePopover` machinery): at most one popover is open
* app-wide (`PopoverStore`); Esc closes and refocuses the trigger; an outside
* pointer press closes; opening focuses the selected option (or the first);
* Arrow/Home/End move focus through the options; choosing one fires `onSelect`,
* closes, and refocuses the trigger. The panel is portaled to <body> and positioned
@@ -22,13 +22,13 @@
* caller intercept the click entirely (the armed-channel fast path).
*/
import { useCallback, useEffect, useRef, type ReactNode } from 'react';
import { type ReactNode } from 'react';
import { createPortal } from 'react-dom';
import { useSettingsPopoverStore } from '../stores/SettingsPopoverStore';
import { usePopover } from '../hooks/usePopover';
import styles from './SelectControl.module.css';
/** Gap (px) between the trigger and the disclosed panel (matches SortControl). */
const GAP = 6;
/** Land on the selected option (falling back to the first). */
const INITIAL_FOCUS = ['[aria-current="true"]', 'button'] as const;
export interface SelectControlOption<V extends string> {
value: V;
@@ -71,64 +71,15 @@ export function SelectControl<V extends string>({
heading,
beforeOpen,
}: SelectControlProps<V>) {
const open = useSettingsPopoverStore((s) => s.openId === id);
const toggle = useSettingsPopoverStore((s) => s.toggle);
const close = useSettingsPopoverStore((s) => s.close);
const triggerRef = useRef<HTMLButtonElement>(null);
const popRef = useRef<HTMLDivElement | null>(null);
const { open, toggle, closeAndRefocus, triggerRef, popRef, setPopNode } = usePopover({
id,
align: 'left',
flip: true,
initialFocus: INITIAL_FOCUS,
});
const current = value !== undefined ? options.find((o) => o.value === value) : undefined;
// Fixed-position from the trigger's rect (no React state → no re-render on
// scroll). Below the trigger by default; above when the viewport below is short.
const place = useCallback(() => {
const trigger = triggerRef.current;
const pop = popRef.current;
if (!trigger || !pop) return;
const r = trigger.getBoundingClientRect();
const below = window.innerHeight - r.bottom - GAP;
const height = pop.offsetHeight;
pop.style.top =
below < height && r.top > height + GAP ? `${r.top - GAP - height}px` : `${r.bottom + GAP}px`;
// Keep the panel on-screen when the trigger sits near the right edge.
const left = Math.min(r.left, window.innerWidth - pop.offsetWidth - GAP);
pop.style.left = `${Math.max(GAP, left)}px`;
}, []);
useEffect(() => {
if (!open) return;
window.addEventListener('resize', place);
window.addEventListener('scroll', place, true);
return () => {
window.removeEventListener('resize', place);
window.removeEventListener('scroll', place, true);
};
}, [open, place]);
// Esc closes + restores focus to the trigger; an outside pointer press closes
// (APG disclosure; non-modal). Esc is captured so it settles here, not on a
// parent (the builder modal also listens for Esc).
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
e.stopPropagation();
close();
triggerRef.current?.focus();
}
};
const onPointer = (e: PointerEvent) => {
const t = e.target as Node;
if (!popRef.current?.contains(t) && !triggerRef.current?.contains(t)) close();
};
document.addEventListener('keydown', onKey, true);
document.addEventListener('pointerdown', onPointer, true);
return () => {
document.removeEventListener('keydown', onKey, true);
document.removeEventListener('pointerdown', onPointer, true);
};
}, [open, close]);
// Arrow/Home/End roving among the option buttons — a convenience on top of the
// natural Tab order, matching what a native select's popup offers.
const onPopKeyDown = (e: React.KeyboardEvent) => {
@@ -138,8 +89,7 @@ export function SelectControl<V extends string>({
// convention) — also keeps focus inside a host modal's trap, since the panel is
// portaled outside it.
if (e.key === 'Tab') {
close();
triggerRef.current?.focus();
closeAndRefocus();
return;
}
const items = Array.from(pop.querySelectorAll<HTMLButtonElement>('button'));
@@ -155,28 +105,9 @@ export function SelectControl<V extends string>({
}
};
// On mount: position before paint, then land focus on the selected option (or
// the first) so keyboard users arrive inside the popover.
const setPopNode = useCallback(
(node: HTMLDivElement | null) => {
popRef.current = node;
if (node) {
place();
// Two queries, not one selector list — `querySelector('a, b')` returns the
// first match in document order, which would always be the first button.
const target =
node.querySelector<HTMLElement>('[aria-current="true"]') ??
node.querySelector<HTMLElement>('button');
target?.focus();
}
},
[place],
);
const choose = (v: V) => {
onSelect(v);
close();
triggerRef.current?.focus();
closeAndRefocus();
};
return (
@@ -192,7 +123,7 @@ export function SelectControl<V extends string>({
disabled={disabled}
onClick={() => {
if (beforeOpen && !beforeOpen()) return;
toggle(id);
toggle();
}}
>
{triggerContent ?? (