All files / src/components/dashboard/widgets/network layout.ts

99.02% Statements 102/103
86.36% Branches 57/66
100% Functions 23/23
100% Lines 82/82

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 205 206 207 208 209                                                                                      12x 12x             30x 30x 30x   80x 29x 29x 51x 50x 51x       80x 61x 29x 29x 80x     29x 30x 30x 35x   30x 32x 32x 45x 75x 41x 45x 41x   45x   32x 45x     30x 31x 29x   29x 29x 61x 61x 61x 80x           29x                       7x 3x 3x 3x 3x   3x 6x         3x 3x 7x 4x 4x 4x 7x 7x 6x 3x 3x         7x                       11x 22x 22x 22x 48x 48x 297x 297x 26x 26x       22x   160x 137x 11x                 4x 4x 12x 12x   4x                           82x 82x 82x        
/**
 * Where each node of a network tile sits: columns, left to right.
 *
 * The network views are layered by nature — agents are granted repositories,
 * repositories hold sources; an agent remembers conversations, a conversation
 * holds entries — so each node kind has a column and every edge crosses from
 * one column to the next. Reading left to right is then reading the question
 * the tile answers: "what can this agent reach?", "what did it keep?".
 *
 * Within a column a node sits at the mean row of its neighbours in the column
 * nearer the anchor (the barycentre heuristic), so a repository's sources
 * gather beside it rather than scattering down the tile, and fewer edges
 * cross. Columns are laid out outward from the anchor in both directions.
 * Nodes with no neighbour on the anchor side keep their input order and sink
 * below the rest — an unreachable source belongs at the bottom, visibly apart.
 */
 
export interface LayoutNode {
  id: string;
  /** Column index; need not be contiguous or start at zero. */
  column: number;
}
 
export interface LayoutEdge {
  source: string;
  target: string;
}
 
export interface Point {
  x: number;
  y: number;
}
 
export interface LayoutOptions {
  /** Horizontal distance between columns. */
  columnGap?: number;
  /** Vertical distance between neighbours in a column. */
  rowGap?: number;
  /** The column the others are ordered outward from. Defaults to the one
   *  holding the first node. */
  anchor?: number;
}
 
export const COLUMN_GAP = 240;
export const ROW_GAP = 64;
 
export function layeredLayout(
  nodes: LayoutNode[],
  edges: LayoutEdge[],
  options: LayoutOptions = {},
): Record<string, Point> {
  const columnGap = options.columnGap ?? COLUMN_GAP;
  const rowGap = options.rowGap ?? ROW_GAP;
  if (nodes.length === 0) return {};
 
  const columnOf = new Map(nodes.map((n) => [n.id, n.column]));
  const neighbours = new Map<string, string[]>();
  for (const e of edges) {
    if (!columnOf.has(e.source) || !columnOf.has(e.target)) continue;
    neighbours.set(e.source, [...(neighbours.get(e.source) ?? []), e.target]);
    neighbours.set(e.target, [...(neighbours.get(e.target) ?? []), e.source]);
  }
 
  // Compress to contiguous column slots, preserving order.
  const used = [...new Set(nodes.map((n) => n.column))].sort((a, b) => a - b);
  const slotOf = new Map(used.map((c, i) => [c, i]));
  const byColumn = new Map<number, string[]>();
  for (const n of nodes) {
    byColumn.set(n.column, [...(byColumn.get(n.column) ?? []), n.id]);
  }
 
  const anchor = options.anchor ?? nodes[0].column;
  const anchorColumn = used.includes(anchor) ? anchor : used[0];
  const rowOf = new Map<string, number>();
  (byColumn.get(anchorColumn) ?? []).forEach((id, i) => rowOf.set(id, i));
 
  const order = (column: number, towards: number) => {
    const ids = byColumn.get(column) ?? [];
    const keyed = ids.map((id, index) => {
      const rows = (neighbours.get(id) ?? [])
        .filter((n) => columnOf.get(n) === towards && rowOf.has(n))
        .map((n) => rowOf.get(n) as number);
      const centre = rows.length
        ? rows.reduce((s, r) => s + r, 0) / rows.length
        : Number.POSITIVE_INFINITY;
      return { id, centre, index };
    });
    keyed.sort((a, b) => a.centre - b.centre || a.index - b.index);
    keyed.forEach(({ id }, i) => rowOf.set(id, i));
  };
 
  const at = used.indexOf(anchorColumn);
  for (let i = at + 1; i < used.length; i++) order(used[i], used[i - 1]);
  for (let i = at - 1; i >= 0; i--) order(used[i], used[i + 1]);
 
  const positions: Record<string, Point> = {};
  for (const column of used) {
    const ids = byColumn.get(column) ?? [];
    const offset = ((ids.length - 1) * rowGap) / 2;
    for (const id of ids) {
      positions[id] = {
        x: (slotOf.get(column) as number) * columnGap,
        y: (rowOf.get(id) as number) * rowGap - offset,
      };
    }
  }
  return positions;
}
 
