All files / src layout-engine.ts

100% Statements 166/166
100% Branches 77/77
100% Functions 28/28
100% Lines 160/160

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                                                                                                72x 72x 72x       68x 64x           72x 72x 72x 72x 72x   72x 2x 2x     66x 66x   66x 66x   72x 8x   58x     66x 66x   66x 66x       68x 68x 68x 8x   60x       58x 58x   58x 58x 58x 58x             58x           58x 2x   58x 273x           58x 211x             58x         8x 8x 8x 8x 8x 8x 8x   8x 11x 24x 11x                       8x                   8x           8x           8x 11x 11x 5x 10x         8x 57x           8x 60x                                   11x 11x 2x 2x 2x     9x 9x   11x 11x   11x 57x 57x   9x 52x 135x 135x       9x                   9x 9x 57x   9x 9x   9x       2x 2x 2x       9x 9x 5x 5x 5x             5x             5x 5x 5x     4x           4x 9x               11x 8x 11x 11x 8x 72x 61x   8x 8x 9x 9x 8x 8x 8x       8x 9x 9x 9x 9x   9x 8x 8x 8x                 8x         8x                         29x 56x     39x                         13x 13x 13x 3x   10x 13x       17x 17x 17x 17x 17x 17x       17x 8x   9x                         15x 15x 7x     8x 8x 8x 8x     8x     8x 3x   5x     11x 8x    
import { BpmnModdle, type BPMNModdle } from 'bpmn-moddle';
import { DiGenerator } from './di-generator';
import { layoutScope } from './hierarchy/subprocess-layout';
import {
  layoutProcessLanes,
  routeMessageFlow,
  isMessageCorridorBlocked,
} from './hierarchy/swimlane-layout';
import { layoutAllLabels, type PlacedEdge, type PlacedShape } from './graph/label-layout';
import { normalizePlaneOrigin } from './plane-normalization';
import { validateFlowContainers } from './validation/bpmn-validation';
import { collectPlaneDiagnostics, type LayoutWarning } from './layout-warnings';
import { alignVerticallyStackedPaths, alignIntraProcessBranches } from './hierarchy/path-alignment';
import type { AutoLayoutOptions, Bounds } from './types';
 
interface PoolEntry {
  element: any;
  bounds: Bounds;
  lanes?: Array<{ element: any; bounds: Bounds }>;
}
 
interface ParticipantLayoutParams {
  participant: any;
  process: any;
  currentY: number;
  allShapesMap: Map<string, Bounds>;
  allShapes: PlacedShape[];
  allEdges: PlacedEdge[];
  allLanes: Array<{ element: any; bounds: Bounds }>;
  allPools: PoolEntry[];
}
 
interface PoolAndLanesParams {
  participant: any;
  process: any;
  result: any;
  currentY: number;
  hasLanes: boolean;
  allLanes?: Array<{ element: any; bounds: Bounds }>;
  allPools: PoolEntry[];
}
 
export class LayoutEngine {
  private moddle: BPMNModdle;
  private diGenerator: DiGenerator;
  private options?: AutoLayoutOptions;
 
  constructor(options?: AutoLayoutOptions) {
    this.options = options;
    this.moddle = new BpmnModdle(options?.moddleExtensions);
    this.diGenerator = new DiGenerator(this.moddle);
  }
 
  public async layout(xml: string): Promise<string> {
    const result = await this.layoutWithDiagnostics(xml);
    return result.xml;
  }
 
  public async layoutWithDiagnostics(
    xml: string
  ): Promise<{ xml: string; warnings: LayoutWarning[] }> {
    const warnings: LayoutWarning[] = [];
    const { rootElement } = await this.moddle.fromXML(xml);
    const definitions: any = rootElement;
    validateFlowContainers(definitions, this.options, warnings);
    const targetElement = this.selectTargetElement(definitions);
 
    if (!targetElement) {
      const { xml: unformatted } = await this.moddle.toXML(definitions, { format: true });
      return { xml: unformatted, warnings };
    }
 
    const diagram = this.diGenerator.ensureDiagram(definitions, targetElement);
    diagram.plane.planeElement = [];
 
    const collaboration = definitions.rootElements?.find(
      (el: any) => el.$type === 'bpmn:Collaboration'
    );
    if (collaboration) {
      this.layoutCollaboration(definitions, collaboration, diagram.plane);
    } else {
      this.layoutSingleProcesses(definitions, diagram.plane);
    }
 
    normalizePlaneOrigin(diagram.plane);
    collectPlaneDiagnostics(diagram.plane, warnings);
 
    const { xml: resultXml } = await this.moddle.toXML(definitions, { format: true });
    return { xml: resultXml, warnings };
  }
 
