page.tsx
27.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
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
"use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { ChevronDown, ChevronRight, Download, Eye, FileText, Folder, Pencil, Puzzle, Shield, Upload, X } from "lucide-react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import {
Card,
Drawer,
Field,
GhostButton,
Pagination,
PrimaryButton,
SearchInput,
Select,
SortHeader,
type SortState,
Spinner,
SysPage,
Toolbar,
} from "@/components/system/kit";
import Perm from "@/components/Perm";
import { usePerms } from "@/lib/usePerms";
import { DeptCheckTree } from "@/components/system/OrgTree";
import {
deleteSkill,
downloadSkillUrl,
fetchSkillFile,
fetchSkillTree,
grantSkill,
listSkills,
listSkillGrants,
listSkillOrgTree,
revokeSkill,
toggleSkill,
uploadSkill,
type OaDept,
type SkillGrant,
type SkillItem,
type SkillTreeNode,
} from "@/lib/auth";
const SOURCE_LABEL: Record<string, string> = { md: "MD 文件", zip: "ZIP 包", builtin: "内置" };
function flattenDepts(nodes: OaDept[], depth = 0, out: { id: string; label: string }[] = []) {
for (const n of nodes) {
out.push({ id: n.id, label: `${" ".repeat(depth)}${n.deptName}` });
if (n.children?.length) flattenDepts(n.children, depth + 1, out);
}
return out;
}
export default function SkillsPage() {
const [items, setItems] = useState<SkillItem[]>([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(true);
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(20);
const [enabled, setEnabled] = useState("");
const [granteeDept, setGranteeDept] = useState("");
const [kwInput, setKwInput] = useState("");
const [keyword, setKeyword] = useState("");
const [sort, setSort] = useState<SortState>({ by: "createdAt", order: "asc" });
const [uploading, setUploading] = useState(false);
const [previewSkillItem, setPreviewSkillItem] = useState<SkillItem | null>(null);
const [drawerTarget, setDrawerTarget] = useState<SkillItem | null>(null);
const [deptTree, setDeptTree] = useState<OaDept[]>([]);
const fileRef = useRef<HTMLInputElement>(null);
const { has } = usePerms();
// 点行统一弹出「技能详情」侧边抽屉(预览态):展示名称/描述/来源/启用/已授权部门。
// 非内置且有授权权限时,抽屉里点「编辑」可改部门授权;内置技能只读,不可编辑。
// 正文内容预览统一走行内「查看」按钮或抽屉内「查看内容」。
const onRowClick = (s: SkillItem) => setDrawerTarget(s);
const load = useCallback(async () => {
setLoading(true);
try {
const d = await listSkills({ keyword, enabled, granteeDeptId: granteeDept, sortBy: sort.by, sortOrder: sort.order, limit: pageSize, offset: (page - 1) * pageSize });
setItems(d.items);
setTotal(d.total);
} finally {
setLoading(false);
}
}, [keyword, enabled, granteeDept, sort, page, pageSize]);
useEffect(() => { load(); }, [load]);
useEffect(() => {
listSkillOrgTree().then((d) => setDeptTree(d.items)).catch(() => {});
}, []);
const deptOptions = useMemo(() => flattenDepts(deptTree), [deptTree]);
const apply = () => { setKeyword(kwInput.trim()); setPage(1); };
const onUpload = async (file: File) => {
setUploading(true);
try {
await uploadSkill(file);
await load();
alert("上传成功。技能默认停用,请在列表中开启后生效。");
} catch (e) {
alert(`上传失败:${(e as Error).message}`);
} finally {
setUploading(false);
if (fileRef.current) fileRef.current.value = "";
}
};
const onToggle = async (s: SkillItem) => {
try {
await toggleSkill(s.id);
await load();
} catch (e) {
alert((e as Error).message);
}
};
const onDelete = async (s: SkillItem) => {
if (!confirm(`确认删除技能「${s.name}」?该操作会同时删除其落盘目录。`)) return;
try {
await deleteSkill(s.id);
await load();
} catch (e) {
alert((e as Error).message);
}
};
return (
<SysPage
title="Skills 管理"
subtitle="上传 .md / .zip 技能包,开启后由 Wiki Copilot 按需自动加载使用(管理员操作)。点击任意一行进入部门授权,点「查看」预览技能内容。"
actions={
<Perm code="oa:skill:upload">
<PrimaryButton onClick={() => fileRef.current?.click()} disabled={uploading}>
<Upload className="h-4 w-4" /> {uploading ? "上传中…" : "上传技能"}
</PrimaryButton>
</Perm>
}
>
<input
ref={fileRef}
type="file"
accept=".md,.zip"
className="hidden"
onChange={(e) => { const f = e.target.files?.[0]; if (f) onUpload(f); }}
/>
<Toolbar>
<SearchInput value={kwInput} onChange={setKwInput} onEnter={apply} placeholder="搜索名称 / 描述" className="w-56" />
<Select value={enabled} onChange={(v) => (setEnabled(v), setPage(1))}>
<option value="">全部状态</option>
<option value="1">已启用</option>
<option value="0">已停用</option>
</Select>
<Select value={granteeDept} onChange={(v) => (setGranteeDept(v), setPage(1))}>
<option value="">全部已授权部门</option>
{deptOptions.map((d) => <option key={d.id} value={d.id}>{d.label}</option>)}
</Select>
{(keyword || enabled || granteeDept) && (
<GhostButton onClick={() => (setKwInput(""), setKeyword(""), setEnabled(""), setGranteeDept(""), setPage(1))}>
<X className="h-4 w-4" /> 重置
</GhostButton>
)}
</Toolbar>
<Card>
<div className="min-h-0 flex-1 overflow-auto">
<table className="w-full table-fixed text-sm">
<colgroup>
<col className="w-[18%]" /><col className="w-[32%]" /><col className="w-[8%]" /><col className="w-[6%]" /><col className="w-[8%]" /><col className="w-[16%]" /><col className="w-[12%]" />
</colgroup>
<thead className="sticky top-0 z-10 bg-blue-50/95 text-left backdrop-blur">
<tr className="whitespace-nowrap border-b border-blue-100 text-slate-500">
<SortHeader label="名称" field="name" sort={sort} onSort={(s) => (setSort(s), setPage(1))} />
<th className="px-4 py-2.5 font-semibold">描述</th>
<th className="px-4 py-2.5 font-semibold">来源</th>
<th className="px-4 py-2.5 font-semibold">内置</th>
<th className="px-4 py-2.5 font-semibold">启用</th>
<th className="px-4 py-2.5 font-semibold">已授权部门</th>
<th className="px-4 py-2.5 font-semibold">操作</th>
</tr>
</thead>
<tbody>
{loading ? (
<tr><td colSpan={7}><Spinner /></td></tr>
) : items.length === 0 ? (
<tr><td colSpan={7} className="py-16 text-center text-slate-400">暂无技能</td></tr>
) : (
items.map((s) => (
<tr
key={s.id}
onClick={() => onRowClick(s)}
className="cursor-pointer border-b border-slate-50 transition hover:bg-blue-50/50"
title={s.isBuiltin ? "点击查看内置技能详情" : has("oa:skill:grant") ? "点击查看详情 / 编辑授权" : "点击查看技能详情"}
>
<td className="truncate px-4 py-2.5 font-medium text-slate-700" title={s.name}>
<Puzzle className="mr-1 inline h-3.5 w-3.5 text-blue-400" />{s.name}
</td>
<td className="truncate px-4 py-2.5 text-slate-500" title={s.description ?? ""}>
{(s.description ?? "").split("\n").map((l) => l.trim()).filter(Boolean)[0] || "—"}
</td>
<td className="whitespace-nowrap px-4 py-2.5 text-slate-500">{SOURCE_LABEL[s.sourceType] ?? s.sourceType}</td>
<td className="whitespace-nowrap px-4 py-2.5">
{s.isBuiltin ? <span className="rounded bg-amber-50 px-1.5 py-0.5 text-xs text-amber-600">内置</span> : <span className="text-slate-300">—</span>}
</td>
<td className="whitespace-nowrap px-4 py-2.5" onClick={(e) => e.stopPropagation()}>
{s.isBuiltin ? (
<span className="text-xs text-emerald-600">恒启用</span>
) : (
<Perm code="oa:skill:toggle" fallback={<span className="text-xs text-slate-400">{s.enabled ? "已启用" : "已停用"}</span>}>
<button
onClick={() => onToggle(s)}
className={`inline-flex h-5 w-9 items-center rounded-full px-0.5 transition ${s.enabled ? "bg-blue-600" : "bg-slate-300"}`}
title={s.enabled ? "点击停用" : "点击启用"}
>
<span className={`h-4 w-4 rounded-full bg-white transition ${s.enabled ? "translate-x-4" : ""}`} />
</button>
</Perm>
)}
</td>
<td className="truncate px-4 py-2.5 text-slate-500" title={s.isBuiltin ? "内置技能恒可用,不受部门授权约束" : (s.grantedLabels || []).join("、")}>
{s.isBuiltin
? <span className="text-xs text-emerald-600">全部(内置)</span>
: (s.grantedLabels && s.grantedLabels.length > 0 ? s.grantedLabels.join("、") : "—")}
</td>
<td className="whitespace-nowrap px-4 py-2.5" onClick={(e) => e.stopPropagation()}>
<div className="flex items-center gap-1.5">
<button onClick={() => setPreviewSkillItem(s)} className="rounded px-1.5 py-0.5 text-xs text-blue-600 hover:bg-blue-50">
<Eye className="mr-0.5 inline h-3.5 w-3.5" />查看
</button>
<Perm code="oa:skill:download">
<a href={downloadSkillUrl(s.id)} className="rounded px-1.5 py-0.5 text-xs text-slate-500 hover:bg-slate-100">
<Download className="mr-0.5 inline h-3.5 w-3.5" />下载
</a>
</Perm>
{!s.isBuiltin && (
<Perm code="oa:skill:remove">
<button onClick={() => onDelete(s)} className="rounded px-1.5 py-0.5 text-xs text-rose-500 hover:bg-rose-50">删除</button>
</Perm>
)}
</div>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
<Pagination page={page} pageSize={pageSize} total={total} onPage={setPage} onPageSize={(s) => (setPageSize(s), setPage(1))} />
</Card>
{previewSkillItem && (
<SkillPreview skill={previewSkillItem} onClose={() => setPreviewSkillItem(null)} />
)}
{drawerTarget && (
<SkillDrawer
key={drawerTarget.id}
skill={drawerTarget}
deptTree={deptTree}
canGrant={has("oa:skill:grant")}
onClose={() => setDrawerTarget(null)}
onPreview={() => { setPreviewSkillItem(drawerTarget); setDrawerTarget(null); }}
onSaved={load}
/>
)}
</SysPage>
);
}
/** 从嵌套部门树构建「id → 祖先 id 列表」映射(根在前,不含自身),用于判断继承。 */
function buildAncestorMap(nodes: OaDept[], trail: string[] = [], out = new Map<string, string[]>()) {
for (const n of nodes) {
out.set(n.id, trail);
if (n.children?.length) buildAncestorMap(n.children, [...trail, n.id], out);
}
return out;
}
/** 从嵌套部门树构建「id → 全部后代 id 列表」映射(不含自身),用于计算中心节点的半选态。 */
function buildDescendantMap(nodes: OaDept[], out = new Map<string, string[]>()) {
const walk = (n: OaDept): string[] => {
const all: string[] = [];
for (const c of n.children ?? []) all.push(c.id, ...walk(c));
out.set(n.id, all);
return all;
};
for (const n of nodes) walk(n);
return out;
}
/**
* 技能详情抽屉(统一入口):点行进来默认「预览态」——只读展示名称/描述/来源/启用/已授权部门,
* 与知识库配置抽屉同一套「预览 + 编辑」交互。
* - 非内置且有授权权限:底部「编辑」切到授权编辑态,勾选部门/中心,保存生效;
* - 内置技能:由系统提供,恒启用、全部部门可用,不提供编辑按钮,只读展示;
* - 正文内容预览统一走底部「查看内容」。
*/
function SkillDrawer({
skill,
deptTree,
canGrant,
onClose,
onPreview,
onSaved,
}: {
skill: SkillItem;
deptTree: OaDept[];
canGrant: boolean;
onClose: () => void;
onPreview: () => void;
onSaved: () => void;
}) {
const isBuiltin = skill.isBuiltin;
// 点行进来是预览;点「编辑」才切到授权编辑态(内置技能无编辑)。
const [isEditing, setIsEditing] = useState(false);
const [grants, setGrants] = useState<SkillGrant[]>([]);
const [loadedOnce, setLoadedOnce] = useState(false);
const [saving, setSaving] = useState(false);
// 内置技能对全部部门可用、不落部门授权,无需拉取 grants。
const reload = useCallback(async () => {
if (isBuiltin) { setLoadedOnce(true); return; }
try {
const d = await listSkillGrants(skill.id);
setGrants(d.items);
} finally {
setLoadedOnce(true);
}
}, [skill.id, isBuiltin]);
useEffect(() => { reload(); }, [reload]);
const ancestorMap = useMemo(() => buildAncestorMap(deptTree), [deptTree]);
const descendantMap = useMemo(() => buildDescendantMap(deptTree), [deptTree]);
const explicitSet = useMemo(
() => new Set(grants.filter((g) => g.granteeType === "dept").map((g) => g.granteeId)),
[grants]
);
const grantIdBy = useMemo(() => {
const m = new Map<string, string>();
grants.filter((g) => g.granteeType === "dept").forEach((g) => m.set(g.granteeId, g.id));
return m;
}, [grants]);
// 预览态「已授权部门」标签:直接从最新 grants 取,保存后即时刷新
const grantedDepts = useMemo(() => grants.filter((g) => g.granteeType === "dept"), [grants]);
const [pendingExplicit, setPendingExplicit] = useState<Set<string>>(new Set());
useEffect(() => { setPendingExplicit(new Set(explicitSet)); }, [explicitSet]);
const hasGrantedAncestor = useCallback(
(id: string) => (ancestorMap.get(id) ?? []).some((a) => pendingExplicit.has(a)),
[ancestorMap, pendingExplicit]
);
const { selected, disabledIds } = useMemo(() => {
const sel = new Set<string>(pendingExplicit);
const dis = new Set<string>();
for (const id of ancestorMap.keys()) {
if (pendingExplicit.has(id)) continue;
if (hasGrantedAncestor(id)) { sel.add(id); dis.add(id); }
}
return { selected: sel, disabledIds: dis };
}, [pendingExplicit, ancestorMap, hasGrantedAncestor]);
const partialIds = useMemo(() => {
const s = new Set<string>();
for (const [id, descs] of descendantMap) {
if (!selected.has(id) && descs.some((d) => selected.has(d))) s.add(id);
}
return s;
}, [descendantMap, selected]);
const badgeOf = useCallback((id: string): string | undefined => {
if (pendingExplicit.has(id)) return "已授权";
if (disabledIds.has(id)) return "继承自上级";
return undefined;
}, [pendingExplicit, disabledIds]);
const onTogglePending = (id: string) => {
setPendingExplicit((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id); else next.add(id);
return next;
});
};
const toAdd = useMemo(() => [...pendingExplicit].filter((id) => !explicitSet.has(id)), [pendingExplicit, explicitSet]);
const toRemove = useMemo(() => [...explicitSet].filter((id) => !pendingExplicit.has(id)), [explicitSet, pendingExplicit]);
const dirty = toAdd.length > 0 || toRemove.length > 0;
const onSave = async () => {
if (saving || !dirty) return;
setSaving(true);
try {
if (toAdd.length) await grantSkill(skill.id, toAdd);
for (const id of toRemove) {
const gid = grantIdBy.get(id);
if (gid) await revokeSkill(skill.id, gid);
}
await reload();
setIsEditing(false);
onSaved();
} catch (e) {
alert((e as Error).message);
} finally {
setSaving(false);
}
};
const onCancelEdits = () => { setPendingExplicit(new Set(explicitSet)); setIsEditing(false); };
const handleClose = () => {
if (dirty && !confirm("有未保存的授权改动,确认放弃吗?")) return;
onClose();
};
const desc = (skill.description ?? "").split("\n").map((l) => l.trim()).filter(Boolean).join(" ") || "—";
return (
<Drawer
open
onClose={handleClose}
title={<><Shield className="mr-1 inline h-4 w-4 text-blue-500" />{skill.name} · {isEditing ? "使用授权" : "技能详情"}</>}
subtitle={
isEditing
? `勾选部门 / 中心,点击「保存」后生效;授某中心 = 其下全部部门可用${dirty ? `(${toAdd.length + toRemove.length} 项待保存)` : ""}`
: isBuiltin
? "内置技能:由系统提供,恒启用、全部部门可用,不可编辑 / 删除 / 授权。"
: "预览详情;点击「编辑」后可修改部门授权。"
}
footer={
isEditing ? (
<>
<GhostButton onClick={onCancelEdits} disabled={saving}>取消</GhostButton>
<PrimaryButton onClick={onSave} disabled={!dirty || saving}>
{saving ? "保存中…" : "保存"}
</PrimaryButton>
</>
) : (
<>
{isBuiltin && <span className="mr-auto self-center text-xs text-slate-400">内置技能不可编辑</span>}
<GhostButton onClick={onPreview}>
<Eye className="h-4 w-4" /> 查看内容
</GhostButton>
{!isBuiltin && canGrant && (
<PrimaryButton onClick={() => setIsEditing(true)}>
<Pencil className="h-4 w-4" /> 编辑
</PrimaryButton>
)}
</>
)
}
>
{/* 名称/描述/来源/启用状态:预览与编辑两态共用(编辑态下为只读上下文,避免只露授权树太突兀);
仅「已授权部门」一项随模式切换——预览为标签,编辑为可勾选的部门授权树。 */}
<div>
<Field label="名称">{skill.name}</Field>
<Field label="描述">{desc}</Field>
<Field label="来源">
{isBuiltin
? <span className="rounded bg-amber-50 px-1.5 py-0.5 text-xs text-amber-600">内置</span>
: <span className="text-slate-700">{SOURCE_LABEL[skill.sourceType] ?? skill.sourceType}</span>}
</Field>
<Field label="启用状态">
{isBuiltin
? <span className="text-xs text-emerald-600">恒启用</span>
: <span className={skill.enabled ? "text-xs text-emerald-600" : "text-xs text-slate-400"}>{skill.enabled ? "已启用" : "已停用"}</span>}
</Field>
{isEditing ? (
<div className="pt-3">
<div className="mb-1 text-xs font-medium text-slate-500">
部门授权
{dirty && <span className="ml-1.5 text-[11px] font-normal text-amber-500">({toAdd.length + toRemove.length} 项未保存)</span>}
</div>
<p className="mb-2 text-[11px] leading-relaxed text-slate-400">
勾选/取消先在本地暂存,点击「保存」才提交生效。授某中心 = 其下全部部门自动继承(显示为「继承自上级」
且锁定,需在该中心节点取消)。未授权的部门在 Wiki Copilot 中看不到、也用不了该技能。
</p>
<div className={`max-h-[50vh] overflow-auto rounded-lg border border-slate-200 p-2 ${saving ? "pointer-events-none opacity-60" : ""}`}>
{!loadedOnce ? (
<div className="py-6 text-center text-xs text-slate-400">加载中…</div>
) : (
<DeptCheckTree
nodes={deptTree}
selected={selected}
onToggle={onTogglePending}
disabledIds={disabledIds}
badgeOf={badgeOf}
partialIds={partialIds}
/>
)}
</div>
</div>
) : (
<Field label="已授权部门">
{isBuiltin ? (
<span className="text-xs text-emerald-600">全部部门(内置,无需授权)</span>
) : !loadedOnce ? (
<span className="text-xs text-slate-400">加载中…</span>
) : grantedDepts.length === 0 ? (
<span className="text-xs text-slate-400">未授权任何部门</span>
) : (
<div className="flex flex-wrap gap-1.5">
{grantedDepts.map((g) => (
<span key={g.id} className="rounded-full border border-blue-200 bg-blue-50 px-2 py-0.5 text-xs text-blue-600">
{g.granteeLabel || "—"}
</span>
))}
</div>
)}
</Field>
)}
</div>
</Drawer>
);
}
/** 拆分 Markdown 顶部的 YAML frontmatter(--- ... ---)与正文。
* frontmatter 单独返回(去掉包裹的 --- 分隔线),用于以朴素元信息头渲染;body 为剩余正文。 */
function splitFrontmatter(text: string): { frontmatter: string; body: string } {
const m = text.match(/^?---\r?\n([\s\S]*?)\r?\n---\r?\n?/);
if (!m) return { frontmatter: "", body: text };
return { frontmatter: m[1].trim(), body: text.slice(m[0].length) };
}
/** 全屏预览:左侧可折叠目录树 + 右侧 Markdown 渲染(仿「Wiki 仓库相关文件」,Typora 风格)。 */
function SkillPreview({ skill, onClose }: { skill: SkillItem; onClose: () => void }) {
const [tree, setTree] = useState<SkillTreeNode[]>([]);
const [activePath, setActivePath] = useState<string>("");
const [content, setContent] = useState<string>("");
const [loadingFile, setLoadingFile] = useState(false);
const openFile = useCallback(async (path: string) => {
setActivePath(path);
setContent("");
setLoadingFile(true);
try {
setContent(await fetchSkillFile(skill.id, path));
} catch {
setContent("(读取失败)");
} finally {
setLoadingFile(false);
}
}, [skill.id]);
useEffect(() => {
fetchSkillTree(skill.id)
.then((d) => {
setTree(d.tree);
// 默认打开 SKILL.md
const findMd = (nodes: SkillTreeNode[]): string | null => {
for (const n of nodes) {
if (n.type === "file" && n.name === "SKILL.md") return n.path;
if (n.children) { const r = findMd(n.children); if (r) return r; }
}
return null;
};
const md = findMd(d.tree) || (d.tree.find((n) => n.type === "file")?.path ?? "");
if (md) openFile(md);
})
.catch(() => {});
}, [skill.id, openFile]);
useEffect(() => {
const h = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
window.addEventListener("keydown", h);
return () => window.removeEventListener("keydown", h);
}, [onClose]);
const isMd = activePath.toLowerCase().endsWith(".md");
return (
<div className="fixed inset-0 z-50 flex flex-col bg-slate-900/50 p-6" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
<div className="mx-auto flex h-full w-full max-w-6xl flex-col overflow-hidden rounded-2xl bg-white shadow-2xl">
<header className="flex shrink-0 items-center justify-between gap-3 border-b border-blue-100 bg-gradient-to-r from-blue-50 to-white px-6 py-4">
<div className="flex items-center gap-2">
<Puzzle className="h-5 w-5 text-blue-500" />
<div>
<div className="text-base font-semibold text-slate-800">{skill.name}</div>
<div className="text-xs text-slate-500">{SOURCE_LABEL[skill.sourceType] ?? skill.sourceType} · 技能内容预览</div>
</div>
</div>
<button onClick={onClose} className="rounded-lg p-1.5 text-slate-400 transition hover:bg-slate-100 hover:text-slate-600">
<X className="h-5 w-5" />
</button>
</header>
<div className="flex min-h-0 flex-1">
<aside className="w-64 shrink-0 overflow-y-auto border-r border-slate-100 bg-slate-50/50 p-2">
{tree.length === 0 ? (
<div className="p-4 text-center text-xs text-slate-400">加载中…</div>
) : (
tree.map((n) => (
<SkillTreeItem key={n.path} node={n} level={0} activePath={activePath} onOpen={openFile} />
))
)}
</aside>
<main className="min-w-0 flex-1 overflow-y-auto bg-white p-8">
{loadingFile ? (
<div className="flex h-full items-center justify-center"><Spinner /></div>
) : isMd ? (
(() => {
const { frontmatter, body } = splitFrontmatter(content);
return (
<>
{frontmatter && (
<div className="mb-6">
<div className="mb-1.5 text-xs font-medium text-slate-400">技能元信息(front-matter)</div>
<pre className="overflow-x-auto whitespace-pre-wrap break-words rounded-lg border border-slate-200 bg-slate-100 p-3 font-mono text-xs leading-relaxed text-slate-800">{frontmatter}</pre>
</div>
)}
<article className="prose prose-slate max-w-none prose-a:text-blue-600 prose-pre:rounded-xl prose-pre:bg-slate-900 prose-table:text-sm">
<ReactMarkdown remarkPlugins={[remarkGfm]}>{body}</ReactMarkdown>
</article>
</>
);
})()
) : (
<pre className="whitespace-pre-wrap break-words rounded-xl bg-slate-50 p-4 text-xs leading-relaxed text-slate-700">{content}</pre>
)}
</main>
</div>
</div>
</div>
);
}
/** 可折叠的技能目录树节点:目录点击展开/收起,文件点击预览。 */
function SkillTreeItem({
node,
level,
activePath,
onOpen,
}: {
node: SkillTreeNode;
level: number;
activePath: string;
onOpen: (path: string) => void;
}) {
const isDir = node.type === "dir";
const [open, setOpen] = useState(true);
return (
<div>
<button
onClick={() => (isDir ? setOpen((o) => !o) : onOpen(node.path))}
style={{ paddingLeft: `${level * 14 + 8}px` }}
className={`flex w-full items-center gap-1 rounded-lg py-1.5 pr-2 text-left text-sm transition ${
isDir
? "font-medium text-slate-500 hover:bg-slate-100"
: activePath === node.path
? "bg-blue-100 text-blue-700"
: "text-slate-600 hover:bg-slate-100"
}`}
>
{isDir ? (
open ? <ChevronDown className="h-3.5 w-3.5 shrink-0 text-slate-400" /> : <ChevronRight className="h-3.5 w-3.5 shrink-0 text-slate-400" />
) : (
<span className="inline-block w-3.5 shrink-0" />
)}
{isDir ? <Folder className="h-4 w-4 shrink-0 text-blue-400" /> : <FileText className="h-4 w-4 shrink-0 text-slate-400" />}
<span className="truncate">{node.name}</span>
</button>
{isDir && open && node.children && node.children.length > 0 && (
<div>
{node.children.map((c) => (
<SkillTreeItem key={c.path} node={c} level={level + 1} activePath={activePath} onOpen={onOpen} />
))}
</div>
)}
</div>
);
}