All files / src/graph label-layout.ts

100% Statements 270/270
100% Branches 169/169
100% Functions 24/24
100% Lines 264/264

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 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620                                                                          343x 343x                   547x       567x 567x                   274x 274x       278x 278x       1963x 1963x 14480x 427x 14053x 433x 13620x 3925x 9695x 2187x   7508x     1963x       467x 7x   460x 460x 460x 900x 3x   897x 897x 678x     460x 460x 460x 636x 636x 2x   634x 634x 559x     460x 460x 460x 227x   233x       281x 281x 281x 380x 380x   281x 281x 144x   281x 281x 65x   281x       14x 3x   11x 11x 11x 11x 14x 14x 1x 1x   13x 13x 13x 13x 47x 47x 47x 9x 9x 9x   38x 38x     13x   11x 11x 5x   11x       196x 196x 196x 76x   120x   120x 120x 120x 139x 139x 139x 139x 123x 123x     120x   120x 17x     120x       17x 17x 17x 19x 22x 22x 22x 22x 22x 22x 22x 19x 19x       17x       4394x       2573x 2573x 2573x 2573x   2573x           2490x     83x 16x   67x 66x   1x       639x 4535x 406x   4129x 4535x 4x   4125x 414x       225x 1769x 6x   1763x 1763x 2571x 82x         267x                             442x 442x 442x 442x 442x   442x 207x             235x 101x             134x 70x             64x                       52x 52x 52x 52x 19x   33x 11x   22x 11x             11x             201x 52x   149x 149x 38x             111x 37x             74x 37x             37x                                       155x 155x   155x 187x 187x             187x 422x 422x 126x         29x       29x 29x             29x 57x 57x             57x 201x 201x 9x         20x 20x 20x             20x                     202x 47x     155x 155x 44x 111x 10x 101x 8x     155x           155x   155x   202x 202x 202x                             17x 17x 17x 17x 17x   17x 12x 12x               5x 17x                         270x 263x     7x 7x 7x   7x 7x 7x 8x 8x 7x 7x       7x 7x 7x 7x       270x             270x 8x 8x 8x 12x 12x 6x 6x 6x 6x         1x 1x 1x 1x 1x 1x       68x   68x 335x 187x       68x 273x 263x        
import {
  ARTIFACT_LABEL_MARGIN,
  BOUNDARY_EVENT_LABEL_MARGIN,
  EVENT_LABEL_MARGIN,
  FLOW_LABEL_MARGIN,
  GATEWAY_LABEL_MARGIN,
  LABEL_LINE_HEIGHT,
} from '../di-constants';
import type { Bounds, Point, ElementDimension } from '../types';
 
export interface PlacedShape {
  element: any;
  bounds: Bounds;
  isExpanded?: boolean;
  labelBounds?: Bounds;
}
 
export interface PlacedEdge {
  element: any;
  waypoints: Point[];
  labelBounds?: Bounds;
}
 
export interface LabelLayoutContext {
  shapes: PlacedShape[];
  edges: PlacedEdge[];
  lanes?: Array<{ element: any; bounds: Bounds }>;
}
 
export interface CollisionContext {
  shapes: PlacedShape[];
  edges: PlacedEdge[];
  placedLabels: Bounds[];
  ignoreElementId?: string;
}
 
export function isEvent(element: any): boolean {
  const t = element?.$type || '';
  return (
    t === 'bpmn:StartEvent' ||
    t === 'bpmn:EndEvent' ||
    t === 'bpmn:IntermediateCatchEvent' ||
    t === 'bpmn:IntermediateThrowEvent' ||
    t === 'bpmn:BoundaryEvent'
  );
}
 
export function isBoundaryEvent(element: any): boolean {
  return (element?.$type || '') === 'bpmn:BoundaryEvent';
}
 
export function isGateway(element: any): boolean {
  const t = element?.$type || '';
  return (
    t === 'bpmn:ExclusiveGateway' ||
    t === 'bpmn:ParallelGateway' ||
    t === 'bpmn:InclusiveGateway' ||
    t === 'bpmn:EventBasedGateway' ||
    t === 'bpmn:ComplexGateway'
  );
}
 
export function isArtifact(element: any): boolean {
  const t = element?.$type || '';
  return t === 'bpmn:DataObjectReference' || t === 'bpmn:DataStoreReference';
}
 
