App.tsx
31.8 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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
import {
Activity, AlarmClock, Blocks, Bot, Boxes, Brain, Check, ChevronDown, ChevronLeft, ClipboardCheck, Database, FileText, FlaskConical,
BellRing, FunctionSquare, GitBranch, Hammer, LayoutDashboard, LayoutGrid, ListChecks, Menu, MessageSquareText, Monitor, Moon, Network,
Pencil, Plus, Presentation, RotateCcw, Rocket, Settings, ShieldCheck, Sun, Trash2, UserRound, Users, Wand2, Zap,
} from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import { Badge, Modal, PageErrorBoundary, Segmented, Spinner, Toaster } from "@/components/ui";
import { AskPage } from "@/features/ask/AskPage";
import { DocumentsPage } from "@/features/documents/DocumentsPage";
import { EvalPage } from "@/features/eval/EvalPage";
import { InboxPage } from "@/features/inbox/InboxPage";
import { MembersPage } from "@/features/members/MembersPage";
import { MemoryPage } from "@/features/memory/MemoryPage";
import { McpPage } from "@/features/mcp/McpPage";
import { AlertsPage, WatchPage } from "@/features/watch/WatchPage";
import { MonitorPage } from "@/features/monitor/MonitorPage";
import { ObjectsPage } from "@/features/objects/ObjectsPage";
import { BlockListPage } from "@/features/ontology/BlockListPage";
import { CanvasPage } from "@/features/ontology/CanvasPage";
import { ModelingPage } from "@/features/ontology/modeling/ModelingPage";
import { ReleaseHub } from "@/features/ontology/ReleasePages";
import { pageOfKind } from "@/features/ontology/routes";
import { SettingsPage } from "@/features/settings/SettingsPage";
import { SopPage } from "@/features/sop/SopPage";
import { SqlPage } from "@/features/sql/SqlPage";
import { DeskPage } from "@/features/workbench/DeskPage";
import { confirmDialog, DialogHost } from "@/lib/dialog";
import {
currentUserId, currentWorkspace, onUserChange, onWorkspaceChange, setCurrentUserId, setCurrentWorkspace,
} from "@/lib/identity";
import { DEV, envApi, switchEnv, useDemoMode, useEnvs, type DemoEnv } from "@/lib/env";
import { go, parseHash } from "@/lib/nav";
import { onto, type InboxCounts, type Me, type UserRec, type WorkspaceRec } from "@/lib/onto";
import { cn } from "@/lib/utils";
import { applyTheme, toast, useAppStore, type Theme } from "@/store/useAppStore";
type PageKey = "desk"
| "ask" | "objects"
| "sop" | "inbox" | "memory"
| "data" | "pipeline" | "documents"
| "modeling" | "canvas" | "b_object" | "b_link" | "b_function" | "b_action" | "b_value" | "publish" | "versions"
| "monitor" | "mcp" | "watch" | "alerts"
| "members" | "eval" | "settings";
/** biz:业务人员(没有搭建权限的老板、员工、审批人)也能看到的入口;其余只给实施和管理员。 */
interface NavItem { key: PageKey; label: string; icon: React.ReactNode; hint: string; biz?: boolean; perm?: string[] }
const I = "h-4 w-4";
/**
* 导航:先「用」,后「建」。
* - 最上面是每个人每天都用的:工作台、提问、对象查询;
* - 业务运转:流程卡、审批与待办、经验库;
* - 搭建:数据接入 → 本体建模(含发布与版本)→ 运行总览;
* - 设置。
* 以前是 22 个入口、三个首页、三处调用记录;合并后同一类信息只在一处。
*/
const NAV: { group: string; items: NavItem[] }[] = [
{ group: "", items: [
{ key: "desk", label: "工作台", icon: <LayoutDashboard className={I} />, hint: "", biz: true },
{ key: "ask", label: "提问", icon: <MessageSquareText className={I} />, hint: "", biz: true },
{ key: "objects", label: "对象查询", icon: <Blocks className={I} />, hint: "", biz: true },
] },
{ group: "业务运转", items: [
{ key: "inbox", label: "审批与待办", icon: <ShieldCheck className={I} />, hint: "", biz: true, perm: ["operate", "approve"] },
{ key: "alerts", label: "预警", icon: <BellRing className={I} />, hint: "", biz: true },
{ key: "sop", label: "流程卡", icon: <ListChecks className={I} />, hint: "", biz: true, perm: ["operate"] },
{ key: "watch", label: "监控与定时", icon: <AlarmClock className={I} />, hint: "" },
{ key: "memory", label: "经验库", icon: <Brain className={I} />, hint: "", biz: true },
] },
{ group: "搭建 · 数据", items: [
{ key: "data", label: "数据连接", icon: <Database className={I} />, hint: "" },
{ key: "documents", label: "知识库", icon: <FileText className={I} />, hint: "" },
] },
{ group: "搭建 · 本体", items: [
{ key: "modeling", label: "AI 建模", icon: <Wand2 className={I} />, hint: "" },
{ key: "b_object", label: "对象", icon: <Boxes className={I} />, hint: "" },
{ key: "b_link", label: "关系", icon: <GitBranch className={I} />, hint: "" },
{ key: "b_function", label: "函数", icon: <FunctionSquare className={I} />, hint: "" },
{ key: "b_action", label: "动作", icon: <Zap className={I} />, hint: "" },
{ key: "b_value", label: "值类型", icon: <Hammer className={I} />, hint: "" },
{ key: "canvas", label: "本体画布", icon: <LayoutGrid className={I} />, hint: "" },
{ key: "publish", label: "发布与版本", icon: <Rocket className={I} />, hint: "" },
] },
{ group: "运行与设置", items: [
{ key: "monitor", label: "运行总览", icon: <Activity className={I} />, hint: "" },
{ key: "mcp", label: "MCP 服务", icon: <Bot className={I} />, hint: "" },
{ key: "members", label: "成员与角色", icon: <Users className={I} />, hint: "" },
{ key: "eval", label: "评测中心", icon: <FlaskConical className={I} />, hint: "" },
{ key: "settings", label: "系统设置", icon: <Settings className={I} />, hint: "" },
] },
];
const ALL = NAV.flatMap((g) => g.items);
/**
* 演示版本默认对外展示的菜单:「问数 → 流程卡 → 审批 → 闭环」这条主线。
* 每个演示版本保存时可以另勾(后面的批次再放出建模、数据接入等);收起的只是菜单,页面仍可 URL 直达。
*/
const DEFAULT_DEMO_NAV: PageKey[] = ["desk", "ask", "objects", "sop", "inbox", "alerts"];
/** 旧链接兼容:合并掉的页面跳到新位置(带上页签)。 */
const REDIRECT: Record<string, [PageKey, Record<string, string>]> = {
home: ["desk", { tab: "build" }], runtime: ["monitor", {}],
audit: ["monitor", { tab: "audit" }], wizard: ["modeling", {}], capability: ["data", { tab: "api" }],
versions: ["publish", { tab: "versions" }], pipeline: ["data", {}],
endpoints: ["data", { tab: "api" }],
};
const THEME_ICON: Record<Theme, React.ReactNode> = {
light: <Sun className={I} />, dark: <Moon className={I} />, system: <Monitor className={I} />,
};
function pageFromHash(): PageKey {
const p = parseHash().page;
return (ALL.find((n) => n.key === p)?.key ?? REDIRECT[p]?.[0] ?? "desk") as PageKey;
}
export default function App() {
const [page, setPage] = useState<PageKey>(pageFromHash);
const [me, setMe] = useState<Me | null>(null);
const [users, setUsers] = useState<UserRec[]>([]);
const [counts, setCounts] = useState<InboxCounts | null>(null);
const [online, setOnline] = useState(true);
const [mobileNavOpen, setMobileNavOpen] = useState(false);
const [folded, setFolded] = useState<Record<string, boolean>>(() => {
try { return JSON.parse(localStorage.getItem("onto.nav.folded") || "{}"); } catch { return {}; }
});
const [uid, setUid] = useState(currentUserId());
const [ws, setWs] = useState(currentWorkspace());
const [spaces, setSpaces] = useState<WorkspaceRec[]>([]);
const demo = useDemoMode();
const { list: envList, env } = useEnvs();
const { theme, setTheme, sidebarCollapsed, toggleSidebar } = useAppStore();
const refresh = useCallback(() => {
void onto.me().then((m) => { setMe(m); setOnline(true); }).catch(() => setOnline(false));
void onto.inbox().then(setCounts).catch(() => undefined);
}, []);
useEffect(() => { applyTheme(theme); }, [theme]);
useEffect(() => { refresh(); }, [refresh, page, uid, ws]);
useEffect(() => { void onto.workspaces().then(setSpaces).catch(() => undefined); }, [uid, ws, page]);
useEffect(() => onWorkspaceChange(setWs), []);
useEffect(() => { void onto.users().then((r) => setUsers(r.users)).catch(() => undefined); }, [uid]);
useEffect(() => onUserChange(setUid), []);
useEffect(() => {
const t = window.setInterval(() => void onto.inbox().then(setCounts).catch(() => undefined), 30000);
return () => window.clearInterval(t);
}, []);
// hash 路由:#/页面?参数。旧的 #/kernel?id=… 按元素种类跳到对应列表页
useEffect(() => {
const on = () => {
const { page: raw, params } = parseHash();
const r = REDIRECT[raw];
if (r) {
const extra: Record<string, string> = {};
params.forEach((v, k) => { extra[k] = v; });
go(r[0], { ...extra, ...r[1] });
return;
}
if (raw === "kernel" && params.get("id")) {
const id = params.get("id")!;
void onto.concept(id).then((c) => go(pageOfKind(c.kind), { id })).catch(() => go("b_object"));
return;
}
setPage(pageFromHash());
};
if (!window.location.hash) go(page); else on();
window.addEventListener("hashchange", on);
return () => window.removeEventListener("hashchange", on);
}, []); // eslint-disable-line react-hooks/exhaustive-deps
const nav = (k: PageKey) => { go(k); setMobileNavOpen(false); };
// 业务人员只看业务入口:搭建期的概念(管道、元素、提案、MCP)对他们没有意义,只会让人不知道从哪下手。
// 身份还没加载出来时按业务人员处理 —— 宁可晚一点多出几个入口,也不能先给看不该看的
// 演示版本只留保存时勾选的菜单;没勾任何搭建类入口时按业务人员渲染,工作台的「搭建进度」页签一并收起(纯显示,权限不变)
const canBuild = !!me && (me.permissions.includes("build") || !!me.roles?.includes("admin"));
const demoNav = new Set<string>(env?.nav?.length ? env.nav : DEFAULT_DEMO_NAV);
const builder = canBuild && (!demo || ALL.some((n) => !n.biz && demoNav.has(n.key)));
const allowed = (n: NavItem) => (!demo || demoNav.has(n.key))
&& (builder || (n.biz && (!n.perm || n.perm.some((p) => me?.permissions.includes(p)))))
const navGroups = NAV.map((g) => ({ ...g, items: g.items.filter(allowed) }))
.filter((g) => g.items.length)
.map((g) => (!builder && g.group ? { ...g, group: g.items.length === 1 ? "" : g.group } : g));
const navKey: PageKey = page;
const current = ALL.find((n) => n.key === navKey)!;
const inboxTotal = (counts?.approvals || 0) + (counts?.tasks || 0) + (counts?.reviews || 0) + (counts?.releases || 0);
const curSpace = spaces.find((x) => x.current) || spaces.find((x) => x.id === ws);
const fold = (g: string) => {
const n = { ...folded, [g]: !folded[g] };
setFolded(n);
try { localStorage.setItem("onto.nav.folded", JSON.stringify(n)); } catch { /* 隐私模式 */ }
};
const fullBleed = ["ask", "modeling", "canvas", "b_object", "b_link", "b_function", "b_action", "b_value", "publish", "sop", "mcp", "watch"].includes(page)
|| (page === "objects" && !parseHash().params.get("key"));
const switchSpace = (id: string) => { setCurrentWorkspace(id); go("desk", builder ? { tab: "build" } : {}); };
return (
<div className="flex h-full">
{mobileNavOpen && <div className="fixed inset-0 z-40 bg-black/40 md:hidden" onClick={() => setMobileNavOpen(false)} aria-hidden />}
<aside className={cn(
"flex shrink-0 flex-col border-r border-line bg-surface transition-[width,transform]",
sidebarCollapsed ? "w-[60px]" : "w-[216px]",
"max-md:fixed max-md:inset-y-0 max-md:left-0 max-md:z-50 max-md:w-[216px]",
mobileNavOpen ? "max-md:translate-x-0" : "max-md:-translate-x-full")}>
<div className="flex h-14 items-center gap-2.5 border-b border-line px-3">
<span className="grid h-8 w-8 shrink-0 place-items-center rounded-lg bg-brand text-white"><Network className={I} /></span>
{!sidebarCollapsed && (
<div className="min-w-0">
<p className="truncate text-body font-semibold leading-tight">本体认知引擎</p>
<p className="truncate text-caption text-muted">Ontology Engine</p>
</div>
)}
</div>
{!sidebarCollapsed && (
<div className="border-b border-line p-2">
<label className="block rounded-lg border border-line bg-elevated px-2.5 py-1.5">
<span className="block text-caption text-muted">本体空间</span>
<select className="w-full truncate bg-transparent text-body font-semibold outline-none" value={curSpace?.id || ws}
onChange={(e) => switchSpace(e.target.value)}>
{!spaces.some((x) => x.id === (curSpace?.id || ws)) && <option value={curSpace?.id || ws}>{curSpace?.display_name || ws || "默认本体"}</option>}
{/* 两个本体同名时带上编号,不然分不清选的是哪个 */}
{spaces.map((x) => <option key={x.id} value={x.id}>
{x.display_name}{spaces.filter((y) => y.display_name === x.display_name).length > 1 ? `(${x.id})` : ""}</option>)}
</select>
</label>
</div>
)}
<nav className="flex-1 space-y-2 overflow-auto p-2">
{navGroups.map((g) => {
const hasActive = g.items.some((n) => n.key === navKey);
const closed = folded[g.group] && !hasActive && !sidebarCollapsed;
return (
<div key={g.group}>
{!sidebarCollapsed && g.group && (
<button className="flex w-full items-center px-2.5 pb-1 pt-2 text-caption font-medium text-muted/70 hover:text-muted"
onClick={() => fold(g.group)}>
<span className="flex-1 text-left">{g.group}</span>
<ChevronDown className={cn("h-3 w-3 transition-transform", closed && "-rotate-90")} />
</button>
)}
{!closed && (
<div className="space-y-0.5">
{g.items.map((n) => (
<button key={n.key} title={sidebarCollapsed ? n.label : undefined} onClick={() => nav(n.key)}
className={cn("flex w-full items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-body transition-colors",
navKey === n.key ? "bg-brand/10 font-medium text-brand" : "text-muted hover:bg-ink/5 hover:text-ink",
sidebarCollapsed && "justify-center px-0")}>
<span className="relative">{n.icon}
{n.key === "inbox" && inboxTotal > 0 && sidebarCollapsed && <i className="absolute -right-1 -top-1 h-2 w-2 rounded-full bg-bad" />}
</span>
{!sidebarCollapsed && <span className="flex-1 truncate text-left">{n.label}</span>}
{!sidebarCollapsed && n.key === "inbox" && inboxTotal > 0 && <Badge tone="bg-bad/10 text-bad">{inboxTotal}</Badge>}
</button>
))}
</div>
)}
</div>
);
})}
</nav>
<div className="space-y-1 border-t border-line p-2">
<button className={cn("flex w-full items-center gap-2.5 rounded-lg px-2.5 py-2 text-body text-muted hover:bg-ink/5", sidebarCollapsed && "justify-center px-0")}
onClick={() => setTheme(theme === "light" ? "dark" : theme === "dark" ? "system" : "light")}>
{THEME_ICON[theme]}
{!sidebarCollapsed && <span>{theme === "light" ? "浅色" : theme === "dark" ? "深色" : "跟随系统"}</span>}
</button>
<button className={cn("flex w-full items-center gap-2.5 rounded-lg px-2.5 py-2 text-body text-muted hover:bg-ink/5", sidebarCollapsed && "justify-center px-0")}
onClick={() => { if (window.matchMedia("(max-width: 767px)").matches) setMobileNavOpen(false); else toggleSidebar(); }}>
<ChevronLeft className={cn(I, "transition-transform", sidebarCollapsed && "rotate-180")} />
{!sidebarCollapsed && <span>收起</span>}
</button>
</div>
</aside>
<div className="flex min-w-0 flex-1 flex-col">
<header className="flex h-14 shrink-0 items-center gap-3 border-b border-line bg-surface px-4">
<button className="btn btn-ghost btn-sm -ml-1 shrink-0 md:hidden" onClick={() => setMobileNavOpen(true)} aria-label="打开导航">
<Menu className={I} />
</button>
<div className="min-w-0">
<h1 className="text-section font-semibold leading-tight">{current.label}</h1>
</div>
<div className="ml-auto flex items-center gap-2">
{!online && <Badge tone="bg-bad/10 text-bad">服务未就绪</Badge>}
{counts && counts.approvals > 0 && (
<button onClick={() => go("inbox", { tab: "approvals" })}>
<Badge tone="bg-warn/10 text-warn"><ClipboardCheck className="h-3 w-3" />{counts.approvals} 张等我审批</Badge>
</button>
)}
{/* 开发环境 / 演示版本:每个演示版本是一份独立冻结的数据,只露出保存时勾选的菜单 */}
<EnvMenu envs={envList?.envs ?? []} nextId={envList?.next_id ?? "v1"} env={env} demo={demo}
admin={!!me?.roles?.includes("admin")} />
<UserMenu me={me} users={users} uid={uid} />
</div>
</header>
<main className={cn("min-h-0 flex-1 p-5", fullBleed ? "overflow-hidden" : "overflow-auto")}>
{/* 切换身份时整页重挂,所有数据按新身份重新加载;每页独立的错误边界,一页出错不影响别的页 */}
<div key={`${uid}@${ws}`} className="h-full">
<PageErrorBoundary resetKey={page} onHome={() => go("desk")}>
{page === "desk" && <DeskPage me={me} builder={builder} />}
{page === "data" && <SqlPage me={me} />}
{page === "documents" && <DocumentsPage onExtracted={refresh} />}
{page === "modeling" && <ModelingPage me={me} />}
{page === "publish" && <ReleaseHub me={me} />}
{page === "canvas" && <CanvasPage me={me} />}
{page === "b_object" && <BlockListPage key="o" kind="object_type" me={me} />}
{page === "b_link" && <BlockListPage key="l" kind="link_type" me={me} />}
{page === "b_function" && <BlockListPage key="f" kind="function" me={me} />}
{page === "b_action" && <BlockListPage key="a" kind="action" me={me} />}
{page === "b_value" && <BlockListPage key="v" kind="value_type" me={me} />}
{page === "sop" && <SopPage me={me} />}
{page === "ask" && <AskPage />}
{page === "objects" && <ObjectsPage me={me} />}
{page === "inbox" && <InboxPage onChanged={refresh} />}
{page === "memory" && <MemoryPage me={me} />}
{page === "monitor" && <MonitorPage />}
{page === "mcp" && <McpPage />}
{page === "watch" && <WatchPage me={me} />}
{page === "alerts" && <AlertsPage />}
{page === "members" && <MembersPage me={me} />}
{page === "eval" && <EvalPage me={me} />}
{page === "settings" && <SettingsPage onChanged={refresh} />}
</PageErrorBoundary>
</div>
</main>
</div>
<Toaster />
<DialogHost />
</div>
);
}
/**
* 右上角的「我」:当前是谁、有什么角色。
* 没有接登录体系之前,身份靠这里切换(演示与验收用)—— 收进菜单里,不再是页头上一个醒目的下拉框。
*/
/** 右上角的环境切换:开发环境 ↔ 各演示版本;管理员可在这里保存、编辑、重置、删除演示版本。 */
function EnvMenu({ envs, nextId, env, demo, admin }: {
envs: DemoEnv[]; nextId: string; env: DemoEnv | null; demo: boolean; admin: boolean;
}) {
const [open, setOpen] = useState(false);
const [editing, setEditing] = useState<DemoEnv | "new" | null>(null);
const [busy, setBusy] = useState(false);
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!open) return;
const on = (e: MouseEvent) => { if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false); };
document.addEventListener("mousedown", on);
return () => document.removeEventListener("mousedown", on);
}, [open]);
const current = demo ? env?.id ?? "" : DEV;
const reset = async () => {
if (!env) return;
setOpen(false);
if (!(await confirmDialog(`把「演示 ${env.id}」恢复到保存时的样子?`, {
desc: "演示中新增的提问、审批、写回记录都会清掉,回到这个版本保存那一刻的数据。开发环境不受影响。", danger: true }))) return;
setBusy(true);
try { await envApi.reset(env.id); toast("ok", `演示 ${env.id} 已重置`); window.location.reload(); }
catch (e) { toast("error", "重置失败", (e as Error).message); }
finally { setBusy(false); }
};
const remove = async (e: DemoEnv) => {
setOpen(false);
if (!(await confirmDialog(`删除「演示 ${e.id} · ${e.label}」?`, {
desc: "会删掉这个版本的两个库(演示库和底稿)以及复制的数据目录,不可恢复。", danger: true }))) return;
setBusy(true);
try { await envApi.remove(e.id); toast("ok", `演示 ${e.id} 已删除`); window.location.reload(); }
catch (err) { toast("error", "删除失败", (err as Error).message); }
finally { setBusy(false); }
};
return (
<div ref={ref} className="relative">
<button className={cn("btn btn-sm shrink-0", demo ? "bg-brand/10 text-brand hover:bg-brand/15" : "btn-ghost")}
onClick={() => setOpen((v) => !v)} aria-haspopup="menu" aria-expanded={open}
title={demo ? `演示 ${env?.id ?? ""}:${env?.label ?? ""}(独立数据,操作不影响开发环境)` : "开发环境:完整功能与开发数据"}>
{busy ? <Spinner className="h-4 w-4" /> : demo ? <Presentation className={I} /> : <Hammer className={I} />}
<span className="max-sm:hidden">{demo ? `演示 ${env?.id ?? ""}` : "开发环境"}</span>
<ChevronDown className="h-3.5 w-3.5 opacity-70" />
</button>
{open && (
<div role="menu" className="card absolute right-0 top-full z-50 mt-1 w-80 p-1.5 animate-fade-up">
<p className="px-2 pb-1 pt-0.5 text-caption leading-snug text-muted">
切换环境。每个演示版本是一份冻结的独立数据,在里面操作不会影响开发环境。
</p>
<button role="menuitem" onClick={() => current !== DEV && switchEnv(DEV)}
className={cn("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-label hover:bg-ink/5",
current === DEV && "bg-brand/10 text-brand")}>
<Hammer className="h-3.5 w-3.5 shrink-0" />
<span className="min-w-0 flex-1">开发环境<span className="ml-1 text-caption text-muted">完整功能</span></span>
{current === DEV && <Check className="h-3.5 w-3.5" />}
</button>
<div className="max-h-72 overflow-auto">
{envs.map((e) => (
<div key={e.id} className={cn("group flex items-center gap-1 rounded-md hover:bg-ink/5", current === e.id && "bg-brand/10 text-brand")}>
<button role="menuitem" className="flex min-w-0 flex-1 items-center gap-2 px-2 py-1.5 text-left text-label"
onClick={() => current !== e.id && switchEnv(e.id)}
title={`库 ${e.db_name};代码 ${e.git_commit || "—"};${e.created_at} 由 ${e.created_by || "—"} 保存${e.reset_at ? `;${e.reset_at} 重置过` : ""}`}>
<Presentation className="h-3.5 w-3.5 shrink-0" />
<span className="min-w-0 flex-1">
<span className="block truncate">演示 {e.id} · {e.label}</span>
<span className="block text-caption text-muted">{e.created_at.slice(0, 16)} · {e.nav.length} 个菜单</span>
</span>
{current === e.id && <Check className="h-3.5 w-3.5 shrink-0" />}
</button>
{admin && (
<span className="flex shrink-0 pr-1 opacity-0 group-hover:opacity-100 focus-within:opacity-100">
<button className="btn btn-ghost btn-sm px-1.5" title="改说明与菜单" onClick={() => { setOpen(false); setEditing(e); }}>
<Pencil className="h-3.5 w-3.5" />
</button>
{current !== e.id && (
<button className="btn btn-ghost btn-sm px-1.5 text-bad" title="删除这个演示版本" onClick={() => void remove(e)}>
<Trash2 className="h-3.5 w-3.5" />
</button>
)}
</span>
)}
</div>
))}
{!envs.length && <p className="px-2 py-1.5 text-label text-muted">还没有演示版本</p>}
</div>
{admin && (
<div className="mt-1 border-t border-line pt-1">
{!demo && (
<button role="menuitem" className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-label hover:bg-ink/5"
onClick={() => { setOpen(false); setEditing("new"); }}>
<Plus className="h-3.5 w-3.5" />保存当前数据为演示版本({nextId})…
</button>
)}
{demo && env && (
<button role="menuitem" className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-label hover:bg-ink/5"
onClick={() => void reset()}>
<RotateCcw className="h-3.5 w-3.5" />重置本版本数据(回到保存时)
</button>
)}
</div>
)}
</div>
)}
{editing && <EnvEditor target={editing} nextId={nextId} onClose={() => setEditing(null)} />}
</div>
);
}
/** 保存 / 编辑演示版本:说明 + 对外展示哪些菜单。编号自动递增,不用手填。 */
function EnvEditor({ target, nextId, onClose }: { target: DemoEnv | "new"; nextId: string; onClose: () => void }) {
const isNew = target === "new";
const [label, setLabel] = useState(isNew ? "" : target.label);
const [nav, setNav] = useState<Set<string>>(() => new Set(isNew ? DEFAULT_DEMO_NAV : target.nav));
const [saving, setSaving] = useState(false);
const toggle = (k: string) => setNav((s) => { const n = new Set(s); if (n.has(k)) n.delete(k); else n.add(k); return n; });
const save = async () => {
if (!nav.size) { toast("error", "至少勾选一个菜单"); return; }
setSaving(true);
const keys = ALL.map((n) => n.key).filter((k) => nav.has(k));
try {
if (isNew) {
const e = await envApi.create(label.trim(), keys);
toast("ok", `已保存为演示 ${e.id}`, "在右上角切换过去即可演示");
} else {
await envApi.update(target.id, { label: label.trim(), nav: keys });
toast("ok", `演示 ${target.id} 已更新`);
}
window.location.reload();
} catch (e) {
toast("error", "保存失败", (e as Error).message);
setSaving(false);
}
};
return (
<Modal open onClose={onClose} width="max-w-2xl"
title={isNew ? `保存为演示版本 ${nextId}` : `编辑演示 ${target.id}`}
desc={isNew
? "把开发环境此刻的全部数据(本体、流程卡、审批、问答、demo 业务表、知识库)冻结成一个独立的库。之后在开发环境继续改,不会影响这个版本。"
: "修改说明和对外展示的菜单,数据不变。"}
footer={<>
<button className="btn btn-ghost" onClick={onClose} disabled={saving}>取消</button>
<button className="btn btn-primary" onClick={() => void save()} disabled={saving}>
{saving && <Spinner className="h-4 w-4" />}{isNew && saving ? "正在复制数据…" : "保存"}
</button>
</>}>
<label className="block text-label font-medium" htmlFor="env-label">说明</label>
<input id="env-label" className="input mt-1 w-full" value={label} onChange={(e) => setLabel(e.target.value)} autoFocus
placeholder="例如:9/30 领导汇报 · 问数 + 流程卡闭环" />
<div className="mt-4 flex items-center justify-between">
<span className="text-label font-medium">对外展示的菜单</span>
<span className="text-caption text-muted">已选 {nav.size} 项 · 没选的只是收起,URL 仍可直达</span>
</div>
<div className="mt-2 grid gap-3 sm:grid-cols-2">
{NAV.map((g) => (
<div key={g.group || "_"}>
<p className="mb-1 text-caption text-muted">{g.group || "常用"}</p>
{g.items.map((n) => (
<label key={n.key} className="flex cursor-pointer items-center gap-2 rounded-md px-1.5 py-1 text-label hover:bg-ink/5">
<input type="checkbox" checked={nav.has(n.key)} onChange={() => toggle(n.key)} />
{n.icon}<span>{n.label}</span>
</label>
))}
</div>
))}
</div>
</Modal>
);
}
function UserMenu({ me, users, uid }: { me: Me | null; users: UserRec[]; uid: string }) {
const [open, setOpen] = useState(false);
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!open) return;
const on = (e: MouseEvent) => { if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false); };
document.addEventListener("mousedown", on);
return () => document.removeEventListener("mousedown", on);
}, [open]);
const name = me?.name || users.find((u) => u.id === uid)?.name || uid;
const ROLE: Record<string, string> = { admin: "管理员", builder: "实施", operator: "业务运营", approver: "审批人", viewer: "只读" };
return (
<div ref={ref} className="relative">
<button className="flex items-center gap-2 rounded-lg px-2 py-1 hover:bg-ink/5" onClick={() => setOpen((v) => !v)}
aria-haspopup="menu" aria-expanded={open}>
<span className="grid h-7 w-7 place-items-center rounded-full bg-brand/15 text-label font-semibold text-brand">{name.slice(0, 1)}</span>
<span className="hidden text-left sm:block">
<span className="block text-label font-medium leading-tight">{name}</span>
<span className="block text-caption leading-tight text-muted">
{(me?.biz_roles?.length ? me.biz_roles : (me?.roles || []).map((r) => ROLE[r] || r)).slice(0, 2).join("、") || "—"}
</span>
</span>
<ChevronDown className="h-3.5 w-3.5 text-muted" />
</button>
{open && (
<div role="menu" className="card absolute right-0 top-full z-50 mt-1 w-64 p-1.5 animate-fade-up">
<p className="px-2 pb-1 pt-0.5 text-caption leading-snug text-muted">切换身份(演示用:审计、审批、数据范围都按所选身份)</p>
<div className="max-h-72 overflow-auto">
{users.map((u) => (
<button key={u.id} role="menuitem"
className={cn("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-label hover:bg-ink/5",
u.id === uid && "bg-brand/10 text-brand")}
onClick={() => { setCurrentUserId(u.id); setOpen(false); }}>
<UserRound className="h-3.5 w-3.5 shrink-0" />
<span className="min-w-0 flex-1 truncate">{u.name}</span>
<span className="shrink-0 text-caption text-muted">{(u.biz_roles.length ? u.biz_roles : u.roles.map((r) => ROLE[r] || r)).slice(0, 1).join("")}</span>
</button>
))}
{!users.length && <p className="px-2 py-1.5 text-label text-muted">没有可切换的成员</p>}
</div>
</div>
)}
</div>
);
}