kit.tsx 23.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
/**
 * 页面通用的拼装件:表单分区、页签、值的显示、对象链接、变更表、来龙去脉、翻页。
 * 基础件(按钮、卡片、弹窗、徽标)在 ui.tsx。
 */
import { ArrowRight, ChevronDown, ChevronLeft, ChevronRight, Search, X } from "lucide-react";
import { Children, Fragment, isValidElement, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { asBool, fmtAgo, fmtDateTime, fmtValue, toneOf, type FieldMeta } from "@/lib/format";
import { go } from "@/lib/nav";
import { onto } from "@/lib/onto";
import { cn } from "@/lib/utils";
import { Badge, Spinner, type BadgeVariant } from "./ui";

/** 表单的一个分区:标题 + 可选的一句说明 + 内容。分区之间靠留白和分隔线拉开。 */
export function FormSection({ title, desc, right, children, className, id }: {
  title: ReactNode; desc?: ReactNode; right?: ReactNode; children: ReactNode; className?: string; id?: string;
}) {
  return (
    <section id={id} className={cn("border-t border-line pt-6 first:border-t-0 first:pt-0", className)}>
      <div className="mb-4 flex items-start gap-3">
        <div className="min-w-0 flex-1">
          <h3 className="text-title font-semibold leading-snug">{title}</h3>
          {desc && <p className="hint">{desc}</p>}
        </div>
        {right && <div className="flex shrink-0 items-center gap-2">{right}</div>}
      </div>
      <div className="space-y-4">{children}</div>
    </section>
  );
}

/** 页签(下划线式),用在详情页和编辑器的顶部。 */
export function Tabs<T extends string>({ value, onChange, options, className }: {
  value: T; onChange: (v: T) => void; options: { key: T; label: ReactNode; count?: number | null }[]; className?: string;
}) {
  return (
    <div className={cn("flex items-center gap-1 border-b border-line", className)}>
      {options.map((o) => (
        <button key={o.key} onClick={() => onChange(o.key)}
                className={cn("-mb-px inline-flex items-center gap-1.5 border-b-2 px-3 py-2 text-body transition-colors",
                  value === o.key ? "border-brand font-medium text-ink" : "border-transparent text-muted hover:text-ink")}>
          {o.label}
          {o.count ? <span className="rounded-full bg-ink/[0.06] px-1.5 text-caption tabular-nums text-muted">{o.count}</span> : null}
        </button>
      ))}
    </div>
  );
}

const TONE_VARIANT: Record<string, BadgeVariant> = { ok: "ok", warn: "warn", danger: "danger", info: "info", neutral: "neutral" };

/** 一个带颜色的状态标签。 */
export function Tone({ tone, children }: { tone: string; children: ReactNode }) {
  return <Badge variant={TONE_VARIANT[tone] || "neutral"}>{children}</Badge>;
}

/** 指向一个对象的链接:显示名称,点了去对象详情。 */
export function ObjLink({ typeId, objKey, label, className }: { typeId: string; objKey: string; label?: string; className?: string }) {
  return (
    <button className={cn("max-w-full truncate text-left text-brand hover:underline", className)} title={label && label !== objKey ? `${label}(${objKey})` : objKey}
            onClick={(e) => { e.stopPropagation(); go("objects", { type: typeId, key: objKey }); }}>
      {label || objKey}
    </button>
  );
}

/** 按字段定义显示一个值:状态带颜色、指向对象的可以点、数字 / 日期按统一格式。 */
export function Value({ v, field, refInfo }: {
  v: unknown; field?: Partial<FieldMeta> | null; refInfo?: { type_id: string; key: string; label: string } | null;
}) {
  if (refInfo) return <ObjLink typeId={refInfo.type_id} objKey={refInfo.key} label={refInfo.label} />;
  if (v === null || v === undefined || v === "") return <span className="text-muted/60">—</span>;
  if (field?.format === "status") {
    const b = field.data_type === "boolean" ? asBool(v) : null;
    if (b === false) return <span className="text-muted/70">否</span>;
    return <Tone tone={toneOf(v, field)}>{b === true ? "是" : String(v)}</Tone>;
  }
  return <>{fmtValue(v, field)}</>;
}

export const isNumeric = (f?: Partial<FieldMeta> | null) =>
  !!f && !f.ref && f.format !== "status" && (["money", "quantity", "percent"].includes(f.format || "") || ["number", "integer"].includes(f.data_type || ""));

/** 「名称:值」的描述列表,用在详情页。 */
export function Desc({ items, cols = 3 }: { items: { label: ReactNode; value: ReactNode; wide?: boolean }[]; cols?: 2 | 3 | 4 }) {
  return (
    <dl className={cn("grid gap-x-6 gap-y-4", cols === 2 ? "sm:grid-cols-2" : cols === 4 ? "sm:grid-cols-2 lg:grid-cols-4" : "sm:grid-cols-2 lg:grid-cols-3")}>
      {items.map((it, i) => (
        <div key={i} className={cn("min-w-0", it.wide && "sm:col-span-full")}>
          <dt className="text-caption text-muted">{it.label}</dt>
          <dd className="mt-0.5 break-words text-body">{it.value}</dd>
        </div>
      ))}
    </dl>
  );
}

export interface Change {
  kind?: string; object_type?: string; type_id?: string; key?: string; object?: string;
  property: string; from: unknown; to: unknown; format?: string; unit?: string;
}

/** 一批变更:按对象分组,逐行「属性:旧值 → 新值」;新建的只列新值。 */
export function ChangeTable({ changes }: { changes: Change[] }) {
  const groups = useMemo(() => {
    const m: { title: string; create: boolean; typeId?: string; objKey?: string; rows: Change[] }[] = [];
    for (const c of changes) {
      const create = c.kind === "create" || (c.from === null && !c.key);
      const title = create ? `新建${c.object_type || ""}` : `${c.object_type || ""}「${c.object || c.key || ""}」`;
      const last = m[m.length - 1];
      if (last && last.title === title) last.rows.push(c);
      else m.push({ title, create, typeId: c.type_id, objKey: c.key, rows: [c] });
    }
    return m;
  }, [changes]);
  if (!changes.length) return null;
  return (
    <div className="space-y-3">
      {groups.map((g, i) => (
        <div key={i} className="overflow-hidden rounded-lg border border-line">
          <div className="flex items-center gap-2 border-b border-line bg-ink/[0.025] px-3 py-2 text-label font-medium">
            {g.create ? <Badge variant="info">新建</Badge> : <Badge variant="warn">修改</Badge>}
            {!g.create && g.typeId && g.objKey
              ? <button className="truncate hover:text-brand hover:underline" onClick={() => go("objects", { type: g.typeId, key: g.objKey })}>{g.title}</button>
              : <span className="truncate">{g.title}</span>}
          </div>
          <table className="w-full text-body">
            <tbody>
              {g.rows.map((c, j) => (
                <tr key={j} className="border-b border-line/50 last:border-b-0">
                  <td className="w-36 whitespace-nowrap px-3 py-1.5 text-label text-muted">{c.property}</td>
                  <td className="px-3 py-1.5">
                    {g.create ? <span>{fmtValue(c.to, c)}</span> : (
                      <span className="inline-flex flex-wrap items-center gap-1.5">
                        <span className="text-muted line-through decoration-muted/40">{fmtValue(c.from, c)}</span>
                        <ArrowRight className="h-3.5 w-3.5 text-muted" />
                        <span className="font-medium">{fmtValue(c.to, c)}</span>
                      </span>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ))}
    </div>
  );
}

export interface TraceNode { kind: string; kind_label: string; id: string; title: string; status: string; link: string; at: string; note: string }

const STATUS_CN: Record<string, [string, BadgeVariant]> = {
  pending_approval: ["待审批", "warn"], executing: ["执行中", "info"], done: ["已完成", "ok"], failed: ["失败", "danger"],
  rejected: ["已驳回", "danger"], cancelled: ["已撤回", "neutral"], reverted: ["已撤销", "neutral"],
  running: ["运行中", "info"], waiting: ["等人处理", "warn"], open: ["待办", "warn"],
};

export function TraceItem({ n }: { n: TraceNode }) {
  const st = STATUS_CN[n.status];
  const body = (
    <>
      <span className="shrink-0 rounded bg-ink/[0.06] px-1.5 py-0.5 text-caption text-muted">{n.kind_label}</span>
      <span className="min-w-0 truncate">{n.title}{n.note && <span className="ml-1 text-muted">· {n.note}</span>}</span>
      {st ? <Badge variant={st[1]}>{st[0]}</Badge> : n.status ? <span className="shrink-0 text-caption text-muted">{n.status}</span> : null}
    </>
  );
  return n.link
    ? <a href={n.link} className="flex items-center gap-2 rounded-md border border-line px-2.5 py-1.5 text-label hover:border-brand/50 hover:bg-brand/[0.03]">{body}</a>
    : <div className="flex items-center gap-2 rounded-md border border-line px-2.5 py-1.5 text-label">{body}</div>;
}

/** 来龙去脉:这条记录从哪来、又引出了什么。两边都空就什么也不显示。 */
export function TraceChain({ kind, id, refreshKey }: { kind: "action_run" | "sop_run" | "task"; id: string; refreshKey?: unknown }) {
  const [t, setT] = useState<{ up: TraceNode[]; down: TraceNode[] } | null>(null);
  useEffect(() => {
    let alive = true;
    setT(null);
    void onto.trace(kind, id).then((r) => { if (alive) setT(r); }).catch(() => { if (alive) setT({ up: [], down: [] }); });
    return () => { alive = false; };
  }, [kind, id, refreshKey]);
  if (!t || (!t.up.length && !t.down.length)) return null;
  return (
    <div className="grid gap-4 sm:grid-cols-2">
      <div>
        <p className="mb-1.5 text-caption text-muted">从哪来</p>
        <div className="space-y-1.5">{t.up.length ? t.up.map((n) => <TraceItem key={n.kind + n.id} n={n} />) : <p className="text-label text-muted/70">人工直接发起</p>}</div>
      </div>
      <div>
        <p className="mb-1.5 text-caption text-muted">引出了什么</p>
        <div className="space-y-1.5">{t.down.length ? t.down.map((n) => <TraceItem key={n.kind + n.id} n={n} />) : <p className="text-label text-muted/70">还没有</p>}</div>
      </div>
    </div>
  );
}

/** 翻页条。 */
export function Pager({ total, limit, offset, onChange, unit = "条" }: {
  total: number; limit: number; offset: number; onChange: (offset: number) => void; unit?: string;
}) {
  const page = Math.floor(offset / limit) + 1;
  const pages = Math.max(1, Math.ceil(total / limit));
  return (
    <div className="flex items-center justify-between gap-3 border-t border-line px-3 py-2 text-label text-muted">
      <span>共 {total} {unit}</span>
      <div className="flex items-center gap-1">
        <button className="btn btn-ghost btn-sm" disabled={page <= 1} onClick={() => onChange(Math.max(0, offset - limit))} aria-label="上一页"><ChevronLeft className="h-4 w-4" /></button>
        <span className="tabular-nums">{page} / {pages}</span>
        <button className="btn btn-ghost btn-sm" disabled={page >= pages} onClick={() => onChange(offset + limit)} aria-label="下一页"><ChevronRight className="h-4 w-4" /></button>
      </div>
    </div>
  );
}

/** 时间:显示相对时间,悬停给出完整时刻。 */
export function Ago({ at, className }: { at?: string | null; className?: string }) {
  if (!at) return <span className={cn("text-muted/60", className)}>—</span>;
  return <span className={className} title={fmtDateTime(at)}>{fmtAgo(at)}</span>;
}

/**
 * 选一个对象:输入就搜,下拉里选。一个控件,不用先搜再去另一个下拉里挑。
 * value 是对象的主键;显示的是它的名称。
 */
export function ObjectPicker({ type, value, onChange, disabled, placeholder, className }: {
  type: string; value: string | null | undefined; onChange: (key: string, label?: string) => void;
  disabled?: boolean; placeholder?: string; className?: string;
}) {
  const [open, setOpen] = useState(false);
  const [q, setQ] = useState("");
  const [opts, setOpts] = useState<{ key: string; label: string }[] | null>(null);
  const [label, setLabel] = useState("");
  const box = useRef<HTMLDivElement>(null);
  useEffect(() => {
    if (!value || !type) { setLabel(""); return; }
    let alive = true;
    void onto.objects(type, String(value), 5).then((r) => {
      const hit = (r.items || []).find((x) => x.key === String(value));
      if (alive) setLabel(hit?.label || "");
    }).catch(() => undefined);
    return () => { alive = false; };
  }, [type, value]);
  useEffect(() => {
    if (!open || !type) return undefined;
    setOpts(null);
    const h = window.setTimeout(() => {
      void onto.objects(type, q, 30).then((r) => setOpts((r.items || []).map((x) => ({ key: x.key, label: x.label })))).catch(() => setOpts([]));
    }, 200);
    return () => window.clearTimeout(h);
  }, [open, q, type]);
  useEffect(() => {
    if (!open) return undefined;
    const off = (e: MouseEvent) => { if (box.current && !box.current.contains(e.target as Node)) setOpen(false); };
    document.addEventListener("mousedown", off);
    return () => document.removeEventListener("mousedown", off);
  }, [open]);
  const shown = value ? (label && label !== value ? `${label}(${value})` : String(value)) : "";
  return (
    <div ref={box} className={cn("relative", className)}>
      <div className={cn("input flex items-center gap-2", disabled && "pointer-events-none bg-ink/[0.03]")} onClick={() => !disabled && setOpen(true)}>
        <Search className="h-3.5 w-3.5 shrink-0 text-muted" />
        {open
          ? <input autoFocus className="min-w-0 flex-1 bg-transparent outline-none" value={q} placeholder="输入名称或编号搜索" onChange={(e) => setQ(e.target.value)} />
          : <span className={cn("min-w-0 flex-1 truncate", !shown && "text-muted/60")}>{shown || placeholder || "请选择"}</span>}
        {value && !disabled && !open && (
          <button className="shrink-0 text-muted hover:text-ink" aria-label="清空" onClick={(e) => { e.stopPropagation(); onChange(""); }}><X className="h-3.5 w-3.5" /></button>
        )}
      </div>
      {open && (
        <div className="absolute z-30 mt-1 max-h-64 w-full overflow-auto rounded-lg border border-line bg-surface py-1 shadow-lg">
          {opts === null ? <div className="px-3 py-2"><Spinner className="h-3.5 w-3.5" /></div>
            : opts.length === 0 ? <p className="px-3 py-2 text-label text-muted">没有找到</p>
              : opts.map((o) => (
                <button key={o.key} className={cn("flex w-full items-center gap-2 px-3 py-1.5 text-left text-body hover:bg-ink/5", o.key === value && "bg-brand/5")}
                        onClick={() => { onChange(o.key, o.label); setLabel(o.label); setOpen(false); setQ(""); }}>
                  <span className="min-w-0 flex-1 truncate">{o.label}</span>
                  {o.label !== o.key && <span className="shrink-0 text-caption text-muted">{o.key}</span>}
                </button>
              ))}
        </div>
      )}
    </div>
  );
}

/**
 * 取数结果的表格:指标结果(列名换成指标和维度的名称,对象维度显示名称并可点)和对象列表(按属性定义显示)。
 * 流程卡的步骤结果、编辑器里的试算、监控的命中明细都用它。
 */
export function ResultGrid({ data, max = 50, onOpen }: { data: any; max?: number; onOpen?: (typeId: string, key: string) => void }) {
  if (!data) return null;
  const open = onOpen || ((t: string, k: string) => go("objects", { type: t, key: k }));
  if (Array.isArray(data.items)) {
    const fields: FieldMeta[] = (data.fields || []).slice(0, 8);
    const items: any[] = data.items;
    if (!items.length) return <p className="text-label text-muted">没有查到</p>;
    return (
      <div className="max-h-80 overflow-auto rounded-lg border border-line">
        <table className="tbl">
          <thead><tr><th>名称</th>{fields.map((f) => <th key={f.name} className={cn(isNumeric(f) && "text-right")}>{f.label}</th>)}</tr></thead>
          <tbody>
            {items.slice(0, max).map((x, i) => (
              <tr key={x.key ?? i} className={cn(x.type_id && "row-link")} onClick={() => x.type_id && open(x.type_id, x.key)}>
                <td className="max-w-[16rem] truncate whitespace-nowrap font-medium">{x.label ?? x.key}</td>
                {fields.map((f) => (
                  <td key={f.name} className={cn("max-w-[14rem] truncate whitespace-nowrap", isNumeric(f) && "num")}>
                    <Value v={x.properties?.[f.name]} field={f} refInfo={x.refs?.[f.name]} />
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
        {items.length > max && <p className="border-t border-line px-3 py-1.5 text-caption text-muted">只列出前 {max} 条,共 {data.total ?? items.length} 条</p>}
      </div>
    );
  }
  if (!Array.isArray(data.rows) || !Array.isArray(data.columns)) return null;
  const cols: string[] = data.columns.map(String);
  const meta: any[] = Array.isArray(data.col_meta) && data.col_meta.length === cols.length
    ? data.col_meta : cols.map((c) => ({ name: c, label: c, role: c === "value" ? "value" : "dim" }));
  // 对象维度有名称列时,编号列不单独显示:名称列显示名称、点了去那个对象
  const show = meta.map((m, i) => ({ m, i })).filter(({ m }) => !(m.role === "dim" && m.name_col));
  if (!data.rows.length) return <p className="text-label text-muted">没有数据</p>;
  return (
    <div className="max-h-80 overflow-auto rounded-lg border border-line">
      <table className="tbl">
        <thead><tr>{show.map(({ m }) => <th key={m.name} className={cn(m.role === "value" && "text-right")}>{m.label}</th>)}</tr></thead>
        <tbody>
          {data.rows.slice(0, max).map((r: any[], ri: number) => (
            <tr key={ri}>
              {show.map(({ m, i }) => {
                if (m.role === "name") {
                  const dim = meta.findIndex((x) => x.name === m.of);
                  const typeId = dim >= 0 ? meta[dim].type_id : "";
                  const key = dim >= 0 ? r[dim] : "";
                  return <td key={m.name} className="whitespace-nowrap">{typeId && key !== null && key !== undefined
                    ? <ObjLink typeId={typeId} objKey={String(key)} label={String(r[i] ?? key)} /> : fmtValue(r[i], null)}</td>;
                }
                return <td key={m.name} className={cn("whitespace-nowrap", m.role === "value" && "num font-medium")}>
                  {m.role === "value" ? fmtValue(r[i], { format: m.format, unit: "" }) : fmtValue(r[i], null)}</td>;
              })}
            </tr>
          ))}
        </tbody>
      </table>
      {data.rows.length > max && <p className="border-t border-line px-3 py-1.5 text-caption text-muted">只列出前 {max} 行,共 {data.rows.length} 行</p>}
    </div>
  );
}

type Opt = { value: string; label: string; disabled?: boolean };

/** 把 <option> 子元素摊平成选项;遇到认不出来的(如 optgroup)返回 null,调用方退回原生下拉。 */
function readOptions(children: ReactNode): Opt[] | null {
  const out: Opt[] = [];
  let ok = true;
  const walk = (nodes: ReactNode) => {
    Children.forEach(nodes, (c) => {
      if (c === null || c === undefined || typeof c === "boolean") return;
      if (!isValidElement(c)) { ok = false; return; }
      const props = c.props as { children?: ReactNode; value?: unknown; disabled?: boolean };
      if (c.type === Fragment) { walk(props.children); return; }
      if (c.type !== "option") { ok = false; return; }
      const label = Children.toArray(props.children).map((x) => (typeof x === "string" || typeof x === "number" ? String(x) : "")).join("");
      out.push({ value: String(props.value ?? label), label, disabled: props.disabled });
    });
  };
  walk(children);
  return ok ? out : null;
}

const SEARCH_FROM = 9;

/**
 * 下拉选择,写法和原生 <select> 相同(value / onChange(e.target.value) / <option> 子元素)。
 * 选项不到 9 个时就是原生下拉;多了以后点开可以输字过滤 —— 对象、属性、动作这类列表一长,原生下拉找不到东西。
 */
export function Select({ value, onChange, disabled, className, children, title }: {
  value?: string | number | null; disabled?: boolean; className?: string; children?: ReactNode; title?: string;
  onChange?: (e: { target: { value: string }; currentTarget: { value: string } }) => void;
}) {
  const opts = useMemo(() => readOptions(children), [children]);
  const [open, setOpen] = useState(false);
  const [q, setQ] = useState("");
  const [at, setAt] = useState(0);
  const box = useRef<HTMLDivElement>(null);
  useEffect(() => {
    if (!open) return undefined;
    const off = (e: MouseEvent) => { if (box.current && !box.current.contains(e.target as Node)) setOpen(false); };
    document.addEventListener("mousedown", off);
    return () => document.removeEventListener("mousedown", off);
  }, [open]);
  const pick = (v: string) => { onChange?.({ target: { value: v }, currentTarget: { value: v } }); setOpen(false); setQ(""); };
  if (!opts || opts.length < SEARCH_FROM) {
    return (
      <select className={className} value={value ?? ""} disabled={disabled} title={title}
              onChange={(e) => onChange?.({ target: { value: e.target.value }, currentTarget: { value: e.target.value } })}>
        {children}
      </select>
    );
  }
  const cur = opts.find((o) => o.value === String(value ?? ""));
  const kw = q.trim().toLowerCase();
  const shown = kw ? opts.filter((o) => o.label.toLowerCase().includes(kw) || o.value.toLowerCase().includes(kw)) : opts;
  return (
    <div ref={box} className={cn("relative", className?.split(" ").filter((c) => /^(w-|min-w-|max-w-|flex-|shrink|grow)/.test(c)).join(" "))} title={title}>
      <div className={cn(className, "flex cursor-pointer items-center gap-1.5", disabled && "pointer-events-none bg-ink/[0.03] text-muted")}
           onClick={() => { if (!disabled) { setOpen(true); setAt(0); } }}>
        {open
          ? <input autoFocus className="min-w-0 flex-1 bg-transparent outline-none" value={q} placeholder={cur?.label || "输入文字筛选"}
                   onChange={(e) => { setQ(e.target.value); setAt(0); }}
                   onKeyDown={(e) => {
                     if (e.key === "ArrowDown") { e.preventDefault(); setAt((i) => Math.min(i + 1, shown.length - 1)); }
                     else if (e.key === "ArrowUp") { e.preventDefault(); setAt((i) => Math.max(i - 1, 0)); }
                     else if (e.key === "Enter") { e.preventDefault(); if (shown[at] && !shown[at].disabled) pick(shown[at].value); }
                     else if (e.key === "Escape") { setOpen(false); setQ(""); }
                   }} />
          : <span className={cn("min-w-0 flex-1 truncate", (!cur || cur.value === "") && "text-muted")}>{cur?.label ?? String(value ?? "")}</span>}
        <ChevronDown className="h-3.5 w-3.5 shrink-0 text-muted" />
      </div>
      {open && (
        <div className="absolute z-30 mt-1 max-h-64 w-full min-w-[12rem] overflow-auto rounded-lg border border-line bg-surface py-1 shadow-lg">
          {shown.length === 0 ? <p className="px-3 py-2 text-label text-muted">没有找到</p>
            : shown.map((o, i) => (
              <button key={`${o.value}-${i}`} type="button" disabled={o.disabled}
                      className={cn("block w-full truncate px-3 py-1.5 text-left text-body hover:bg-ink/5",
                                    i === at && "bg-ink/5", o.value === String(value ?? "") && "font-medium text-brand", o.disabled && "text-muted")}
                      onMouseEnter={() => setAt(i)} onClick={() => pick(o.value)}>
                {o.label || " "}
              </button>
            ))}
        </div>
      )}
    </div>
  );
}