export function isFlow(element: any): boolean {
  const t = element?.$type || '';
  return t === 'bpmn:SequenceFlow' || t === 'bpmn:MessageFlow';
}
 
export function estimateWordWidth(word: string): number {
  let width = 0;
  for (const char of word) {
    if (char === ' ') {
      width += 3.5;
    } else if (/[mwMW]/.test(char)) {
      width += 9.5;
    } else if (/[ijlrtfI1]/.test(char)) {
      width += 3.5;
    } else if (/[A-Z]/.test(char)) {
      width += 7.5;
    } else {
      width += 6.0;
    }
  }
  return width;
}
 
export function computeLabelVisualShift(text?: string): number {
  if (!text || text.trim() === '') {
    return 0;
  }
  const words = text.split(/\s+/);
  let maxWordW = 0;
  for (const w of words) {
    if (!w) {
      continue;
    }
    const wLen = estimateWordWidth(w);
    if (wLen > maxWordW) {
      maxWordW = wLen;
    }
  }
  const lines = text.split('\n');
  let maxLineW = 0;
  for (const line of lines) {
    const trimmedLine = line.trim();
    if (!trimmedLine) {
      continue;
    }
    const lLen = estimateWordWidth(trimmedLine);
    if (lLen > maxLineW) {
      maxLineW = lLen;
    }
  }
  const neededW = Math.ceil(maxWordW) + 4;
  const boxW = Math.ceil(maxLineW);
  if (boxW < neededW) {
    return 2;
  }
  return 0;
}
 
export function estimateLabelDimensions(text: string): { width: number; height: number } {
  const lines = text.split('\n');
  let maxLineWidth = 0;
  for (const line of lines) {
    const lineWidth = estimateWordWidth(line);
    maxLineWidth = Math.max(maxLineWidth, Math.ceil(lineWidth) + 4);
  }
  let width = Math.max(20, maxLineWidth);
  if (width % 2 !== 0) {
    width += 1;
  }
  let height = lines.length === 1 ? LABEL_LINE_HEIGHT : lines.length * (LABEL_LINE_HEIGHT - 1) + 1;
  if (height % 2 !== 0) {
    height += 1;
  }
  return { width, height };
}
 
export function estimateTextAnnotationDimensions(text?: string, width = 100): ElementDimension {
  if (!text || text.trim() === '') {
    return { width, height: 30 };
  }
  const maxLineW = width - 14;
  const rawLines = text.split('\n');
  let totalLines = 0;
  for (const rawLine of rawLines) {
    const trimmed = rawLine.trim();
    if (!trimmed) {
      totalLines++;
      continue;
    }
    const words = trimmed.split(/\s+/);
    let curLineW = 0;
    let lineWords = 0;
    for (const w of words) {
      const wLen = estimateWordWidth(w);
      const space = lineWords > 0 ? 4 : 0;
      if (lineWords > 0 && curLineW + space + wLen > maxLineW) {
        totalLines++;
        curLineW = wLen;
        lineWords = 1;
      } else {
        curLineW += space + wLen;
        lineWords++;
      }
    }
    totalLines++;
  }
  let height = Math.max(30, Math.round(totalLines * 14.4 + 14));
  if (height % 2 !== 0) {
    height += 1;
  }
  return { width, height };
}
 
export function generateTextWrapCandidates(text: string): string[] {
  const trimmed = text.trim();
  const words = trimmed.split(/\s+/);
  if (words.length <= 1) {
    return [trimmed];
  }
  const candidates: string[] = [trimmed];
 
  let bestMidSplit = '';
  let minDiff = Number.POSITIVE_INFINITY;
  for (let i = 1; i < words.length; i++) {
    const line1 = words.slice(0, i).join(' ');
    const line2 = words.slice(i).join(' ');
    const diff = Math.abs(line1.length - line2.length);
    if (diff < minDiff) {
      minDiff = diff;
      bestMidSplit = `${line1}\n${line2}`;
    }
  }
  candidates.push(bestMidSplit);
 
  if (words.length >= 3) {
    appendThreeLineWrapCandidates(words, candidates);
  }
 
  return candidates;
}
 
