RefSelect.tsx 13.9 KB
/**
 * 引用选择器:凡是「填一个本体里的名字」的地方都用它,不再让人对着空白框猜。
 *
 * 选项来自 /api/cap/ref-options(参数上的 x-ref 决定取什么):已发布的在前,草稿标「草稿」
 * (试运行可用、正式运行前要发布),流程里可引用的变量($xxx)单独一组,实在不在列表里的可以「自定义…」手填。
 * 选项为空时直接告诉人去哪里建,而不是给一个空下拉。
 */
import { Trash2, X } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { go } from "@/lib/nav";
import { onto, type RefOption } from "@/lib/onto";
import { cn } from "@/lib/utils";
import { Select } from "@/components/kit";

const cache = new Map<string, { at: number; p: Promise<RefOption[]> }>();
const TTL = 20_000;

export function refOptions(ref: string, of = ""): Promise<RefOption[]> {
  const k = `${ref}|${of}`;
  const hit = cache.get(k);
  if (hit && Date.now() - hit.at < TTL) return hit.p;
  const p = onto.refOptions(ref, of).catch(() => [] as RefOption[]);
  cache.set(k, { at: Date.now(), p });
  return p;
}

/** 新建 / 发布了元素之后调用,下拉马上能看到新东西。 */
export function invalidateRefOptions() { cache.clear(); }

export function useRefOptions(ref?: string, of = ""): RefOption[] | null {
  const [opts, setOpts] = useState<RefOption[] | null>(null);
  useEffect(() => {
    if (!ref) { setOpts([]); return; }
    let alive = true;
    setOpts(null);
    void refOptions(ref, of).then((o) => { if (alive) setOpts(o); });
    return () => { alive = false; };
  }, [ref, of]);
  return opts;
}

/** 选项为空时告诉人去哪里建。 */
const EMPTY_HINT: Record<string, [string, string]> = {
  metric: ["还没有聚合函数(指标)", "b_function"], rule: ["还没有规则", "b_function"],
  decision: ["还没有决策表", "b_function"], object_set: ["还没有对象集", "b_function"],
  function: ["还没有函数", "b_function"], object_type: ["还没有对象类型", "b_object"],
  action: ["还没有动作", "b_action"], role: ["还没有业务角色", "members"], user: ["还没有成员", "members"],
  recipient: ["还没有成员或角色", "members"], endpoint: ["还没有登记外部端点", "data"],
  datasource: ["还没有接入数据源", "data"], sop: ["还没有流程卡", "sop"], concept: ["本体还是空的", "modeling"],
  dimension: ["这个指标还没有可拆分的维度(在指标的取数绑定里配)", "b_function"],
  filters: ["这个指标还没有可拆分的维度", "b_function"],
  property: ["这个对象还没有可写属性(在对象属性里勾「可写」)", "b_object"],
};

const DEP_LABEL: Record<string, string> = { dimension: "指标", filters: "指标", property: "对象类型", values: "对象类型", vars: "函数" };

function isExpr(v: unknown) { return typeof v === "string" && (v.startsWith("$") || v.startsWith("=")); }

