data.tsx 19.2 KB
/**
 * 取值控件:流程里每一个「要填一个值」的地方都用它。
 *
 * - ValueInput:一个值有三种来源 —— 常量(按类型给输入框 / 下拉 / 开关 / 对象搜索)、引用上游数据(级联选择,
 *   只列这一步之前走得到的步骤,字段带类型)、公式(fx,可以用列表函数和比较,变量自动补全)。
 * - RefPicker:只能引用数据(循环的数据来源、条件的左边)。
 * - TemplateText:一段文字里夹着数据(通知内容、任务说明)。
 * - ExprInput:公式编辑器(计算节点、条件的高级写法、自动执行条件)。
 *
 * 存进定义的仍然是 `$变量.字段` / `=公式`,界面上显示成「查工单 · 用料行 · 数量」这样的胶囊。
 */
import { autocompletion, type CompletionContext } from "@codemirror/autocomplete";
import { EditorView } from "@codemirror/view";
import CodeMirror from "@uiw/react-codemirror";
import { Braces, ChevronDown, ChevronRight, FunctionSquare, Search, Type, X } from "lucide-react";
import { createContext, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { ObjectPicker, Select } from "@/components/kit";
import type { DataSchema, FlowMeta, FlowOutput } from "@/lib/onto";
import { cn } from "@/lib/utils";
import { refLabel, refType, refsIn } from "./model";

/** 当前这一步能用的数据(编辑器按选中的节点算好放进来)。 */
export interface DataScope { outputs: FlowOutput[]; meta: FlowMeta | null; extra?: FlowOutput[] }
export const ScopeCtx = createContext<DataScope>({ outputs: [], meta: null });
export const useScope = () => useContext(ScopeCtx);

/** 在局部范围里多加几份数据(写数据的「这一行」「本次写入」)。 */
export function WithExtra({ extra, children }: { extra: FlowOutput[]; children: ReactNode }) {
  const sc = useScope();
  return <ScopeCtx.Provider value={{ ...sc, extra: [...(sc.extra || []), ...extra] }}>{children}</ScopeCtx.Provider>;
}

const all = (sc: DataScope) => [...(sc.extra || []), ...sc.outputs];

export const TYPE_TAG: Record<string, string> = {
  string: "文字", number: "数字", integer: "整数", boolean: "是否", date: "日期", array: "列表", list: "列表",
  object: "对象", any: "任意", choice: "单选", period: "周期", text: "文字",
};

function TypeTag({ t }: { t?: string }) {
  return <span className="shrink-0 rounded bg-ink/5 px-1 text-[11px] leading-4 text-muted">{TYPE_TAG[t || "any"] || t}</span>;
}

/** 类型能不能接上:要列表的只给列表,要数字的给数字 / 任意……文字什么都能接。 */
function compatible(want: string | undefined, got: string): boolean {
  if (!want || want === "any" || got === "any") return true;
  if (want === "list" || want === "array") return got === "array" || got === "list";
  if (want === "string" || want === "text" || want === "choice") return got !== "array" && got !== "object";
  if (want === "number" || want === "integer") return got === "number" || got === "integer";
  if (want === "object") return got === "object";
  return want === got || (want === "date" && got === "string");
}

// ---------------------------------------------------------------- 浮层
function Floating({ anchor, onClose, children, width = 320 }: { anchor: HTMLElement | null; onClose: () => void; children: ReactNode; width?: number }) {
  const box = useRef<HTMLDivElement>(null);
  const [pos, setPos] = useState<{ left: number; top: number; up: boolean } | null>(null);
  useEffect(() => {
    if (!anchor) return;
    const r = anchor.getBoundingClientRect();
    const up = r.bottom + 340 > window.innerHeight && r.top > 360;
    setPos({ left: Math.max(8, Math.min(r.right - width, window.innerWidth - width - 8)), top: up ? r.top - 4 : r.bottom + 4, up });
  }, [anchor, width]);
  useEffect(() => {
    const off = (e: MouseEvent) => {
      if (box.current?.contains(e.target as Node) || anchor?.contains(e.target as Node)) return;
      onClose();
    };
    const esc = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("mousedown", off);
    document.addEventListener("keydown", esc);
    return () => { document.removeEventListener("mousedown", off); document.removeEventListener("keydown", esc); };
  }, [anchor, onClose]);
  if (!pos) return null;
  return createPortal(
    <div ref={box} style={{ left: pos.left, top: pos.top, width, transform: pos.up ? "translateY(-100%)" : undefined }}
         className="fixed z-[80] max-h-[340px] overflow-auto rounded-lg border border-line bg-surface p-1.5 shadow-xl">
      {children}
    </div>, document.body);
}

// ---------------------------------------------------------------- 级联选择
function FieldRows({ schema, path, depth, want, onPick, q }: {
  schema: DataSchema; path: string; depth: number; want?: string; onPick: (ref: string) => void; q: string;
}) {
  const fields = schema.type === "array" ? (schema.items?.fields || []) : (schema.fields || []);
  const base = schema.type === "array" ? `${path}[0]` : path;
  return (
    <>
      {fields.map((f) => <FieldRow key={f.name} f={f} path={`${base}.${f.name}`} depth={depth} want={want} onPick={onPick} q={q}
                                   prefix={schema.type === "array" ? "第 1 条 · " : ""} />)}
    </>
  );
}

function FieldRow({ f, path, depth, want, onPick, q, prefix = "" }: {
  f: DataSchema; path: string; depth: number; want?: string; onPick: (ref: string) => void; q: string; prefix?: string;
}) {
  const nested = (f.type === "object" && (f.fields || []).length > 0) || (f.type === "array" && (f.items?.fields || []).length > 0);
  const [open, setOpen] = useState(!!q);
  useEffect(() => { if (q) setOpen(true); }, [q]);
  const label = `${prefix}${f.label || f.name}`;
  const hit = !q || label.includes(q) || String(f.name).includes(q);
  const ok = compatible(want, f.type);
  if (!hit && !nested) return null;
  return (
    <div>
      <div className="flex items-center gap-1 rounded hover:bg-brand/5" style={{ paddingLeft: depth * 12 }}>
        {nested ? (
          <button className="p-0.5 text-muted" onClick={() => setOpen((o) => !o)}>
            {open ? <ChevronDown className="h-3 w-3" /> : <ChevronRight className="h-3 w-3" />}
          </button>
        ) : <span className="w-4" />}
        <button disabled={!ok} title={ok ? path : "类型对不上"}
                className={cn("flex min-w-0 flex-1 items-center gap-1.5 py-1 pr-1 text-left text-label", !ok && "cursor-not-allowed opacity-40")}
                onClick={() => onPick(`$${path}`)}>
          <span className="min-w-0 flex-1 truncate">{label}</span><TypeTag t={f.type} />
        </button>
      </div>
      {nested && open && <FieldRows schema={f} path={path} depth={depth + 1} want={want} onPick={onPick} q={q} />}
    </div>
  );
}

export function PickerMenu({ want, onPick, anchor, onClose }: {
  want?: string; onPick: (ref: string) => void; anchor: HTMLElement | null; onClose: () => void;
}) {
  const sc = useScope();
  const [q, setQ] = useState("");
  const outs = all(sc);
  return (
    <Floating anchor={anchor} onClose={onClose}>
      <div className="mb-1 flex items-center gap-1 rounded-md border border-line px-2">
        <Search className="h-3.5 w-3.5 text-muted" />
        <input autoFocus className="h-7 min-w-0 flex-1 bg-transparent text-label outline-none" placeholder="搜字段" value={q} onChange={(e) => setQ(e.target.value)} />
      </div>
      {outs.length === 0 && <p className="px-2 py-3 text-caption text-muted">这一步之前还没有能引用的数据。先从「开始」或上一个节点连一条线过来。</p>}
      {outs.map((o) => {
        const ok = compatible(want, o.schema?.type || "any");
        return (
          <div key={o.id} className="mb-1">
            <div className="flex items-center gap-1 px-1.5 pt-1">
              <button disabled={!ok} className={cn("flex min-w-0 flex-1 items-center gap-1.5 rounded py-0.5 text-left text-caption font-medium text-muted hover:text-brand", !ok && "opacity-50")}
                      title={ok ? `$${o.var}` : "类型对不上"} onClick={() => onPick(`$${o.var}`)}>
                <span className="min-w-0 truncate">{o.kind === "param" ? "开始 · " : o.kind === "item" ? "循环 · " : ""}{o.title}</span>
                <TypeTag t={o.schema?.type} />
              </button>
            </div>
            {o.schema && <FieldRows schema={o.schema} path={o.var} depth={0} want={want} onPick={onPick} q={q} />}
          </div>
        );
      })}
    </Floating>
  );
}

export function Chip({ text, onClear, disabled, tone = "brand" }: { text: string; onClear?: () => void; disabled?: boolean; tone?: "brand" | "bad" }) {
  return (
    <span title={text} className={cn("inline-flex min-w-0 max-w-full items-center gap-1 rounded-md px-1.5 py-0.5 text-label",
      tone === "bad" ? "bg-bad/10 text-bad" : "bg-brand/10 text-brand")}>
      <Braces className="h-3 w-3 shrink-0" /><span className="min-w-0 truncate">{text}</span>
      {onClear && !disabled && <button className="shrink-0" onClick={onClear} title="清除"><X className="h-3 w-3" /></button>}
    </span>
  );
}

/** 只能引用一份数据。 */
export function RefPicker({ value, onChange, want, disabled, placeholder = "选择数据" }: {
  value: string; onChange: (v: string) => void; want?: string; disabled?: boolean; placeholder?: string;
}) {
  const sc = useScope();
  const btn = useRef<HTMLButtonElement>(null);
  const [open, setOpen] = useState(false);
  const known = !value || all(sc).some((o) => String(value).replace(/^\$/, "").split(/[.[]/)[0] === o.var);
  return (
    <>
      <button ref={btn} type="button" disabled={disabled} onClick={() => setOpen((o) => !o)}
              className={cn("input flex h-8 w-full min-w-0 items-center justify-between gap-1 text-left", !value && "text-muted")}>
        {value ? <Chip text={shortLabel(refLabel(value, all(sc)))} tone={known ? "brand" : "bad"} /> : <span className="truncate">{placeholder}</span>}
        <ChevronDown className="h-3.5 w-3.5 shrink-0 text-muted" />
      </button>
      {open && <PickerMenu want={want} anchor={btn.current} onClose={() => setOpen(false)} onPick={(r) => { onChange(r); setOpen(false); }} />}
    </>
  );
}

// ---------------------------------------------------------------- 公式
function completions(sc: DataScope) {
  const vars: { label: string; detail: string; type: string }[] = [];
  const walk = (s: DataSchema | undefined, path: string, depth: number) => {
    if (!s || depth > 3) return;
    const fields = s.type === "array" ? s.items?.fields : s.fields;
    for (const f of fields || []) {
      const p = s.type === "array" ? `${path}[0].${f.name}` : `${path}.${f.name}`;
      vars.push({ label: p, detail: f.label || "", type: "property" });
      walk(f, p, depth + 1);
    }
  };
  for (const o of all(sc)) {
    vars.push({ label: o.var, detail: o.title, type: "variable" });
    walk(o.schema, o.var, 0);
  }
  for (const v of ["today", "now_id", "this_month"]) vars.push({ label: v, detail: "内置", type: "constant" });
  const fns = (sc.meta?.list_functions || []).map((f) => ({ label: f.name, detail: f.sig, info: f.desc, type: "function", apply: `${f.name}(` }));
  return (ctx: CompletionContext) => {
    const w = ctx.matchBefore(/[\w一-鿿.[\]]+/);
    if (!w || (w.from === w.to && !ctx.explicit)) return null;
    return { from: w.from, options: [...vars, ...fns], validFor: /^[\w一-鿿.[\]]*$/ };
  };
}

export function ExprInput({ value, onChange, disabled, placeholder = "如:sum_by(q.items, '金额') > 5000", minHeight = 34 }: {
  value: string; onChange: (v: string) => void; disabled?: boolean; placeholder?: string; minHeight?: number;
}) {
  const sc = useScope();
  const ext = useMemo(() => [autocompletion({ override: [completions(sc)] }), EditorView.lineWrapping,
    EditorView.theme({ "&": { fontSize: "13px" }, ".cm-content": { fontFamily: "var(--font-mono, Consolas, monospace)" } })],
  // eslint-disable-next-line react-hooks/exhaustive-deps
  [sc.outputs, sc.extra, sc.meta]);
  return (
    <div className={cn("overflow-hidden rounded-md border border-line focus-within:border-brand focus-within:ring-2 focus-within:ring-brand/20", disabled && "opacity-70")}>
      <CodeMirror value={value} editable={!disabled} placeholder={placeholder} extensions={ext} minHeight={`${minHeight}px`}
                  basicSetup={{ lineNumbers: false, foldGutter: false, highlightActiveLine: false, autocompletion: false }}
                  onChange={onChange} />
    </div>
  );
}

// ---------------------------------------------------------------- 一个值
export interface ValueSpec { type?: string; options?: string[]; object_type?: string; placeholder?: string }

type Mode = "const" | "ref" | "expr";
const modeOf = (v: unknown): Mode => (typeof v === "string" && /^\$[^\s$]+$/.test(v.trim()) ? "ref"
  : typeof v === "string" && v.startsWith("=") ? "expr" : "const");

function ConstInput({ value, onChange, spec, disabled }: { value: any; onChange: (v: any) => void; spec: ValueSpec; disabled?: boolean }) {
  const t = spec.type || "string";
  if (t === "boolean") {
    return (
      <Select className="input h-8 w-full" disabled={disabled} value={value === true ? "true" : value === false ? "false" : ""}
              onChange={(e) => onChange(e.target.value === "" ? "" : e.target.value === "true")}>
        <option value="">请选择</option><option value="true">是</option><option value="false">否</option>
      </Select>
    );
  }
  if (spec.options?.length) {
    return (
      <Select className="input h-8 w-full" disabled={disabled} value={value ?? ""} onChange={(e) => onChange(e.target.value)}>
        <option value="">请选择</option>{spec.options.map((o) => <option key={o} value={o}>{o}</option>)}
      </Select>
    );
  }
  if (t === "object" && spec.object_type) {
    return <ObjectPicker className="w-full" type={spec.object_type} value={value ?? ""} disabled={disabled} onChange={(k) => onChange(k)} />;
  }
  if (t === "list" || t === "array") {
    return <p className="flex h-8 items-center rounded-md border border-dashed border-line px-2 text-caption text-muted">多行数据:点右边 {"{}"} 选一份上游的列表</p>;
  }
  return (
    <input className="input h-8 w-full" disabled={disabled} value={value ?? ""} placeholder={spec.placeholder || (t === "date" ? "YYYY-MM-DD" : "填一个值")}
           type={t === "number" || t === "integer" ? "number" : t === "date" ? "date" : "text"}
           onChange={(e) => onChange((t === "number" || t === "integer") && e.target.value !== "" ? Number(e.target.value) : e.target.value)} />
  );
}

const MODES = [["const", Type, "填一个值"], ["ref", Braces, "引用上游的数据"], ["expr", FunctionSquare, "写公式"]] as const;

/** 显示用:长路径只留最后两段(「… · 当前这一条 · 门店」),完整的放在悬停提示里。 */
export const shortLabel = (label: string) => {
  const parts = label.split(" · ");
  return parts.length > 2 ? `…${parts.slice(-2).join(" · ")}` : label;
};

export function ValueInput({ value, onChange, disabled, ...spec }: ValueSpec & { value: any; onChange: (v: any) => void; disabled?: boolean }) {
  const sc = useScope();
  const box = useRef<HTMLDivElement>(null);
  const modeBtn = useRef<HTMLButtonElement>(null);
  const [mode, setMode] = useState<Mode>(modeOf(value));
  const [open, setOpen] = useState(false);
  const [menu, setMenu] = useState(false);
  useEffect(() => { setMode(modeOf(value)); }, [value]);
  const switchTo = (m: Mode) => {
    setMode(m);
    setMenu(false);
    if (m === "expr" && !String(value ?? "").startsWith("=")) onChange("=");
    if (m === "const" && modeOf(value) !== "const") onChange("");
    if (m === "ref") setOpen(true);
  };
  const outs = all(sc);
  const known = mode !== "ref" || outs.some((o) => String(value).replace(/^\$/, "").split(/[.[]/)[0] === o.var);
  const full = mode === "ref" ? refLabel(String(value), outs) : "";
  const Cur = MODES.find((m) => m[0] === mode)![1];
  return (
    <div ref={box} className="flex min-w-0 items-start gap-1">
      <div className="min-w-0 flex-1">
        {mode === "ref" ? (
          <button type="button" disabled={disabled} onClick={() => setOpen((o) => !o)} title={`${full}(${TYPE_TAG[refType(String(value), outs)] || "任意"})`}
                  className="input flex h-8 w-full min-w-0 items-center gap-1 text-left">
            {value ? <Chip text={shortLabel(full)} tone={known ? "brand" : "bad"} onClear={() => onChange("")} disabled={disabled} />
              : <span className="text-muted">选择数据</span>}
          </button>
        ) : mode === "expr" ? (
          <ExprInput value={String(value ?? "").replace(/^=/, "")} disabled={disabled} onChange={(v) => onChange(`=${v}`)} />
        ) : <ConstInput value={value} onChange={onChange} spec={spec} disabled={disabled} />}
      </div>
      {!disabled && (
        <button ref={modeBtn} type="button" title={`${MODES.find((m) => m[0] === mode)![2]}(点击切换:填值 / 引用数据 / 公式)`}
                className={cn("flex h-8 w-7 shrink-0 items-center justify-center rounded-md border border-line",
                  mode === "const" ? "text-muted hover:bg-ink/5" : "bg-brand/10 text-brand")}
                onClick={() => setMenu((m) => !m)}>
          <Cur className="h-3.5 w-3.5" />
        </button>
      )}
      {menu && (
        <Floating anchor={modeBtn.current} onClose={() => setMenu(false)} width={168}>
          {MODES.map(([m, Icon, tip]) => (
            <button key={m} className={cn("flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-label hover:bg-ink/5", mode === m && "text-brand")}
                    onClick={() => switchTo(m)}><Icon className="h-3.5 w-3.5" />{tip}</button>
          ))}
        </Floating>
      )}
      {open && <PickerMenu want={spec.type} anchor={box.current} onClose={() => setOpen(false)} onPick={(r) => { onChange(r); setMode("ref"); setOpen(false); }} />}
    </div>
  );
}

// ---------------------------------------------------------------- 一段文字夹数据
export function TemplateText({ value, onChange, disabled, rows = 2, placeholder }: {
  value: string; onChange: (v: string) => void; disabled?: boolean; rows?: number; placeholder?: string;
}) {
  const sc = useScope();
  const ta = useRef<HTMLTextAreaElement>(null);
  const btn = useRef<HTMLButtonElement>(null);
  const [open, setOpen] = useState(false);
  const insert = (ref: string) => {
    const el = ta.current;
    const at = el ? el.selectionStart ?? value.length : value.length;
    onChange(`${value.slice(0, at)}${ref}${value.slice(at)}`);
    setOpen(false);
    window.setTimeout(() => { el?.focus(); el?.setSelectionRange(at + ref.length, at + ref.length); }, 0);
  };
  const used = [...new Set(refsIn(value))];
  return (
    <div>
      <textarea ref={ta} className="input w-full" rows={rows} disabled={disabled} value={value} placeholder={placeholder} onChange={(e) => onChange(e.target.value)} />
      <div className="mt-1 flex flex-wrap items-center gap-1">
        {!disabled && <button ref={btn} type="button" className="btn btn-sm" onClick={() => setOpen((o) => !o)}><Braces className="h-3.5 w-3.5" />插入数据</button>}
        {used.map((r) => <Chip key={r} text={refLabel(r, all(sc))} />)}
      </div>
      {open && <PickerMenu anchor={btn.current} onClose={() => setOpen(false)} onPick={insert} />}
    </div>
  );
}