data.tsx
19.2 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
/**
* 取值控件:流程里每一个「要填一个值」的地方都用它。
*
* - 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>
);
}