  private selectTargetElement(definitions: any): any {
    const rootElements = definitions.rootElements || [];
    const collaboration = rootElements.find((el: any) => el.$type === 'bpmn:Collaboration');
    if (collaboration) {
      return collaboration;
    }
    return rootElements.find((el: any) => el.$type === 'bpmn:Process');
  }
 
  private layoutSingleProcesses(definitions: any, plane: any): void {
    const processes = definitions.rootElements.filter((el: any) => el.$type === 'bpmn:Process');
    let startY = 100;
 
    for (const process of processes) {
      const result = layoutScope(process, this.options);
      alignIntraProcessBranches({ process, result, options: this.options });
      const laneResult = layoutProcessLanes(process, result.shapes, {
        startX: 100,
        startY,
        totalWidth: result.width,
        edges: result.edges,
      });
 
      layoutAllLabels({
        shapes: result.shapes,
        edges: result.edges,
        lanes: laneResult.lanes,
      });
 
      for (const lane of laneResult.lanes) {
        this.diGenerator.addShape(plane, lane.element, lane.bounds);
      }
      for (const s of result.shapes) {
        this.diGenerator.addShape(plane, s.element, {
          ...s.bounds,
          isExpanded: s.isExpanded,
          labelBounds: s.labelBounds,
        });
      }
      for (const e of result.edges) {
        this.diGenerator.addEdge(plane, {
          bpmnElement: e.element,
          waypoints: e.waypoints,
          labelBounds: e.labelBounds,
        });
      }
 
      startY += Math.max(result.height, laneResult.totalHeight) + 60;
    }
  }
 
  private layoutCollaboration(definitions: any, collaboration: any, plane: any): void {
    const participants = collaboration.participants || [];
    const allShapesMap = new Map<string, Bounds>();
    const allShapes: PlacedShape[] = [];
    const allEdges: PlacedEdge[] = [];
    const allLanes: Array<{ element: any; bounds: Bounds }> = [];
    const allPools: PoolEntry[] = [];
    let currentY = 80;
 
    for (const participant of participants) {
      const procRef = participant.processRef?.id || participant.processRef;
      const process = definitions.rootElements.find((el: any) => el.id === procRef);
      currentY = this.layoutParticipant({
        participant,
        process,
        currentY,
        allShapesMap,
        allShapes,
        allEdges,
        allLanes,
        allPools,
      });
    }
 
    alignVerticallyStackedPaths({
      definitions,
      collaboration,
      allShapesMap,
      allShapes,
      allEdges,
      allLanes,
      allPools,
    });
 
    this.routeAllMessageFlows(collaboration.messageFlows || [], allShapesMap, {
      plane,
      participants,
      edges: allEdges,
    });
 
    layoutAllLabels({
      shapes: allShapes,
      edges: allEdges,
      lanes: allLanes,
    });
 
    for (const pool of allPools) {
      this.diGenerator.addShape(plane, pool.element, pool.bounds);
      if (pool.lanes) {
        for (const lane of pool.lanes) {
          this.diGenerator.addShape(plane, lane.element, lane.bounds);
        }
      }
    }
 
    for (const s of allShapes) {
      this.diGenerator.addShape(plane, s.element, {
        ...s.bounds,
        isExpanded: s.isExpanded,
        labelBounds: s.labelBounds,
      });
    }
    for (const e of allEdges) {
      this.diGenerator.addEdge(plane, {
        bpmnElement: e.element,
        waypoints: e.waypoints,
        labelBounds: e.labelBounds,
      });
    }
  }
 
