All files / src plane-normalization.ts

100% Statements 37/37
100% Branches 21/21
100% Functions 4/4
100% Lines 37/37

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                71x 71x   71x 629x 355x   629x 139x   629x 273x     71x       71x 71x   71x 494x 494x   71x 273x 656x 656x     71x       10x 122x 122x   10x 87x 208x 208x           71x 71x 71x   71x 4x     67x 71x   71x 57x     10x    
import { CANVAS_MARGIN } from './di-constants';
 
interface PlaneGeometry {
  boundsList: any[];
  waypointLists: any[][];
}
 
function collectPlaneGeometry(elements: any[]): PlaneGeometry {
  const boundsList: any[] = [];
  const waypointLists: any[][] = [];
 
  for (const el of elements) {
    if (el.bounds) {
      boundsList.push(el.bounds);
    }
    if (el.label?.bounds) {
      boundsList.push(el.label.bounds);
    }
    if (Array.isArray(el.waypoint)) {
      waypointLists.push(el.waypoint);
    }
  }
  return { boundsList, waypointLists };
}
 
function computeMinCoordinates(geometry: PlaneGeometry): { minX: number; minY: number } {
  let minX = Infinity;
  let minY = Infinity;
 
  for (const b of geometry.boundsList) {
    minX = Math.min(minX, b.x);
    minY = Math.min(minY, b.y);
  }
  for (const waypoints of geometry.waypointLists) {
    for (const pt of waypoints) {
      minX = Math.min(minX, pt.x);
      minY = Math.min(minY, pt.y);
    }
  }
  return { minX, minY };
}
 
function applyShift(geometry: PlaneGeometry, shiftX: number, shiftY: number): void {
  for (const b of geometry.boundsList) {
    b.x += shiftX;
    b.y += shiftY;
  }
  for (const waypoints of geometry.waypointLists) {
    for (const pt of waypoints) {
      pt.x += shiftX;
      pt.y += shiftY;
    }
  }
}
 
export function normalizePlaneOrigin(plane: any, margin = CANVAS_MARGIN): void {
  const elements = plane?.planeElement || [];
  const geometry = collectPlaneGeometry(elements);
  const { minX, minY } = computeMinCoordinates(geometry);
 
  if (!Number.isFinite(minX) || !Number.isFinite(minY)) {
    return;
  }
 
  const shiftX = minX < margin ? margin - minX : 0;
  const shiftY = minY < margin ? margin - minY : 0;
 
  if (shiftX === 0 && shiftY === 0) {
    return;
  }
 
  applyShift(geometry, shiftX, shiftY);
}