function appendThreeLineWrapCandidates(words: string[], candidates: string[]): void {
  let best3Split = '';
  let min3Diff = Number.POSITIVE_INFINITY;
  for (let i = 1; i < words.length - 1; i++) {
    for (let j = i + 1; j < words.length; j++) {
      const l1 = words.slice(0, i).join(' ');
      const l2 = words.slice(i, j).join(' ');
      const l3 = words.slice(j).join(' ');
      const maxLen = Math.max(l1.length, l2.length, l3.length);
      const minLen = Math.min(l1.length, l2.length, l3.length);
      const diff = maxLen - minLen;
      if (diff < min3Diff) {
        min3Diff = diff;
        best3Split = `${l1}\n${l2}\n${l3}`;
      }
    }
  }
  candidates.push(best3Split);
}
 
export function boxesOverlap(a: Bounds, b: Bounds): boolean {
  return a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y;
}
 
export function doesSegmentCollideWithBox(p1: Point, p2: Point, box: Bounds): boolean {
  const minX = Math.min(p1.x, p2.x);
  const maxX = Math.max(p1.x, p2.x);
  const minY = Math.min(p1.y, p2.y);
  const maxY = Math.max(p1.y, p2.y);
 
  if (
    maxX <= box.x + 1 ||
    minX >= box.x + box.width - 1 ||
    maxY <= box.y + 1 ||
    minY >= box.y + box.height - 1
  ) {
    return false;
  }
 
  if (p1.y === p2.y) {
    return p1.y >= box.y - 1 && p1.y <= box.y + box.height + 1;
  }
  if (p1.x === p2.x) {
    return p1.x >= box.x - 1 && p1.x <= box.x + box.width + 1;
  }
  return true;
}
 
export function doesBoxCollide(box: Bounds, cctx: CollisionContext): boolean {
  for (const s of cctx.shapes) {
    if (s.element.id === cctx.ignoreElementId) {
      continue;
    }
    const t = s.element?.$type;
    if (t === 'bpmn:Participant' || t === 'bpmn:Lane') {
      continue;
    }
    if (boxesOverlap(box, s.bounds)) {
      return true;
    }
  }
 
  for (const edge of cctx.edges) {
    if (edge.element.id === cctx.ignoreElementId) {
      continue;
    }
    const wps = edge.waypoints;
    for (let i = 0; i < wps.length - 1; i++) {
      if (doesSegmentCollideWithBox(wps[i], wps[i + 1], box)) {
        return true;
      }
    }
  }
 
  return cctx.placedLabels.some((lbl) => boxesOverlap(box, lbl));
}
 
export interface ElementLabelGeom {
  elementBounds: Bounds;
  dim: { width: number; height: number };
  margin: number;
  element?: any;
  text?: string;
}
 
function computeOrthogonalElementBounds(
  geom: ElementLabelGeom,
  side: 'bottom' | 'top' | 'right' | 'left'
): Bounds {
  const { elementBounds, dim, margin, element, text } = geom;
  const shift = computeLabelVisualShift(text);
  const cx = Math.round(elementBounds.x + elementBounds.width / 2) - shift;
  const cy = Math.round(elementBounds.y + elementBounds.height / 2);
  const isBoundary = isBoundaryEvent(element);
 
  if (side === 'bottom') {
    return {
      x: cx - dim.width / 2,
      y: elementBounds.y + elementBounds.height + margin,
      width: dim.width,
      height: dim.height,
    };
  }
  if (side === 'top') {
    return {
      x: cx - dim.width / 2,
      y: elementBounds.y - margin - dim.height,
      width: dim.width,
      height: dim.height,
    };
  }
  if (side === 'right') {
    return {
      x: elementBounds.x + elementBounds.width + margin,
      y: isBoundary ? elementBounds.y + elementBounds.height + margin : cy - dim.height / 2,
      width: dim.width,
      height: dim.height,
    };
  }
  return {
    x: elementBounds.x - margin - dim.width,
    y: isBoundary ? elementBounds.y + elementBounds.height + margin : cy - dim.height / 2,
    width: dim.width,
    height: dim.height,
  };
}
 
function computeGatewayDiagonalBounds(
  geom: ElementLabelGeom,
  corner: 'top-right' | 'bottom-right' | 'top-left' | 'bottom-left'
): Bounds {
  const { elementBounds, dim } = geom;
  const cx = Math.round(elementBounds.x + elementBounds.width / 2);
  const cy = Math.round(elementBounds.y + elementBounds.height / 2);
  if (corner === 'top-right') {
    return { x: cx + 14, y: cy - 14 - dim.height, width: dim.width, height: dim.height };
  }
  if (corner === 'bottom-right') {
    return { x: cx + 14, y: cy + 14, width: dim.width, height: dim.height };
  }
  if (corner === 'top-left') {
    return {
      x: cx - 14 - dim.width,
      y: cy - 14 - dim.height,
      width: dim.width,
      height: dim.height,
    };
  }
  return { x: cx - 14 - dim.width, y: cy + 14, width: dim.width, height: dim.height };
}
 
