RefSelect.tsx
13.9 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
/**
* 引用选择器:凡是「填一个本体里的名字」的地方都用它,不再让人对着空白框猜。
*
* 选项来自 /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}`);
}