509 lines
15 KiB
TypeScript
509 lines
15 KiB
TypeScript
"use client";
|
||
|
||
// The pixel HUD primitives, small on purpose: every page composes these.
|
||
//
|
||
// 这里是全站控件的唯一出口:按钮、输入框、下拉、多行框、tab、chip、弹窗、轻提示。
|
||
// 规格(高度/边框/圆角/字号)在 app/globals.css 的 --ctl-* token 里,只有两档
|
||
// (md / sm),所以同一行里的控件永远一样高。页面里不要再手写
|
||
// className="pixel-button" / "pixel-input" 这类类名,也不要用 window.confirm /
|
||
// window.alert —— 前者用 PixelButton / LinkButton / Input / Select / Textarea,
|
||
// 后者用 useConfirm() / useToast()。
|
||
|
||
import { Search, X } from "lucide-react";
|
||
import Link from "next/link";
|
||
import {
|
||
createContext,
|
||
useCallback,
|
||
useContext,
|
||
useEffect,
|
||
useMemo,
|
||
useRef,
|
||
useState,
|
||
type AnchorHTMLAttributes,
|
||
type ButtonHTMLAttributes,
|
||
type InputHTMLAttributes,
|
||
type ReactNode,
|
||
type SelectHTMLAttributes,
|
||
type TextareaHTMLAttributes,
|
||
} from "react";
|
||
|
||
import { copyText } from "@/lib/format";
|
||
|
||
export function Panel({
|
||
title,
|
||
icon,
|
||
actions,
|
||
children,
|
||
className = "",
|
||
bodyClass = "p-3",
|
||
}: {
|
||
title?: ReactNode;
|
||
icon?: ReactNode;
|
||
actions?: ReactNode;
|
||
children: ReactNode;
|
||
className?: string;
|
||
bodyClass?: string;
|
||
}) {
|
||
return (
|
||
<section className={"pixel-panel " + className}>
|
||
{(title || actions) && (
|
||
<header className="flex items-center gap-2 border-b-[3px] border-[var(--pixel-border)] px-3 py-2">
|
||
{icon}
|
||
{title && <h2 className="pixel-title flex-1 truncate">{title}</h2>}
|
||
{actions}
|
||
</header>
|
||
)}
|
||
<div className={bodyClass}>{children}</div>
|
||
</section>
|
||
);
|
||
}
|
||
|
||
type ButtonVariant = "default" | "primary" | "danger" | "ghost";
|
||
type ButtonSize = "md" | "sm";
|
||
|
||
type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
|
||
variant?: ButtonVariant;
|
||
size?: ButtonSize;
|
||
/** 只有图标:正方形按钮(弹窗关闭、表格行内的小动作)。 */
|
||
icon?: boolean;
|
||
};
|
||
|
||
function buttonClasses({ variant = "default", size = "md", icon = false, className = "" }: ButtonProps) {
|
||
const classes = ["pixel-button"];
|
||
if (variant !== "default") classes.push("pixel-button--" + variant);
|
||
if (size === "sm") classes.push("pixel-button--sm");
|
||
if (icon) classes.push("pixel-button--icon");
|
||
if (className) classes.push(className);
|
||
return classes.join(" ");
|
||
}
|
||
|
||
export function PixelButton({ variant, size, icon, className, ...rest }: ButtonProps) {
|
||
return <button className={buttonClasses({ variant, size, icon, className })} {...rest} />;
|
||
}
|
||
|
||
/** 长得像按钮的导航链接:跳页面的"按钮"不该另写一套样式。 */
|
||
export function LinkButton({
|
||
variant,
|
||
size,
|
||
icon,
|
||
className,
|
||
...rest
|
||
}: Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "href"> & {
|
||
href: string;
|
||
variant?: ButtonVariant;
|
||
size?: ButtonSize;
|
||
icon?: boolean;
|
||
}) {
|
||
return (
|
||
<Link
|
||
className={buttonClasses({ variant, size, icon, className } as ButtonProps)}
|
||
{...rest}
|
||
/>
|
||
);
|
||
}
|
||
|
||
export function Dot({ tone = "gray", pulse = false }: { tone?: string; pulse?: boolean }) {
|
||
return <span className={"pixel-dot pixel-dot--" + tone + (pulse ? " pixel-blink" : "")} />;
|
||
}
|
||
|
||
export function Badge({ tone = "gray", children }: { tone?: string; children: ReactNode }) {
|
||
return <span className={"pixel-badge pixel-badge--" + tone}>{children}</span>;
|
||
}
|
||
|
||
/** 单行输入:全站同一规格。 */
|
||
export function Input({ className = "", ...rest }: InputHTMLAttributes<HTMLInputElement>) {
|
||
return <input className={"pixel-input " + className} {...rest} />;
|
||
}
|
||
|
||
export function Select({ className = "", children, ...rest }: SelectHTMLAttributes<HTMLSelectElement>) {
|
||
return (
|
||
<select className={"pixel-select " + className} {...rest}>
|
||
{children}
|
||
</select>
|
||
);
|
||
}
|
||
|
||
export function Textarea({ className = "", ...rest }: TextareaHTMLAttributes<HTMLTextAreaElement>) {
|
||
return <textarea className={"pixel-textarea " + className} {...rest} />;
|
||
}
|
||
|
||
/** 带放大镜的搜索框:规格与 Input 相同,只是图标在里面。 */
|
||
export function SearchInput({ className = "", ...rest }: InputHTMLAttributes<HTMLInputElement>) {
|
||
return (
|
||
<span className={"pixel-search " + className}>
|
||
<Search size={12} />
|
||
<input className="pixel-search__input" {...rest} />
|
||
</span>
|
||
);
|
||
}
|
||
|
||
export function Field({
|
||
label,
|
||
hint,
|
||
children,
|
||
className = "",
|
||
}: {
|
||
label: string;
|
||
hint?: ReactNode;
|
||
children: ReactNode;
|
||
className?: string;
|
||
}) {
|
||
return (
|
||
<label className={"block pixel-field " + className}>
|
||
<span className="pixel-title block pb-1">{label}</span>
|
||
{children}
|
||
{hint && <span className="pixel-muted block pt-1 text-[12px]">{hint}</span>}
|
||
</label>
|
||
);
|
||
}
|
||
|
||
/** 一排 tab(单选)。多选、一次排十几个的那种用 Chip。 */
|
||
export function Tabs({
|
||
items,
|
||
value,
|
||
onChange,
|
||
}: {
|
||
items: { value: string; label: string }[];
|
||
value: string;
|
||
onChange: (value: string) => void;
|
||
}) {
|
||
return (
|
||
<div className="pixel-tabs">
|
||
{items.map((item) => (
|
||
<button
|
||
key={item.value}
|
||
className={"pixel-tab" + (item.value === value ? " pixel-tab--on" : "")}
|
||
onClick={() => onChange(item.value)}
|
||
type="button"
|
||
>
|
||
{item.label}
|
||
</button>
|
||
))}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/** 可切换的小块(多选,或用来表示"当前选中谁"):办公室点名、Agent 类型筛选。 */
|
||
export function Chip({
|
||
on = false,
|
||
children,
|
||
className = "",
|
||
...rest
|
||
}: ButtonHTMLAttributes<HTMLButtonElement> & { on?: boolean }) {
|
||
return (
|
||
<button
|
||
type="button"
|
||
aria-pressed={on}
|
||
className={"pixel-chip" + (on ? " pixel-chip--on" : "") + (className ? " " + className : "")}
|
||
{...rest}
|
||
>
|
||
{children}
|
||
</button>
|
||
);
|
||
}
|
||
|
||
type ConfirmOptions = {
|
||
title: string;
|
||
body?: ReactNode;
|
||
confirmLabel?: string;
|
||
cancelLabel?: string;
|
||
/** 危险动作(删除、吊销、断开):确认按钮变红。 */
|
||
danger?: boolean;
|
||
};
|
||
|
||
type ToastTone = "ok" | "error";
|
||
|
||
type UIContextValue = {
|
||
confirm: (options: ConfirmOptions) => Promise<boolean>;
|
||
toast: (tone: ToastTone, message: ReactNode) => void;
|
||
};
|
||
|
||
const UIContext = createContext<UIContextValue | null>(null);
|
||
|
||
/** 全站弹窗与轻提示的唯一实现:挂在 app/layout.tsx,页面只消费下面两个 hook。 */
|
||
export function UIProvider({ children }: { children: ReactNode }) {
|
||
const [pending, setPending] = useState<(ConfirmOptions & { resolve: (value: boolean) => void }) | null>(null);
|
||
const [toasts, setToasts] = useState<{ id: number; tone: ToastTone; message: ReactNode }[]>([]);
|
||
const nextId = useRef(1);
|
||
|
||
const confirm = useCallback(
|
||
(options: ConfirmOptions) =>
|
||
new Promise<boolean>((resolve) => {
|
||
setPending({ ...options, resolve });
|
||
}),
|
||
[],
|
||
);
|
||
|
||
const toast = useCallback((tone: ToastTone, message: ReactNode) => {
|
||
const id = nextId.current++;
|
||
setToasts((current) => [...current, { id, tone, message }]);
|
||
// 报错要留得久一点(用户要读接口返回),成功提示扫一眼就够了。
|
||
const ttl = tone === "error" ? 8000 : 3200;
|
||
window.setTimeout(() => setToasts((current) => current.filter((item) => item.id !== id)), ttl);
|
||
}, []);
|
||
|
||
const value = useMemo(() => ({ confirm, toast }), [confirm, toast]);
|
||
|
||
const answer = (result: boolean) => {
|
||
pending?.resolve(result);
|
||
setPending(null);
|
||
};
|
||
|
||
return (
|
||
<UIContext.Provider value={value}>
|
||
{children}
|
||
{pending && (
|
||
<Modal
|
||
size="sm"
|
||
title={pending.title}
|
||
onClose={() => answer(false)}
|
||
footer={
|
||
<>
|
||
{/* 默认焦点给"取消":危险动作不该被一次回车确认掉。 */}
|
||
<PixelButton autoFocus onClick={() => answer(false)}>
|
||
{pending.cancelLabel ?? "取消"}
|
||
</PixelButton>
|
||
<PixelButton variant={pending.danger ? "danger" : "primary"} onClick={() => answer(true)}>
|
||
{pending.confirmLabel ?? "确认"}
|
||
</PixelButton>
|
||
</>
|
||
}
|
||
>
|
||
{pending.body ? <div className="text-[13px] leading-relaxed">{pending.body}</div> : null}
|
||
</Modal>
|
||
)}
|
||
{toasts.length > 0 && (
|
||
<div className="pixel-toast-stack" role="status" aria-live="polite">
|
||
{toasts.map((item) => (
|
||
<div key={item.id} className={"pixel-toast pixel-toast--" + item.tone}>
|
||
<span className="pixel-toast__body">{item.message}</span>
|
||
<PixelButton
|
||
size="sm"
|
||
icon
|
||
variant="ghost"
|
||
aria-label="关闭提示"
|
||
title="关闭"
|
||
onClick={() => setToasts((current) => current.filter((row) => row.id !== item.id))}
|
||
>
|
||
<X size={12} />
|
||
</PixelButton>
|
||
</div>
|
||
))}
|
||
</div>
|
||
)}
|
||
</UIContext.Provider>
|
||
);
|
||
}
|
||
|
||
/**
|
||
* 统一的确认弹窗:替代 window.confirm。用法
|
||
*
|
||
* const confirm = useConfirm();
|
||
* if (!(await confirm({ title: "删除登记?", body: "…", danger: true }))) return;
|
||
*/
|
||
export function useConfirm() {
|
||
return useContext(UIContext)?.confirm ?? missingConfirm;
|
||
}
|
||
|
||
/** 统一的轻提示(右下角):替代 window.alert。 */
|
||
export function useToast() {
|
||
return useContext(UIContext)?.toast ?? missingToast;
|
||
}
|
||
|
||
/**
|
||
* 忘了挂 UIProvider 时不要静默失败,也不退回原生弹窗(那正是要消掉的东西):
|
||
* 打一条明确的 console.error,确认类操作按"用户没有同意"处理。
|
||
*/
|
||
const missingConfirm: UIContextValue["confirm"] = () => {
|
||
console.error("useConfirm: <UIProvider> 没挂上(应在 app/layout.tsx),本次操作被当作「未确认」");
|
||
return Promise.resolve(false);
|
||
};
|
||
|
||
const missingToast: UIContextValue["toast"] = () => {
|
||
console.error("useToast: <UIProvider> 没挂上(应在 app/layout.tsx),这条提示没有显示");
|
||
};
|
||
|
||
export function Modal({
|
||
title,
|
||
onClose,
|
||
children,
|
||
footer,
|
||
size = "md",
|
||
}: {
|
||
title: ReactNode;
|
||
onClose: () => void;
|
||
children: ReactNode;
|
||
footer?: ReactNode;
|
||
size?: "sm" | "md" | "lg";
|
||
}) {
|
||
useEffect(() => {
|
||
const onKey = (event: KeyboardEvent) => {
|
||
if (event.key === "Escape") onClose();
|
||
};
|
||
window.addEventListener("keydown", onKey);
|
||
return () => window.removeEventListener("keydown", onKey);
|
||
}, [onClose]);
|
||
return (
|
||
<div className="pixel-scrim" onClick={onClose} role="presentation">
|
||
<div
|
||
className={"pixel-panel pixel-dialog" + (size === "md" ? "" : " pixel-dialog--" + size)}
|
||
onClick={(event) => event.stopPropagation()}
|
||
role="dialog"
|
||
aria-modal="true"
|
||
aria-label={typeof title === "string" ? title : undefined}
|
||
>
|
||
<header className="pixel-dialog__head">
|
||
<h2 className="pixel-title flex-1 truncate">{title}</h2>
|
||
<PixelButton size="sm" icon variant="ghost" onClick={onClose} aria-label="关闭" title="关闭(Esc)">
|
||
<X size={12} />
|
||
</PixelButton>
|
||
</header>
|
||
<div className="pixel-dialog__body">{children}</div>
|
||
{footer && <footer className="pixel-dialog__foot">{footer}</footer>}
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
export function Empty({ title, hint }: { title: string; hint?: ReactNode }) {
|
||
return (
|
||
<div className="pixel-muted py-8 text-center">
|
||
<p>{title}</p>
|
||
{hint && <p className="pt-1 text-[12px]">{hint}</p>}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/** 页面与弹窗共用的错误条:一处写法,一个外观。 */
|
||
export function ErrorNote({ error }: { error?: ReactNode }) {
|
||
if (!error) return null;
|
||
return (
|
||
<div className="pixel-badge pixel-badge--red mb-3 inline-flex max-w-full px-3 py-2">
|
||
<span className="break-all">{error}</span>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
export function CopyButton({ text, label = "copy" }: { text: string; label?: string }) {
|
||
const [done, setDone] = useState(false);
|
||
return (
|
||
<PixelButton
|
||
size="sm"
|
||
variant="ghost"
|
||
type="button"
|
||
onClick={async () => {
|
||
if (await copyText(text)) {
|
||
setDone(true);
|
||
setTimeout(() => setDone(false), 1200);
|
||
}
|
||
}}
|
||
>
|
||
{done ? "copied" : label}
|
||
</PixelButton>
|
||
);
|
||
}
|
||
|
||
export function JsonBlock({ value, className = "" }: { value: unknown; className?: string }) {
|
||
return (
|
||
<pre className={"pixel-pre pixel-scroll max-h-[420px] " + className}>
|
||
{typeof value === "string" ? value : JSON.stringify(value, null, 2)}
|
||
</pre>
|
||
);
|
||
}
|
||
|
||
export function Spinner({ label = "loading" }: { label?: string }) {
|
||
return (
|
||
<p className="pixel-muted pixel-blink py-4 text-center">
|
||
{label}
|
||
<span className="pixel-cursor">_</span>
|
||
</p>
|
||
);
|
||
}
|
||
|
||
export function KV({ rows }: { rows: [string, ReactNode][] }) {
|
||
return (
|
||
<dl className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1">
|
||
{rows.map(([key, value], index) => (
|
||
<div key={key + index} className="contents">
|
||
<dt className="pixel-muted">{key}</dt>
|
||
<dd className="pixel-mono break-all">{value}</dd>
|
||
</div>
|
||
))}
|
||
</dl>
|
||
);
|
||
}
|
||
|
||
/* ---- 翻页:全站列表统一用 usePager + Pager 这一对 ---- */
|
||
|
||
/** 客户端翻页状态。列表数据先全量取回,再由 Pager 切片展示。 */
|
||
export function usePaged<T>(rows: T[], defaultSize = 20) {
|
||
const [page, setPage] = useState(1);
|
||
const [pageSize, setPageSize] = useState(defaultSize);
|
||
const pageCount = Math.max(1, Math.ceil(rows.length / pageSize));
|
||
const safePage = Math.min(Math.max(1, page), pageCount);
|
||
const offset = (safePage - 1) * pageSize;
|
||
return {
|
||
rows: rows.slice(offset, offset + pageSize),
|
||
offset,
|
||
page: safePage,
|
||
setPage,
|
||
pageCount,
|
||
total: rows.length,
|
||
pageSize,
|
||
setPageSize: (size: number) => {
|
||
setPageSize(size);
|
||
setPage(1);
|
||
},
|
||
};
|
||
}
|
||
|
||
export function Pager({
|
||
page,
|
||
pageCount,
|
||
total,
|
||
pageSize,
|
||
onPage,
|
||
onPageSize,
|
||
sizes = [10, 20, 50, 100],
|
||
}: {
|
||
page: number;
|
||
pageCount: number;
|
||
total: number;
|
||
pageSize: number;
|
||
onPage: (page: number) => void;
|
||
onPageSize: (size: number) => void;
|
||
sizes?: number[];
|
||
}) {
|
||
return (
|
||
<div className="pixel-pager">
|
||
<PixelButton size="sm" disabled={page <= 1} onClick={() => onPage(page - 1)} aria-label="上一页">
|
||
←
|
||
</PixelButton>
|
||
<span className="pixel-muted pixel-mono">
|
||
{page} / {pageCount}
|
||
</span>
|
||
<PixelButton
|
||
size="sm"
|
||
disabled={page >= pageCount}
|
||
onClick={() => onPage(page + 1)}
|
||
aria-label="下一页"
|
||
>
|
||
→
|
||
</PixelButton>
|
||
<span className="pixel-muted pixel-mono ml-auto">共 {total} 条</span>
|
||
<Select
|
||
className="w-auto"
|
||
aria-label="每页条数"
|
||
value={String(pageSize)}
|
||
onChange={(event) => onPageSize(Number(event.target.value))}
|
||
>
|
||
{sizes.map((size) => (
|
||
<option key={size} value={size}>
|
||
{size} 条/页
|
||
</option>
|
||
))}
|
||
</Select>
|
||
</div>
|
||
);
|
||
}
|