GraphPage.tsx 12.2 KB
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>
  );
}