All files / src/hierarchy path-alignment.ts

100% Statements 269/269
100% Branches 139/139
100% Functions 44/44
100% Lines 252/252

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 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563                                                                                                        18x 70x 70x 1x           11x 11x 22x   11x 18x 17x     11x       15x 15x 15x 15x   15x 25x 1x   24x 24x 24x 1x   23x 25x 25x     15x             11x 11x 11x 44x 44x 44x 44x 38x 33x 33x       11x       7x 7x 25x 25x 24x                 11x 11x 17x 17x 17x 1x   16x 16x 16x 12x     11x       22x 22x 22x 1x   21x 21x 21x 14x     7x 4x 4x 4x       4x 4x     3x 3x 3x       3x 3x               6x 6x 6x 25x 25x 24x     6x 19x 6x 39x 39x 19x 19x           20x 20x 20x 9x 9x     11x 11x 11x 4x 4x     7x 17x 7x 15x     7x 7x           7x 7x 12x 12x 22x 7x     12x 7x       7x 6x 6x     7x       25x 18x     14x 7x 14x   56x       14x 28x 7x       7x 14x 14x     7x 6x 6x 9x   6x 5x 5x                                           6x 45x 45x                                 2x 2x 2x   2x 5x 5x 2x 2x       2x 5x 5x 5x 4x   69x 5x 6x 6x 3x 3x       2x                 4x 17x 17x 6x 3x       4x       73x 73x 249x 249x 249x 244x 244x 244x     73x               24x 51x 51x 1x   50x 519x 50x                               275x 232x   424x 43x 19x   24x 24x 24x 18x     6x 6x 6x 73x 6x         6x 2x     4x 4x 35x 4x         4x 1x     3x 3x 1x     7x 2x           2x                           73x 294x 73x   73x               73x 275x 275x 2x       71x       73x 352x 73x 73x 71x     2x 2x 6x 6x     2x 26x 2x 24x 24x 20x 20x       2x 2x 29x   2x   2x       12x 12x   12x 14x 25x 14x 10x 702x 81x   10x 1275x 72x   10x     58x 58x       10x       12x    
import type { AutoLayoutOptions, Bounds, Point } from '../types';
import {
  buildScopeGraph,
  getRefId,
  partitionScopeElements,
  rerouteProcessEdges,
  type ScopeLayoutResult,
} from './subprocess-layout';
import { findFeedbackEdges } from '../graph/cycle-removal';
 
export interface CollaborationAlignmentContext {
  definitions: any;
  collaboration: any;
  allShapesMap: Map<string, Bounds>;
  allShapes: Array<{ element: any; bounds: Bounds; isExpanded?: boolean; labelBounds?: Bounds }>;
  allEdges: Array<{ element: any; waypoints: Point[]; isFeedback?: boolean; labelBounds?: Bounds }>;
  allLanes?: Array<{ element: any; bounds: Bounds }>;
  allPools?: Array<{ element: any; bounds: Bounds }>;
}
 
export interface IntraProcessAlignmentContext {
  process: any;
  result: ScopeLayoutResult;
  options?: AutoLayoutOptions;
  feedbackEdges?: Set<string>;
}
 
interface MessagePair {
  srcId: string;
  tgtId: string;
  srcProc: any;
  tgtProc: any;
}
 
interface ProcessForwardInfo {
  process: any;
  feedbackEdges: Set<string>;
  forwardSuccessors: Map<string, string[]>;
}
 
interface ShiftSubtreeContext {
  allShapesMap: Map<string, Bounds>;
  forwardSuccessors: Map<string, string[]>;
}
 
interface PairShiftContext {
  allShapesMap: Map<string, Bounds>;
  procInfos: Map<string, ProcessForwardInfo>;
  modifiedProcesses: Set<string>;
}
 
function mapProcessElements(elements: any[], process: any, map: Map<string, any>): void {
  for (const el of elements) {
    map.set(el.id, process);
    if (el.$type === 'bpmn:SubProcess' && el.flowElements) {
      mapProcessElements(el.flowElements, process, map);
    }
  }
}
 
function buildNodeProcessMap(definitions: any): Map<string, any> {
  const map = new Map<string, any>();
  const processes = (definitions.rootElements || []).filter(
    (el: any) => el.$type === 'bpmn:Process'
  );
  for (const proc of processes) {
    if (proc.flowElements) {
      mapProcessElements(proc.flowElements, proc, map);
    }
  }
  return map;
}
 
