All files / src/graph coordinate-assignment.ts

100% Statements 221/221
100% Branches 116/116
100% Functions 31/31
100% Lines 197/197

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 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423                                                          83x 83x 83x 83x   83x 83x             83x       83x             83x 83x 83x 301x   83x 365x 365x   83x                             83x 83x 83x   83x 365x 365x 365x 365x 365x     83x 83x 83x 4x 4x 4x 4x 4x   83x               83x 83x 83x 83x   83x 365x 365x 365x     365x 365x 365x 365x   365x 365x 365x 365x 365x   365x     83x                       83x 83x 301x 301x 301x 365x 365x     365x 365x   301x     83x 83x 83x 83x   83x 301x 301x 4x 4x   301x 301x 301x     83x               75x 75x 75x   75x 1925x 252x 301x   240x 301x   252x     252x   252x     21x                             264x 75x 70x     5x 10x 78x   10x 88x                   166x 2766x 280x 166x 118x     48x     56x 56x   56x 56x 56x     48x               8x 8x 8x 8x 8x 8x   8x 131x 15x   15x 526x 102x 64x       58x       64x   102x     102x 102x   110x 102x     15x 15x 15x 64x 64x 64x   8x             15x 15x 64x   15x 1x 7x     15x 15x 64x   15x             8x 8x 8x 7x 7x 7x   8x               365x 13x 13x   352x 99x   253x 240x   13x       240x 240x 7x 7x   233x 240x   305x   240x 36x 50x     233x 190x   75x 43x             43x 43x 43x             489x 402x 147x 147x 147x 121x   26x 147x 147x 24x   2x     402x 122x 122x 122x 122x   122x 27x 27x        
import type { DirectedGraph } from './graph';
import { getElementDimensions, DEFAULT_GRID_SPACING } from '../di-constants';
import { alignMergeNodeTrack } from './dummy-nodes';
import type { AutoLayoutOptions, Bounds } from '../types';
 
export interface CoordinateOptions extends AutoLayoutOptions {
  feedbackEdges?: Set<string>;
  nodeToLane?: Map<string, number>;
}
 
interface TrackContext {
  tracks: Map<string, number>;
  graph: DirectedGraph;
  feedbackEdges?: Set<string>;
  nodeToLane?: Map<string, number>;
}
 
interface ColConfig {
  maxRank: number;
  startX: number;
  gridSpacing: number;
  widthBudget?: number;
}
 
export function assignCoordinates(
  graph: DirectedGraph,
  ranks: Map<string, number>,
  options?: CoordinateOptions
): Map<string, Bounds> {
  const nodes = graph.getNodes();
  const gridSpacing = options?.gridSpacing ?? DEFAULT_GRID_SPACING;
  const hasLanes = Boolean(options?.nodeToLane && options.nodeToLane.size > 0);
  const startX = hasLanes ? 180 : 100;
 
  const { rankGroups, maxRank } = groupNodesByRank(nodes, ranks);
  const { colWidths, colX, rankRows } = computeColumnPositions(graph, rankGroups, {
    maxRank,
    startX,
    gridSpacing,
    widthBudget: hasLanes ? undefined : options?.widthBudget,
  });
 
  const tracks = hasLanes
    ? computeLaneAwareTracks(graph, ranks, options!)
    : computeFlatTracks(graph, ranks, options?.feedbackEdges);
 
  return computeFinalBounds(nodes, tracks, { colWidths, colX, ranks, rankRows });
}
 
function groupNodesByRank(
  nodes: Array<{ id: string }>,
  ranks: Map<string, number>
): { rankGroups: Map<number, string[]>; maxRank: number } {
  const maxRank = Math.max(0, ...ranks.values());
  const rankGroups = new Map<number, string[]>();
  for (let r = 0; r <= maxRank; r++) {
    rankGroups.set(r, []);
  }
  for (const node of nodes) {
    const rank = ranks.get(node.id)!;
    rankGroups.get(rank)!.push(node.id);
  }
  return { rankGroups, maxRank };
}
 
interface ColInfo {
  colWidths: Map<number, number>;
  colX: Map<number, number>;
  ranks: Map<string, number>;
  rankRows: Map<number, number>;
}
 
