GraphView.tsx 5.76 KB
"use client";

import { useEffect, useRef } from "react";
import type { OntologyNode, OntologyEdge } from "@/lib/ontology-api";

// 节点分组配色:页面类型一组暖/主色,维度节点一组辅助色
const GROUP_COLORS: Record<string, string> = {
  // 页面类型
  entities: "#6366f1",
  products: "#10b981",
  procedures: "#f59e0b",
  scripts: "#ec4899",
  policies: "#ef4444",
  comparisons: "#8b5cf6",
  sources: "#64748b",
  concepts: "#14b8a6",
  troubleshooting: "#f97316",
  synthesis: "#06b6d4",
  // 维度节点
  brand: "#0ea5e9",
  series: "#38bdf8",
  category: "#a855f7",
  subbiz: "#c084fc",
  role: "#22c55e",
  scenario: "#eab308",
  objection: "#fb7185",
  skill: "#2dd4bf",
  tag: "#94a3b8",
  policy_type: "#f87171",
  script_type: "#f472b6",
  system: "#60a5fa",
};

function colorOf(group: string): string {
  return GROUP_COLORS[group] || "#94a3b8";
}

interface Props {
  nodes: OntologyNode[];
  edges: OntologyEdge[];
  onSelect?: (node: OntologyNode | null) => void;
  filterGroups?: Set<string>; // 若提供,仅显示这些 group 的节点
}

export default function GraphView({ nodes, edges, onSelect, filterGroups }: Props) {
  const containerRef = useRef<HTMLDivElement>(null);
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const cyRef = useRef<any>(null);

  useEffect(() => {
    let destroyed = false;
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    let cy: any = null;

    (async () => {
      const cytoscape = (await import("cytoscape")).default;
      const fcose = (await import("cytoscape-fcose")).default;
      try {
        cytoscape.use(fcose);
      } catch {
        /* 重复注册忽略 */
      }
      if (destroyed || !containerRef.current) return;

      const showNode = (n: OntologyNode) => !filterGroups || filterGroups.has(n.group);
      const visibleIds = new Set(nodes.filter(showNode).map((n) => n.id));

      const elements = [
        ...nodes.filter(showNode).map((n) => ({
          data: {
            id: n.id,
            label: n.label,
            group: n.group,
            color: colorOf(n.group),
            size: Math.min(70, 20 + (n.degree || 0) * 2.5),
            isPage: n.is_page ? 1 : 0,
            raw: n,
          },
        })),
        ...edges
          .filter((e) => visibleIds.has(e.source) && visibleIds.has(e.target))
          .map((e) => ({ data: { source: e.source, target: e.target, rel: e.rel } })),
      ];

      cy = cytoscape({
        container: containerRef.current,
        elements,
        style: [
          {
            selector: "node",
            style: {
              "background-color": "data(color)",
              label: "data(label)",
              width: "data(size)",
              height: "data(size)",
              "font-size": 9,
              "font-family": "system-ui, sans-serif",
              color: "#334155",
              "text-valign": "bottom",
              "text-halign": "center",
              "text-margin-y": 3,
              "text-max-width": "90px",
              "text-wrap": "ellipsis",
              "border-width": 1,
              "border-color": "#ffffff",
              "overlay-opacity": 0,
            },
          },
          {
            // 页面节点方形、维度节点圆形,视觉区分
            selector: "node[isPage = 1]",
            style: { shape: "round-rectangle" },
          },
          {
            selector: "node[isPage = 0]",
            style: { shape: "ellipse", "font-size": 8, color: "#64748b" },
          },
          {
            selector: "edge",
            style: {
              width: 1,
              "line-color": "#e2e8f0",
              "curve-style": "bezier",
              "target-arrow-shape": "triangle",
              "target-arrow-color": "#e2e8f0",
              "arrow-scale": 0.5,
              opacity: 0.7,
            },
          },
          {
            selector: "node:selected",
            style: { "border-width": 3, "border-color": "#0f172a" },
          },
          {
            selector: ".faded",
            style: { opacity: 0.12 },
          },
          {
            selector: ".highlight",
            style: { "line-color": "#f59e0b", "target-arrow-color": "#f59e0b", width: 2, opacity: 1 },
          },
        ],
        layout: {
          name: "fcose",
          quality: "default",
          animate: false,
          nodeRepulsion: 8000,
          idealEdgeLength: 90,
          nodeSeparation: 90,
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
        } as any,
        wheelSensitivity: 0.2,
        minZoom: 0.1,
        maxZoom: 3,
      });

      cyRef.current = cy;

      // 点击节点:高亮邻域 + 回调详情
      cy.on("tap", "node", (evt: { target: { data: () => { raw: OntologyNode; id: string } } } & Record<string, unknown>) => {
        const node = evt.target as unknown as {
          data: () => { raw: OntologyNode };
          neighborhood: () => unknown;
          closedNeighborhood: () => { addClass: (c: string) => void };
        };
        cy.elements().addClass("faded");
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const nb = (evt.target as any).closedNeighborhood();
        nb.removeClass("faded");
        nb.connectedEdges?.().addClass?.("highlight");
        onSelect?.(node.data().raw);
      });

      // 点击空白:还原
      cy.on("tap", (evt: { target: unknown }) => {
        if (evt.target === cy) {
          cy.elements().removeClass("faded").removeClass("highlight");
          onSelect?.(null);
        }
      });
    })();

    return () => {
      destroyed = true;
      cy?.destroy();
    };
  }, [nodes, edges, filterGroups, onSelect]);

  return <div ref={containerRef} className="w-full h-full bg-slate-50 rounded-lg" />;
}

export { GROUP_COLORS, colorOf };