GraphPage.tsx
12.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
import {
Camera, Download, Filter, Maximize, Merge, Minus, Pause, Play, Plus, RefreshCw,
Sparkles, Tag, Type as TypeIcon,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { api } from "@/lib/api";
import { cn } from "@/lib/utils";
import { toast } from "@/store/useAppStore";
import { Badge, Card, ErrorNote, Skeleton } from "@/components/ui";
import type { DocumentItem, GraphPayload, GraphStats, OntologyResponse } from "@/lib/types";
import { DuplicatesPanel } from "./DuplicatesPanel";
import { FilterPanel, type GraphFilters } from "./FilterPanel";
import { NodeSearch } from "./NodeSearch";
import { PropertyPanel, type Selection } from "./PropertyPanel";
import { SigmaGraph, type ColorBy, type LayoutKind, type SigmaGraphHandle } from "./SigmaGraph";
type RightTab = "property" | "filter" | "duplicates";
const COLOR_OPTIONS: { key: ColorBy; label: string }[] = [
{ key: "type", label: "按类型" },
{ key: "community", label: "按社区" },
{ key: "degree", label: "按度数" },
];
const LAYOUT_OPTIONS: { key: LayoutKind; label: string }[] = [
{ key: "forceatlas2", label: "力导向" },
{ key: "circlepack", label: "分组聚集" },
{ key: "circular", label: "环形" },
];
export function GraphPage() {
const sigmaRef = useRef<SigmaGraphHandle>(null);
const [data, setData] = useState<GraphPayload | null>(null);
const [stats, setStats] = useState<GraphStats | null>(null);
const [docs, setDocs] = useState<DocumentItem[]>([]);
const [onto, setOnto] = useState<OntologyResponse | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [filters, setFilters] = useState<GraphFilters>({
types: null, relations: null, docId: null, minDegree: 0, limit: 500,
});
// 滑块拖动时 filters 每帧都在变;真正触发请求的是防抖后的 appliedFilters,
// 否则拖一次「显示上限」会打出几十个请求,还会把图反复重建。
const [appliedFilters, setAppliedFilters] = useState(filters);
useEffect(() => {
const t = setTimeout(() => setAppliedFilters(filters), 280);
return () => clearTimeout(t);
}, [filters]);
const [colorBy, setColorBy] = useState<ColorBy>("type");
const [layout, setLayout] = useState<LayoutKind>("forceatlas2");
const [layoutRunning, setLayoutRunning] = useState(true);
const [showNodeLabels, setShowNodeLabels] = useState(true);
const [showEdgeLabels, setShowEdgeLabels] = useState(false);
const [selection, setSelection] = useState<Selection>(null);
const [rightTab, setRightTab] = useState<RightTab>("property");
const [egoMode, setEgoMode] = useState<{ node: string; hops: number } | null>(null);
const load = useCallback(async () => {
setLoading(true);
setError(null);
try {
const f = appliedFilters;
const [g, s] = await Promise.all([
egoMode
? api.ego(egoMode.node, egoMode.hops, f.limit)
: api.graph({
type: f.types ? [...f.types].join(",") : "",
relation: f.relations ? [...f.relations].join(",") : "",
docId: f.docId, minDegree: f.minDegree, limit: f.limit,
}),
api.graphStats(),
]);
setData(g);
setStats(s);
} catch (e) {
setError(e instanceof Error ? e.message : "图谱加载失败");
} finally {
setLoading(false);
}
}, [appliedFilters, egoMode]);
useEffect(() => { void load(); }, [load]);
useEffect(() => {
void api.documents().then(setDocs).catch(() => undefined);
void api.ontology().then(setOnto).catch(() => undefined);
}, []);
const communities = useMemo(() => stats?.communities ?? [], [stats]);
const empty = !loading && data && data.nodes.length === 0;
const focus = (id: string) => {
setSelection({ kind: "node", id });
setRightTab("property");
sigmaRef.current?.focusNode(id);
};
const expand = (id: string) => {
setEgoMode({ node: id, hops: 1 });
setSelection({ kind: "node", id });
toast("info", `已切换到「${id}」的邻域视图`, "再次双击其他节点可继续展开,点「全图」返回");
};
return (
<div className="flex h-full min-h-0 flex-col gap-3">
{/* 工具条 */}
<Card className="shrink-0 p-2">
<div className="flex flex-wrap items-center gap-2">
<NodeSearch onPick={focus} />
<div className="flex items-center gap-0.5 rounded-lg border border-line p-0.5">
{COLOR_OPTIONS.map((o) => (
<button key={o.key}
className={cn("rounded-md px-2 py-1 text-xs transition-colors",
colorBy === o.key ? "bg-brand text-white" : "text-muted hover:bg-ink/5")}
onClick={() => setColorBy(o.key)}>{o.label}</button>
))}
</div>
<select className="input w-auto py-1 text-xs" value={layout}
onChange={(e) => setLayout(e.target.value as LayoutKind)}>
{LAYOUT_OPTIONS.map((o) => <option key={o.key} value={o.key}>{o.label}</option>)}
</select>
<div className="flex items-center gap-0.5">
<button className={cn("btn btn-sm", showNodeLabels && "btn-primary")}
onClick={() => setShowNodeLabels(!showNodeLabels)} title="节点标签">
<TypeIcon className="h-3.5 w-3.5" />
</button>
<button className={cn("btn btn-sm", showEdgeLabels && "btn-primary")}
onClick={() => setShowEdgeLabels(!showEdgeLabels)} title="关系标签">
<Tag className="h-3.5 w-3.5" />
</button>
<button className="btn btn-sm" onClick={() => {
if (layoutRunning) setLayoutRunning(false);
else { setLayoutRunning(true); sigmaRef.current?.restartLayout(); }
}} title={layoutRunning ? "暂停布局" : "继续布局"}>
{layoutRunning ? <Pause className="h-3.5 w-3.5" /> : <Play className="h-3.5 w-3.5" />}
</button>
</div>
<div className="flex items-center gap-0.5">
<button className="btn btn-sm" onClick={() => sigmaRef.current?.zoomIn()} title="放大">
<Plus className="h-3.5 w-3.5" /></button>
<button className="btn btn-sm" onClick={() => sigmaRef.current?.zoomOut()} title="缩小">
<Minus className="h-3.5 w-3.5" /></button>
<button className="btn btn-sm" onClick={() => sigmaRef.current?.reset()} title="适配视图">
<Maximize className="h-3.5 w-3.5" /></button>
</div>
<div className="ml-auto flex items-center gap-1.5">
{egoMode && (
<button className="btn btn-sm" onClick={() => setEgoMode(null)}>
<RefreshCw className="h-3.5 w-3.5" />返回全图
</button>
)}
<button className="btn btn-sm" onClick={() => sigmaRef.current?.exportPNG("graph.png")} title="导出 PNG">
<Camera className="h-3.5 w-3.5" />
</button>
<a className="btn btn-sm" href={api.exportUrl("json")} title="导出 JSON">
<Download className="h-3.5 w-3.5" />JSON
</a>
<a className="btn btn-sm" href={api.exportUrl("graphml")} title="导出 GraphML">GraphML</a>
<button className="btn btn-sm" onClick={() => void load()} title="刷新">
<RefreshCw className="h-3.5 w-3.5" />
</button>
</div>
</div>
<div className="mt-2 flex flex-wrap items-center gap-1.5 border-t border-line pt-2 text-xs text-muted">
{stats && (
<>
<Badge tone="bg-brand/10 text-brand">{stats.entity_count} 实体</Badge>
<Badge tone="bg-brand2/10 text-brand2">{stats.relation_count} 关系</Badge>
{stats.community_count > 0 && <Badge>{stats.community_count} 社区</Badge>}
<Badge>平均度 {stats.avg_degree}</Badge>
{stats.isolated > 0 && <Badge tone="bg-warn/10 text-warn">{stats.isolated} 孤立点</Badge>}
</>
)}
{egoMode ? (
<span>邻域视图:<b className="text-ink">{egoMode.node}</b> · {egoMode.hops} 跳 · {data?.nodes.length ?? 0} 节点</span>
) : data && (
<span>
当前渲染 <b className="tabular-nums text-ink">{data.nodes.length}</b> / {data.total_matched} 个匹配节点
{data.truncated && "(已按度数截断,可调高显示上限或双击节点展开邻域)"}
</span>
)}
</div>
</Card>
{/* 主体 */}
<div className="grid min-h-0 flex-1 gap-3 lg:grid-cols-[1fr_360px]">
<Card className="relative min-h-[420px] overflow-hidden">
{loading && (
<div className="absolute inset-0 z-20 flex items-center justify-center bg-surface/70 backdrop-blur-[1px]">
<div className="flex flex-col items-center gap-2">
<Skeleton className="h-24 w-24 rounded-full" />
<p className="text-xs text-muted">正在加载图谱…</p>
</div>
</div>
)}
{error && <div className="p-3"><ErrorNote onRetry={load}>{error}</ErrorNote></div>}
{empty && (
<div className="flex h-full flex-col items-center justify-center gap-2 p-6 text-center">
<Sparkles className="h-8 w-8 text-muted/50" />
<p className="text-[14px] font-medium">当前筛选条件下没有节点</p>
<p className="max-w-sm text-xs text-muted">
放宽筛选,或先到「文档」页上传并抽取一份业务文档。
</p>
<button className="btn btn-sm mt-2"
onClick={() => setFilters({ types: null, relations: null, docId: null, minDegree: 0, limit: 500 })}>
重置筛选
</button>
</div>
)}
<SigmaGraph
ref={sigmaRef}
data={data}
colorBy={colorBy}
layout={layout}
layoutRunning={layoutRunning}
showNodeLabels={showNodeLabels}
showEdgeLabels={showEdgeLabels}
selectedNode={selection?.kind === "node" ? selection.id : null}
onSelectNode={(id) => { setSelection(id ? { kind: "node", id } : null); if (id) setRightTab("property"); }}
onSelectEdge={(e) => { setSelection({ kind: "edge", ...e }); setRightTab("property"); }}
onDoubleClickNode={expand}
onLayoutStateChange={setLayoutRunning}
/>
</Card>
<Card className="flex min-h-[420px] flex-col overflow-hidden">
<div className="flex shrink-0 border-b border-line">
{([
{ key: "property", label: "详情", icon: <TypeIcon className="h-3.5 w-3.5" /> },
{ key: "filter", label: "筛选", icon: <Filter className="h-3.5 w-3.5" /> },
{ key: "duplicates", label: "消歧", icon: <Merge className="h-3.5 w-3.5" /> },
] as const).map((t) => (
<button key={t.key}
className={cn("flex flex-1 items-center justify-center gap-1.5 px-3 py-2 text-[13px] transition-colors",
rightTab === t.key
? "border-b-2 border-brand font-medium text-brand"
: "border-b-2 border-transparent text-muted hover:text-ink")}
onClick={() => setRightTab(t.key)}>
{t.icon}{t.label}
</button>
))}
</div>
<div className="min-h-0 flex-1 overflow-hidden">
{rightTab === "property" && (
<PropertyPanel selection={selection} entityTypes={onto?.entity_types ?? []}
onSelect={(s) => { setSelection(s); if (s?.kind === "node") sigmaRef.current?.focusNode(s.id); }}
onExpand={expand} onChanged={load} />
)}
{rightTab === "filter" && (
<FilterPanel stats={stats} documents={docs} filters={filters} onChange={setFilters}
communities={communities} colorBy={colorBy} />
)}
{rightTab === "duplicates" && <DuplicatesPanel onMerged={load} />}
</div>
</Card>
</div>
</div>
);
}