function buildProcessForwardInfo(process: any): ProcessForwardInfo {
  const { regularNodes, boundaryEvents, sequenceFlows } = partitionScopeElements(process);
  const graph = buildScopeGraph(regularNodes, boundaryEvents, sequenceFlows);
  const feedbackEdges = findFeedbackEdges(graph);
  const forwardSuccessors = new Map<string, string[]>();
 
  for (const flow of sequenceFlows) {
    if (feedbackEdges.has(flow.id)) {
      continue;
    }
    const srcId = getRefId(flow.sourceRef);
    const tgtId = getRefId(flow.targetRef);
    if (!srcId || !tgtId) {
      continue;
    }
    const succs = forwardSuccessors.get(srcId) || [];
    succs.push(tgtId);
    forwardSuccessors.set(srcId, succs);
  }
 
  return { process, feedbackEdges, forwardSuccessors };
}
 
function collectReachableNodes(
  startId: string,
  forwardSuccessors: Map<string, string[]>
): Set<string> {
  const reachable = new Set<string>();
  const queue = [startId];
  while (queue.length > 0) {
    const current = queue.shift()!;
    reachable.add(current);
    const succs = forwardSuccessors.get(current) || [];
    for (const succ of succs) {
      if (!reachable.has(succ)) {
        reachable.add(succ);
        queue.push(succ);
      }
    }
  }
  return reachable;
}
 
function shiftSubtreeNodes(startId: string, deltaX: number, ctx: ShiftSubtreeContext): void {
  const reachable = collectReachableNodes(startId, ctx.forwardSuccessors);
  for (const id of reachable) {
    const b = ctx.allShapesMap.get(id);
    if (b) {
      b.x += deltaX;
    }
  }
}
 
function collectInterPoolMessagePairs(
  messageFlows: any[],
  nodeToProcess: Map<string, any>
): MessagePair[] {
  const pairs: MessagePair[] = [];
  for (const mf of messageFlows) {
    const srcId = getRefId(mf.sourceRef);
    const tgtId = getRefId(mf.targetRef);
    if (!srcId || !tgtId) {
      continue;
    }
    const srcProc = nodeToProcess.get(srcId);
    const tgtProc = nodeToProcess.get(tgtId);
    if (srcProc && tgtProc && srcProc !== tgtProc) {
      pairs.push({ srcId, tgtId, srcProc, tgtProc });
    }
  }
  return pairs;
}
 
function applyPairShift(pair: MessagePair, ctx: PairShiftContext): boolean {
  const srcBounds = ctx.allShapesMap.get(pair.srcId);
  const tgtBounds = ctx.allShapesMap.get(pair.tgtId);
  if (!srcBounds || !tgtBounds) {
    return false;
  }
  const srcCenter = Math.round(srcBounds.x + srcBounds.width / 2);
  const tgtCenter = Math.round(tgtBounds.x + tgtBounds.width / 2);
  if (srcCenter === tgtCenter) {
    return false;
  }
 
  if (srcCenter > tgtCenter) {
    const delta = srcCenter - tgtCenter;
    const tgtInfo = ctx.procInfos.get(pair.tgtProc.id)!;
    shiftSubtreeNodes(pair.tgtId, delta, {
      allShapesMap: ctx.allShapesMap,
      forwardSuccessors: tgtInfo.forwardSuccessors,
    });
    ctx.modifiedProcesses.add(pair.tgtProc.id);
    return true;
  }
 
  const delta = tgtCenter - srcCenter;
  const srcInfo = ctx.procInfos.get(pair.srcProc.id)!;
  shiftSubtreeNodes(pair.srcId, delta, {
    allShapesMap: ctx.allShapesMap,
    forwardSuccessors: srcInfo.forwardSuccessors,
  });
  ctx.modifiedProcesses.add(pair.srcProc.id);
  return true;
}
 