function computeRowTrackOffsets(
  nodes: Array<{ id: string }>,
  tracks: Map<string, number>,
  colInfo: ColInfo
): Map<number, number> {
  const rowOffsets = new Map<number, number>();
  const rowMinTrack = new Map<number, number>();
  const rowMaxTrack = new Map<number, number>();
 
  for (const node of nodes) {
    const rank = colInfo.ranks.get(node.id) || 0;
    const row = colInfo.rankRows.get(rank) || 0;
    const track = tracks.get(node.id) || 0;
    rowMinTrack.set(row, Math.min(rowMinTrack.get(row) ?? track, track));
    rowMaxTrack.set(row, Math.max(rowMaxTrack.get(row) ?? track, track));
  }
 
  const maxRow = Math.max(0, ...Array.from(colInfo.rankRows.values()));
  rowOffsets.set(0, 0);
  for (let r = 1; r <= maxRow; r++) {
    const prevMax = rowMaxTrack.get(r - 1)!;
    const currMin = rowMinTrack.get(r)!;
    const prevOffset = rowOffsets.get(r - 1)!;
    const offset = prevOffset + (prevMax - currMin) + 2.0;
    rowOffsets.set(r, offset);
  }
  return rowOffsets;
}
 
function computeFinalBounds(
  nodes: Array<{ id: string; data?: any }>,
  tracks: Map<string, number>,
  colInfo: ColInfo
): Map<string, Bounds> {
  const boundsMap = new Map<string, Bounds>();
  const centerY = 140;
  const trackSpacing = 120;
  const rowOffsets = computeRowTrackOffsets(nodes, tracks, colInfo);
 
  for (const node of nodes) {
    const rank = colInfo.ranks.get(node.id) || 0;
    const row = colInfo.rankRows.get(rank) || 0;
    const dim = node.data?.isDummy
      ? { width: 0, height: 0 }
      : getElementDimensions(node.data?.$type);
    const w = node.data?.customWidth ?? dim.width;
    const h = node.data?.customHeight ?? dim.height;
    const colWidth = colInfo.colWidths.get(rank)!;
    const x = colInfo.colX.get(rank)! + (colWidth - w) / 2;
 
    const baseTrack = tracks.get(node.id)!;
    const rowOffset = rowOffsets.get(row)!;
    const track = baseTrack + rowOffset;
    const trackY = centerY + track * trackSpacing;
    const y = Math.round(trackY - h / 2);
 
    boundsMap.set(node.id, { x, y, width: w, height: h });
  }
 
  return boundsMap;
}
 
function computeColumnPositions(
  graph: DirectedGraph,
  rankGroups: Map<number, string[]>,
  config: ColConfig
): {
  colWidths: Map<number, number>;
  colX: Map<number, number>;
  rankRows: Map<number, number>;
} {
  const colWidths = new Map<number, number>();
  for (let r = 0; r <= config.maxRank; r++) {
    const nodeIds = rankGroups.get(r)!;
    let maxWidth = 0;
    for (const id of nodeIds) {
      const node = graph.getNode(id)!;
      const dim = node.data?.isDummy
        ? { width: 0, height: 0 }
        : getElementDimensions(node.data?.$type);
      const w = node.data?.customWidth ?? dim.width;
      maxWidth = Math.max(maxWidth, w);
    }
    colWidths.set(r, Math.max(36, maxWidth));
  }
 
  const colX = new Map<number, number>();
  const rankRows = new Map<number, number>();
  let currentX = config.startX;
  let currentRow = 0;
 
  for (let r = 0; r <= config.maxRank; r++) {
    const w = colWidths.get(r)!;
    if (config.widthBudget && r > 0 && currentX + w - config.startX > config.widthBudget) {
      currentRow += 1;
      currentX = config.startX;
    }
    rankRows.set(r, currentRow);
    colX.set(r, currentX);
    currentX += w + config.gridSpacing;
  }
 
  return { colWidths, colX, rankRows };
}
 
function computeFlatTracks(
  graph: DirectedGraph,
  ranks: Map<string, number>,
  feedbackEdges?: Set<string>
): Map<string, number> {
  const tracks = new Map<string, number>();
  const maxRank = Math.max(...ranks.values(), 0);
  const ctx: TrackContext = { tracks, graph, feedbackEdges };
 
  for (let r = 0; r <= maxRank; r++) {
    const nodesInRank = graph.getNodes().filter((n) => (ranks.get(n.id) || 0) === r);
    for (const node of nodesInRank) {
      const inEdges = graph
        .inEdges(node.id)
        .filter((e) => !feedbackEdges?.has(e.id) && !e.id.startsWith('_attach_'));
      tracks.set(node.id, calculateSingleNodeTrack(node, inEdges, ctx));
    }
    resolveRankCollisions(nodesInRank, tracks);
  }
 
  refineDummyTracksWithBarycenterSweeps({ graph, ranks, ctx }, maxRank);
 
  return tracks;
}
 