function computeDiagonalElementBounds(
  geom: ElementLabelGeom,
  corner: 'top-right' | 'bottom-right' | 'top-left' | 'bottom-left'
): Bounds {
  if (isGateway(geom.element)) {
    return computeGatewayDiagonalBounds(geom, corner);
  }
  const { elementBounds, dim, margin } = geom;
  if (corner === 'top-right') {
    return {
      x: elementBounds.x + elementBounds.width + margin,
      y: elementBounds.y - margin - dim.height,
      width: dim.width,
      height: dim.height,
    };
  }
  if (corner === 'bottom-right') {
    return {
      x: elementBounds.x + elementBounds.width + margin,
      y: elementBounds.y + elementBounds.height + margin,
      width: dim.width,
      height: dim.height,
    };
  }
  if (corner === 'top-left') {
    return {
      x: elementBounds.x - margin - dim.width,
      y: elementBounds.y - margin - dim.height,
      width: dim.width,
      height: dim.height,
    };
  }
  return {
    x: elementBounds.x - margin - dim.width,
    y: elementBounds.y + elementBounds.height + margin,
    width: dim.width,
    height: dim.height,
  };
}
 
interface PlacementAttempt {
  labelBounds: Bounds;
  text: string;
}
 
export interface PlacementContext {
  shape: PlacedShape;
  margin: number;
  cctx: CollisionContext;
}
 
function findBestOrthogonalPlacement(pctx: PlacementContext): PlacementAttempt | undefined {
  const wrapCandidates = generateTextWrapCandidates(pctx.shape.element.name);
  const sides: Array<'bottom' | 'top' | 'right' | 'left'> = ['bottom', 'top', 'right', 'left'];
 
  for (const text of wrapCandidates) {
    const dim = estimateLabelDimensions(text);
    const geom: ElementLabelGeom = {
      elementBounds: pctx.shape.bounds,
      dim,
      margin: pctx.margin,
      element: pctx.shape.element,
      text,
    };
    for (const side of sides) {
      const candidate = computeOrthogonalElementBounds(geom, side);
      if (!doesBoxCollide(candidate, pctx.cctx)) {
        return { labelBounds: candidate, text };
      }
    }
  }
 
  return undefined;
}
 
function findBestDiagonalPlacement(pctx: PlacementContext): PlacementAttempt {
  const wrapCandidates = generateTextWrapCandidates(pctx.shape.element.name);
  const corners: Array<'top-right' | 'bottom-right' | 'top-left' | 'bottom-left'> = [
    'top-right',
    'bottom-right',
    'top-left',
    'bottom-left',
  ];
 
  for (const text of wrapCandidates) {
    const dim = estimateLabelDimensions(text);
    const geom: ElementLabelGeom = {
      elementBounds: pctx.shape.bounds,
      dim,
      margin: pctx.margin,
      element: pctx.shape.element,
      text,
    };
    for (const corner of corners) {
      const candidate = computeDiagonalElementBounds(geom, corner);
      if (!doesBoxCollide(candidate, pctx.cctx)) {
        return { labelBounds: candidate, text };
      }
    }
  }
 
  const fallbackText = wrapCandidates[wrapCandidates.length - 1];
  const dim = estimateLabelDimensions(fallbackText);
  const geom: ElementLabelGeom = {
    elementBounds: pctx.shape.bounds,
    dim,
    margin: pctx.margin,
    element: pctx.shape.element,
    text: fallbackText,
  };
  return {
    labelBounds: computeOrthogonalElementBounds(geom, 'bottom'),
    text: fallbackText,
  };
}
 