function updateProcessEdges(
  process: any,
  feedbackEdges: Set<string>,
  ctx: CollaborationAlignmentContext
): void {
  const { regularNodes, boundaryEvents } = partitionScopeElements(process);
  const processBoundsMap = new Map<string, Bounds>();
  for (const n of [...regularNodes, ...boundaryEvents]) {
    const b = ctx.allShapesMap.get(n.id);
    if (b) {
      processBoundsMap.set(n.id, b);
    }
  }
  const rerouted = rerouteProcessEdges(process, processBoundsMap, feedbackEdges);
  const reroutedMap = new Map(rerouted.map((e) => [e.element.id, e]));
  for (const edge of ctx.allEdges) {
    const newRoute = reroutedMap.get(edge.element.id);
    if (newRoute) {
      edge.waypoints = newRoute.waypoints;
      edge.isFeedback = newRoute.isFeedback;
    }
  }
}
 
export function alignCollaborationPaths(opts: CollaborationAlignmentContext): void {
  const { definitions, collaboration } = opts;
  const messageFlows = collaboration?.messageFlows || [];
  if (messageFlows.length === 0) {
    unifyCollaborationPoolWidths(opts);
    return;
  }
 
  const nodeToProcess = buildNodeProcessMap(definitions);
  const pairs = collectInterPoolMessagePairs(messageFlows, nodeToProcess);
  if (pairs.length === 0) {
    unifyCollaborationPoolWidths(opts);
    return;
  }
 
  const procInfos = new Map<string, ProcessForwardInfo>();
  const processes = definitions.rootElements.filter((el: any) => el.$type === 'bpmn:Process');
  for (const p of processes) {
    procInfos.set(p.id, buildProcessForwardInfo(p));
  }
 
  const modifiedProcesses = new Set<string>();
  const pairCtx: PairShiftContext = {
    allShapesMap: opts.allShapesMap,
    procInfos,
    modifiedProcesses,
  };
 
  const MAX_PASSES = 10;
  for (let pass = 0; pass < MAX_PASSES; pass++) {
    let shifted = false;
    for (const pair of pairs) {
      if (applyPairShift(pair, pairCtx)) {
        shifted = true;
      }
    }
    if (!shifted) {
      break;
    }
  }
 
  for (const procId of modifiedProcesses) {
    const info = procInfos.get(procId)!;
    updateProcessEdges(info.process, info.feedbackEdges, opts);
  }
 
  unifyCollaborationPoolWidths(opts);
}
 
export function unifyCollaborationPoolWidths(opts: CollaborationAlignmentContext): void {
  if (!opts.allPools || opts.allPools.length <= 1) {
    return;
  }
 
  let unifiedWidth = Math.max(...opts.allPools.map((p) => p.bounds.width));
  for (const pool of opts.allPools) {
    const poolShapes = opts.allShapes.filter(
      (s) =>
        s.bounds.x >= pool.bounds.x &&
        s.bounds.y >= pool.bounds.y &&
        s.bounds.y + s.bounds.height <= pool.bounds.y + pool.bounds.height
    );
    if (poolShapes.length > 0) {
      const maxShapeRight = Math.max(...poolShapes.map((s) => s.bounds.x + s.bounds.width));
      unifiedWidth = Math.max(unifiedWidth, maxShapeRight - pool.bounds.x + 60);
    }
  }
 
  for (const pool of opts.allPools) {
    pool.bounds.width = unifiedWidth;
    opts.allShapesMap.set(pool.element.id, pool.bounds);
  }
 
  if (opts.allLanes) {
    for (const lane of opts.allLanes) {
      const pool = opts.allPools.find(
        (p) => lane.bounds.y >= p.bounds.y && lane.bounds.y < p.bounds.y + p.bounds.height
      );
      if (pool) {
        lane.bounds.width = pool.bounds.width - (lane.bounds.x - pool.bounds.x);
        opts.allShapesMap.set(lane.element.id, lane.bounds);
      }
    }
  }
}
 
interface GatewayObstacleCandidate {
  candidateGateway: any;
  joinGateway: any;
  obstacleNode: any;
  nonJoinNodes: any[];
  targetX: number;
  deltaX: number;
}
 
interface CorridorCheckContext {
  gCenterX: number;
  yRange: { top: number; bottom: number };
  boundsMap: Map<string, Bounds>;
}
 
function findCorridorObstacle(nodes: any[], ctx: CorridorCheckContext): any | undefined {
  return nodes.find((n) => {
    const b = ctx.boundsMap.get(n.id);
    return (
      b &&
      b.y >= ctx.yRange.top &&
      b.y + b.height <= ctx.yRange.bottom + 40 &&
      ctx.gCenterX >= b.x &&
      ctx.gCenterX <= b.x + b.width
    );
  });
}
 
