ui.tsx 11.4 KB
import {
  AlertTriangle, Check, CheckCircle2, ChevronRight, Copy, Info, Loader2, X, XCircle,
} from "lucide-react";
import { useEffect, useRef, useState, type ReactNode } from "react";
import { cn } from "@/lib/utils";
import { useAppStore } from "@/store/useAppStore";

export function Card({ className, children, ...rest }: React.HTMLAttributes<HTMLDivElement>) {
  return <div className={cn("card", className)} {...rest}>{children}</div>;
}

export function CardHeader({ title, desc, right, className }: {
  title: ReactNode; desc?: ReactNode; right?: ReactNode; className?: string;
}) {
  return (
    <div className={cn("flex items-start justify-between gap-3 px-4 py-3 border-b border-line", className)}>
      <div className="min-w-0">
        <h3 className="text-[14px] font-semibold leading-tight truncate">{title}</h3>
        {desc && <p className="text-xs text-muted mt-0.5">{desc}</p>}
      </div>
      {right && <div className="flex items-center gap-1.5 shrink-0">{right}</div>}
    </div>
  );
}

export function Badge({ tone = "bg-ink/5 text-muted", children, className }: {
  tone?: string; children: ReactNode; className?: string;
}) {
  return (
    <span className={cn("inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-medium",
      tone, className)}>{children}</span>
  );
}

export function Pill({ color, children, onClick, title }: {
  color?: string; children: ReactNode; onClick?: () => void; title?: string;
}) {
  return (
    <span
      title={title}
      onClick={onClick}
      className={cn("inline-flex items-center gap-1.5 rounded-md px-2 py-0.5 text-[12px] font-medium",
        onClick && "cursor-pointer hover:opacity-80")}
      style={color
        ? { background: `${color}1f`, color, boxShadow: `inset 0 0 0 1px ${color}33` }
        : undefined}
    >
      {color && <i className="h-1.5 w-1.5 rounded-full" style={{ background: color }} />}
      {children}
    </span>
  );
}

export function Spinner({ className }: { className?: string }) {
  return <Loader2 className={cn("h-4 w-4 animate-spin", className)} />;
}

export function Progress({ value, className }: { value: number; className?: string }) {
  return (
    <div className={cn("h-1.5 w-full overflow-hidden rounded-full bg-ink/8", className)}>
      <div
        className="h-full rounded-full transition-[width] duration-500 ease-out"
        style={{ width: `${Math.min(100, Math.max(0, value))}%`,
                 background: "linear-gradient(90deg, rgb(var(--brand)), rgb(var(--brand2)))" }}
      />
    </div>
  );
}

export function Empty({ icon, title, desc, action }: {
  icon?: ReactNode; title: string; desc?: string; action?: ReactNode;
}) {
  return (
    <div className="flex flex-col items-center justify-center gap-2 px-6 py-12 text-center">
      {icon && <div className="mb-1 text-muted/50">{icon}</div>}
      <p className="text-[14px] font-medium">{title}</p>
      {desc && <p className="max-w-sm text-xs text-muted leading-relaxed">{desc}</p>}
      {action && <div className="mt-3">{action}</div>}
    </div>
  );
}

export function Skeleton({ className }: { className?: string }) {
  return <div className={cn("skeleton", className)} />;
}

export function ErrorNote({ children, onRetry }: { children: ReactNode; onRetry?: () => void }) {
  return (
    <div className="flex items-start gap-2 rounded-lg border border-bad/30 bg-bad/5 px-3 py-2 text-[13px]">
      <XCircle className="mt-0.5 h-4 w-4 shrink-0 text-bad" />
      <div className="min-w-0 flex-1 break-words">{children}</div>
      {onRetry && <button className="btn btn-sm shrink-0" onClick={onRetry}>重试</button>}
    </div>
  );
}