/**
 * Columns by link distance, for a graph with no kinds to layer on — a graph
 * knowledge source's entities. Each connected component is walked from its
 * best-connected node; its neighbours form the next column, and so on.
 */
export function columnsByDistance(
  ids: string[],
  edges: LayoutEdge[],
): LayoutNode[] {
  const adjacent = new Map<string, Set<string>>(ids.map((id) => [id, new Set()]));
  for (const e of edges) {
    Iif (!adjacent.has(e.source) || !adjacent.has(e.target)) continue;
    adjacent.get(e.source)?.add(e.target);
    adjacent.get(e.target)?.add(e.source);
  }
  const byDegree = [...ids].sort(
    (a, b) =>
      (adjacent.get(b)?.size ?? 0) - (adjacent.get(a)?.size ?? 0) ||
      ids.indexOf(a) - ids.indexOf(b),
  );
 
  const column = new Map<string, number>();
  for (const root of byDegree) {
    if (column.has(root)) continue;
    column.set(root, 0);
    const queue = [root];
    while (queue.length) {
      const current = queue.shift() as string;
      for (const next of adjacent.get(current) ?? []) {
        if (!column.has(next)) {
          column.set(next, (column.get(current) as number) + 1);
          queue.push(next);
        }
      }
    }
  }
  return ids.map((id) => ({ id, column: column.get(id) ?? 0 }));
}
 
/**
 * Everything a selected node leads to and comes from, along edge direction.
 *
 * Selecting an agent lights its whole reach (repositories, their sources,
 * its memory); selecting a source lights the repositories that hold it and
 * the agents that reach it — but not those agents' other repositories, which
 * an undirected walk would drag in.
 */
export function lineageOf(id: string, edges: LayoutEdge[]): Set<string> {
  const walk = (next: (e: LayoutEdge) => [string, string]) => {
    const seen = new Set([id]);
    const queue = [id];
    while (queue.length) {
      const current = queue.shift() as string;
      for (const e of edges) {
        const [from, to] = next(e);
        if (from === current && !seen.has(to)) {
          seen.add(to);
          queue.push(to);
        }
      }
    }
    return seen;
  };
  const down = walk((e) => [e.source, e.target]);
  const up = walk((e) => [e.target, e.source]);
  return new Set([...down, ...up]);
}
 
/**
 * A node and what it touches, one hop either way: what a selection lights on
 * an undirected web (the source map), where every edge is a tie rather than
 * a direction and `lineageOf` would walk the whole connected component.
 */
export function neighboursOf(id: string, edges: LayoutEdge[]): Set<string> {
  const near = new Set([id]);
  for (const e of edges) {
    if (e.source === id) near.add(e.target);
    if (e.target === id) near.add(e.source);
  }
  return near;
}
 
/**
 * An edge's ends as drawn: left to right. Nodes take edges in on their left
 * and send them from their right, so an edge whose target sits left of its
 * source (an agent's memory, drawn beside it on the left; a relationship
 * pointing back a column) would leave rightwards and loop back behind both
 * nodes. Direction is still the data's — lineage walks the real edges.
 */
export function drawnEnds<E extends LayoutEdge>(
  edge: E,
  positions: Record<string, Point>,
): [string, string] {
  const from = positions[edge.source];
  const to = positions[edge.target];
  return from && to && to.x < from.x
    ? [edge.target, edge.source]
    : [edge.source, edge.target];
}