interface NonJoinContext {
  sequenceFlows: any[];
  joinId: string;
  nodeMap: Map<string, any>;
}
 
function collectNonJoinSubtree(nonJoinFlows: any[], ctx: NonJoinContext): any[] {
  const result: any[] = [];
  const visited = new Set<string>();
  const queue: string[] = [];
 
  for (const f of nonJoinFlows) {
    const id = getRefId(f.targetRef);
    if (id && id !== ctx.joinId && !visited.has(id)) {
      visited.add(id);
      queue.push(id);
    }
  }
 
  while (queue.length > 0) {
    const curId = queue.shift()!;
    const node = ctx.nodeMap.get(curId);
    if (node) {
      result.push(node);
    }
    const out = ctx.sequenceFlows.filter((f) => getRefId(f.sourceRef) === curId);
    for (const f of out) {
      const tgtId = getRefId(f.targetRef);
      if (tgtId && !visited.has(tgtId) && tgtId !== ctx.joinId) {
        visited.add(tgtId);
        queue.push(tgtId);
      }
    }
  }
  return result;
}
 
function findNextColumnNodeX(
  regularNodes: any[],
  range: { minX: number; maxX: number },
  boundsMap: Map<string, Bounds>
): number | undefined {
  let targetX: number | undefined;
  for (const n of regularNodes) {
    const b = boundsMap.get(n.id);
    if (b && b.x >= range.minX && b.x < range.maxX) {
      if (targetX === undefined || b.x < targetX) {
        targetX = b.x;
      }
    }
  }
  return targetX;
}
 
function buildForwardSuccessorsMap(sequenceFlows: any[]): Map<string, string[]> {
  const map = new Map<string, string[]>();
  for (const flow of sequenceFlows) {
    const srcId = getRefId(flow.sourceRef);
    const tgtId = getRefId(flow.targetRef);
    if (srcId && tgtId) {
      const list = map.get(srcId) || [];
      list.push(tgtId);
      map.set(srcId, list);
    }
  }
  return map;
}
 
function findGatewayJoinFlow(
  outgoing: any[],
  gBounds: Bounds,
  ctx: { sequenceFlows: any[]; boundsMap: Map<string, Bounds> }
): any | undefined {
  return outgoing.find((f) => {
    const tgtId = getRefId(f.targetRef);
    if (!tgtId) {
      return false;
    }
    const tgtBounds = ctx.boundsMap.get(tgtId);
    const incCount = ctx.sequenceFlows.filter((sf) => getRefId(sf.targetRef) === tgtId).length;
    return tgtBounds && tgtBounds.y > gBounds.y && incCount >= 2;
  });
}
 
interface GatewayCandidateContext {
  regularNodes: any[];
  sequenceFlows: any[];
  boundsMap: Map<string, Bounds>;
  nodeMap: Map<string, any>;
  forwardSuccessors: Map<string, string[]>;
}
 
function evaluateGatewayCandidate(
  node: any,
  ctx: GatewayCandidateContext
): GatewayObstacleCandidate | undefined {
  if (!node.$type?.endsWith('Gateway') || node.$type?.includes('Parallel')) {
    return undefined;
  }
  const outgoing = ctx.sequenceFlows.filter((f) => getRefId(f.sourceRef) === node.id);
  if (outgoing.length < 2) {
    return undefined;
  }
  const gBounds = ctx.boundsMap.get(node.id)!;
  const joinFlow = findGatewayJoinFlow(outgoing, gBounds, ctx);
  if (!joinFlow) {
    return undefined;
  }
 
  const joinId = getRefId(joinFlow.targetRef)!;
  const jBounds = ctx.boundsMap.get(joinId)!;
  const gCenterX = Math.round(gBounds.x + gBounds.width / 2);
  const otherNodes = ctx.regularNodes.filter((n) => n.id !== node.id && n.id !== joinId);
  const obstacle = findCorridorObstacle(otherNodes, {
    gCenterX,
    yRange: { top: gBounds.y + gBounds.height, bottom: jBounds.y },
    boundsMap: ctx.boundsMap,
  });
  if (!obstacle) {
    return undefined;
  }
 
  const obsBounds = ctx.boundsMap.get(obstacle.id)!;
  const reachable = collectReachableNodes(node.id, ctx.forwardSuccessors);
  const parallelNodes = ctx.regularNodes.filter((n) => !reachable.has(n.id) && n.id !== joinId);
  const targetX = findNextColumnNodeX(
    parallelNodes,
    { minX: obsBounds.x + obsBounds.width, maxX: jBounds.x },
    ctx.boundsMap
  );
  if (targetX === undefined || targetX <= gBounds.x) {
    return undefined;
  }
 
  const deltaX = targetX - gBounds.x;
  if (gBounds.x + deltaX + gBounds.width + 60 > jBounds.x) {
    return undefined;
  }
 
  const nonJoinFlows = outgoing.filter((f) => f !== joinFlow);
  const nonJoinNodes = collectNonJoinSubtree(nonJoinFlows, {
    sequenceFlows: ctx.sequenceFlows,
    joinId,
    nodeMap: ctx.nodeMap,
  });
 
  return {
    candidateGateway: node,
    joinGateway: ctx.nodeMap.get(joinId)!,
    obstacleNode: obstacle,
    nonJoinNodes,
    targetX,
    deltaX,
  };
}
 