export function RefSelect({ refKind, of, value, onChange, disabled, vars = [], placeholder, className, allowCustom = true }: {
  refKind: string; of?: string; value: any; onChange: (v: any) => void; disabled?: boolean;
  /** 可引用的变量,如 ["$shortage", "$item.仓库"] */
  vars?: string[]; placeholder?: string; className?: string; allowCustom?: boolean;
}) {
  const base = refKind.split(":")[0];
  const needsDep = refKind.includes(":");
  const depMissing = needsDep && (!of || String(of).startsWith("$"));
  const opts = useRefOptions(depMissing ? undefined : refKind, of || "");
  const [custom, setCustom] = useState(false);
  const known = useMemo(() => new Set((opts || []).map((o) => String(o.value))), [opts]);
  const str = value === undefined || value === null ? "" : String(value);
  const showCustom = custom || (str !== "" && opts !== null && !known.has(str) && !vars.includes(str));

  if (depMissing) {
    return <Select className={cn("input h-8", className)} disabled><option>先选上面的{DEP_LABEL[base] || "依赖项"}</option></Select>;
  }
  if (showCustom && allowCustom) {
    return (
      <div className={cn("flex items-center gap-1", className)}>
        <input className={cn("input h-8 flex-1", isExpr(str) && "font-mono text-label")} value={str} disabled={disabled}
               placeholder={placeholder || "手填名称,或 $变量"} autoFocus={custom}
               onChange={(e) => onChange(e.target.value)} />
        {!disabled && (
          <button className="btn btn-ghost btn-sm" title="改为从列表选" onClick={() => { setCustom(false); onChange(""); }}>
            <X className="h-3.5 w-3.5" />
          </button>
        )}
      </div>
    );
  }
  const published = (opts || []).filter((o) => o.status !== "draft");
  const drafts = (opts || []).filter((o) => o.status === "draft");
  const groups = new Map<string, RefOption[]>();
  for (const o of published) groups.set(o.group || "", [...(groups.get(o.group || "") || []), o]);
  const sel = (opts || []).find((o) => String(o.value) === str);
  const empty = opts !== null && !opts.length && !vars.length;
  const hint = EMPTY_HINT[base];
  return (
    <div className={cn("min-w-0", className)}>
      <Select className={cn("input h-8 w-full", sel?.status === "draft" && "border-warn/60")} value={str} disabled={disabled || opts === null}
              onChange={(e) => {
                if (e.target.value === "__custom__") { setCustom(true); return; }
                const o = (opts || []).find((x) => String(x.value) === e.target.value);
                onChange(o && typeof o.value === "number" ? o.value : e.target.value);
              }}>
        <option value="">{opts === null ? "加载中…" : empty ? `(${hint?.[0] || "没有可选项"})` : placeholder || "请选择"}</option>
        {[...groups].map(([g, os]) => {
          const items = os.map((o) => <option key={String(o.value)} value={String(o.value)} title={o.hint}>{o.label}{o.label !== String(o.value) ? `(${o.value})` : ""}</option>);
          return g ? <optgroup key={g} label={g}>{items}</optgroup> : items;
        })}
        {drafts.length > 0 && (
          <optgroup label="草稿(试运行可用,正式运行前要发布)">
            {drafts.map((o) => <option key={String(o.value)} value={String(o.value)} title={o.hint}>{o.label} · 草稿</option>)}
          </optgroup>
        )}
        {vars.length > 0 && (
          <optgroup label="流程里的变量">
            {vars.map((v) => <option key={v} value={v}>{v}</option>)}
          </optgroup>
        )}
        {allowCustom && <option value="__custom__">自定义…</option>}
      </Select>
      {sel?.hint && <p className="mt-0.5 truncate text-caption text-muted" title={sel.hint}>{sel.hint}</p>}
      {sel?.status === "draft" && <p className="mt-0.5 text-caption text-warn">草稿:试运行可以用,正式运行前要先发布本体</p>}
      {empty && hint && (
        <button className="mt-0.5 text-caption text-brand hover:underline" onClick={() => go(hint[1])}>去建一个 →</button>
      )}
    </div>
  );
}

/** 多选(维度、概念列表):已选的显示成小标签,下拉里挑一个就加一个。 */
export function RefMulti({ refKind, of, value, onChange, disabled, vars = [] }: {
  refKind: string; of?: string; value: any; onChange: (v: string[]) => void; disabled?: boolean; vars?: string[];
}) {
  const list: string[] = Array.isArray(value) ? value.map(String) : value ? [String(value)] : [];
  return (
    <div className="space-y-1">
      {list.length > 0 && (
        <div className="flex flex-wrap gap-1">
          {list.map((v) => (
            <span key={v} className="chip">
              {v}
              {!disabled && <button aria-label={`移除 ${v}`} onClick={() => onChange(list.filter((x) => x !== v))}><X className="h-3 w-3" /></button>}
            </span>
          ))}
        </div>
      )}
      {!disabled && (
        <RefSelect refKind={refKind} of={of} value="" vars={vars} placeholder={list.length ? "再加一个…" : "请选择"}
                   onChange={(v) => { if (v !== "" && !list.includes(String(v))) onChange([...list, String(v)]); }} />
      )}
    </div>
  );
}

/** 统计时间:本期 / 上期 / 上周 / 近 N 天……存的是系统认得的写法(current / last_week / days:30 / 2026-08)。 */
export function TimeInput({ value, onChange, disabled, vars = [] }: {
  value: any; onChange: (v: any) => void; disabled?: boolean; vars?: string[];
}) {
  const str = value && typeof value === "object" ? `${value.start || ""}~${value.end || ""}` : String(value ?? "");
  const range = typeof value === "object" && value !== null;
  const [mode, setMode] = useState<"pick" | "month" | "range">(range ? "range" : /^\d{4}-\d{1,2}$/.test(str) ? "month" : "pick");
  return (
    <div className="space-y-1">
      <div className="flex gap-1">
        {([["pick", "常用"], ["month", "指定月"], ["range", "起止日期"]] as const).map(([k, l]) => (
          <button key={k} type="button" disabled={disabled}
                  className={cn("rounded px-1.5 py-0.5 text-caption", mode === k ? "bg-brand/10 text-brand" : "text-muted hover:text-ink")}
                  onClick={() => { setMode(k); onChange(k === "range" ? { start: "", end: "" } : ""); }}>{l}</button>
        ))}
      </div>
      {mode === "pick" && <RefSelect refKind="time" value={range ? "" : value} onChange={onChange} disabled={disabled} vars={vars} placeholder="不限(全部时间)" />}
      {mode === "month" && <input type="month" className="input h-8" value={str} disabled={disabled} onChange={(e) => onChange(e.target.value)} />}
      {mode === "range" && (
        <div className="flex items-center gap-1">
          <input type="date" className="input h-8 min-w-0 flex-1" value={range ? value.start || "" : ""} disabled={disabled}
                 onChange={(e) => onChange({ ...(range ? value : {}), start: e.target.value })} />
          <span className="text-caption text-muted">至</span>
          <input type="date" className="input h-8 min-w-0 flex-1" value={range ? value.end || "" : ""} disabled={disabled}
                 onChange={(e) => onChange({ ...(range ? value : {}), end: e.target.value })} />
        </div>
      )}
    </div>
  );
}

