All files / src/components/dashboard/widgets/network EntityGraph.tsx

82.6% Statements 38/46
45.83% Branches 22/48
72.72% Functions 16/22
85% Lines 34/40

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                          6x                     6x 6x                     6x   6x 1x                                         6x   6x 3x           3x 4x   3x 1x 2x     2x 2x   3x               6x       1x 1x 1x     1x 1x 1x 1x       1x   1x 1x 1x                                 1x   1x                                       1x 1x           1x                                                                  
import { TONES } from "@/components/appearance/tones";
import {
  GraphData,
  KnowledgeGraphEdge,
  KnowledgeGraphNode,
  NodeTypeDefinition,
} from "@/objects/Knowledge";
import { Edge, Handle, Node, NodeProps, Position } from "@xyflow/react";
import React, { useMemo, useState } from "react";
import FlowFrame from "./FlowFrame";
import {
  columnsByDistance,
  drawnEnds,
  layeredLayout,
  lineageOf,
} from "./layout";
 
/**
 * A graph knowledge source's entities and relationships, read-only.
 *
 * The editor on the source's own page (`GraphKnowledgeSection`) is where a
 * graph is built; this is the same graph as a board tile — what an agent
 * granted the source retrieves over. It keeps the positions the editor saved
 * when every entity has one, and otherwise lays the graph out by link
 * distance from its best-connected entity.
 */
 
/** Entity type colours, by the names svc-ai's node-type catalogue uses.
 *  Hex because they colour an inline border, which a class cannot. */
const TYPE_HEX: Record<string, string> = {
  teal: "#14b8a6",
  blue: TONES.blue.hex,
  violet: TONES.violet.hex,
  amber: TONES.amber.hex,
  rose: TONES.rose.hex,
  emerald: TONES.emerald.hex,
  indigo: TONES.indigo.hex,
  gray: "#9ca3af",
};
 
const ENTITY_W = 140;
const ENTITY_H = 36;
 
interface EntityData extends Record<string, unknown> {
  entity: KnowledgeGraphNode;
  colour: string;
  typeName: string;
  dimmed: boolean;
}
 
type EntityFlowNode = Node<EntityData, "entity">;
 
const hidden = "!opacity-0 !pointer-events-none !min-w-0 !min-h-0 !size-px";
 
const EntityNode: React.FC<NodeProps<EntityFlowNode>> = ({ data, selected }) => (
  <div
    style={{ width: ENTITY_W, height: ENTITY_H, borderLeftColor: data.colour }}
    className={`flex flex-col justify-center rounded-md border border-l-4 border-gray-200 dark:border-gray-600 bg-white dark:bg-gray-800 px-2 shadow-sm transition-opacity ${
      data.dimmed ? "opacity-25" : "opacity-100"
    } ${
      selected
        ? "ring-2 ring-offset-1 ring-gray-900 dark:ring-gray-100 dark:ring-offset-gray-900"
        : ""
    }`}
  >
    <Handle type="target" position={Position.Left} className={hidden} />
    <span className="truncate text-[11px] font-medium leading-tight text-gray-800 dark:text-gray-100">
      {data.entity.name || "(unnamed)"}
    </span>
    <span className="truncate text-[9px] uppercase tracking-wide text-gray-400 dark:text-gray-500">
      {data.typeName}
    </span>
    <Handle type="source" position={Position.Right} className={hidden} />
  </div>
);
 
const nodeTypes = { entity: EntityNode };
 
const asLayoutEdges = (edges: KnowledgeGraphEdge[]) =>
  edges.map((e) => ({ source: e.source_id, target: e.target_id }));
 
/** Saved editor positions when every entity has one, else a layout. */
export function entityPositions(
  graph: GraphData,
): Record<string, { x: number; y: number }> {
  const saved = graph.nodes.every(
    (n) => typeof n.x === "number" && typeof n.y === "number",
  );
  if (saved && graph.nodes.length) {
    return Object.fromEntries(
      graph.nodes.map((n) => [n.id, { x: n.x as number, y: n.y as number }]),
    );
  }
  const edges = asLayoutEdges(graph.edges);
  return layeredLayout(
    columnsByDistance(
      graph.nodes.map((n) => n.id),
      edges,
    ),
    edges,
    { columnGap: 200, rowGap: 52, anchor: 0 },
  );
}
 
const EntityGraph: React.FC<{
  graph: GraphData;
  nodeTypes?: NodeTypeDefinition[];
}> = ({ graph, nodeTypes: typeDefs = [] }) => {
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const types = useMemo(
    () => Object.fromEntries(typeDefs.map((d) => [d.name, d])),
    [typeDefs],
  );
  const positions = useMemo(() => entityPositions(graph), [graph]);
  const layoutEdges = useMemo(() => asLayoutEdges(graph.edges), [graph]);
  const lit = useMemo(
    () => (selectedId ? lineageOf(selectedId, layoutEdges) : null),
    [layoutEdges, selectedId],
  );
 
  const flowNodes: EntityFlowNode[] = useMemo(
    () =>
      graph.nodes.map((entity) => {
        const def = types[entity.label];
        return {
          id: entity.id,
          type: "entity",
          position: positions[entity.id] ?? { x: 0, y: 0 },
          selected: entity.id === selectedId,
          ariaLabel: `${entity.label}: ${entity.name}`,
          data: {
            entity,
            colour: TYPE_HEX[def?.color ?? "gray"] ?? TYPE_HEX.gray,
            typeName: def?.display_name ?? entity.label,
            dimmed: !!lit && !lit.has(entity.id),
          },
        };
      }),
    [graph, positions, types, lit, selectedId],
  );
 
  const flowEdges: Edge[] = useMemo(
    () =>
      graph.edges.map((e) => {
        const on = !lit || (lit.has(e.source_id) && lit.has(e.target_id));
        const [source, target] = drawnEnds(
          { source: e.source_id, target: e.target_id },
          positions,
        );
        return {
          id: e.id,
          source,
          target,
          selectable: false,
          focusable: false,
          label: selectedId && on ? e.relationship : undefined,
          labelStyle: { fontSize: 9 },
          style: { stroke: TYPE_HEX.gray, strokeWidth: 1.25, opacity: on ? 0.8 : 0.1 },
        };
      }),
    [graph, lit, selectedId, positions],
  );
 
  const selected = graph.nodes.find((n) => n.id === selectedId) ?? null;
  const relations = selected
    ? graph.edges.filter(
        (e) => e.source_id === selected.id || e.target_id === selected.id,
      ).length
    : 0;
 
  return (
    <div className="flex h-full min-h-0 flex-col gap-2">
      <FlowFrame
        testId="entity-graph"
        nodes={flowNodes}
        edges={flowEdges}
        nodeTypes={nodeTypes}
        onNodeClick={(_, node) =>
          setSelectedId((id) => (id === node.id ? null : node.id))
        }
        onPaneClick={() => setSelectedId(null)}
      />
      <p className="min-h-[1.5rem] truncate text-[11px] text-gray-500 dark:text-gray-400">
        {selected ? (
          <>
            <span className="font-medium text-gray-700 dark:text-gray-200">
              {selected.name}
            </span>
            {` · ${types[selected.label]?.display_name ?? selected.label} · ${relations} relationship${
              relations === 1 ? "" : "s"
            }`}
          </>
        ) : (
          <span className="italic text-gray-400 dark:text-gray-500">
            Select an entity to see what it is related to.
          </span>
        )}
      </p>
    </div>
  );
};
 
export default EntityGraph;