  private layoutParticipant(params: ParticipantLayoutParams): number {
    const {
      participant,
      process,
      currentY,
      allShapesMap,
      allShapes,
      allEdges,
      allLanes,
      allPools,
    } = params;
    if (!process) {
      const poolBounds = this.layoutBlackBoxPool(participant, currentY, allPools);
      allShapesMap.set(participant.id, poolBounds);
      return currentY + 160;
    }
 
    const result = layoutScope(process, this.options);
    const hasLanes = Boolean(process.laneSets && process.laneSets[0]?.lanes?.length > 0);
 
    const deltaX = hasLanes ? 0 : 150 - result.minX;
    const deltaY = hasLanes ? currentY - 80 : currentY + 20 - result.minY;
 
    for (const s of result.shapes) {
      s.bounds.x += deltaX;
      s.bounds.y += deltaY;
    }
    for (const e of result.edges) {
      for (const wp of e.waypoints) {
        wp.x += deltaX;
        wp.y += deltaY;
      }
    }
 
    const poolBounds = this.createPoolAndLanes({
      participant,
      process,
      result,
      currentY,
      hasLanes,
      allLanes,
      allPools,
    });
 
    allShapesMap.set(participant.id, poolBounds);
    for (const s of result.shapes) {
      allShapesMap.set(s.element.id, s.bounds);
    }
    allShapes.push(...result.shapes);
    allEdges.push(...result.edges);
 
    return currentY + poolBounds.height + 60;
  }
 
  private layoutBlackBoxPool(participant: any, currentY: number, allPools?: PoolEntry[]): Bounds {
    const poolBounds: Bounds = { x: 100, y: currentY, width: 400, height: 100 };
    allPools?.push({ element: participant, bounds: poolBounds });
    return poolBounds;
  }
 
  private createPoolAndLanes(params: PoolAndLanesParams): Bounds {
    const { participant, process, result, currentY, hasLanes, allLanes, allPools } = params;
    if (hasLanes) {
      const laneStartX = 130;
      const laneWidth = Math.max(400, result.width + 30);
      const laneResult = layoutProcessLanes(process, result.shapes, {
        startX: laneStartX,
        startY: currentY,
        totalWidth: laneWidth,
        edges: result.edges,
      });
 
      const poolBounds: Bounds = {
        x: 100,
        y: currentY,
        width: laneWidth + 30,
        height: laneResult.totalHeight,
      };
 
      allPools?.push({ element: participant, bounds: poolBounds, lanes: laneResult.lanes });
      allLanes?.push(...laneResult.lanes);
      return poolBounds;
    }
 
    const poolBounds: Bounds = {
      x: 100,
      y: currentY,
      width: Math.max(400, result.width + 100),
      height: Math.max(120, result.height + 40),
    };
    allPools?.push({ element: participant, bounds: poolBounds });
    return poolBounds;
  }
 
  private routeAllMessageFlows(
    messageFlows: any[],
    allShapesMap: Map<string, Bounds>,
    options: { plane: any; participants: any[]; edges: PlacedEdge[] }
  ): void {
    const participantIds = new Set(options.participants.map((p: any) => p.id));
    const poolBoundsList = options.participants
      .map((p: any) => allShapesMap.get(p.id))
      .filter((b): b is Bounds => Boolean(b));
    const flowNodeBounds = Array.from(allShapesMap.entries())
      .filter(([id]) => !participantIds.has(id))
      .map(([, b]) => b);
 
    const flowsByTarget = new Map<string, any[]>();
    for (const flow of messageFlows) {
      const tgtId = flow.targetRef?.id || flow.targetRef;
      if (tgtId) {
        const list = flowsByTarget.get(tgtId) || [];
        list.push(flow);
        flowsByTarget.set(tgtId, list);
      }
    }
 
    for (const flow of messageFlows) {
      const srcId = flow.sourceRef?.id || flow.sourceRef;
      const tgtId = flow.targetRef?.id || flow.targetRef;
      const srcBounds = allShapesMap.get(srcId);
      const tgtBounds = allShapesMap.get(tgtId);
 
      if (srcBounds && tgtBounds) {
        const interPoolChannelY = computeInterPoolChannelY(srcBounds, tgtBounds, poolBoundsList);
        const flowsForTarget = flowsByTarget.get(tgtId)!;
        const targetPortX = computeTargetPortX({
          flow,
          flowsForTarget,
          tgtBounds,
          allShapesMap,
          obstacles: flowNodeBounds,
          channelY: interPoolChannelY,
        });
 
        const waypoints = routeMessageFlow(srcBounds, tgtBounds, {
          obstacles: flowNodeBounds,
          interPoolChannelY,
          targetPortX,
        });
        options.edges.push({ element: flow, waypoints });
      }
    }
  }
}
 