export function layoutElementLabel(
  shape: PlacedShape,
  placedLabels: Bounds[],
  ctx: LabelLayoutContext
): void {
  if (!shape.element?.name || shape.element.name.trim() === '') {
    return;
  }
 
  let margin = EVENT_LABEL_MARGIN;
  if (isGateway(shape.element)) {
    margin = GATEWAY_LABEL_MARGIN;
  } else if (isArtifact(shape.element)) {
    margin = ARTIFACT_LABEL_MARGIN;
  } else if (isBoundaryEvent(shape.element)) {
    margin = BOUNDARY_EVENT_LABEL_MARGIN;
  }
 
  const cctx: CollisionContext = {
    shapes: ctx.shapes,
    edges: ctx.edges,
    placedLabels,
    ignoreElementId: shape.element.id,
  };
  const pctx: PlacementContext = { shape, margin, cctx };
 
  const placement = findBestOrthogonalPlacement(pctx) || findBestDiagonalPlacement(pctx);
 
  shape.labelBounds = placement.labelBounds;
  shape.element.name = placement.text;
  placedLabels.push(placement.labelBounds);
}
 
export interface PathLabelGeom {
  p1: Point;
  p2: Point;
  dim: { width: number; height: number };
  margin: number;
  text?: string;
}
 
export function computePathSegmentLabel(
  geom: PathLabelGeom,
  side: 'top' | 'bottom' | 'right' | 'left'
): Bounds {
  const { p1, p2, dim, margin, text } = geom;
  const isHorizontal = p1.y === p2.y;
  const shift = computeLabelVisualShift(text);
  const mx = Math.round((p1.x + p2.x) / 2) - shift;
  const my = Math.round((p1.y + p2.y) / 2);
 
  if (isHorizontal) {
    const y = side === 'top' ? p1.y - margin - dim.height : p1.y + margin;
    return {
      x: mx - dim.width / 2,
      y,
      width: dim.width,
      height: dim.height,
    };
  }
 
  const x = side === 'right' ? p1.x + margin : p1.x - margin - dim.width;
  return {
    x,
    y: my - dim.height / 2,
    width: dim.width,
    height: dim.height,
  };
}
 
export function layoutPathLabel(
  edge: PlacedEdge,
  placedLabels: Bounds[],
  ctx: LabelLayoutContext
): void {
  if (!edge.element?.name || edge.element.name.trim() === '' || edge.waypoints.length < 2) {
    return;
  }
 
  const wrapCandidates = generateTextWrapCandidates(edge.element.name);
  const wps = edge.waypoints;
  const margin = FLOW_LABEL_MARGIN;
 
  let bestSegIndex = 0;
  let maxSegLen = 0;
  for (let i = 0; i < wps.length - 1; i++) {
    const len = Math.hypot(wps[i + 1].x - wps[i].x, wps[i + 1].y - wps[i].y);
    if (len > maxSegLen) {
      maxSegLen = len;
      bestSegIndex = i;
    }
  }
 
  const p1 = wps[bestSegIndex];
  const p2 = wps[bestSegIndex + 1];
  const isHorizontal = p1.y === p2.y;
  const sides: Array<'top' | 'bottom' | 'right' | 'left'> = isHorizontal
    ? ['top', 'bottom']
    : ['right', 'left'];
 
  const cctx: CollisionContext = {
    shapes: ctx.shapes,
    edges: ctx.edges,
    placedLabels,
    ignoreElementId: edge.element.id,
  };
 
  for (const text of wrapCandidates) {
    const dim = estimateLabelDimensions(text);
    const geom: PathLabelGeom = { p1, p2, dim, margin, text };
    for (const side of sides) {
      const candidate = computePathSegmentLabel(geom, side);
      if (!doesBoxCollide(candidate, cctx)) {
        edge.labelBounds = candidate;
        edge.element.name = text;
        placedLabels.push(candidate);
        return;
      }
    }
  }
 
  const fallbackText = wrapCandidates[0];
  const dim = estimateLabelDimensions(fallbackText);
  const geom: PathLabelGeom = { p1, p2, dim, margin, text: fallbackText };
  const fallbackBounds = computePathSegmentLabel(geom, sides[0]);
  edge.labelBounds = fallbackBounds;
  placedLabels.push(fallbackBounds);
}
 
export function layoutAllLabels(ctx: LabelLayoutContext): void {
  const placedLabels: Bounds[] = [];
 
  for (const shape of ctx.shapes) {
    if (isEvent(shape.element) || isGateway(shape.element) || isArtifact(shape.element)) {
      layoutElementLabel(shape, placedLabels, ctx);
    }
  }
 
  for (const edge of ctx.edges) {
    if (isFlow(edge.element)) {
      layoutPathLabel(edge, placedLabels, ctx);
    }
  }
}