/**
 * 键值编辑器:键从选项里选(指标的维度 / 对象的属性 / 函数的输入),值手填或引用变量。
 * 用于「只看哪些(过滤)」「新建对象的属性值」「规则 / 决策表的输入」。
 */
export function KeyValueEditor({ refKind, of, value, onChange, disabled, vars = [], valueHint = "值,或 $变量" }: {
  refKind: string; of?: string; value: any; onChange: (v: Record<string, any>) => void; disabled?: boolean;
  vars?: string[]; valueHint?: string;
}) {
  const obj: Record<string, any> = value && typeof value === "object" && !Array.isArray(value) ? value : {};
  const base = refKind.split(":")[0];
  const depMissing = refKind.includes(":") && (!of || String(of).startsWith("$"));
  const opts = useRefOptions(depMissing ? undefined : refKind, of || "");
  const entries = Object.entries(obj);
  const set = (k: string, v: any) => { const n = { ...obj }; if (v === "" || v === undefined) delete n[k]; else n[k] = v; onChange(n); };
  if (depMissing) return <p className="text-caption text-muted">先选上面的{DEP_LABEL[base] || "依赖项"}</p>;
  // 函数输入 / 对象属性:把每个可填项都列出来,一目了然;过滤条件只列已加的
  const listAll = base === "vars" || base === "values";
  const rows = listAll ? [...(opts || []).map((o) => String(o.value)), ...entries.map(([k]) => k).filter((k) => !(opts || []).some((o) => String(o.value) === k))] : entries.map(([k]) => k);
  const unused = (opts || []).filter((o) => !(String(o.value) in obj));
  return (
    <div className="space-y-1">
      {rows.map((k) => {
        const o = (opts || []).find((x) => String(x.value) === k);
        const v = obj[k];
        return (
          <div key={k} className="flex items-center gap-1">
            <span className="w-28 shrink-0 truncate text-label" title={o?.hint || k}>{o?.label || k}</span>
            {o?.enum?.length ? (
              <Select className="input h-8 min-w-0 flex-1" value={v ?? ""} disabled={disabled} onChange={(e) => set(k, e.target.value)}>
                <option value="">(不填)</option>
                {o.enum.map((x) => <option key={x}>{x}</option>)}
                {vars.map((x) => <option key={x} value={x}>{x}</option>)}
              </Select>
            ) : (
              <input className={cn("input h-8 min-w-0 flex-1", isExpr(v) && "font-mono text-label")} disabled={disabled}
                     list={vars.length ? `kv-vars-${base}` : undefined}
                     value={typeof v === "object" ? JSON.stringify(v) : v ?? ""} placeholder={valueHint}
                     onChange={(e) => {
                       const raw = e.target.value;
                       set(k, raw !== "" && !isExpr(raw) && !Number.isNaN(Number(raw)) && o?.type === "number" ? Number(raw) : raw);
                     }} />
            )}
            {!disabled && !listAll && (
              <button className="btn btn-ghost btn-sm" aria-label="删除这一条" onClick={() => set(k, undefined)}><Trash2 className="h-3.5 w-3.5" /></button>
            )}
          </div>
        );
      })}
      {vars.length > 0 && <datalist id={`kv-vars-${base}`}>{vars.map((x) => <option key={x} value={x} />)}</datalist>}
      {!listAll && !disabled && unused.length > 0 && (
        <Select className="input h-8 w-auto text-label" value="" onChange={(e) => e.target.value && set(e.target.value, obj[e.target.value] ?? "")}>
          <option value="">+ 加一条</option>
          {unused.map((o) => <option key={String(o.value)} value={String(o.value)}>{o.label}</option>)}
        </Select>
      )}
      {opts !== null && !opts.length && !entries.length && (
        <p className="text-caption text-muted">{EMPTY_HINT[base]?.[0] || "没有可填的项"}</p>
      )}
    </div>
  );
}

/** 把 SOP 变量列表转成 RefSelect 能用的 $引用。 */
export function varRefs(vars: { name: string }[]): string[] {
  return vars.map((v) => `$${v.name}`);
}