const DUMMY_TRACK_SWEEP_ITERATIONS = 2;
 
interface SweepContext {
  graph: DirectedGraph;
  ranks: Map<string, number>;
  ctx: TrackContext;
}
 
/**
 * Dummy nodes are free virtual routing points reserved along the corridor of a
 * multi-rank edge; nudging them toward the barycenter of their neighbors (a
 * forward/backward Sugiyama-style sweep) straightens their chain and reduces
 * bends without perturbing the placement of any real BPMN element.
 */
function refineDummyTracksWithBarycenterSweeps(sweep: SweepContext, maxRank: number): void {
  const hasDummyNodes = sweep.graph.getNodes().some((n) => n.data?.isDummy);
  if (!hasDummyNodes) {
    return;
  }
 
  for (let iter = 0; iter < DUMMY_TRACK_SWEEP_ITERATIONS; iter++) {
    for (let r = maxRank - 1; r >= 0; r--) {
      sweepRankDummyBarycenter(sweep, r, 'out');
    }
    for (let r = 0; r <= maxRank; r++) {
      sweepRankDummyBarycenter(sweep, r, 'in');
    }
  }
}
 
function sweepRankDummyBarycenter(
  sweep: SweepContext,
  rank: number,
  direction: 'in' | 'out'
): void {
  const { graph, ranks, ctx } = sweep;
  const nodesInRank = graph.getNodes().filter((n) => (ranks.get(n.id) || 0) === rank);
  const dummiesInRank = nodesInRank.filter((n) => n.data?.isDummy);
  if (dummiesInRank.length === 0) {
    return;
  }
 
  for (const node of dummiesInRank) {
    // Each dummy node has exactly one in-edge and one out-edge by construction
    // (see insertDummyNodes), and neither is ever a feedback edge.
    const neighborEdges = direction === 'out' ? graph.outEdges(node.id) : graph.inEdges(node.id);
    const neighborIds = neighborEdges.map((e) => (direction === 'out' ? e.target : e.source));
    // The full forward pass above already assigned a track to every node.
    const neighborTracks = neighborIds.map((id) => ctx.tracks.get(id)!);
    const barycenter = neighborTracks.reduce((a, b) => a + b, 0) / neighborTracks.length;
    ctx.tracks.set(node.id, barycenter);
  }
 
  resolveRankCollisions(nodesInRank, ctx.tracks);
}
 
function computeLaneAwareTracks(
  graph: DirectedGraph,
  ranks: Map<string, number>,
  options: CoordinateOptions
): Map<string, number> {
  const nodeToLane = options.nodeToLane!;
  const feedbackEdges = options.feedbackEdges;
  const maxLane = Math.max(0, ...Array.from(nodeToLane.values()));
  const maxRank = Math.max(...ranks.values(), 0);
  const laneTrackCounts = new Map<number, number>();
  const localTracks = new Map<string, number>();
 
  for (let l = 0; l <= maxLane; l++) {
    const laneNodes = graph.getNodes().filter((n) => (nodeToLane.get(n.id) ?? 0) === l);
    const ctx: TrackContext = { tracks: localTracks, graph, feedbackEdges, nodeToLane };
 
    for (let r = 0; r <= maxRank; r++) {
      const nodesInRank = laneNodes.filter((n) => (ranks.get(n.id) || 0) === r);
      for (const node of nodesInRank) {
        const inEdges = graph
          .inEdges(node.id)
          .filter(
            (e) =>
              !feedbackEdges?.has(e.id) &&
              !e.id.startsWith('_attach_') &&
              (nodeToLane.get(e.source) ?? 0) === l
          );
        localTracks.set(node.id, calculateSingleNodeTrack(node, inEdges, ctx));
      }
      resolveRankCollisions(nodesInRank, localTracks);
    }
 
    const count = normalizeLaneTracks(laneNodes, localTracks);
    const hasFeedback = graph
      .getEdges()
      .some((e) => Boolean(feedbackEdges?.has(e.id)) && nodeToLane.get(e.source) === l);
    laneTrackCounts.set(l, hasFeedback ? count + 1 : count);
  }
 
  const laneStartTrack = computeLaneStartOffsets(maxLane, laneTrackCounts);
  const globalTracks = new Map<string, number>();
  for (const node of graph.getNodes()) {
    const lane = nodeToLane.get(node.id) ?? 0;
    const start = laneStartTrack.get(lane)!;
    globalTracks.set(node.id, start + (localTracks.get(node.id) || 0));
  }
  return globalTracks;
}
 