/**
 * 弹窗。**内容区自带内边距,动作按钮走 `footer`**。
 *
 * 以前 body 是裸的 overflow-auto,每个表单自己补 padding —— 结果就是漏补的那几个
 * 输入框直接贴着弹窗边框,保存按钮浮在滚动区里,长表单一滚就找不着。
 * 边距和底栏在这里统一兜住,调用方不用再想这件事。
 */
export function Modal({ open, onClose, title, desc, children, footer, width = "max-w-lg", bodyClass }: {
  open: boolean; onClose: () => void; title: ReactNode; desc?: ReactNode;
  children: ReactNode; footer?: ReactNode; width?: string; bodyClass?: string;
}) {
  const ref = useRef<HTMLDivElement>(null);
  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4"
         onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="absolute inset-0 bg-black/40 backdrop-blur-[2px]" />
      <div ref={ref}
           className={cn("card relative z-10 flex max-h-[88vh] w-full animate-fade-up flex-col overflow-hidden",
             width)}>
        <CardHeader className="shrink-0" title={title} desc={desc} right={
          <button className="btn btn-ghost btn-sm" onClick={onClose} aria-label="关闭">
            <X className="h-4 w-4" />
          </button>} />
        <div className={cn("min-h-0 flex-1 overflow-auto px-4 py-4", bodyClass)}>{children}</div>
        {footer && (
          <div className="flex shrink-0 flex-wrap items-center justify-end gap-2 border-t border-line
                          bg-elevated px-4 py-3">
            {footer}
          </div>
        )}
      </div>
    </div>
  );
}

export function Confirm({ open, title, body, danger, confirmText = "确定", onConfirm, onClose }: {
  open: boolean; title: string; body: ReactNode; danger?: boolean;
  confirmText?: string; onConfirm: () => void; onClose: () => void;
}) {
  return (
    <Modal open={open} onClose={onClose} title={title} width="max-w-md"
           footer={
             <>
               <button className="btn" onClick={onClose}>取消</button>
               <button className={cn("btn", danger ? "btn-danger" : "btn-primary")}
                       onClick={() => { onConfirm(); onClose(); }}>{confirmText}</button>
             </>
           }>
      <div className="text-[13px] leading-relaxed">{body}</div>
    </Modal>
  );
}

/**
 * 折叠区。问答页一屏的信息量太大 —— SQL、轨迹、解释全摊开是一片噪声,
 * 全藏起来又变回黑盒。所以折叠条本身要带足够摘要:不展开也知道里面是什么、
 * 值不值得展开。
 */
export function Collapse({ open, onToggle, icon, title, summary, right, tone, children }: {
  open: boolean; onToggle: () => void; icon?: ReactNode; title: ReactNode;
  summary?: ReactNode; right?: ReactNode; tone?: string; children: ReactNode;
}) {
  return (
    <div className={cn("overflow-hidden rounded-lg border border-line", tone)}>
      <div className="flex items-center gap-2 px-2.5 py-1.5">
        <button className="flex min-w-0 flex-1 items-center gap-2 text-left" onClick={onToggle}>
          <ChevronRight className={cn("h-3.5 w-3.5 shrink-0 text-muted transition-transform",
            open && "rotate-90")} />
          {icon && <span className="shrink-0 text-muted">{icon}</span>}
          <span className="shrink-0 text-[12px] font-medium">{title}</span>
          {summary && (
            <span className="min-w-0 flex-1 truncate text-[11.5px] text-muted">{summary}</span>
          )}
        </button>
        {right && <div className="flex shrink-0 items-center gap-1">{right}</div>}
      </div>
      {open && <div className="border-t border-line p-2.5">{children}</div>}
    </div>
  );
}

