RelationGraph.tsx 11.1 KB
/**
 * 表关系图:每张表一个卡片,列出主键和参与关联的字段;关联画成「字段 → 字段」的连线。
 * 从一个字段拖到另一张表的字段就新建一条关联;点连线可以删除。
 */
import {
  Background, ConnectionMode, Controls, Handle, MarkerType, Position, ReactFlow, applyNodeChanges,
  type Connection, type Edge, type Node, type NodeChange, type NodeProps,
} from "@xyflow/react";
import "@xyflow/react/dist/style.css";
import Graph from "graphology";
import circular from "graphology-layout/circular";
import forceAtlas2 from "graphology-layout-forceatlas2";
import noverlap from "graphology-layout-noverlap";
import { KeyRound, Trash2 } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { api } from "@/lib/api";
import { cn } from "@/lib/utils";
import { toast } from "@/store/useAppStore";
import type { SmModel, SmRelation } from "@/lib/types";

type TData = { model: SmModel; fields: { name: string; type: string; pk: boolean; linked: boolean }[]; onOpen: (id: number) => void; isolated: boolean };

const ROW = 22;

function TableNode({ data }: NodeProps<Node<TData>>) {
  const m = data.model;
  return (
    <div className={cn("w-[230px] overflow-hidden rounded-lg border border-line bg-surface shadow-sm", data.isolated && "opacity-60")}>
      <button className="block w-full border-b border-line bg-brand/[0.06] px-2.5 py-1.5 text-left"
              title={`${m.description || m.physical_table}${data.isolated ? "(没有任何关联)" : ""} · 双击查看字段`}
              onDoubleClick={() => data.onOpen(m.id)}>
        <span className="block truncate font-mono text-label font-semibold">{m.physical_table}</span>
        {m.description && <span className="block truncate text-caption text-muted">{m.description}</span>}
      </button>
      {data.fields.map((f) => (
        <div key={f.name} className={cn("relative flex items-center gap-1.5 px-2.5 font-mono text-caption",
          f.linked && "bg-ok/[0.06]")} style={{ height: ROW }}>
          <Handle id={`${f.name}|l`} type="source" position={Position.Left}
                  className="!h-2 !w-2 !border-0 !bg-brand/50" />
          {f.pk ? <KeyRound className="h-3 w-3 shrink-0 text-warn" /> : <span className="w-3 shrink-0" />}
          <span className={cn("min-w-0 flex-1 truncate", f.linked && "font-semibold")}>{f.name}</span>
          <span className="max-w-[70px] shrink-0 truncate text-muted">{f.type}</span>
          <Handle id={`${f.name}|r`} type="source" position={Position.Right}
                  className="!h-2 !w-2 !border-0 !bg-brand/50" />
        </div>
      ))}
    </div>
  );
}
const nodeTypes = { table: TableNode };

const posKey = (dsId: number) => `relgraph.pos.${dsId}`;
function loadPos(dsId: number): Record<string, { x: number; y: number }> {
  try { return JSON.parse(localStorage.getItem(posKey(dsId)) || "{}"); } catch { return {}; }
}

