All files / src/apps/user/pages/knowledge/map SourceMapCanvas.tsx

78.78% Statements 26/33
71.21% Branches 47/66
66.66% Functions 8/12
83.33% Lines 25/30

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                                                                          4x   4x 20x 20x 20x 20x     20x         20x                                                                         4x   4x                                 4x                 7x   5x 12x 12x 12x                         7x   5x 7x 7x 7x 7x 39x   7x                                                     7x                                                            
import { GeneratedMark } from "@/components/badge/GeneratedMark";
import FlowFrame from "@/components/dashboard/widgets/network/FlowFrame";
import type { Point } from "@/components/dashboard/widgets/network/layout";
import { STATUS_TONE_RING } from "@/components/detail";
import type { SourceMap, SourceMapNode } from "@/objects/Knowledge";
import { Edge, Handle, Node, NodeProps, Position } from "@xyflow/react";
import { Bot, TriangleAlert } from "lucide-react";
import React, { useMemo } from "react";
 
import { SOURCE_HEALTH, SOURCE_HEALTH_LABEL } from "../scales";
import { sourceIcon } from "../util";
import { edgeId, percent, sizeOf, strengthWord, type Visible } from "./mapModel";
 
/**
 * The source map drawn: React Flow over the force layout's positions. Kept
 * apart from `SourceMap` (its controls, evidence panel and table) so page
 * tests can stand it in, as they do the time-series chart.
 *
 * A source is a circle sized by what it holds, its ring the meaning of its
 * health (`SOURCE_HEALTH`, named on hover and in the panel — never colour
 * alone); a suggestion's ring is dashed; an agent is a square. A connection
 * is a straight line between centres, as wide as the tie is strong, all in
 * one neutral ink: a kind of evidence is named, not tinted.
 */
 
export type MapSelection = { kind: "node" | "edge"; id: string };
 
interface MapNodeData extends Record<string, unknown> {
  node: SourceMapNode;
  size: number;
  health: string;
  dimmed: boolean;
}
 
type MapFlowNode = Node<MapNodeData, "mapNode">;
 
/** Both ends of every line meet at a node's centre. */
const CENTRED = "!opacity-0 !pointer-events-none !min-w-0 !min-h-0 !size-px !top-1/2";
 
const MapNodeView: React.FC<NodeProps<MapFlowNode>> = ({ data, selected }) => {
  const { node, size, health, dimmed } = data;
  const isAgent = node.kind === "agent";
  const Icon = isAgent ? Bot : sourceIcon(String(node.meta.source_type ?? ""));
  const ring = isAgent
    ? "border-gray-300 dark:border-gray-600"
    : STATUS_TONE_RING[SOURCE_HEALTH[health] ?? "neutral"];
  const title = isAgent
    ? node.label
    : `${node.label} · ${SOURCE_HEALTH_LABEL[health] ?? health}${
        node.kind === "suggestion" ? " · not in this repository" : ""
      }`;
  return (
    <div
      style={{ width: size, height: size }}
      className={`relative transition-opacity ${dimmed ? "opacity-20" : node.kind === "suggestion" ? "opacity-80" : "opacity-100"}`}
      title={title}
    >
      <Handle type="target" position={Position.Top} className={CENTRED} />
      <GeneratedMark generated={node.meta.is_ai_generated === true} size="sm">
        <div
          style={{ width: size, height: size }}
          className={`flex items-center justify-center border-2 bg-white dark:bg-gray-800 shadow-sm ${
            isAgent ? "rounded-lg" : "rounded-full"
          } ${ring} ${node.kind === "suggestion" ? "border-dashed" : ""} ${
            selected
              ? "ring-2 ring-offset-2 ring-gray-900 dark:ring-gray-100 dark:ring-offset-gray-900"
              : ""
          }`}
        >
          <Icon className="size-[40%] text-gray-500 dark:text-gray-400" aria-hidden="true" />
        </div>
      </GeneratedMark>
      {SOURCE_HEALTH[health] === "warning" && !isAgent && (
        // The ring's warning in a shape too: amber and green are close under
        // protanopia.
        <TriangleAlert
          className="absolute -right-1 -top-1 size-4 rounded-full bg-white dark:bg-gray-800 p-0.5 text-amber-600"
          aria-hidden="true"
        />
      )}
      <div className="pointer-events-none absolute left-1/2 top-full mt-1 w-36 -translate-x-1/2 truncate text-center text-[11px] leading-tight text-gray-700 dark:text-gray-200">
        {node.label}
      </div>
      <Handle type="source" position={Position.Top} className={CENTRED} />
    </div>
  );
};
 