/** 分段切换。比一排按钮更像「同一组里选一个」,也省掉选中态靠主色按钮硬撑。 */
export function Segmented<T extends string>({ value, options, onChange, className }: {
  value: T; options: { key: T; label: ReactNode; badge?: ReactNode }[];
  onChange: (v: T) => void; className?: string;
}) {
  return (
    <div className={cn("inline-flex items-center gap-0.5 rounded-lg border border-line bg-elevated p-0.5",
      className)}>
      {options.map((o) => (
        <button key={o.key} onClick={() => onChange(o.key)}
                className={cn("inline-flex items-center gap-1.5 whitespace-nowrap rounded-[6px] px-2.5 py-1",
                  "text-[12.5px] font-medium transition-colors",
                  value === o.key ? "bg-surface text-ink shadow-sm" : "text-muted hover:text-ink")}>
          {o.label}
          {o.badge}
        </button>
      ))}
    </div>
  );
}

/** 表单字段。label / 说明 / 控件的间距定死在一处,免得每个表单各写一套。 */
export function Field({ label, hint, required, children, className }: {
  label: ReactNode; hint?: ReactNode; required?: boolean;
  children: ReactNode; className?: string;
}) {
  return (
    <div className={cn("min-w-0", className)}>
      <label className="label">
        {label}
        {required && <span className="ml-0.5 text-bad">*</span>}
      </label>
      {children}
      {hint && <p className="mt-1 text-[11.5px] leading-relaxed text-muted">{hint}</p>}
    </div>
  );
}

/** 复制按钮。到处都要,统一带个「已复制」反馈。 */
export function CopyButton({ text, label = "复制", className }: {
  text: string; label?: string; className?: string;
}) {
  const [done, setDone] = useState(false);
  return (
    <button className={cn("btn btn-ghost btn-sm", className)} title={label}
            onClick={async () => {
              try {
                await navigator.clipboard.writeText(text);
                setDone(true);
                window.setTimeout(() => setDone(false), 1400);
              } catch { /* 没有剪贴板权限就静默失败,不值得为它弹个错 */ }
            }}>
      {done ? <Check className="h-3.5 w-3.5 text-ok" /> : <Copy className="h-3.5 w-3.5" />}
      {label && <span>{done ? "已复制" : label}</span>}
    </button>
  );
}

const TOAST_ICON = {
  info: <Info className="h-4 w-4 text-brand2" />,
  ok: <CheckCircle2 className="h-4 w-4 text-ok" />,
  warn: <AlertTriangle className="h-4 w-4 text-warn" />,
  error: <XCircle className="h-4 w-4 text-bad" />,
};

export function Toaster() {
  const { toasts, dismiss } = useAppStore();
  return (
    <div className="pointer-events-none fixed bottom-4 right-4 z-[60] flex w-[min(92vw,26rem)] flex-col gap-2">
      {toasts.map((t) => (
        <div key={t.id}
             className="card pointer-events-auto flex animate-fade-up items-start gap-2.5 p-3">
          <span className="mt-0.5 shrink-0">{TOAST_ICON[t.kind]}</span>
          <div className="min-w-0 flex-1">
            <p className="text-[13px] font-medium leading-snug break-words">{t.text}</p>
            {t.detail && <p className="mt-0.5 text-xs text-muted break-words">{t.detail}</p>}
          </div>
          <button className="btn btn-ghost btn-sm shrink-0 -mr-1 -mt-1"
                  onClick={() => dismiss(t.id)} aria-label="关闭提示">
            <X className="h-3.5 w-3.5" />
          </button>
        </div>
      ))}
    </div>
  );
}

/** 小尺寸横向统计块,概览与工具条复用 */
export function Stat({ label, value, hint, tone }: {
  label: string; value: ReactNode; hint?: string; tone?: string;
}) {
  return (
    <div className="min-w-0">
      <p className="text-[11px] uppercase tracking-wide text-muted">{label}</p>
      <p className={cn("mt-0.5 text-[20px] font-semibold leading-tight tabular-nums", tone)}>{value}</p>
      {hint && <p className="mt-0.5 text-[11px] text-muted truncate">{hint}</p>}
    </div>
  );
}