From 429e3d448d3d6d6724dfd61ff61e2962a23ac936 Mon Sep 17 00:00:00 2001 From: Ben Vinegar <2153+benvinegar@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:59:30 -0500 Subject: [PATCH 1/2] feat(web): one-row toolbar with icon controls and a View menu The browser review page's toolbar was two rows of text buttons and wrapped to three at 800px. It is now one 44px row: layout, refresh, copy link, and the pane toggles are icon buttons, viewed progress is a ring, and the line and review toggles plus the theme picker live in a View menu that shows each shortcut. Adds the inline SVG icon module the rest of the page builds on. Co-Authored-By: Claude Fable 5.2 --- .changeset/web-toolbar-one-row.md | 5 + packages/hunk/src/web/app/ReviewApp.tsx | 96 ++-- packages/hunk/src/web/app/ReviewControls.tsx | 168 ++++--- packages/hunk/src/web/app/ThemeMenu.tsx | 130 +++--- packages/hunk/src/web/app/Toolbar.tsx | 158 +++---- packages/hunk/src/web/app/ViewMenu.tsx | 290 ++++++++++++ packages/hunk/src/web/app/ViewedControls.tsx | 35 -- packages/hunk/src/web/app/ViewedProgress.tsx | 48 ++ packages/hunk/src/web/app/useReviewTools.tsx | 2 + packages/hunk/src/web/icons/Icon.tsx | 40 ++ packages/hunk/src/web/icons/iconPaths.tsx | 86 ++++ packages/hunk/src/web/styles.css | 438 +++++++++++++++++-- test/web/review-accessibility.e2e.ts | 9 +- test/web/review-keyboard.e2e.ts | 17 +- test/web/review-notes.e2e.ts | 9 +- test/web/review-screenshots.e2e.ts | 24 +- test/web/review-shell.e2e.ts | 84 +++- test/web/review-tools-screenshots.e2e.ts | 18 +- test/web/review-viewed.e2e.ts | 28 +- test/web/webTestHarness.ts | 20 +- 20 files changed, 1344 insertions(+), 361 deletions(-) create mode 100644 .changeset/web-toolbar-one-row.md create mode 100644 packages/hunk/src/web/app/ViewMenu.tsx delete mode 100644 packages/hunk/src/web/app/ViewedControls.tsx create mode 100644 packages/hunk/src/web/app/ViewedProgress.tsx create mode 100644 packages/hunk/src/web/icons/Icon.tsx create mode 100644 packages/hunk/src/web/icons/iconPaths.tsx diff --git a/.changeset/web-toolbar-one-row.md b/.changeset/web-toolbar-one-row.md new file mode 100644 index 000000000..bd8abac09 --- /dev/null +++ b/.changeset/web-toolbar-one-row.md @@ -0,0 +1,5 @@ +--- +"hunkdiff": patch +--- + +The browser review page's toolbar is now one compact row of icon controls that stays on one line in narrow windows, with wrapping, line numbers, agent notes, hidden viewed files, and the theme moved into a new View menu and a Commands button that opens the command palette. diff --git a/packages/hunk/src/web/app/ReviewApp.tsx b/packages/hunk/src/web/app/ReviewApp.tsx index bf878b011..dfa94cbb0 100644 --- a/packages/hunk/src/web/app/ReviewApp.tsx +++ b/packages/hunk/src/web/app/ReviewApp.tsx @@ -97,7 +97,7 @@ import { NotesTab } from "../notesPanel/NotesTab"; import { OverviewTab } from "../overview/OverviewTab"; import { selectWebReviewOverview } from "../panel/overviewInput"; import { webLocalKeyCommands, withWebLocalChords } from "../panel/panelCommands"; -import type { WebLocalCommandId } from "../commands/webLocalCommands"; +import { webModChordLabel, type WebLocalCommandId } from "../commands/webLocalCommands"; import { readSidePanelPreferences, resolveSidePanelOpen, @@ -108,13 +108,14 @@ import { SidePanel, type SidePanelTool } from "../panel/SidePanel"; import type { ThemeMenuOption } from "./ThemeMenu"; import { ToastRegion } from "../actions/toasts"; import { reviewLinkWithCapability, watchReviewCapability } from "../session/capability"; -import { ReviewControls } from "./ReviewControls"; +import { FilterField, ReviewActions } from "./ReviewControls"; import { Toolbar } from "./Toolbar"; import { useReviewInteraction } from "./useReviewInteraction"; import { useReviewTools } from "./useReviewTools"; import { useViewedFiles, type ViewedFiles } from "../viewed/useViewedFiles"; import type { ReviewViewedControls } from "../stream/FileSection"; -import { ViewedControls } from "./ViewedControls"; +import { ViewedProgress } from "./ViewedProgress"; +import { ViewMenu } from "./ViewMenu"; /** Width of one monospace column on this page, measured once the fonts are in place. */ function useColumnWidth() { @@ -791,9 +792,16 @@ export function ReviewApp({ session }: { session: ReviewSession }) { }); const toolsRef = useRef(undefined); toolsRef.current = tools; - const panelHint = webCommandChords(pageKeymap, "hunk.web.toggleSidePanel") - .map(formatKeyChord) - .join(" / "); + const pageHint = (commandId: WebLocalCommandId) => + webCommandChords(pageKeymap, commandId).map(formatKeyChord).join(" / ") || undefined; + const panelHint = pageHint("hunk.web.toggleSidePanel"); + const viewMenuHints = { + wrap: keyHint("hunk.view.toggleLineWrap"), + lineNumbers: keyHint("hunk.view.toggleLineNumbers"), + agentNotes: keyHint("hunk.view.toggleAgentNotes"), + hideViewed: pageHint("hunk.web.toggleHideViewed"), + theme: keyHint("hunk.view.openThemeSelector"), + }; const panelTools: SidePanelTool[] = overview ? [ { @@ -902,42 +910,56 @@ export function ReviewApp({ session }: { session: ReviewSession }) { ? `Loading ${mirror.loadedFiles} of ${mirror.totalFiles}` : undefined } - preferences={preferences} + layout={preferences.layout} + onLayout={(next) => updatePreferences({ layout: next })} sidebarOpen={sidebarOpen} resolvedLayout={layout} - themes={themeOptions} - themeId={selectedId} - {...(theme ? { themeLabel: theme.label } : {})} - themeMenuOpen={themeMenuOpen} - onThemeMenuOpen={setThemeMenuOpen} keyHint={keyHint} - onPreferences={updatePreferences} onToggleSidebar={() => updatePreferences({ sidebarOpen: !sidebarOpen })} - onTheme={choose} - controls={ - <> - void interactive.refresh()} - {...(keyHint("hunk.app.refresh") - ? { refreshKeyHint: keyHint("hunk.app.refresh") } - : {})} - onCopyLink={copyLink} - sessionEnded={sessionEnded} - /> - - + filterField={ + + } + viewedProgress={} + viewMenu={ + void interactive.toggleAgentNotes()} + hideViewed={viewed.hideViewed} + onToggleHideViewed={viewed.toggleHideViewed} + sessionEnded={sessionEnded} + themes={themeOptions} + themeId={selectedId} + {...(theme ? { themeLabel: theme.label } : {})} + themeMenuOpen={themeMenuOpen} + onThemeMenuOpen={setThemeMenuOpen} + onTheme={choose} + hints={viewMenuHints} + /> + } + reviewActions={ + void interactive.refresh()} + {...(keyHint("hunk.app.refresh") + ? { refreshKeyHint: keyHint("hunk.app.refresh") } + : {})} + onCopyLink={copyLink} + sessionEnded={sessionEnded} + /> } + onOpenCommands={tools.openPalette} + commandsHint={webModChordLabel("k")} panelOpen={panelOpen} {...(panelHint ? { panelHint } : {})} onTogglePanel={() => updatePanel({ open: !panelOpen })} diff --git a/packages/hunk/src/web/app/ReviewControls.tsx b/packages/hunk/src/web/app/ReviewControls.tsx index 4a95a0d91..785562afd 100644 --- a/packages/hunk/src/web/app/ReviewControls.tsx +++ b/packages/hunk/src/web/app/ReviewControls.tsx @@ -2,84 +2,118 @@ /** * The toolbar's review controls: the shared file filter, refresh, and "Copy review link". * - * The filter and agent-note visibility are shared with every surface of the review, the - * terminal included, so the filter says so beside itself. Refresh reopens the session's input - * (`POST /refresh`), paced by the session. Copying the review link is the one deliberate way the - * capability leaves the page. + * The filter is shared with every surface of the review, the terminal included, so the field + * says so beside itself and in its tooltip. Refresh reopens the session's input + * (`POST /refresh`), paced by the session. Copying the review link is the one deliberate way + * the capability leaves the page. Refresh and copy are icon buttons whose accessible names + * carry their state ("Refreshing…", "Copied", "Copy failed"), and the copy result also shows + * as a brief visible label. */ import { forwardRef, useState } from "react"; +import { Icon } from "../icons/Icon"; -export interface ReviewControlsProps { +export interface FilterFieldProps { filterText: string; onFilterChange: (text: string) => void; - /** The shortcut that focuses the filter, for its tooltip. */ + /** The shortcut that focuses the filter, shown in the field and its tooltip. */ filterKeyHint?: string; - refreshing: boolean; - onRefresh: () => void; - refreshKeyHint?: string; - onCopyLink: () => Promise; - /** The session has ended: the filter and refresh need it, so both are disabled. */ + /** The session has ended: the filter needs it, so it is disabled. */ sessionEnded?: boolean; } -/** The filter field, refresh button, and copy-link button. */ -export const ReviewControls = forwardRef( - function ReviewControls(props, filterRef) { - const [copied, setCopied] = useState<"idle" | "copied" | "failed">("idle"); +/** The shared file filter field. */ +export const FilterField = forwardRef( + function FilterField(props, filterRef) { return ( -
- - - -
+ /> + + {props.filterKeyHint ? ( + + ) : null} + ); }, ); + +export interface ReviewActionsProps { + refreshing: boolean; + onRefresh: () => void; + refreshKeyHint?: string; + onCopyLink: () => Promise; + /** The session has ended: refresh needs it, so it is disabled. */ + sessionEnded?: boolean; +} + +/** The refresh and copy-link icon buttons. */ +export function ReviewActions(props: ReviewActionsProps) { + const [copied, setCopied] = useState<"idle" | "copied" | "failed">("idle"); + const copyLabel = + copied === "copied" ? "Copied" : copied === "failed" ? "Copy failed" : "Copy link"; + + return ( + <> + + + + ); +} diff --git a/packages/hunk/src/web/app/ThemeMenu.tsx b/packages/hunk/src/web/app/ThemeMenu.tsx index 5ef8820aa..a1bf9432f 100644 --- a/packages/hunk/src/web/app/ThemeMenu.tsx +++ b/packages/hunk/src/web/app/ThemeMenu.tsx @@ -1,16 +1,16 @@ /** @jsxImportSource react */ /** - * The theme picker: a toolbar button that opens a listbox of the built-in themes. + * The theme picker's list: a listbox of the built-in themes, opened from the View menu's + * Theme row or with `t` (the terminal's `hunk.view.openThemeSelector`). * - * A real button and a real listbox rather than a native ``, so it can wear the theme's own colors. + * Keyboard behaves like a select: the arrow keys, Home, and End move the active option, typing + * a letter jumps to the next theme starting with it, Enter or Space chooses, and Escape or Tab + * closes. Opening starts at the current theme; closing hands focus back through `onClose`, + * which the View menu points at its own button. When the session resolved a theme, the first + * option follows it ("Use session theme") and choosing it clears this browser's override. */ -import { useEffect, useId, useRef, useState, type KeyboardEvent } from "react"; +import { useEffect, useId, useRef, useState, type KeyboardEvent, type RefObject } from "react"; import type { WebTheme } from "../theme/themeIndex"; /** One choice in the menu. */ @@ -20,35 +20,32 @@ export interface ThemeMenuProps { themes: readonly ThemeMenuOption[]; /** The option shown as chosen. */ themeId: string | undefined; - /** The theme in effect, named on the button. */ - currentLabel?: string; open: boolean; onOpenChange: (open: boolean) => void; onTheme: (themeId: string) => void; - /** The shortcut that opens the menu, for its tooltip. */ - keyHint?: string; + /** The region a click inside does not count as "outside" (the menu's anchor). */ + anchorRef: RefObject; + /** Returns focus to the control that owns the list once it closes from the keyboard. */ + onClose: () => void; } -/** The toolbar's theme picker. */ +/** The theme picker's listbox, shown while `open`. */ export function ThemeMenu({ themes, themeId, open, onOpenChange, onTheme, - keyHint, - currentLabel, + anchorRef, + onClose, }: ThemeMenuProps) { const listId = useId(); - const buttonRef = useRef(null); const listRef = useRef(null); - const rootRef = useRef(null); const currentIndex = Math.max( 0, themes.findIndex((theme) => theme.id === themeId), ); const [active, setActive] = useState(currentIndex); - const label = currentLabel ?? themes.find((theme) => theme.id === themeId)?.label; // Opening starts at the current theme and moves focus into the list. useEffect(() => { @@ -66,20 +63,21 @@ export function ThemeMenu({ ?.scrollIntoView({ block: "nearest" }); }, [active, open]); - // A click anywhere else closes the menu without choosing. + // A click anywhere else closes the list without choosing. useEffect(() => { if (!open) return; const onPointerDown = (event: PointerEvent) => { - if (!rootRef.current?.contains(event.target as Node)) onOpenChange(false); + if (!anchorRef.current?.contains(event.target as Node)) onOpenChange(false); }; window.addEventListener("pointerdown", onPointerDown); return () => window.removeEventListener("pointerdown", onPointerDown); - }, [open, onOpenChange]); + }, [open, onOpenChange, anchorRef]); const close = () => { onOpenChange(false); - buttonRef.current?.focus(); + onClose(); }; + const choose = (index: number) => { const theme = themes[index]; if (theme) onTheme(theme.id); @@ -123,61 +121,39 @@ export function ThemeMenu({ } }; + if (!open) return null; + return ( -
- - {open ? ( -
    + {themes.map((theme, index) => ( +
  • setActive(index)} + onClick={() => choose(index)} > - {themes.map((theme, index) => ( -
  • setActive(index)} - onClick={() => choose(index)} - > - - {theme.appearance === "light" ? "☀" : "☾"} - - {theme.label} -
  • - ))} -
- ) : null} -
+ + {theme.appearance === "light" ? "☀" : "☾"} + + {theme.label} + + ))} + ); } diff --git a/packages/hunk/src/web/app/Toolbar.tsx b/packages/hunk/src/web/app/Toolbar.tsx index 253c2dada..9dccb3998 100644 --- a/packages/hunk/src/web/app/Toolbar.tsx +++ b/packages/hunk/src/web/app/Toolbar.tsx @@ -1,20 +1,21 @@ /** @jsxImportSource react */ /** - * The page's toolbar: what the terminal's menu bar title says, plus web-native view controls. + * Lays out the page's toolbar as one row: what the terminal's menu bar title says on the left, + * web-native view controls on the right. * * The left side mirrors the terminal's `topTitle` — review title, file count, and total - * `+A -D` — with connection and load state beside it. The right side holds the per-browser - * view controls: sidebar, layout (auto, split, unified), wrapping, line numbers, and theme. - * They are real buttons, styled from the theme's tokens, and each names the shortcut that - * does the same thing (from the page's keymap, so a remap shows up here too). None of them - * reaches the session. + * `+A -D` — with connection and load state beside it (a quiet dot while connected, words while + * loading, reconnecting, or failed). The right side holds the shared filter, viewed progress, + * layout (auto, split, unified), the View menu, refresh, copy link, the command palette, and + * the side panel. Controls are icon buttons where the icon says enough; each names its action + * and the shortcut that does the same thing (from the page's keymap, so a remap shows up here + * too) in its tooltip. Narrow windows drop labels before controls (`styles.css`) so the row + * never wraps. None of the view controls reaches the session. */ import type { KeyboardEvent, ReactNode } from "react"; import type { LayoutMode } from "../../core/run/commandInputs"; import type { WebImplementedCommandId } from "../commands/webCommandTable"; - -import type { WebViewPreferences } from "../view/viewPreferences"; -import { ThemeMenu, type ThemeMenuOption } from "./ThemeMenu"; +import { Icon, type IconName } from "../icons/Icon"; export interface ToolbarProps { title: string; @@ -23,27 +24,28 @@ export interface ToolbarProps { deletions: number; status: { label: string; state: "connected" | "loading" | "reconnecting" | "failed" }; progress?: string; - preferences: WebViewPreferences; + layout: LayoutMode; + onLayout: (layout: LayoutMode) => void; sidebarOpen: boolean; resolvedLayout: "split" | "unified"; - themes: readonly ThemeMenuOption[]; - /** The theme option shown as chosen. */ - themeId: string | undefined; - /** The theme in effect. */ - themeLabel?: string; /** The session's source, shown beside the title. */ sourceLabel?: string; /** The shared file filter, when the session has one. */ filter?: string; /** Sidecar notes the session left out of the shared state; the terminal still shows them. */ omittedNotes?: number; - themeMenuOpen: boolean; - onThemeMenuOpen: (open: boolean) => void; - onPreferences: (next: Partial) => void; onToggleSidebar: () => void; - onTheme: (themeId: string) => void; - /** Review controls shown before the view controls (filter, refresh, copy link). */ - controls?: ReactNode; + /** The filter field. */ + filterField?: ReactNode; + /** Viewed progress. */ + viewedProgress?: ReactNode; + /** The View menu. */ + viewMenu?: ReactNode; + /** Refresh and copy link. */ + reviewActions?: ReactNode; + /** Opens the command palette, and the chord that does the same. */ + onOpenCommands?: () => void; + commandsHint?: string; /** The shortcut label for one command, when it has one on this page. */ keyHint: (commandId: WebImplementedCommandId) => string | undefined; /** Whether the side panel of review tools is open, and how to toggle it. */ @@ -52,10 +54,10 @@ export interface ToolbarProps { onTogglePanel?: () => void; } -const LAYOUTS: readonly { mode: LayoutMode; command: WebImplementedCommandId }[] = [ - { mode: "auto", command: "hunk.view.layoutAuto" }, - { mode: "split", command: "hunk.view.layoutSplit" }, - { mode: "unified", command: "hunk.view.layoutUnified" }, +const LAYOUTS: readonly { mode: LayoutMode; command: WebImplementedCommandId; icon: IconName }[] = [ + { mode: "auto", command: "hunk.view.layoutAuto", icon: "layout-auto" }, + { mode: "split", command: "hunk.view.layoutSplit", icon: "layout-split" }, + { mode: "unified", command: "hunk.view.layoutUnified", icon: "layout-unified" }, ]; /** A tooltip naming one action and, when bound, its shortcut. */ @@ -65,16 +67,17 @@ function hinted(label: string, hint: string | undefined) { /** The page toolbar. */ export function Toolbar(props: ToolbarProps) { - const { preferences, keyHint } = props; + const { keyHint } = props; + const connected = props.status.state === "connected"; // Arrow keys move the choice within the layout group, as in any radio group. const onLayoutKeyDown = (event: KeyboardEvent) => { const step = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 }[event.key]; if (step === undefined) return; event.preventDefault(); - const index = LAYOUTS.findIndex((layout) => layout.mode === preferences.layout); + const index = LAYOUTS.findIndex((layout) => layout.mode === props.layout); const next = LAYOUTS[(index + step + LAYOUTS.length) % LAYOUTS.length]!; - props.onPreferences({ layout: next.mode }); + props.onLayout(next.mode); event.currentTarget.querySelector(`[data-testid="layout-${next.mode}"]`)?.focus(); }; @@ -92,17 +95,33 @@ export function Toolbar(props: ToolbarProps) { onClick={props.onToggleSidebar} data-testid="toggle-sidebar" > - +
- + {/* The tooltip carries the whole title, which a narrow toolbar truncates. */} + {props.title} - - {props.fileCount === 1 ? "1 file" : `${props.fileCount} files`} + + + {props.fileCount === 1 ? "1 file" : `${props.fileCount} files`} + + {`+${props.additions}`} + {`-${props.deletions}`} + + {/* Connected is the quiet default: a dot whose words stay available to assistive + technology. Every other state keeps its words on screen. */} + + {props.status.label} - {`+${props.additions}`} - {`-${props.deletions}`} {props.filter ? ( {`filter: ${props.filter}`} @@ -117,9 +136,6 @@ export function Toolbar(props: ToolbarProps) { {`${props.omittedNotes} agent ${props.omittedNotes === 1 ? "note" : "notes"} not shown`} ) : null} - - {props.status.label} - {props.progress ? ( {props.progress} @@ -127,22 +143,25 @@ export function Toolbar(props: ToolbarProps) { ) : null}
- {props.controls} + {props.filterField} + {props.viewedProgress} +
diff --git a/packages/hunk/src/web/app/ViewMenu.tsx b/packages/hunk/src/web/app/ViewMenu.tsx new file mode 100644 index 000000000..8e3029abb --- /dev/null +++ b/packages/hunk/src/web/app/ViewMenu.tsx @@ -0,0 +1,290 @@ +/** @jsxImportSource react */ +/** + * Shows the toolbar's View menu: the display toggles that do not earn a toolbar button of + * their own, plus the theme picker. + * + * Rows: Wrap long lines, Line numbers (this browser's view preferences), Agent notes (shared + * with every surface through the `hunk.view.toggleAgentNotes` command path, and labelled as + * shared), Hide viewed files (this browser only), and Theme, which opens the theme listbox + * (`ThemeMenu`) in place of the menu. Each row names its shortcut from the page's keymap, so a + * remap shows up here too; the shortcuts work with the menu closed. + * + * Menu semantics follow `ThemeMenu`: opening moves focus to the first row, the arrow keys, + * Home, and End move between rows, Escape closes and returns focus to the View button, Tab + * and a click elsewhere close it. Toggling a row keeps the menu open so several can change at + * once. The menu stays mounted while closed (`hidden`), so the rows' state stays queryable. + */ +import { + useCallback, + useEffect, + useId, + useRef, + useState, + type KeyboardEvent, + type ReactNode, +} from "react"; +import { Icon } from "../icons/Icon"; +import { ThemeMenu, type ThemeMenuOption } from "./ThemeMenu"; + +export interface ViewMenuProps { + wrapLines: boolean; + showLineNumbers: boolean; + onPreferences: (next: { wrapLines?: boolean; showLineNumbers?: boolean }) => void; + agentNotesVisible: boolean; + onToggleAgentNotes: () => void; + hideViewed: boolean; + onToggleHideViewed: () => void; + /** The session has ended: shared toggles need it, so they are disabled. */ + sessionEnded?: boolean; + themes: readonly ThemeMenuOption[]; + /** The theme option shown as chosen. */ + themeId: string | undefined; + /** The theme in effect, named on the Theme row. */ + themeLabel?: string; + themeMenuOpen: boolean; + onThemeMenuOpen: (open: boolean) => void; + onTheme: (themeId: string) => void; + /** Shortcut labels for the rows that have one on this page. */ + hints: { + wrap: string | undefined; + lineNumbers: string | undefined; + agentNotes: string | undefined; + hideViewed: string | undefined; + theme: string | undefined; + }; +} + +/** The selector for every row the arrow keys move between. */ +const ROW_SELECTOR = '[role="menuitemcheckbox"]:not(:disabled), [role="menuitem"]:not(:disabled)'; + +interface ToggleRowProps { + label: string; + /** Extra words for assistive technology only, appended to the visible label. */ + spokenSuffix?: string; + /** A short visible note beside the label ("shared"). */ + note?: string; + checked: boolean; + hint?: string; + title: string; + disabled?: boolean; + testId?: string; + onToggle: () => void; +} + +/** One checkable menu row with its shortcut and an on/off switch. */ +function ToggleRow(props: ToggleRowProps) { + return ( + + ); +} + +/** A labelled group of rows. */ +function RowGroup({ label, children }: { label: string; children: ReactNode }) { + const id = useId(); + return ( +
+ + {children} +
+ ); +} + +/** The toolbar's View button and menu. */ +export function ViewMenu(props: ViewMenuProps) { + const { themeMenuOpen, onThemeMenuOpen } = props; + const [open, setOpen] = useState(false); + const menuId = useId(); + const rootRef = useRef(null); + const buttonRef = useRef(null); + const menuRef = useRef(null); + const themeLabel = + props.themeLabel ?? props.themes.find((theme) => theme.id === props.themeId)?.label; + + const rows = (): HTMLElement[] => + menuRef.current ? Array.from(menuRef.current.querySelectorAll(ROW_SELECTOR)) : []; + + // Opening moves focus to the first row. + useEffect(() => { + if (open) rows()[0]?.focus(); + }, [open]); + + // The theme list replaces the menu, whichever way it opened (`t` or the Theme row). + useEffect(() => { + if (themeMenuOpen) setOpen(false); + }, [themeMenuOpen]); + + // A click anywhere else closes the menu. + useEffect(() => { + if (!open) return; + const onPointerDown = (event: PointerEvent) => { + if (!rootRef.current?.contains(event.target as Node)) setOpen(false); + }; + window.addEventListener("pointerdown", onPointerDown); + return () => window.removeEventListener("pointerdown", onPointerDown); + }, [open]); + + const focusButton = useCallback(() => buttonRef.current?.focus(), []); + + const onMenuKeyDown = (event: KeyboardEvent) => { + const items = rows(); + const index = items.indexOf(document.activeElement as HTMLElement); + const last = items.length - 1; + const moves: Record number> = { + ArrowDown: () => (index >= last ? 0 : index + 1), + ArrowUp: () => (index <= 0 ? last : index - 1), + Home: () => 0, + End: () => last, + }; + const move = moves[event.key]; + if (move) { + event.preventDefault(); + items[move()]?.focus(); + return; + } + if (event.key === "Escape") { + event.preventDefault(); + setOpen(false); + focusButton(); + return; + } + if (event.key === "Tab") setOpen(false); + }; + + return ( +
+ +