const nodeTypes = { mapNode: MapNodeView };
 
const NOUN: Record<string, string> = {
  source: "Source",
  suggestion: "Suggested source",
  agent: "Agent",
};
 
export interface SourceMapCanvasProps {
  map: SourceMap;
  positions: Record<string, Point>;
  visible: Visible;
  selection: MapSelection | null;
  /** What the selection touches; everything else is dimmed. */
  lit: Set<string> | null;
  healthOf: (node: SourceMapNode) => string;
  onSelect: (selection: MapSelection | null) => void;
}
 
const SourceMapCanvas: React.FC<SourceMapCanvasProps> = ({
  map,
  positions,
  visible,
  selection,
  lit,
  healthOf,
  onSelect,
}) => {
  const flowNodes: MapFlowNode[] = useMemo(
    () =>
      map.nodes.map((node) => {
        const size = sizeOf(node);
        const at = positions[node.id] ?? { x: 0, y: 0 };
        return {
          id: node.id,
          type: "mapNode",
          position: { x: at.x - size / 2, y: at.y - size / 2 },
          hidden: !visible.nodes.has(node.id),
          selected: selection?.kind === "node" && selection.id === node.id,
          ariaLabel: `${NOUN[node.kind] ?? "Node"}: ${node.label}`,
          data: { node, size, health: healthOf(node), dimmed: !!lit && !lit.has(node.id) },
        };
      }),
    [map, positions, visible, selection, lit, healthOf],
  );
 
  const flowEdges: Edge[] = useMemo(
    () =>
      map.edges.map((edge) => {
        const id = edgeId(edge);
        const chosen = selection?.kind === "edge" && selection.id === id;
        const on = !lit || (lit.has(edge.source) && lit.has(edge.target));
        const toSuggestion = [edge.source, edge.target].some((end) =>
          map.nodes.some((n) => n.id === end && n.kind === "suggestion"),
        );
        return {
          id,
          source: edge.source,
          target: edge.target,
          type: "straight",
          hidden: !visible.edges.has(id),
          selectable: edge.kind === "evidence",
          interactionWidth: 18,
          ariaLabel:
            edge.kind === "evidence"
              ? `${strengthWord(edge.weight)} connection, ${percent(edge.weight)}`
              : "Cites",
          className: chosen
            ? "text-gray-900 dark:text-gray-100"
            : "text-gray-400 dark:text-gray-500",
          style: {
            stroke: "currentColor",
            strokeWidth: edge.kind === "evidence" ? 1 + 5 * edge.weight : 1.25,
            strokeDasharray:
              edge.kind === "cited_by" ? "2 4" : toSuggestion ? "6 4" : undefined,
            opacity: chosen ? 1 : on ? 0.75 : 0.08,
          },
        };
      }),
    [map, visible, selection, lit],
  );
 
  return (
    <FlowFrame<MapFlowNode>
      testId="source-map"
      frameClassName="h-[28rem]"
      nodes={flowNodes}
      edges={flowEdges}
      nodeTypes={nodeTypes}
      fitViewOptions={{ padding: 0.18 }}
      onNodeClick={(_, node) =>
        onSelect(
          selection?.kind === "node" && selection.id === node.id
            ? null
            : { kind: "node", id: node.id },
        )
      }
      onEdgeClick={(_, edge) => {
        const original = map.edges.find((e) => edgeId(e) === edge.id);
        if (original?.kind !== "evidence") return;
        onSelect(
          selection?.kind === "edge" && selection.id === edge.id
            ? null
            : { kind: "edge", id: edge.id },
        );
      }}
      onPaneClick={() => onSelect(null)}
    />
  );
};
 
export default SourceMapCanvas;