示例工程 16-shadcn-ui-component-layer
16-shadcn-ui-component-layer/app/src/App.tsx
import { useCallback, useEffect, useState } from "react";
import { Toast } from "@base-ui-components/react/toast";
import { Button } from "./components/ui/button";
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogTitle,
DialogTrigger,
} from "./components/ui/dialog";
import { Field } from "./components/ui/field";
import { Input } from "./components/ui/input";
import { Select } from "./components/ui/select";
import { Tabs, TabsList, TabsPanel, TabsTab } from "./components/ui/tabs";
import { cn } from "./lib/utils";
type TabId = "buttons" | "dialog" | "select";
declare global {
interface Window {
appInfo: {
platform: string;
versions: { electron: string; chrome: string; node: string };
};
__setTab?: (tab: TabId) => void;
__openDialog?: () => void;
__closeDialog?: () => void;
__openSelect?: () => void;
__toast?: () => void;
__clearToasts?: () => void;
__snapshot?: () => unknown;
__smoke?: () => Promise<unknown>;
}
}
const options = [
{ value: "sans", label: "Sans-serif(系统默认)" },
{ value: "serif", label: "Serif(衬线)" },
{ value: "mono", label: "Monospace(等宽)" },
];
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
export default function App() {
const toast = Toast.useToastManager();
const [tab, setTab] = useState<TabId>("buttons");
const [dialogOpen, setDialogOpen] = useState(false);
const [selectOpen, setSelectOpen] = useState(false);
const [selectValue, setSelectValue] = useState("sans");
const [name, setName] = useState("智慧笔记本");
const addToast = useCallback(() => {
toast.add({
id: "demo-toast",
title: "设置已保存",
description: "组件层示例:通知归属当前窗口。",
timeout: 0,
});
}, [toast]);
useEffect(() => {
window.__setTab = (next) => setTab(next);
window.__openDialog = () => setDialogOpen(true);
window.__closeDialog = () => setDialogOpen(false);
window.__openSelect = () => setSelectOpen(true);
window.__toast = addToast;
window.__clearToasts = () => {
for (const item of toast.toasts) toast.close(item.id);
};
window.__snapshot = () => ({ tab, dialogOpen, selectValue });
window.__smoke = async () => {
const q = <T extends Element>(selector: string): T | null =>
document.querySelector<T>(selector);
setTab("buttons");
await sleep(60);
const primary = q<HTMLElement>('[data-testid="primary-button"]');
const merge = q<HTMLElement>('[data-testid="merge-demo"]');
const primaryBg = primary
? getComputedStyle(primary).backgroundColor
: "missing";
const mergePadding = merge
? getComputedStyle(merge).paddingLeft
: "missing";
setTab("dialog");
await sleep(80);
setDialogOpen(true);
await sleep(180);
const popup = q<HTMLElement>('[data-testid="dialog-popup"]');
const dialogOpened = Boolean(popup);
const focusInside = popup
? popup.contains(document.activeElement)
: false;
setDialogOpen(false);
await sleep(220);
const dialogClosed = !q('[data-testid="dialog-popup"]');
const trigger = q<HTMLElement>('[data-testid="dialog-trigger"]');
const focusReturned = document.activeElement === trigger;
setTab("select");
await sleep(80);
setSelectOpen(true);
await sleep(180);
const listbox = q<HTMLElement>('[role="listbox"]');
const optionCount = listbox
? listbox.querySelectorAll('[role="option"]').length
: 0;
const serif = q<HTMLElement>('[data-testid="select-item-serif"]');
if (serif) {
const rect = serif.getBoundingClientRect();
const move = {
bubbles: true,
clientX: rect.x + 8,
clientY: rect.y + 8,
};
serif.dispatchEvent(new MouseEvent("mousemove", move));
serif.dispatchEvent(new PointerEvent("pointermove", move));
await sleep(80);
serif.dispatchEvent(
new PointerEvent("pointerdown", { bubbles: true, button: 0 }),
);
serif.click();
}
await sleep(220);
const triggerText = q<HTMLElement>(
'[data-testid="select-trigger"]',
)?.textContent;
const selectValueOk = Boolean(triggerText?.includes("Serif"));
const stateValue =
q<HTMLElement>('[data-testid="select-value"]')?.textContent ?? "";
addToast();
await sleep(150);
const toastVisible = Boolean(q('[data-testid="toast"]'));
return {
primaryBg,
mergePadding,
dialogOpened,
focusInside,
dialogClosed,
focusReturned,
options: optionCount,
selectValue: selectValueOk,
triggerText: triggerText ?? "",
stateValue,
toastVisible,
};
};
}, [addToast, dialogOpen, selectValue, tab]);
return (
<div className="min-h-screen bg-surface px-8 py-7 text-text">
<header className="flex items-end justify-between gap-6 border-b border-border pb-4">
<div>
<h1 className="text-2xl font-semibold" data-testid="app-title">
组件层工作台
</h1>
<p className="mt-1 text-sm text-muted">
Base UI · cva · cn() · 组件源码入库
</p>
</div>
<span className="rounded-full border border-border px-3 py-1 text-xs text-muted">
{window.appInfo?.platform ?? "unknown"} · Electron{" "}
{window.appInfo?.versions.electron ?? "—"}
</span>
</header>
<Tabs
value={tab}
onValueChange={(value) => setTab(value as TabId)}
className="mt-5"
>
<TabsList>
<TabsTab value="buttons" data-testid="tab-buttons">
按钮与表单
</TabsTab>
<TabsTab value="dialog" data-testid="tab-dialog">
对话框
</TabsTab>
<TabsTab value="select" data-testid="tab-select">
选择与通知
</TabsTab>
</TabsList>
<TabsPanel value="buttons">
<div className="grid grid-cols-2 gap-4">
<div className="rounded-card border border-border bg-panel p-5">
<h2 className="text-sm font-semibold">Button 变体</h2>
<p className="mt-1 text-xs text-muted">
cva 管变体,cn() 管调用方覆盖。
</p>
<div className="mt-4 flex flex-wrap gap-2">
<Button data-testid="primary-button">主操作</Button>
<Button variant="secondary">次要</Button>
<Button variant="outline">描边</Button>
<Button variant="ghost">幽灵</Button>
<Button variant="destructive">危险</Button>
</div>
<div className="mt-4 flex gap-2">
<Button size="sm">小</Button>
<Button size="md">中</Button>
<Button size="icon" aria-label="添加">
+
</Button>
</div>
</div>
<div className="rounded-card border border-border bg-panel p-5">
<h2 className="text-sm font-semibold">Input 与合并</h2>
<div className="mt-3 flex flex-col gap-3">
<Field
label="工作区名称"
description="Field 把 label 与说明包在一起。"
>
<Input
data-testid="name-input"
value={name}
onChange={(event) => setName(event.target.value)}
/>
</Field>
<Button
data-testid="merge-demo"
className="w-fit px-6"
variant="secondary"
>
px-2 被 px-6 覆盖
</Button>
</div>
</div>
</div>
<div className="mt-4 rounded-card border border-border bg-surface p-4 text-xs text-muted">
组件源码在 <code>src/components/ui/</code>,每个文件头记录
provenance;升级时逐文件 diff,不跑运行时组件库。
</div>
</TabsPanel>
<TabsPanel value="dialog">
<div className="rounded-card border border-border bg-panel p-5">
<h2 className="text-sm font-semibold">Dialog 与焦点</h2>
<p className="mt-1 text-sm text-muted">
Base UI 负责焦点陷阱、Esc 与焦点归还;我们只写样式与内容。
</p>
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
<DialogTrigger
data-testid="dialog-trigger"
className="mt-4 h-9 rounded-card bg-primary px-4 text-sm font-medium text-primary-foreground"
>
打开对话框
</DialogTrigger>
<DialogContent>
<DialogTitle className="text-base font-semibold">
发布变更
</DialogTitle>
<DialogDescription className="mt-1 text-sm text-muted">
这是一个受控 Dialog;关闭后焦点应回到触发按钮。
</DialogDescription>
<div className="mt-4">
<Field label="变更说明">
<Input
data-testid="dialog-input"
autoFocus
defaultValue="更新组件层"
/>
</Field>
</div>
<div className="mt-5 flex justify-end gap-2">
<DialogClose data-testid="dialog-cancel">取消</DialogClose>
<Button
data-testid="dialog-confirm"
onClick={() => setDialogOpen(false)}
>
确认
</Button>
</div>
</DialogContent>
</Dialog>
</div>
<div className="mt-4 rounded-card border border-border bg-surface p-4 text-sm text-muted">
Electron 注意:无边框窗口的 <code>-webkit-app-region: drag</code>{" "}
会盖住弹层按钮,弹层区域要显式 <code>no-drag</code>;Esc
也要避免与退出全屏、全局快捷键冲突。
</div>
</TabsPanel>
<TabsPanel value="select">
<div className="grid grid-cols-2 gap-4">
<div className="rounded-card border border-border bg-panel p-5">
<h2 className="text-sm font-semibold">Select</h2>
<p className="mt-1 text-xs text-muted">
Base UI 用 <code>render</code> 组合,不是 Radix 的{" "}
<code>asChild</code>。
</p>
<div className="mt-4">
<Select
label="界面字体"
value={selectValue}
options={options}
open={selectOpen}
onOpenChange={setSelectOpen}
onValueChange={(value) => {
setSelectValue(value);
setSelectOpen(false);
}}
/>
</div>
<p className="mt-3 text-xs text-muted">
当前选择:<code data-testid="select-value">{selectValue}</code>
</p>
</div>
<div className="rounded-card border border-border bg-panel p-5">
<h2 className="text-sm font-semibold">Toast</h2>
<p className="mt-1 text-xs text-muted">
通知归属当前窗口,多窗口时不要广播到所有窗口。
</p>
<Button
className="mt-4"
variant="secondary"
data-testid="toast-button"
onClick={addToast}
>
显示通知
</Button>
<ul className="mt-4 list-disc pl-5 text-xs text-muted">
<li>IME 组合输入时不要触发快捷键</li>
<li>Toast 不抢焦点,但要有 aria-live</li>
<li>关闭按钮 ≥ 24px 点击区</li>
</ul>
</div>
</div>
<div
className={cn(
"mt-4 rounded-card border border-dashed border-border p-4 text-xs text-muted",
"nodrag",
)}
data-testid="drag-note"
>
无边框窗口拖拽区与弹层冲突时,给弹层加 <code>no-drag</code>;
这个示例不是无边框窗口,只展示约定。
</div>
</TabsPanel>
</Tabs>
</div>
);
}