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:
yuez committed 2026-10-26 20:28:47 +08:00
1 parent a8425a51b6
commit 88e73c7737
98 files changed
+17676 -2871

No files matched your search

+50 -58
View File
@@ -1,11 +1,12 @@
import { useEffect, useRef } from "react";
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Icon, type IconName } from "@/components/icons";
import { LangMenu } from "@/components/shared/lang-menu";
import { Icon } from "@/components/icons";
import { CommandPalette } from "@/components/shared/command-palette";
import { NavList, pageName } from "@/components/shared/nav-list";
import { PagePill } from "@/components/shared/page-pill";
import { PrefsMenu } from "@/components/shared/prefs-menu";
import { ServerChip } from "@/components/shared/server-chip";
import { ThemeMenu } from "@/components/shared/theme-menu";
import { SidebarItem } from "@/components/ui/sidebar-item";
import { clearPairMeta } from "@/features/connect/pairing";
import { api, getDeviceToken, onUnauthorized } from "@/lib/api";
import { CONNECT_PATH, safeNext } from "@/lib/routing";
@@ -16,31 +17,6 @@ import { useWorkspacesStore } from "@/stores/workspaces";
import { Link, Outlet, useNavigate, useRouterState } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
interface NavItem {
to: "/workspaces" | "/chat" | "/status";
labelKey: string;
icon: IconName;
match: (pathname: string) => boolean;
}
const NAV: NavItem[] = [
{
to: "/workspaces",
labelKey: "nav.workspaces",
icon: "folder",
match: (p) => p === "/workspaces" || p.startsWith("/workspace/"),
},
{ to: "/chat", labelKey: "nav.chat", icon: "chat", match: (p) => p.startsWith("/chat") },
{ to: "/status", labelKey: "nav.status", icon: "status", match: (p) => p.startsWith("/status") },
];
function pageName(pathname: string): string {
if (pathname.startsWith("/connect")) return "connect";
if (pathname.startsWith("/status")) return "status";
if (pathname.startsWith("/chat")) return "chat";
return "workspaces";
}
function RouteTitle({ pathname }: { pathname: string }) {
const { t } = useTranslation();
const server = useConnectionStore((state) => state.server);
@@ -91,19 +67,28 @@ function RouteTitle({ pathname }: { pathname: string }) {
);
}
function NavLinks({ pathname }: { pathname: string }) {
/** Topbar palette entry: icon + label (≤1099 label hidden) + platform kbd hint. */
function PaletteTrigger({ onOpen }: { onOpen: () => void }) {
const { t } = useTranslation();
const [kbd, setKbd] = useState("Ctrl K");
useEffect(() => {
const platform = typeof navigator === "undefined" ? "" : navigator.platform || "";
setKbd(/Mac|iPhone|iPad/.test(platform) ? "⌘K" : "Ctrl K");
}, []);
return (
<>
{NAV.map((item) => (
<SidebarItem key={item.to} active={item.match(pathname)} asChild>
<Link to={item.to}>
<Icon name={item.icon} />
<span>{t(item.labelKey)}</span>
</Link>
</SidebarItem>
))}
</>
<button
type="button"
className="btn btn--ghost btn--sm palette-trigger"
aria-label={t("shell.searchHint")}
title={t("shell.searchHint")}
onClick={onOpen}
>
<Icon name="search" />
<span className="palette-trigger__label">{t("shell.searchAction")}</span>
<span className="kbd palette-trigger__kbd">{kbd}</span>
</button>
);
}
@@ -122,6 +107,7 @@ export function AppShell() {
const ownsSocket = !pathname.startsWith("/chat");
const page = pageName(pathname);
const redirectingRef = useRef(false);
const [paletteOpen, setPaletteOpen] = useState(false);
const info = useQuery({
queryKey: ["info"],
@@ -191,28 +177,42 @@ export function AppShell() {
};
}, [disconnect, href, isConnect, navigate, ownsSocket, paired, setWsState]);
/** ⌘K / Ctrl-K opens the palette on every navigation page (never on /connect). */
useEffect(() => {
if (!paired || isConnect) return;
const onKeyDown = (event: KeyboardEvent) => {
if (!(event.metaKey || event.ctrlKey) || event.key.toLowerCase() !== "k") return;
if (event.defaultPrevented) return;
event.preventDefault();
setPaletteOpen(true);
};
document.addEventListener("keydown", onKeyDown);
return () => document.removeEventListener("keydown", onKeyDown);
}, [paired, isConnect]);
const connectionLost = paired && !isConnect && (wsState === "reconnecting" || wsState === "closed");
return (
<div className="shell bg-background text-foreground" data-ws-state={wsState} data-paired={paired ? "true" : "false"}>
<header className="topbar">
<Link to="/workspaces" className="brand">
<Link to="/workspaces" className="brand" aria-label="pi2.nvim">
<img
className="brand__logo"
src="/pi2-nvim.png"
alt=""
width={24}
height={24}
width={22}
height={22}
decoding="async"
/>
<span className="brand__text">pi2.nvim</span>
</Link>
{isConnect ? null : <PagePill page={page} onSearch={() => setPaletteOpen(true)} />}
<RouteTitle pathname={pathname} />
<div className="spacer" />
<div className="actions">
{isConnect ? null : <PaletteTrigger onOpen={() => setPaletteOpen(true)} />}
{isConnect ? null : <ServerChip />}
<LangMenu />
<ThemeMenu />
<PrefsMenu />
</div>
</header>
@@ -231,15 +231,11 @@ export function AppShell() {
) : null}
<div className="body">
{/* <600 has no persistent navigation strip: the page pill owns navigation. */}
{isConnect ? null : (
<>
<aside className="sidebar">
<div className="nav-label">{t("shell.navLabel")}</div>
<NavLinks pathname={pathname} />
</aside>
<aside className="rail">
<NavLinks pathname={pathname} />
</aside>
<NavList variant="sidebar" page={page} />
<NavList variant="rail" page={page} />
</>
)}
<main className="main">
@@ -247,11 +243,7 @@ export function AppShell() {
</main>
</div>
{isConnect ? null : (
<nav className="tabbar">
<NavLinks pathname={pathname} />
</nav>
)}
{isConnect ? null : <CommandPalette open={paletteOpen} onOpenChange={setPaletteOpen} />}
</div>
);
}
+3
View File
@@ -34,6 +34,7 @@ import {
Send,
Server,
Settings,
SlidersHorizontal,
Smartphone,
Square,
Sun,
@@ -83,6 +84,7 @@ export type IconName =
| "trash"
| "more"
| "settings"
| "sliders"
| "sun"
| "moon"
| "monitor"
@@ -132,6 +134,7 @@ const ICONS: Record<IconName, IconComponent> = {
trash: Trash2,
more: MoreHorizontal,
settings: Settings,
sliders: SlidersHorizontal,
sun: Sun,
moon: Moon,
monitor: Monitor,
@@ -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>
);
}
+106
View File
@@ -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>
);
}
+51
View File
@@ -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}
/>
</>
);
}
+99
View File
@@ -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>
);
}
+187
View File
@@ -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>
);
}
+77 -16
View File
@@ -9,6 +9,13 @@ export const Dialog = DialogPrimitive.Root;
export const DialogTrigger = DialogPrimitive.Trigger;
export const DialogClose = DialogPrimitive.Close;
/**
* Open-dialog stack. Every mounted modal pushes its id and the capture-phase
* Escape listener only acts on the topmost entry, so a stacked dialog (or the
* command palette above it) closes exactly one layer per Escape.
*/
const modalStack: string[] = [];
export interface ModalProps {
open: boolean;
onOpenChange: (open: boolean) => void;
@@ -20,9 +27,16 @@ export interface ModalProps {
size?: "default" | "wide";
className?: string;
contentClassName?: string;
/** Element that receives focus when the dialog closes (the trigger). */
returnFocusTo?: React.RefObject<HTMLElement | null>;
}
/** Radix dialog styled as the base.css `.modal-backdrop > .modal` (bottom sheet <600px). */
/**
* Radix dialog styled as `base.css .modal-backdrop > .modal`:
* `aria-labelledby`, initial focus on the title-bar close button, a Tab trap
* (Radix FocusScope), capture-phase Escape for the topmost layer only, and
* focus returned to the trigger. <600px it becomes a bottom sheet.
*/
export function Modal({
open,
onOpenChange,
@@ -33,8 +47,38 @@ export function Modal({
size = "default",
className,
contentClassName,
returnFocusTo,
}: ModalProps) {
const { t } = useTranslation();
const contentRef = React.useRef<HTMLDivElement>(null);
const closeRef = React.useRef<HTMLButtonElement>(null);
const titleId = React.useId();
const onOpenChangeRef = React.useRef(onOpenChange);
onOpenChangeRef.current = onOpenChange;
React.useEffect(() => {
if (!open) return;
const entry = titleId;
modalStack.push(entry);
const onKeyDownCapture = (event: KeyboardEvent) => {
if (event.key !== "Escape") return;
if (modalStack[modalStack.length - 1] !== entry) return;
const content = contentRef.current;
const active = document.activeElement;
// Another overlay owns the focus (command palette): leave Escape to it.
if (content && active && !content.contains(active) && active !== document.body) return;
event.preventDefault();
event.stopPropagation();
onOpenChangeRef.current(false);
};
document.addEventListener("keydown", onKeyDownCapture, true);
return () => {
document.removeEventListener("keydown", onKeyDownCapture, true);
const index = modalStack.lastIndexOf(entry);
if (index !== -1) modalStack.splice(index, 1);
};
}, [open, titleId]);
return (
<DialogPrimitive.Root open={open} onOpenChange={onOpenChange}>
<DialogPrimitive.Portal>
@@ -47,23 +91,40 @@ export function Modal({
*/}
<DialogPrimitive.Overlay className={cn("modal-backdrop", className)}>
<DialogPrimitive.Content
ref={contentRef}
aria-labelledby={titleId}
className={cn("modal", "modal-content", size === "wide" && "modal--wide", contentClassName)}
onOpenAutoFocus={(event) => {
// Prototype parity: first focusable is the title-bar close button.
event.preventDefault();
closeRef.current?.focus();
}}
onCloseAutoFocus={(event) => {
if (!returnFocusTo?.current) return;
event.preventDefault();
returnFocusTo.current.focus();
}}
>
<DialogPrimitive.Title asChild>
<h3>
<span>{title}</span>
<DialogPrimitive.Close asChild>
<button type="button" className="btn btn--ghost btn--sm" aria-label={t("common.close")}>
<X size={16} aria-hidden="true" />
</button>
</DialogPrimitive.Close>
</h3>
</DialogPrimitive.Title>
{description ? (
<DialogPrimitive.Description className="muted">{description}</DialogPrimitive.Description>
) : null}
{children}
{footer ? <div className="modal-actions">{footer}</div> : null}
<DialogPrimitive.Title asChild>
<h3 id={titleId}>
<span>{title}</span>
<DialogPrimitive.Close asChild>
<button
ref={closeRef}
type="button"
className="icon-btn"
aria-label={t("common.close")}
>
<X size={16} aria-hidden="true" />
</button>
</DialogPrimitive.Close>
</h3>
</DialogPrimitive.Title>
{description ? (
<DialogPrimitive.Description className="muted">{description}</DialogPrimitive.Description>
) : null}
{children}
{footer ? <div className="modal-actions">{footer}</div> : null}
</DialogPrimitive.Content>
</DialogPrimitive.Overlay>
</DialogPrimitive.Portal>
+27 -3
View File
@@ -5,14 +5,38 @@ import { cn } from "@/lib/utils";
export interface SidebarItemProps extends React.HTMLAttributes<HTMLElement> {
active?: boolean;
/**
* Icon-only compact row (sidebar / rail): 44×44 hit area, 20px icon, and a
* pure-CSS `.has-tip[data-tip]` tooltip instead of a text label.
*/
compact?: boolean;
/** Tooltip text; also becomes the accessible name in compact mode. */
tip?: string;
asChild?: boolean;
}
/** Sidebar / rail / tabbar navigation row; compose the link or button as a child. */
export function SidebarItem({ active, asChild = false, className, children, ...props }: SidebarItemProps) {
/**
* Sidebar / rail navigation row. Compose the link or button as a child
* (`asChild`) so router links keep their own props and prefetching.
*/
export function SidebarItem({
active = false,
compact = false,
tip,
asChild = false,
className,
children,
...props
}: SidebarItemProps) {
const Comp = asChild ? Slot : "a";
return (
<Comp className={cn("nav-item", active && "active", className)} aria-current={active ? "page" : undefined} {...props}>
<Comp
className={cn("nav-item", compact && "has-tip", active && "active", className)}
aria-current={active ? "page" : undefined}
aria-label={compact ? tip : undefined}
data-tip={compact ? tip : undefined}
{...props}
>
{children}
</Comp>
);