export function RelationGraph({ dsId, models: allModels, relations: allRelations, onChanged, onOpenTable, focusId, onFocus }: {
  dsId: number; models: SmModel[]; relations: SmRelation[];
  onChanged: () => void; onOpenTable: (modelId: number) => void;
  /** 只看这张表和直接关联到它的表;null = 全部 */
  focusId: number | null; onFocus: (id: number | null) => void;
}) {
  const [showAll, setShowAll] = useState(false);
  const [picked, setPicked] = useState<SmRelation | null>(null);

  // 几十张表时整张图看不清:聚焦某张表,只留它和它的直接邻居
  const { models, relations } = useMemo(() => {
    if (focusId === null || !allModels.some((m) => m.id === focusId)) return { models: allModels, relations: allRelations };
    const rels = allRelations.filter((r) => r.from_model_id === focusId || r.to_model_id === focusId);
    const ids = new Set<number>([focusId]);
    rels.forEach((r) => { ids.add(r.from_model_id); ids.add(r.to_model_id); });
    return { models: allModels.filter((m) => ids.has(m.id)), relations: rels };
  }, [allModels, allRelations, focusId]);

  const layout = useMemo(() => {
    const saved = loadPos(dsId);
    const g = new Graph({ multi: true });
    models.forEach((m) => g.addNode(String(m.id), { size: 10 }));
    relations.forEach((r) => {
      const a = String(r.from_model_id), b = String(r.to_model_id);
      if (g.hasNode(a) && g.hasNode(b) && a !== b) g.addEdge(a, b);
    });
    circular.assign(g, { scale: 500 });
    if (g.order > 2) {
      forceAtlas2.assign(g, { iterations: 300, settings: { ...forceAtlas2.inferSettings(g), gravity: 2, scalingRatio: 8 } });
      noverlap.assign(g, { maxIterations: 300, settings: { margin: 60, ratio: 1.2 } });
    }
    const pts = models.map((m) => g.getNodeAttributes(String(m.id)) as { x: number; y: number });
    const xs = pts.map((p) => p.x), ys = pts.map((p) => p.y);
    const [x0, x1, y0, y1] = [Math.min(...xs), Math.max(...xs), Math.min(...ys), Math.max(...ys)];
    const side = Math.ceil(Math.sqrt(models.length));
    // 卡片约 230 宽、100~200 高:按这个尺度铺开,fitView 后字还看得清
    const W = 270 * side, H = 190 * side;
    const fit = (v: number, lo: number, hi: number, span: number) => (hi > lo ? ((v - lo) / (hi - lo)) * span : span / 2);
    return Object.fromEntries(models.map((m, i) => [String(m.id),
      saved[String(m.id)] ?? { x: fit(pts[i].x, x0, x1, W), y: fit(pts[i].y, y0, y1, H) }]));
  }, [dsId, models, relations]);

  const buildNodes = useCallback((): Node<TData>[] => {
    const linked = new Map<number, Set<string>>();
    relations.forEach((r) => {
      if (!linked.has(r.from_model_id)) linked.set(r.from_model_id, new Set());
      if (!linked.has(r.to_model_id)) linked.set(r.to_model_id, new Set());
      linked.get(r.from_model_id)!.add(r.from_column);
      linked.get(r.to_model_id)!.add(r.to_column);
    });
    return models.map((m) => {
      const pk = new Set((m.primary_key || "").split(",").map((x) => x.trim()).filter(Boolean));
      const lk = linked.get(m.id) ?? new Set<string>();
      let cols = m.columns.filter((c) => showAll || pk.has(c.name) || lk.has(c.name));
      if (!cols.length) cols = m.columns.slice(0, 3);
      return {
        id: String(m.id), type: "table", position: layout[String(m.id)],
        data: { model: m, onOpen: onOpenTable, isolated: lk.size === 0,
                fields: cols.map((c) => ({ name: c.name, type: c.data_type.replace(/\(.*\)/, ""), pk: pk.has(c.name), linked: lk.has(c.name) })) },
      };
    });
  }, [models, relations, showAll, layout, onOpenTable]);

  const [nodes, setNodes] = useState<Node<TData>[]>(buildNodes);
  useEffect(() => {
    // 换了显示字段 / 关联变化:保留拖过的位置
    setNodes((cur) => {
      const at = Object.fromEntries(cur.map((n) => [n.id, n.position]));
      return buildNodes().map((n) => ({ ...n, position: at[n.id] ?? n.position }));
    });
  }, [buildNodes]);

  const onNodesChange = (changes: NodeChange<Node<TData>>[]) => setNodes((ns) => {
    const next = applyNodeChanges(changes, ns);
    if (changes.some((c) => c.type === "position" && !c.dragging)) {
      try { localStorage.setItem(posKey(dsId), JSON.stringify(Object.fromEntries(next.map((n) => [n.id, n.position])))); }
      catch { /* 记不住位置不影响使用 */ }
    }
    return next;
  });

  const edges: Edge[] = useMemo(() => relations.map((r) => {
    const a = layout[String(r.from_model_id)], b = layout[String(r.to_model_id)];
    const leftToRight = !a || !b || a.x <= b.x;
    return {
      id: String(r.id), source: String(r.from_model_id), target: String(r.to_model_id),
      sourceHandle: `${r.from_column}|${leftToRight ? "r" : "l"}`, targetHandle: `${r.to_column}|${leftToRight ? "l" : "r"}`,
      type: "default", label: r.cardinality || "N:1",
      labelStyle: { fontSize: 10 }, labelBgPadding: [4, 2] as [number, number],
      style: { strokeWidth: picked?.id === r.id ? 2.5 : 1.5, stroke: picked?.id === r.id ? "#6366f1" : "#64748b" },
      markerEnd: { type: MarkerType.ArrowClosed, width: 14, height: 14 },
    };
  }), [relations, layout, picked]);

  const connect = async (c: Connection) => {
    if (!c.source || !c.target || c.source === c.target) return;
    const [fromCol] = (c.sourceHandle || "").split("|");
    const [toCol] = (c.targetHandle || "").split("|");
    if (!fromCol || !toCol) return;
    try {
      await api.upsertSqlRelation(dsId, { from_model_id: Number(c.source), from_column: fromCol,
                                          to_model_id: Number(c.target), to_column: toCol,
                                          join_type: "inner", cardinality: "N:1" });
      toast("ok", "已新增关联", `${fromCol} → ${toCol}`);
      onChanged();
    } catch (e) { toast("error", "新增失败", e instanceof Error ? e.message : String(e)); }
  };

  const remove = async (r: SmRelation) => {
    try { await api.deleteSqlRelation(r.id); setPicked(null); onChanged(); }
    catch (e) { toast("error", "删除失败", e instanceof Error ? e.message : String(e)); }
  };

  const nameOf = (id: number) => allModels.find((m) => m.id === id)?.physical_table ?? `#${id}`;

  return (
    <div className="card overflow-hidden">
      <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5 border-b border-line px-4 py-2 text-label">
        <h3 className="text-title font-semibold">表关系图</h3>
        <label className="flex items-center gap-1.5 text-muted">
          聚焦
          <select className="input w-auto max-w-[220px] py-1" value={focusId ?? ""}
                  onChange={(e) => { setPicked(null); onFocus(e.target.value ? Number(e.target.value) : null); }}>
            <option value="">全部表</option>
            {allModels.map((m) => <option key={m.id} value={m.id}>{m.physical_table}</option>)}
          </select>
        </label>
        <label className="flex items-center gap-1.5">
          <input type="checkbox" checked={showAll} onChange={(e) => setShowAll(e.target.checked)} />显示全部字段
        </label>
        <span className="text-muted">{models.length} 张表 · {relations.length} 条关联 · 从字段拖到另一张表的字段可新建关联 · 淡色表没有任何关联</span>
        <span className="flex-1" />
        {picked && (
          <span className="flex items-center gap-2">
            <code className="text-label">{nameOf(picked.from_model_id)}.{picked.from_column} → {nameOf(picked.to_model_id)}.{picked.to_column}</code>
            <button className="btn btn-sm text-bad" onClick={() => void remove(picked)}><Trash2 className="h-3.5 w-3.5" />删除这条</button>
          </span>
        )}
      </div>
      <div className="h-[min(62vh,640px)] min-h-[360px]">
        <ReactFlow key={focusId ?? "all"} nodes={nodes} edges={edges} nodeTypes={nodeTypes} onNodesChange={onNodesChange}
                   connectionMode={ConnectionMode.Loose} onConnect={(c) => void connect(c)}
                   onEdgeClick={(_, e) => setPicked(relations.find((r) => String(r.id) === e.id) ?? null)}
                   onPaneClick={() => setPicked(null)}
                   fitView fitViewOptions={{ padding: 0.08 }} minZoom={0.15} proOptions={{ hideAttribution: true }}>
          <Background gap={20} />
          <Controls showInteractive={false} />
        </ReactFlow>
      </div>
    </div>
  );
}