feat(web): port the pi2-web-ui-design v0.1.1 UI
Sync the React console with the v0.1.1 prototype (20 CHGs): Quiet Workbench
shell, Chat IA v3, tool-family rendering, and the mobile page pill.
Shell / tokens (CHG-01/04/15/20):
- tokens.css rewritten from the prototype (three-layer light/dark/system),
`--tabbar-h` removed, new faint/border-subtle/surface-1-2/fs-*/dur-*/reading-max
- 56px icon-only nav rail/sidebar (44x44 hit targets, CSS tooltips, active is a
solid primary fill, no left bar), 52px topbar, merged preferences menu,
⌘K/Cmd-K palette
- `<600` gets a topbar page pill + page sheet; the bottom tabbar is gone
Pages (CHG-01): workspaces becomes a card grid with whole-card links and a
320px recent-activity column; status gets four metric tiles + a zero-primary
layout; connect gets a two-column hero, one primary per state and a collapsed
manual form.
Chat IA v3 (CHG-02/10-14/16-19): two columns, single-workspace tree with a
workspace switch, single-line rows with attention, body-level row popover,
session tray (todo/tasks) replacing the right panel, context ring moved into a
composer telemetry line, right-aligned user messages, queued messages as one
stream entity plus a composer status bar, and an in-place subagent child view.
Tool rendering (CHG-05/06/09): new `features/chat/tools` module — one row per
call, DTO adapter for the daemon's block shape, 11 kind families, state
semantics ("one state, one meaning"), 44px touch targets and the diff row
contrast fix.
i18n: 729 keys per language (zh/en parity checked), 0 unresolved keys.
Verification: web typecheck + 297 vitest + vite build green, root typecheck
green, `scripts/smoke.sh` green, and a new visual harness
(`scripts/ui-mock-server.mjs` + `scripts/ui-shots.mjs`, docs/ui-parity.md)
shoots 4 pages x 3 viewports x 2 themes = 24 screenshots clean with
overflow/console/primary/tabbar assertions. `scripts/e2e/ui-e2e.mjs` selectors
are updated to the new DOM; that suite still needs a real pi + nvim to run.
This commit is contained in:
1 parent
a8425a51b6
commit
88e73c7737
98 files changed
+17676
-2871
No files matched your search
@@ -0,0 +1,291 @@
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
import { useTheme } from "next-themes";
|
||||
import { Fragment, useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Icon, type IconName } from "@/components/icons";
|
||||
import { NAV } from "@/components/shared/nav-list";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useSessionsStore } from "@/stores/sessions";
|
||||
import { useWorkspacesStore } from "@/stores/workspaces";
|
||||
|
||||
interface PaletteItem {
|
||||
id: string;
|
||||
group: string;
|
||||
icon: IconName;
|
||||
label: string;
|
||||
hint?: string;
|
||||
keywords?: string;
|
||||
href?: string;
|
||||
action?: () => void;
|
||||
}
|
||||
|
||||
export interface CommandPaletteProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* ⌘K / Ctrl-K command palette (CHG-08). Groups: pages, connection, sessions,
|
||||
* workspaces, theme. The input autofocuses, ↑↓/Home/End move `aria-selected`,
|
||||
* Enter runs, Escape closes, Tab stays inside the dialog, and closing returns
|
||||
* focus to whatever had it before the palette opened.
|
||||
*/
|
||||
export function CommandPalette({ open, onOpenChange }: CommandPaletteProps) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const { resolvedTheme, setTheme } = useTheme();
|
||||
const workspaces = useWorkspacesStore((state) => state.items);
|
||||
const byWorkspace = useSessionsStore((state) => state.byWorkspace);
|
||||
|
||||
const [query, setQuery] = useState("");
|
||||
const [index, setIndex] = useState(0);
|
||||
const [visible, setVisible] = useState(false);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
const panelRef = useRef<HTMLDivElement>(null);
|
||||
const previousFocusRef = useRef<HTMLElement | null>(null);
|
||||
|
||||
const groupPages = t("shell.palettePages");
|
||||
const groupConnection = t("shell.connection");
|
||||
const groupSessions = t("shell.paletteSessions");
|
||||
const groupWorkspaces = t("shell.paletteWorkspaces");
|
||||
const groupActions = t("shell.paletteActions");
|
||||
|
||||
const all: PaletteItem[] = [];
|
||||
for (const entry of NAV) {
|
||||
all.push({
|
||||
id: `page-${entry.key}`,
|
||||
group: groupPages,
|
||||
icon: entry.icon,
|
||||
label: t(entry.labelKey),
|
||||
keywords: `${entry.key} ${entry.to}`,
|
||||
href: entry.to,
|
||||
});
|
||||
}
|
||||
all.push({
|
||||
id: "page-connect",
|
||||
group: groupConnection,
|
||||
icon: "plug",
|
||||
label: t("shell.openConnection"),
|
||||
keywords: "connect pairing pair",
|
||||
href: "/connect",
|
||||
});
|
||||
for (const session of Object.values(byWorkspace).flat()) {
|
||||
all.push({
|
||||
id: `session-${session.sessionId}`,
|
||||
group: groupSessions,
|
||||
icon: "chat",
|
||||
label: session.name ?? session.sessionId,
|
||||
hint: t(`state.${session.status}`),
|
||||
keywords: `${session.sessionId} ${session.model?.id ?? ""} ${session.cwd}`,
|
||||
href: `/chat/${encodeURIComponent(session.sessionId)}`,
|
||||
});
|
||||
}
|
||||
for (const workspace of workspaces) {
|
||||
const name = workspace.name || workspace.cwd;
|
||||
all.push({
|
||||
id: `workspace-${workspace.workspaceId}`,
|
||||
group: groupWorkspaces,
|
||||
icon: "folder",
|
||||
label: name,
|
||||
hint: workspace.cwd,
|
||||
keywords: `${workspace.name} ${workspace.cwd}`,
|
||||
href: `/chat?workspace=${encodeURIComponent(workspace.workspaceId)}`,
|
||||
});
|
||||
}
|
||||
all.push({
|
||||
id: "action-theme",
|
||||
group: groupActions,
|
||||
icon: resolvedTheme === "dark" ? "sun" : "moon",
|
||||
label: t("shell.toggleTheme"),
|
||||
keywords: "theme dark light appearance",
|
||||
action: () => setTheme(resolvedTheme === "dark" ? "light" : "dark"),
|
||||
});
|
||||
|
||||
const needle = query.trim().toLowerCase();
|
||||
const filtered = needle
|
||||
? all.filter((item) =>
|
||||
`${item.label} ${item.keywords ?? ""} ${item.hint ?? ""}`.toLowerCase().includes(needle),
|
||||
)
|
||||
: all;
|
||||
|
||||
// Open: remember focus, fade in on the next frame, focus the input.
|
||||
// Close/unmount: hand focus back to the previous element.
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setVisible(false);
|
||||
return;
|
||||
}
|
||||
previousFocusRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
|
||||
const frame = requestAnimationFrame(() => {
|
||||
setVisible(true);
|
||||
inputRef.current?.focus();
|
||||
});
|
||||
return () => {
|
||||
cancelAnimationFrame(frame);
|
||||
const target = previousFocusRef.current;
|
||||
previousFocusRef.current = null;
|
||||
target?.focus();
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setQuery("");
|
||||
setIndex(0);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
// Keep the selected row scrolled into view.
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
listRef.current
|
||||
?.querySelector<HTMLElement>('[role="option"][aria-selected="true"]')
|
||||
?.scrollIntoView({ block: "nearest" });
|
||||
}, [index, open, needle]);
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
const selected = filtered[Math.min(index, Math.max(0, filtered.length - 1))];
|
||||
|
||||
function run(item: PaletteItem) {
|
||||
onOpenChange(false);
|
||||
if (item.href) void navigate({ href: item.href });
|
||||
else item.action?.();
|
||||
}
|
||||
|
||||
function move(delta: number) {
|
||||
if (!filtered.length) return;
|
||||
setIndex((current) => (current + delta + filtered.length) % filtered.length);
|
||||
}
|
||||
|
||||
function onKeyDown(event: React.KeyboardEvent<HTMLDivElement>) {
|
||||
switch (event.key) {
|
||||
case "Escape":
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
onOpenChange(false);
|
||||
break;
|
||||
case "ArrowDown":
|
||||
event.preventDefault();
|
||||
move(1);
|
||||
break;
|
||||
case "ArrowUp":
|
||||
event.preventDefault();
|
||||
move(-1);
|
||||
break;
|
||||
case "Home":
|
||||
event.preventDefault();
|
||||
setIndex(0);
|
||||
break;
|
||||
case "End":
|
||||
event.preventDefault();
|
||||
setIndex(Math.max(0, filtered.length - 1));
|
||||
break;
|
||||
case "Enter":
|
||||
event.preventDefault();
|
||||
if (selected) run(selected);
|
||||
break;
|
||||
case "Tab": {
|
||||
// aria-modal dialog: keep Tab inside the palette (input + rows).
|
||||
const options = Array.from(
|
||||
panelRef.current?.querySelectorAll<HTMLElement>('[role="option"]') ?? [],
|
||||
);
|
||||
const focusables = inputRef.current ? [inputRef.current, ...options] : options;
|
||||
if (!focusables.length) break;
|
||||
const first = focusables[0]!;
|
||||
const last = focusables[focusables.length - 1]!;
|
||||
if (event.shiftKey && document.activeElement === first) {
|
||||
event.preventDefault();
|
||||
last.focus();
|
||||
} else if (!event.shiftKey && document.activeElement === last) {
|
||||
event.preventDefault();
|
||||
first.focus();
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn("palette-backdrop", visible && "open")}
|
||||
onClick={(event) => {
|
||||
if (event.target === event.currentTarget) onOpenChange(false);
|
||||
}}
|
||||
>
|
||||
<div
|
||||
ref={panelRef}
|
||||
className="palette"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={t("shell.search")}
|
||||
onKeyDown={onKeyDown}
|
||||
>
|
||||
<div className="palette__input">
|
||||
<Icon name="search" />
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="text"
|
||||
role="combobox"
|
||||
aria-expanded="true"
|
||||
aria-controls="palette-list"
|
||||
aria-autocomplete="list"
|
||||
aria-label={t("shell.search")}
|
||||
placeholder={t("shell.search")}
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
value={query}
|
||||
onChange={(event) => {
|
||||
setQuery(event.target.value);
|
||||
setIndex(0);
|
||||
}}
|
||||
/>
|
||||
<span className="kbd">esc</span>
|
||||
</div>
|
||||
<div ref={listRef} className="palette__list" id="palette-list" role="listbox" aria-label={t("shell.search")}>
|
||||
{filtered.length === 0 ? (
|
||||
<div className="palette__empty">{t("shell.paletteEmpty")}</div>
|
||||
) : (
|
||||
filtered.map((item, position) => (
|
||||
<Fragment key={item.id}>
|
||||
{item.group !== filtered[position - 1]?.group ? (
|
||||
<div className="palette__group">{item.group}</div>
|
||||
) : null}
|
||||
<button
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={position === index}
|
||||
className="palette__item"
|
||||
onMouseEnter={() => setIndex(position)}
|
||||
onClick={() => run(item)}
|
||||
>
|
||||
<Icon name={item.icon} />
|
||||
<span className="grow truncate">{item.label}</span>
|
||||
{item.hint ? <span className="palette__hint truncate">{item.hint}</span> : null}
|
||||
</button>
|
||||
</Fragment>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
<div className="palette__foot">
|
||||
<span>
|
||||
<span className="kbd">↑↓</span>
|
||||
{t("shell.paletteMove")}
|
||||
</span>
|
||||
<span>
|
||||
<span className="kbd">↵</span>
|
||||
{t("shell.paletteOpen")}
|
||||
</span>
|
||||
<span>
|
||||
<span className="kbd">esc</span>
|
||||
{t("shell.paletteClose")}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { Link } from "@tanstack/react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Icon, type IconName } from "@/components/icons";
|
||||
import { SidebarItem } from "@/components/ui/sidebar-item";
|
||||
import { serverDotClass } from "@/components/ui/status-dot";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useConnectionStore } from "@/stores/connection";
|
||||
|
||||
/** `NAV` is the single source of truth for the icon strip, the page sheet and the palette. */
|
||||
export type PageName = "workspaces" | "chat" | "status" | "connect";
|
||||
export type NavKey = "workspaces" | "chat" | "status";
|
||||
|
||||
export interface NavEntry {
|
||||
key: NavKey;
|
||||
to: "/workspaces" | "/chat" | "/status";
|
||||
labelKey: string;
|
||||
icon: IconName;
|
||||
match: (pathname: string) => boolean;
|
||||
}
|
||||
|
||||
export const NAV: NavEntry[] = [
|
||||
{
|
||||
key: "workspaces",
|
||||
to: "/workspaces",
|
||||
labelKey: "nav.workspaces",
|
||||
icon: "folder",
|
||||
match: (p) => p === "/workspaces" || p.startsWith("/workspace/"),
|
||||
},
|
||||
{ key: "chat", to: "/chat", labelKey: "nav.chat", icon: "chat", match: (p) => p.startsWith("/chat") },
|
||||
{ key: "status", to: "/status", labelKey: "nav.status", icon: "status", match: (p) => p.startsWith("/status") },
|
||||
];
|
||||
|
||||
/** Resolve the current top-level page; detail routes fall back to their section. */
|
||||
export function pageName(pathname: string): PageName {
|
||||
if (pathname.startsWith("/connect")) return "connect";
|
||||
if (pathname.startsWith("/status")) return "status";
|
||||
if (pathname.startsWith("/chat")) return "chat";
|
||||
return "workspaces";
|
||||
}
|
||||
|
||||
export function navEntryFor(page: PageName): NavEntry {
|
||||
return NAV.find((entry) => entry.key === page) ?? NAV[0]!;
|
||||
}
|
||||
|
||||
export interface NavListProps {
|
||||
/** Sidebar (≥840) and rail (600–839) render the same component; CSS decides visibility. */
|
||||
variant: "sidebar" | "rail";
|
||||
page: PageName;
|
||||
}
|
||||
|
||||
/**
|
||||
* 56px compact icon strip: three 44×44 nav rows (icon only, tooltip carries the
|
||||
* label) plus the shared footer (server status → /status, pairing → /connect).
|
||||
* Both variants render the footer — the design contract explicitly requires it.
|
||||
*/
|
||||
export function NavList({ variant, page }: NavListProps) {
|
||||
const { t } = useTranslation();
|
||||
const server = useConnectionStore((state) => state.server);
|
||||
|
||||
const status = server?.status ?? "offline";
|
||||
const name = server?.name ?? "pi2.nvim";
|
||||
const version = server?.pluginVersion ?? server?.version ?? "";
|
||||
const serverTip = t("shell.railServerTip", { name, status: t(`state.${status}`), version });
|
||||
const connectTip = t("shell.connection");
|
||||
|
||||
return (
|
||||
<aside className={variant} aria-label={t("shell.navLabel")}>
|
||||
{NAV.map((entry) => (
|
||||
<SidebarItem
|
||||
key={entry.to}
|
||||
active={entry.key === page}
|
||||
compact
|
||||
tip={t(entry.labelKey)}
|
||||
asChild
|
||||
>
|
||||
<Link to={entry.to}>
|
||||
<Icon name={entry.icon} />
|
||||
</Link>
|
||||
</SidebarItem>
|
||||
))}
|
||||
<div className="sidebar__foot">
|
||||
<Link
|
||||
to="/status"
|
||||
className="rail-foot__link has-tip"
|
||||
data-tip={serverTip}
|
||||
aria-label={serverTip}
|
||||
>
|
||||
<Icon name="server" />
|
||||
<span
|
||||
className={cn("rail-foot__dot dot dot--lg", serverDotClass(status))}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</Link>
|
||||
<Link
|
||||
to="/connect"
|
||||
className="rail-foot__link has-tip"
|
||||
data-tip={connectTip}
|
||||
aria-label={connectTip}
|
||||
>
|
||||
<Icon name="plug" />
|
||||
</Link>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Icon } from "@/components/icons";
|
||||
import { navEntryFor, type PageName } from "@/components/shared/nav-list";
|
||||
import { PageSheet } from "@/components/shared/page-sheet";
|
||||
|
||||
export interface PagePillProps {
|
||||
page: PageName;
|
||||
/** Opens the command palette (the <600 search entry lives inside the sheet). */
|
||||
onSearch: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Topbar page pill, visible only <600px (CSS): current page icon + label +
|
||||
* chevron. `aria-haspopup="dialog"` + a controlled `aria-expanded`; the sheet
|
||||
* returns focus to the pill when it closes.
|
||||
*/
|
||||
export function PagePill({ page, onSearch }: PagePillProps) {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
const pillRef = useRef<HTMLButtonElement>(null);
|
||||
const entry = navEntryFor(page);
|
||||
const label = t("shell.pageSwitch", { page: t(entry.labelKey) });
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
ref={pillRef}
|
||||
type="button"
|
||||
className="page-pill"
|
||||
aria-haspopup="dialog"
|
||||
aria-expanded={open}
|
||||
aria-label={label}
|
||||
title={label}
|
||||
onClick={() => setOpen(true)}
|
||||
>
|
||||
<Icon name={entry.icon} />
|
||||
<span className="page-pill__label">{t(entry.labelKey)}</span>
|
||||
<Icon name="chevron-down" />
|
||||
</button>
|
||||
<PageSheet
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
page={page}
|
||||
onSearch={onSearch}
|
||||
returnFocusTo={pillRef}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { Link } from "@tanstack/react-router";
|
||||
import type { RefObject } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Icon } from "@/components/icons";
|
||||
import { NAV, type NavKey, type PageName } from "@/components/shared/nav-list";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useConnectionStore } from "@/stores/connection";
|
||||
import { useSessionsStore } from "@/stores/sessions";
|
||||
import { useWorkspacesStore } from "@/stores/workspaces";
|
||||
|
||||
export interface PageSheetProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
page: PageName;
|
||||
/** Closes the sheet, then opens the command palette (the <600 search entry). */
|
||||
onSearch: () => void;
|
||||
/** Element focused when the sheet closes — the page pill. */
|
||||
returnFocusTo?: RefObject<HTMLElement | null>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Page sheet (CHG-20): one dialog with two layouts — 26rem centered ≥600,
|
||||
* bottom sheet <600 (top radius 20px, starts at translateY(24px), padding-bottom
|
||||
* 20px + safe area). Five rows: three pages, a separator, search, connection.
|
||||
* The current row carries `aria-current="page"` + a check; the other page rows
|
||||
* show a live fact on the right.
|
||||
*/
|
||||
export function PageSheet({ open, onOpenChange, page, onSearch, returnFocusTo }: PageSheetProps) {
|
||||
const { t } = useTranslation();
|
||||
const workspaces = useWorkspacesStore((state) => state.items);
|
||||
const byWorkspace = useSessionsStore((state) => state.byWorkspace);
|
||||
const server = useConnectionStore((state) => state.server);
|
||||
|
||||
const sessionCount = Object.values(byWorkspace).reduce((total, list) => total + list.length, 0);
|
||||
const status = server?.status ?? "unknown";
|
||||
const version = server?.pluginVersion ?? server?.version ?? "";
|
||||
|
||||
function fact(key: NavKey): string {
|
||||
if (key === "workspaces") return t("shell.pageFactWorkspaces", { n: workspaces.length });
|
||||
if (key === "chat") return t("shell.pageFactChat", { n: sessionCount });
|
||||
return t("shell.pageFactStatus", { state: t(`state.${status}`), version });
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
title={t("shell.pages")}
|
||||
returnFocusTo={returnFocusTo}
|
||||
>
|
||||
<div className="sheet-list">
|
||||
{NAV.map((entry) => {
|
||||
const current = entry.key === page;
|
||||
return (
|
||||
<Link
|
||||
key={entry.to}
|
||||
to={entry.to}
|
||||
className={cn("sheet-row", current && "is-current")}
|
||||
aria-current={current ? "page" : undefined}
|
||||
onClick={() => onOpenChange(false)}
|
||||
>
|
||||
<Icon name={entry.icon} />
|
||||
<span className="sheet-row__label">{t(entry.labelKey)}</span>
|
||||
{current ? (
|
||||
<span className="sheet-row__check">
|
||||
<Icon name="check" />
|
||||
</span>
|
||||
) : (
|
||||
<span className="sheet-row__fact">{fact(entry.key)}</span>
|
||||
)}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
<div className="sheet-sep" />
|
||||
<button
|
||||
type="button"
|
||||
className="sheet-row sheet-row--quiet"
|
||||
onClick={() => {
|
||||
onOpenChange(false);
|
||||
onSearch();
|
||||
}}
|
||||
>
|
||||
<Icon name="search" />
|
||||
<span className="sheet-row__label">{t("shell.searchAction")}</span>
|
||||
</button>
|
||||
<Link
|
||||
to="/connect"
|
||||
className="sheet-row sheet-row--quiet"
|
||||
onClick={() => onOpenChange(false)}
|
||||
>
|
||||
<Icon name="plug" />
|
||||
<span className="sheet-row__label">{t("shell.connection")}</span>
|
||||
</Link>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
import { useTheme } from "next-themes";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Icon, type IconName } from "@/components/icons";
|
||||
import { LANGUAGES, currentLanguage, languageLabel, setLanguage, type Language } from "@/lib/i18n";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
type ThemeValue = "light" | "dark" | "system";
|
||||
|
||||
const THEMES: ThemeValue[] = ["light", "dark", "system"];
|
||||
const THEME_ICON: Record<ThemeValue, IconName> = { light: "sun", dark: "moon", system: "monitor" };
|
||||
|
||||
function isThemeValue(value: string | undefined): value is ThemeValue {
|
||||
return value === "light" || value === "dark" || value === "system";
|
||||
}
|
||||
|
||||
/**
|
||||
* Single topbar preference entry (appearance + language), per v0.1.1 CHG-04:
|
||||
* one sliders trigger, `role=menu` popover with two `role=group`s of
|
||||
* `menuitemradio` rows, `aria-checked` + check mark, roving focus
|
||||
* (ArrowDown/ArrowUp/Home/End), Escape returns focus to the trigger, and a
|
||||
* click outside closes it.
|
||||
*/
|
||||
export function PrefsMenu() {
|
||||
const { t } = useTranslation();
|
||||
const { theme, setTheme } = useTheme();
|
||||
const [mounted, setMounted] = useState(false);
|
||||
const [open, setOpen] = useState(false);
|
||||
const wrapRef = useRef<HTMLDivElement>(null);
|
||||
const triggerRef = useRef<HTMLButtonElement>(null);
|
||||
const menuRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => setMounted(true), []);
|
||||
|
||||
const themeValue: ThemeValue = mounted && isThemeValue(theme) ? theme : "system";
|
||||
const language: Language = currentLanguage();
|
||||
|
||||
/** Focus target on open: the active radio, else the first row (prototype `open()`). */
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const rows = Array.from(menuRef.current?.querySelectorAll<HTMLElement>('[role="menuitemradio"]') ?? []);
|
||||
if (!rows.length) return;
|
||||
const active = menuRef.current?.querySelector<HTMLElement>(".menu__item.is-active");
|
||||
(active ?? rows[0])?.focus();
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const onDocumentClick = (event: MouseEvent) => {
|
||||
if (wrapRef.current?.contains(event.target as Node)) return;
|
||||
setOpen(false);
|
||||
};
|
||||
document.addEventListener("click", onDocumentClick);
|
||||
return () => document.removeEventListener("click", onDocumentClick);
|
||||
}, [open]);
|
||||
|
||||
function close(focusBack: boolean) {
|
||||
setOpen(false);
|
||||
if (focusBack) triggerRef.current?.focus();
|
||||
}
|
||||
|
||||
function rows(): HTMLElement[] {
|
||||
return Array.from(menuRef.current?.querySelectorAll<HTMLElement>('[role="menuitemradio"]') ?? []);
|
||||
}
|
||||
|
||||
function onMenuKeyDown(event: React.KeyboardEvent<HTMLDivElement>) {
|
||||
const list = rows();
|
||||
if (!list.length) return;
|
||||
const index = list.indexOf(document.activeElement as HTMLElement);
|
||||
switch (event.key) {
|
||||
case "ArrowDown":
|
||||
event.preventDefault();
|
||||
list[(index + 1) % list.length]?.focus();
|
||||
break;
|
||||
case "ArrowUp":
|
||||
event.preventDefault();
|
||||
list[(index - 1 + list.length) % list.length]?.focus();
|
||||
break;
|
||||
case "Home":
|
||||
event.preventDefault();
|
||||
list[0]?.focus();
|
||||
break;
|
||||
case "End":
|
||||
event.preventDefault();
|
||||
list[list.length - 1]?.focus();
|
||||
break;
|
||||
case "Escape":
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
close(true);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
function chooseLanguage(next: Language) {
|
||||
if (next === language) {
|
||||
close(true);
|
||||
return;
|
||||
}
|
||||
void setLanguage(next);
|
||||
close(true);
|
||||
}
|
||||
|
||||
return (
|
||||
<div ref={wrapRef} className={cn("lang-menu", "prefs", open && "open")}>
|
||||
<button
|
||||
ref={triggerRef}
|
||||
type="button"
|
||||
className="icon-btn pref-trigger"
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={open}
|
||||
aria-label={t("shell.preferences")}
|
||||
title={t("shell.preferences")}
|
||||
onClick={() => setOpen((value) => !value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== "ArrowDown") return;
|
||||
event.preventDefault();
|
||||
setOpen(true);
|
||||
}}
|
||||
>
|
||||
<Icon name="sliders" />
|
||||
</button>
|
||||
{open ? (
|
||||
<div
|
||||
ref={menuRef}
|
||||
className="menu"
|
||||
role="menu"
|
||||
aria-label={t("shell.preferences")}
|
||||
onKeyDown={onMenuKeyDown}
|
||||
>
|
||||
<div className="menu__label">{t("shell.appearance")}</div>
|
||||
<div role="group" aria-label={t("shell.appearance")} data-theme-seg="">
|
||||
{THEMES.map((value) => {
|
||||
const active = themeValue === value;
|
||||
const label = t(`shell.${value}`);
|
||||
return (
|
||||
<button
|
||||
key={value}
|
||||
type="button"
|
||||
role="menuitemradio"
|
||||
aria-checked={active}
|
||||
aria-label={`${t("shell.theme")}: ${label}`}
|
||||
data-v={value}
|
||||
className={cn("menu__item", active && "is-active")}
|
||||
onClick={() => setTheme(value)}
|
||||
>
|
||||
<Icon name={THEME_ICON[value]} />
|
||||
<span className="grow">{label}</span>
|
||||
<span className="menu__check" hidden={!active}>
|
||||
<Icon name="check" />
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div className="menu__sep" />
|
||||
<div className="menu__label">{t("shell.language")}</div>
|
||||
<div role="group" aria-label={t("shell.language")} data-lang-seg="">
|
||||
{LANGUAGES.map((lang) => {
|
||||
const active = language === lang;
|
||||
return (
|
||||
<button
|
||||
key={lang}
|
||||
type="button"
|
||||
role="menuitemradio"
|
||||
aria-checked={active}
|
||||
data-lang={lang}
|
||||
className={cn("menu__item", active && "is-active")}
|
||||
onClick={() => chooseLanguage(lang)}
|
||||
>
|
||||
<Icon name="globe" />
|
||||
<span className="grow">{languageLabel(lang)}</span>
|
||||
<span className="menu__check" hidden={!active}>
|
||||
<Icon name="check" />
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user