Files
siftlode/frontend/src/components/ui/ActionMenu.tsx
T
peter f130a1c05a fix(keys): epic-end review round 1 — Back, menus and dialogs keep the focus where it belongs
Deep-review of E11 (19 raised, 14 confirmed; 2 refuted, 3 latent test-hardening notes dropped).

- Back from a sub-view (a Plex show page, a Messages thread) restores the item it was opened from
  even when focus was still inside the view: the first attempt now waits one task, past the
  sub-view's own popstate listener (measured in Chrome: it left focus on <body>).
- The restore listener is installed at load, so the first Back after a reload finds it; a push
  cancels a restore still waiting for the last landing's lists.
- Navigating over an overlay asks it again, a render apart, while its entry stays: the Plex
  player peels one panel per Back step, so Shift+W over info + stats closed one panel and dropped
  the navigation.
- j/k: a native <button> item keeps its own Tab stop; landing twice on the same item no longer
  leaks its tabindex; after the focused item is removed (a hidden card) the next j goes on from
  its slot when that slot is on screen.
- An abandoned `g` no longer swallows a modifier chord (g, then Mod+K opened the browser search).
- A hover card above a dialog no longer switches its Tab trap off (player, Modal, wizard,
  Lightbox): new layerStack `anyBlockingLayerAbove`.
- "Manage views…" closes its menu before opening the dialog, through a shared `closeThenAct`
  that ActionMenu now uses too.
- Copy: the EN welcome says "Feed"; the EN unreachable reason no longer claims a change;
  stale comments about PlayerModal's scroll lock and dialog contract.
2026-09-13 17:17:49 +02:00

213 lines
8.8 KiB
TypeScript

