All files / src/apps/user/pages/knowledge/map forceLayout.ts

100% Statements 50/50
86.36% Branches 19/22
100% Functions 22/22
100% Lines 40/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                                                                                                          6x   6x 6x   6x     19x         19x 19x 6x 6x 6x 6x 6x         6x 60x       208x 166x               19x 17x 125x 92x 92x 17x 57x 83x 56x   92x 92x   184x   17x         92x 56x 56x         92x               92x 92x       4805x   17x 17x 92x   17x    
import {
  forceCollide,
  forceLink,
  forceManyBody,
  forceRadial,
  forceSimulation,
  forceX,
  forceY,
  type SimulationLinkDatum,
  type SimulationNodeDatum,
} from "d3-force";
 
import type { Point } from "@/components/dashboard/widgets/network/layout";
 
/**
 * Where each node of a source map sits: a force layout, because a web of
 * sources tied by evidence has no layers to put in columns (the network
 * tiles' `layeredLayout` is for agent → repository → source).
 *
 * Ties pull their ends together — the stronger the tie, the shorter it
 * wants to be and the harder it pulls — every node pushes the others off,
 * and none overlaps another. The repository's own sources gather in the
 * middle; suggestions sit on a ring outside them and agents on one outside
 * that, so what the repository holds is always the centre of the picture.
 *
 * Deterministic: the same map always lays out the same way. Nodes are taken
 * in id order, the simulation draws on a seeded random source, and it is
 * stopped at once and run for a fixed number of ticks here, synchronously —
 * it never animates, and never runs on after the layout is returned.
 */
 
/** 0: in the repository; 1: a suggestion; 2: an agent. */
export type Ring = 0 | 1 | 2;
 
export interface ForceNode {
  id: string;
  ring: Ring;
  /** Its drawn diameter, so nodes keep clear of one another. */
  size: number;
}
 
export interface ForceLink {
  source: string;
  target: string;
  /** 0–1: how strong the tie is. */
  weight: number;
}
 
export interface ForceOptions {
  ticks?: number;
  seed?: number;
}
 
export const TICKS = 300;
/** The longest and shortest a tie wants to be: weak ties sit far apart. */
export const LINK_FAR = 240;
export const LINK_NEAR = 90;
/** How far outside the repository's sources each outer ring sits. */
export const RING_GAP = 170;
 
/** The radius the repository's own sources gather within. */
export const coreRadius = (members: number) => 70 * Math.sqrt(Math.max(members, 1));
 
/** A small, fast, seedable generator (mulberry32): d3 asks it for the jiggle
 *  that separates nodes that start on one spot. */
export function seeded(seed: number): () => number {
  let state = seed >>> 0;
  return () => {
    state = (state + 0x6d2b79f5) >>> 0;
    let t = state;
    t = Math.imul(t ^ (t >>> 15), t | 1);
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}
 
/** How long a tie of this weight wants to be. */
export const linkDistance = (weight: number) =>
  LINK_FAR - (LINK_FAR - LINK_NEAR) * Math.min(Math.max(weight, 0), 1);
 
type SimNode = SimulationNodeDatum & ForceNode;
 
const byKey = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
const linkKey = (l: ForceLink) => `${l.source}\u0000${l.target}`;
type SimLink = SimulationLinkDatum<SimNode> & { weight: number };
 
export function forceLayout(
  nodes: ForceNode[],
  links: ForceLink[],
  { ticks = TICKS, seed = 1 }: ForceOptions = {},
): Record<string, Point> {
  if (nodes.length === 0) return {};
  const ordered: SimNode[] = [...nodes]
    .sort((a, b) => byKey(a.id, b.id))
    .map((n) => ({ ...n }));
  const known = new Set(ordered.map((n) => n.id));
  const ties: SimLink[] = links
    .filter((l) => known.has(l.source) && known.has(l.target) && l.source !== l.target)
    .sort((a, b) => byKey(linkKey(a), linkKey(b)))
    .map((l) => ({ source: l.source, target: l.target, weight: l.weight }));
 
  const core = coreRadius(ordered.filter((n) => n.ring === 0).length);
  const ringRadius = (ring: Ring) => (ring === 0 ? 0 : core + RING_GAP * ring);
  // A gentle pull to the middle: ties, not the centre, arrange the core.
  const centre = (n: SimNode) => (n.ring === 0 ? 0.06 : 0);
 
  const simulation = forceSimulation<SimNode>(ordered)
    .randomSource(seeded(seed))
    .force(
      "link",
      forceLink<SimNode, SimLink>(ties)
        .id((n) => n.id)
        .distance((l) => linkDistance(l.weight))
        .strength((l) => 0.05 + 0.6 * Math.min(Math.max(l.weight, 0), 1)),
    )
    .force("charge", forceManyBody<SimNode>().strength(-260).distanceMax(700))
    .force(
      "collide",
      forceCollide<SimNode>((n) => n.size / 2 + 26),
    )
    // The repository's own sources to the middle…
    .force("x", forceX<SimNode>(0).strength(centre))
    .force("y", forceY<SimNode>(0).strength(centre))
    // …and everything else onto its ring.
    .force(
      "rings",
      forceRadial<SimNode>((n) => ringRadius(n.ring), 0, 0).strength((n) =>
        n.ring === 0 ? 0 : 0.8,
      ),
    )
    .stop();
  for (let i = 0; i < ticks; i++) simulation.tick();
 
  const positions: Record<string, Point> = {};
  for (const n of ordered) {
    positions[n.id] = { x: Math.round(n.x ?? 0), y: Math.round(n.y ?? 0) };
  }
  return positions;
}