function normalizeLaneTracks(
  laneNodes: Array<{ id: string }>,
  localTracks: Map<string, number>
): number {
  let minT = 0;
  for (const n of laneNodes) {
    minT = Math.min(minT, localTracks.get(n.id)!);
  }
  if (minT < 0) {
    for (const n of laneNodes) {
      localTracks.set(n.id, localTracks.get(n.id)! - minT);
    }
  }
  let maxT = 0;
  for (const n of laneNodes) {
    maxT = Math.max(maxT, localTracks.get(n.id)!);
  }
  return laneNodes.length === 0 ? 1 : maxT + 1;
}
 
function computeLaneStartOffsets(
  maxLane: number,
  laneTrackCounts: Map<number, number>
): Map<number, number> {
  const offsets = new Map<number, number>();
  offsets.set(0, 0);
  for (let l = 1; l <= maxLane; l++) {
    const prev = offsets.get(l - 1)!;
    const count = laneTrackCounts.get(l - 1)!;
    offsets.set(l, prev + count);
  }
  return offsets;
}
 
function calculateSingleNodeTrack(
  node: { id: string; data?: any },
  inEdges: Array<{ id: string; source: string; target: string }>,
  ctx: TrackContext
): number {
  if (node.data?.$type === 'bpmn:BoundaryEvent') {
    const hostId = node.data?.attachedToRef?.id || node.data?.attachedToRef;
    return (ctx.tracks.get(hostId) || 0) + 1;
  }
  if (inEdges.length === 0) {
    return 0;
  }
  if (inEdges.length === 1) {
    return calculateSingleParentTrack(node.id, inEdges[0].source, ctx);
  }
  return alignMergeNodeTrack(node.id, inEdges, ctx.tracks);
}
 
function calculateSingleParentTrack(nodeId: string, parentId: string, ctx: TrackContext): number {
  const parentNode = ctx.graph.getNode(parentId);
  if (parentNode?.data?.$type === 'bpmn:BoundaryEvent') {
    const hostId = parentNode.data?.attachedToRef?.id || parentNode.data?.attachedToRef;
    return (ctx.tracks.get(hostId) || 0) + 1;
  }
  const parentTrack = ctx.tracks.get(parentId) || 0;
  let siblings = ctx.graph
    .outEdges(parentId)
    .filter((e) => !ctx.feedbackEdges?.has(e.id) && !e.id.startsWith('_attach_'));
 
  if (ctx.nodeToLane) {
    const currentLane = ctx.nodeToLane.get(nodeId);
    siblings = siblings.filter((e) => ctx.nodeToLane!.get(e.target) === currentLane);
  }
 
  if (siblings.length <= 1) {
    return parentTrack;
  }
  const siblingIndex = siblings.findIndex((e) => e.target === nodeId);
  const count = siblings.length;
  // For an odd sibling count this centers exactly on the parent's track (the
  // middle branch gets offset 0). For an even count there is no exact
  // center, so round down rather than split the difference: that keeps one
  // branch on the parent's own track instead of offsetting every branch by
  // a fraction, which otherwise forces a bend on every branch at both the
  // split and the merge (issue #88).
  const centerIndex = Math.floor((count - 1) / 2);
  const offset = siblingIndex - centerIndex;
  return parentTrack + offset;
}
 
function resolveRankCollisions(
  nodesInRank: Array<{ id: string; data?: any; order?: number }>,
  tracks: Map<string, number>
): void {
  const regularNodes = nodesInRank.filter((n) => n.data?.$type !== 'bpmn:BoundaryEvent');
  regularNodes.sort((a, b) => {
    const tA = tracks.get(a.id) || 0;
    const tB = tracks.get(b.id) || 0;
    if (tA !== tB) {
      return tA - tB;
    }
    const oA = a.order ?? 0;
    const oB = b.order ?? 0;
    if (oA !== oB) {
      return oA - oB;
    }
    return a.id.localeCompare(b.id);
  });
 
  for (let i = 1; i < regularNodes.length; i++) {
    const prevId = regularNodes[i - 1].id;
    const currId = regularNodes[i].id;
    const prevTrack = tracks.get(prevId) || 0;
    let currTrack = tracks.get(currId) || 0;
 
    if (currTrack < prevTrack + 1) {
      currTrack = prevTrack + 1;
      tracks.set(currId, currTrack);
    }
  }
}