DraftGraph.tsx 7.62 KB
/**
 * 这次草案的关系图:对象是节点、关系是连线(标出名字和基数);已有的对象灰色显示。
 * 节点上列出计算属性 / 状态,边框颜色看它和挂在它上面的函数、动作能不能直接用(绿 = 都能用、黄 = 有还差的)。
 * 点节点 / 连线在右侧看那条草案的详情。
 */
import {
  Background, Controls, Handle, MarkerType, Position, ReactFlow, type Edge, type Node, 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 { useMemo } from "react";
import { Empty } from "@/components/ui";
import { KIND_COLOR, type ModelDraftItem } from "@/lib/onto";
import { cn } from "@/lib/utils";
import type { DraftCtx } from "./DraftDetail";
import { DRAFT_STATE, draftState, itemKind, weakReason } from "./util";

type NData = { name: string; item?: ModelDraftItem; props: number; derived: string[]; fns: number; acts: number;
  weak: number; reqs: number; selected: boolean };

function ObjNode({ data }: NodeProps<Node<NData>>) {
  const st = data.item ? draftState(data.item) : null;
  const color = !data.item ? "#94a3b8" : st === "pending" ? (data.weak ? "#f59e0b" : "#16a34a") : KIND_COLOR.object_type;
  return (
    <div className={cn("min-w-[130px] max-w-[220px] rounded-xl border-2 bg-surface px-2.5 py-1.5 shadow-sm",
      !data.item && "border-dashed opacity-70", data.selected && "ring-2 ring-brand/50")}
         style={{ borderColor: color }}>
      <Handle type="target" position={Position.Left} className="!opacity-0" />
      <p className="break-words text-label font-semibold">{data.name}</p>
      <p className="text-caption text-muted">
        {data.item ? `${data.props} 个属性` : "已有对象"}{data.fns ? ` · 函数 ${data.fns}` : ""}{data.acts ? ` · 动作 ${data.acts}` : ""}
      </p>
      {data.derived.length > 0 && (
        <p className="mt-0.5 line-clamp-2 text-caption text-brand" title={data.derived.join("、")}>算:{data.derived.join("、")}</p>
      )}
      {data.weak > 0 && st === "pending" && <p className="text-caption text-[#b45309]">{data.weak} 条还差点东西</p>}
      {data.reqs > 0 && <p className="text-caption text-muted">落实 {data.reqs} 条文档条目</p>}
      {st && st !== "pending" && <p className={cn("text-caption", st === "live" ? "text-ok" : "text-muted")}>{DRAFT_STATE[st].label}</p>}
      <Handle type="source" position={Position.Right} className="!opacity-0" />
    </div>
  );
}
const nodeTypes = { obj: ObjNode };

export function DraftGraph({ ctx, selected, onSelect }: { ctx: DraftCtx; selected: string; onSelect: (itemId: string) => void }) {
  const { nodes, edges } = useMemo(() => {
    const objs = ctx.items.filter((x) => itemKind(x) === "object_type" && x.status !== "rejected");
    const alias: Record<string, string> = {};
    objs.forEach((o) => [o.payload.name, ...(o.payload.synonyms || [])].forEach((n: string) => { alias[n] = o.payload.name; }));
    const norm = (ref: string) => alias[ctx.objName[ref] || ref] || ctx.objName[ref] || ref;
    const links = ctx.items.filter((x) => itemKind(x) === "link_type" && x.status !== "rejected");
    const names = new Set(objs.map((o) => o.payload.name));
    links.forEach((l) => [l.payload.spec?.from_type, l.payload.spec?.to_type].forEach((r) => { if (r) names.add(norm(r)); }));
    const on = (kind: string, field: string, n: string) =>
      ctx.items.filter((x) => itemKind(x) === kind && x.status !== "rejected" && norm(x.payload?.spec?.[field] || "") === n);
    const count = (kind: string, field: string, n: string) => on(kind, field, n).length;
    // 力导向排一下:连得多的聚在一起,再去掉重叠
    const g = new Graph({ multi: true });
    names.forEach((n) => g.addNode(n, { size: 12 }));
    links.forEach((l) => {
      const a = norm(l.payload.spec?.from_type || ""), b = norm(l.payload.spec?.to_type || "");
      if (g.hasNode(a) && g.hasNode(b) && a !== b) g.addEdge(a, b);
    });
    circular.assign(g, { scale: 400 });
    if (g.order > 2) {
      forceAtlas2.assign(g, { iterations: 300, settings: { ...forceAtlas2.inferSettings(g), gravity: 1, scalingRatio: 10 } });
      noverlap.assign(g, { maxIterations: 200, settings: { margin: 40, ratio: 1.2 } });
    }
    // 力导向的坐标尺度不固定:缩放到一个和节点数相称的框里,免得 fitView 缩得太小、卡片看不清
    const pts = [...names].map((n) => g.getNodeAttributes(n) 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.sqrt(names.size);
    const W = 190 * side, H = 130 * side;
    const fit = (v: number, lo: number, hi: number, span: number) => (hi > lo ? ((v - lo) / (hi - lo)) * span : span / 2);
    const byName: Record<string, ModelDraftItem> = Object.fromEntries(objs.map((o) => [o.payload.name, o]));
    const nodes: Node<NData>[] = [...names].map((n) => {
      const a = g.getNodeAttributes(n) as { x: number; y: number };
      const item = byName[n];
      const related = [...(item ? [item] : []), ...on("function", "object_type", n), ...on("action", "target_type", n)];
      const props: any[] = item?.payload?.spec?.properties || [];
      return { id: n, type: "obj", position: { x: fit(a.x, x0, x1, W), y: fit(a.y, y0, y1, H) },
               data: { name: n, item, props: props.length,
                       derived: props.filter((p) => p.expression).map((p) => p.display_name || p.name),
                       fns: count("function", "object_type", n), acts: count("action", "target_type", n),
                       weak: related.filter((x) => x.status === "pending" && weakReason(x)).length,
                       reqs: new Set(related.flatMap((x) => x.payload?.req_ids || [])).size,
                       selected: !!item && item.id === selected } };
    });
    const edges: Edge[] = links.map((l) => {
      const s = l.payload.spec || {};
      return { id: l.id, source: norm(s.from_type || ""), target: norm(s.to_type || ""),
               label: `${l.payload.name}(${s.cardinality || "?"})`,
               markerEnd: { type: MarkerType.ArrowClosed },
               style: { stroke: l.id === selected ? "#6366f1" : KIND_COLOR.link_type, strokeWidth: l.id === selected ? 2.5 : 1.5 },
               labelStyle: { fontSize: 11 }, labelBgStyle: { fillOpacity: 0.85 } };
    }).filter((e) => names.has(e.source) && names.has(e.target));
    return { nodes, edges };
  }, [ctx, selected]);

  if (!nodes.length) return <Empty title="这次草案里没有对象" />;
  return (
    <div className="relative h-full min-h-[360px]">
      <p className="absolute left-2 top-2 z-10 rounded-md bg-surface/90 px-2 py-1 text-caption text-muted shadow-sm">
        <span className="mr-2"><i className="mr-1 inline-block h-2 w-2 rounded-full bg-[#16a34a]" />都能直接用</span>
        <span className="mr-2"><i className="mr-1 inline-block h-2 w-2 rounded-full bg-[#f59e0b]" />有还差的</span>
        <span><i className="mr-1 inline-block h-2 w-2 rounded-full bg-[#94a3b8]" />已有对象</span></p>
      <ReactFlow nodes={nodes} edges={edges} nodeTypes={nodeTypes} fitView minZoom={0.2} nodesConnectable={false}
                 onNodeClick={(_, n) => { const it = (n.data as NData).item; if (it) onSelect(it.id); }}
                 onEdgeClick={(_, e) => onSelect(e.id)} proOptions={{ hideAttribution: true }}>
        <Background gap={20} />
        <Controls showInteractive={false} />
      </ReactFlow>
    </div>
  );
}