export interface ApproachContext {
  targetBounds: Bounds;
  obstacles: Bounds[];
  channelY?: number;
}
 
export function findEnclosingPool(bounds: Bounds, pools: Bounds[]): Bounds | undefined {
  return (
    pools.find((p) => p === bounds) ??
    pools.find(
      (p) =>
        bounds.x >= p.x - 5 &&
        bounds.x + bounds.width <= p.x + p.width + 5 &&
        bounds.y >= p.y - 5 &&
        bounds.y + bounds.height <= p.y + p.height + 5
    )
  );
}
 
export function computeInterPoolChannelY(
  srcBounds: Bounds,
  tgtBounds: Bounds,
  pools: Bounds[]
): number | undefined {
  const srcPool = findEnclosingPool(srcBounds, pools);
  const tgtPool = findEnclosingPool(tgtBounds, pools);
  if (!srcPool || !tgtPool || srcPool === tgtPool) {
    return undefined;
  }
  const [upper, lower] = srcPool.y < tgtPool.y ? [srcPool, tgtPool] : [tgtPool, srcPool];
  return Math.round((upper.y + upper.height + lower.y) / 2);
}
 
export function getEffectiveApproachX(sourceBounds: Bounds, ctx: ApproachContext): number {
  const isUpward = sourceBounds.y >= ctx.targetBounds.y + ctx.targetBounds.height;
  const centerX = Math.round(sourceBounds.x + sourceBounds.width / 2);
  const srcY = isUpward ? sourceBounds.y : sourceBounds.y + sourceBounds.height;
  const tgtY = isUpward ? ctx.targetBounds.y + ctx.targetBounds.height : ctx.targetBounds.y;
  const midY = ctx.channelY ?? Math.round((srcY + tgtY) / 2);
  const blocked = isMessageCorridorBlocked(centerX, [srcY, midY], {
    ignore: [sourceBounds, ctx.targetBounds],
    obstacles: ctx.obstacles,
  });
  if (blocked) {
    return sourceBounds.x + sourceBounds.width + 20;
  }
  return centerX;
}
 
export interface TargetPortParams {
  flow: any;
  flowsForTarget: any[];
  tgtBounds: Bounds;
  allShapesMap: Map<string, Bounds>;
  obstacles: Bounds[];
  channelY?: number;
}
 
export function computeTargetPortX(params: TargetPortParams): number | undefined {
  const { flow, flowsForTarget, tgtBounds, allShapesMap, obstacles, channelY } = params;
  if (flowsForTarget.length <= 1) {
    return undefined;
  }
 
  const sorted = [...flowsForTarget].sort((a, b) => {
    const srcA = allShapesMap.get(a.sourceRef?.id || a.sourceRef);
    const srcB = allShapesMap.get(b.sourceRef?.id || b.sourceRef);
    const xA = srcA
      ? getEffectiveApproachX(srcA, { targetBounds: tgtBounds, obstacles, channelY })
      : 0;
    const xB = srcB
      ? getEffectiveApproachX(srcB, { targetBounds: tgtBounds, obstacles, channelY })
      : 0;
    if (xA !== xB) {
      return xA - xB;
    }
    return (a.id || '').localeCompare(b.id || '');
  });
 
  const index = sorted.findIndex((f) => f.id === flow.id);
  return tgtBounds.x + Math.round((tgtBounds.width * (index + 1)) / (sorted.length + 1));
}