function findCandidateObstacle(
  process: any,
  boundsMap: Map<string, Bounds>
): GatewayObstacleCandidate | undefined {
  const { regularNodes, sequenceFlows } = partitionScopeElements(process);
  const nodeMap = new Map<string, any>(regularNodes.map((n) => [n.id, n]));
  const forwardSuccessors = buildForwardSuccessorsMap(sequenceFlows);
 
  const ctx: GatewayCandidateContext = {
    regularNodes,
    sequenceFlows,
    boundsMap,
    nodeMap,
    forwardSuccessors,
  };
 
  for (const node of regularNodes) {
    const candidate = evaluateGatewayCandidate(node, ctx);
    if (candidate) {
      return candidate;
    }
  }
 
  return undefined;
}
 
export function alignIntraProcessBranches(ctx: IntraProcessAlignmentContext): boolean {
  const { process, result } = ctx;
  const boundsMap = new Map<string, Bounds>(result.shapes.map((s) => [s.element.id, s.bounds]));
  const candidate = findCandidateObstacle(process, boundsMap);
  if (!candidate) {
    return false;
  }
 
  const nodesToShift = [candidate.candidateGateway, ...candidate.nonJoinNodes];
  for (const n of nodesToShift) {
    const b = boundsMap.get(n.id)!;
    b.x += candidate.deltaX;
  }
 
  const rerouted = rerouteProcessEdges(process, boundsMap, ctx.feedbackEdges);
  const reroutedMap = new Map(rerouted.map((e) => [e.element.id, e]));
  for (const e of result.edges) {
    const newRoute = reroutedMap.get(e.element.id);
    if (newRoute) {
      e.waypoints = newRoute.waypoints;
      e.isFeedback = newRoute.isFeedback;
    }
  }
 
  let maxRight = 0;
  for (const s of result.shapes) {
    maxRight = Math.max(maxRight, s.bounds.x + s.bounds.width);
  }
  result.width = maxRight - result.minX;
 
  return true;
}
 
export function alignVerticallyStackedPaths(opts: CollaborationAlignmentContext): void {
  const { definitions, collaboration } = opts;
  const participants = collaboration?.participants || [];
 
  for (const part of participants) {
    const procRef = part.processRef?.id || part.processRef;
    const process = (definitions.rootElements || []).find((el: any) => el.id === procRef);
    if (process) {
      const partShapes = opts.allShapes.filter((s) => {
        const p = process.flowElements?.find((fe: any) => fe.id === s.element.id);
        return Boolean(p);
      });
      const partEdges = opts.allEdges.filter((e) => {
        const p = process.flowElements?.find((fe: any) => fe.id === e.element.id);
        return Boolean(p);
      });
      const fakeResult: ScopeLayoutResult = {
        width: 0,
        height: 0,
        minX: Math.min(...partShapes.map((s) => s.bounds.x), 100),
        minY: Math.min(...partShapes.map((s) => s.bounds.y), 100),
        shapes: partShapes,
        edges: partEdges,
      };
      alignIntraProcessBranches({ process, result: fakeResult });
    }
  }
 
  alignCollaborationPaths(opts);
}