import { Fragment, useState, type ReactNode } from "react";
import { ChevronRight, MoreHorizontal } from "lucide-react";
import { PopoverItem, PopoverSurface, closeThenAct, useAnchoredPopover } from "./AnchoredPopover";
// A reusable "⋯ more actions" overflow menu: a compact trigger that opens a list of one-shot actions.
// Built on the R8 AnchoredPopover platform (arrows/typeahead/Escape/anchor-flip), same as ViewSwitcher
// and LanguageSwitcher. Use it to keep occasional actions out of a crowded toolbar. The items are
// fire-and-close (`onSelect`); a `disabled` item (e.g. a mutation already in flight) is inert.
//
// E10 S2 split the ITEM LIST out of the trigger (`MenuItemList`) so the ⋯ menu and the right-click
// context menu (`ContextMenu`) render the same rows from the same item type. That is the whole point
// of the split: a context menu that drifts from the overflow menu beside it is two menus, and the
// user has to learn both.
/** Shared surface paint for every menu built on this file — the ⋯ menu, its submenus, and
* `ContextMenu`. One constant so a context menu can never look like a different component. */
export const MENU_SURFACE = "glass-menu min-w-52 rounded-xl p-1.5 animate-[popIn_0.16s_ease]";
const ROW =
"flex w-full items-center gap-2.5 rounded-lg px-2 py-1.5 text-left text-sm outline-hidden transition disabled:opacity-50";
interface MenuItemBase {
id: string;
label: string;
icon?: ReactNode; // an element (so a caller can swap in a spinning icon while pending)
disabled?: boolean;
/** Optional native tooltip (carries a longer hint the label alone can't).
*
* KNOWN GAP, deliberately still open: on a `disabled` row this reaches nobody — a disabled button
* fires no pointer events, so no tooltip, and floating-ui's roving focus skips it. E10 review
* round 1 tried an `aria-disabled` "inert" row to fix that; round 2 found `useListNavigation`
* skips `aria-disabled` identically (`isListIndexDisabled`), which AnchoredPopover's own comment
* already said — so the swap fixed nothing and made the mouse worse (the row took the active
* highlight, then no-opped on click). Reverted. A real fix has to put the reason somewhere a
* disabled row is not: a visible hint line in the menu, or an `aria-describedby` note. */
title?: string;
/** Draw a divider above this item. Ignored on the first item — a menu never opens with a rule. */
separatorBefore?: boolean;
}
interface ActionItem extends MenuItemBase {
onSelect: () => void;
/** Destructive action: painted in the danger colour, like the outline-danger buttons. */
danger?: boolean;
items?: never;
}
interface SubmenuItem extends MenuItemBase {
/** Non-empty → this row opens a submenu instead of firing. */
items: readonly ActionMenuItem[];
onSelect?: never;
}
// A discriminated union rather than "onSelect and items are both optional": the invariant is
// "a row either fires or it opens a submenu, never both and never neither", and this codebase's
// house rule is that such a rule lives in the type, not in a comment above it.
export type ActionMenuItem = ActionItem | SubmenuItem;
const isSubmenu = (it: ActionMenuItem): it is SubmenuItem => Array.isArray(it.items);
/** The rows of a menu: leaf actions, submenus and separators, from one item array. Rendered inside a
* `PopoverSurface` (which supplies the list registry) — see `ActionMenu` and `ContextMenu`.
* `onClose` closes the ROOT menu, so selecting deep inside a submenu dismisses the whole stack. */
export function MenuItemList({
items,
onClose,
}: {
items: readonly ActionMenuItem[];
onClose: () => void;
}) {
return (
<>
{items.map((it, i) => (
<Fragment key={it.id}>
{it.separatorBefore && i > 0 && (
<div role="separator" className="my-1 h-px bg-border" aria-hidden="true" />
)}
{isSubmenu(it) ? (
<SubMenu item={it} onClose={onClose} />
) : (
<PopoverItem
role="menuitem"
disabled={it.disabled}
label={it.label}
title={it.title}
// Any row may open a dialog (a confirm), so every row closes first — see closeThenAct.
onSelect={() => closeThenAct(onClose, it.onSelect)}
className={`${ROW}${it.danger ? " text-danger" : ""}`}
>
{it.icon && (
<span className={`shrink-0 ${it.danger ? "text-danger" : "text-muted"}`}>
{it.icon}
</span>
)}
<span className="flex-1 truncate">{it.label}</span>
</PopoverItem>
)}
</Fragment>
))}
</>
);
}
/** One row that opens a nested menu. It is a real `PopoverItem`, so the parent's roving focus and
* typeahead reach it; the nested popover anchors to that same button.
*
* Why it nests correctly with no extra wiring: this component renders INSIDE the parent's
* `PopoverSurface`, i.e. inside its `<FloatingNode>`, so `useFloatingNodeId()` picks the parent up
* as its tree parent. That is what makes Floating UI's outside-press tree-aware — a press inside
* the submenu is not "outside" the parent, and Escape closes the topmost layer only. */
function SubMenu({ item, onClose }: { item: SubmenuItem; onClose: () => void }) {
const [open, setOpen] = useState(false);
const pop = useAnchoredPopover({
open,
onOpenChange: setOpen,
placement: "right-start",
offset: 2,
// A mouse expects the submenu to fall open under the pointer; a finger has no hover and taps.
hoverAlso: true,
// Target lists can be long (every playlist you own), so shrink to the viewport instead of
// running off the bottom at 768px.
fitHeight: true,
});
return (
<>
<PopoverItem
elementRef={pop.refs.setReference}
{...pop.getReferenceProps()}
role="menuitem"
disabled={item.disabled}
label={item.label}
title={item.title}
aria-haspopup="menu"
aria-expanded={open}
onKeyDown={(e) => {
// The native-menu keys. Enter/Space already open it via useClick; ArrowRight is the one
// the click handler doesn't cover.
if (e.key === "ArrowRight") {
e.preventDefault();
setOpen(true);
}
}}
className={ROW}
>
{item.icon && <span className="shrink-0 text-muted">{item.icon}</span>}
<span className="flex-1 truncate">{item.label}</span>
<ChevronRight className="h-4 w-4 shrink-0 text-muted" aria-hidden="true" />
</PopoverItem>
<PopoverSurface
popover={pop}
ariaLabel={item.label}
className={`${MENU_SURFACE} overflow-y-auto`}
style={{ maxHeight: "min(24rem, var(--fit-max-h))" }}
>
{/* ArrowLeft steps back out to the parent row — Escape would close the whole stack, and a
submenu you can only leave by dismissing everything is not a submenu. Focus returns to
the trigger via the surface's own returnFocus. */}
<div
onKeyDown={(e) => {
if (e.key === "ArrowLeft") {
e.preventDefault();
e.stopPropagation();
setOpen(false);
}
}}
>
<MenuItemList items={item.items} onClose={onClose} />
</div>
</PopoverSurface>
</>
);
}
export default function ActionMenu({
items,
ariaLabel,
className,
trigger,
}: {
items: readonly ActionMenuItem[];
/** Accessible name for the trigger (e.g. "Catalog actions"). */
ariaLabel: string;
/** Trigger className override; omit for the default glass ⋯ icon button. */
className?: string;
/** Custom trigger content; omit for the default ⋯ icon. */
trigger?: ReactNode;
}) {
const [open, setOpen] = useState(false);
// A disabled item (a mutation already in flight) is skipped by roving keyboard nav automatically:
// PopoverItem renders it as a native `disabled` button, which useListNavigation reads and never
// focuses. No explicit disabledIndices needed. See ActionMenu.dom.test.tsx for the guard.
const pop = useAnchoredPopover({ open, onOpenChange: setOpen, placement: "bottom-end" });
return (
<>
<button
type="button"
ref={pop.refs.setReference}
{...pop.getReferenceProps()}
aria-label={ariaLabel}
title={ariaLabel}
className={
className ??
"glass-card glass-hover flex items-center justify-center rounded-xl p-2 text-sm transition"
}
>
{trigger ?? <MoreHorizontal className="h-5 w-5" aria-hidden="true" />}
</button>
<PopoverSurface popover={pop} ariaLabel={ariaLabel} className={MENU_SURFACE}>
<MenuItemList items={items} onClose={() => setOpen(false)} />
</PopoverSurface>
</>
);
}