@mark1russell7/layout-contract 0.10.3 → 0.10.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -133,6 +133,11 @@ declare function segmentsCross(a: Point, b: Point, c: Point, d: Point): boolean;
133
133
  declare function crossingPoint(a: Point, b: Point, c: Point, d: Point): Point | undefined;
134
134
  /** This function gives the shortest distance from `p` to the segment `ab`. A segment of length 0 is the point `a`. */
135
135
  declare function pointSegmentDistance(p: Point, a: Point, b: Point): number;
136
+ /**
137
+ * This function gives the shortest distance from `p` to a polyline. A polyline of one point is that point, and an empty polyline gives `Infinity`.
138
+ * The hit test of a route uses it with the polyline of `samplePath`.
139
+ */
140
+ declare function pointPolylineDistance(p: Point, points: readonly Point[]): number;
136
141
  /** A ring of a polygon: its corners in order, as `[x, y]` pairs. The last corner connects to the first. */
137
142
  type Ring = readonly (readonly [number, number])[];
138
143
  /** This function tells if the point (`x`, `y`) is inside a ring, by the even-odd rule. A ring can be concave. The answer for a point on the border can be each value. */
@@ -142,6 +147,12 @@ declare function pointInRing(x: number, y: number, ring: Ring): boolean;
142
147
  * Thus a point inside the outer ring and inside a hole is out. The answer for a point on a border can be each value.
143
148
  */
144
149
  declare function pointInRings(x: number, y: number, rings: readonly Ring[]): boolean;
150
+ /**
151
+ * This function gives the distance from `p` to a region. A point in the region gives 0, so a hit test compares the value with its slack.
152
+ * A hole of a polygon is not in the region. A polygon with no corner gives `Infinity`.
153
+ * The distance to an ellipse is along the line to its center. Thus the value is the shortest distance or more, and the two are equal on the axes.
154
+ */
155
+ declare function pointRegionDistance(p: Point, region: Region): number;
145
156
  /**
146
157
  * This function gives the centroid of the area of a ring, by the shoelace formula. The order of the corners can be
147
158
  * clockwise or counterclockwise. A ring with the area 0 gives the mean of its corners. An empty ring is a `RangeError`.
@@ -154,6 +165,8 @@ declare function ringCentroid(ring: Ring): Point;
154
165
  * gives an empty ring. The part of a convex ring is convex. The part of a concave ring can have sides of length 0 on the line.
155
166
  */
156
167
  declare function clipRing(ring: Ring, a: number, b: number, c: number): Ring;
168
+ /** This function gives the middle of a rectangle. */
169
+ declare function rectCenter(rect: Rect): Point;
157
170
  /** This function gives the distance between the centers of two rectangles. */
158
171
  declare function boxCenterDistance(a: Rect, b: Rect): number;
159
172
  /**
@@ -726,5 +739,5 @@ declare function minEffectOf(spec: Pick<MeasureSpec, "minEffect">, a?: number, b
726
739
  * Two equal values are a tie, also two infinite values. A value `NaN` is an error.
727
740
  */
728
741
  declare function compareMeasure(candidate: number, baseline: number, spec: Pick<MeasureSpec, "direction" | "minEffect">): Verdict;
729
- export { CorpusEntry as $, shapeKindsOf as A, convexCorners as At, LayoutInput as B, pointSegmentDistance as Bt, checkShapes as C, SIDES as Ct, ruleLevel as D, boundsOf as Dt, itemShapeOf as E, SizedRect as Et, LayoutBox as F, grow as Ft, PairGap as G, segmentsCross as Gt, PackInput as H, regionPerimeter as Ht, LayoutCell as I, marginSides as It, canonicalInput as J, toSizedRect as Jt, Port as K, snapRect as Kt, LayoutContainer as L, overlapOf as Lt, shapeSupportProblems as M, cornersInConvex as Mt, shapesOf as N, crossingPoint as Nt, shapeKindOf as O, boxCenterDistance as Ot, Item as P, dropIndex as Pt, ClaimBreak as Q, LayoutEdge as R, pointInRing as Rt, boxArea as S, Ring as St, isShapeKind as T, Sides as Tt, PackInputOptions as U, ringCentroid as Ut, Obstacle as V, regionArea as Vt, PackLink as W, scaleRect as Wt, portPoint as X, packLinks as Y, translate as Yt, toPackInput as Z, ShapeKind as _, splitFolds as _t, MeasureSpec as a, FamilyCell as at, ShapeLimit as b, Rect as bt, minEffectOf as c, SplitFold as ct, SHAPE_KINDS as d, corpusHashOf as dt, CorpusSplit as et, SHAPE_KIND_IDS as f, declaredClaimOf as ft, ShapeInput as g, splitFileName as gt, ShapeGeometry as h, leaveOneSeedOut as ht, JointMeasureId as i, FamilyBy as it, shapeLevel as j, convexOverlap as jt, shapeKindProblem as k, clipRing as kt, DEFAULT_SHAPES as l, checkDeclared as lt, ShapeCheck as m, familyOf as mt, JOINT_MEASURES as n, Declares as nt, Verdict as o, SPLIT_SCHEMA as ot, ShapeBound as p, declaredCounts as pt, Resize as q, toRect as qt, JOINT_MOVED_MIN as r, FAMILY_ANY_KIND as rt, compareMeasure as s, SplitCorpus as st, Direction as t, DeclaredClaim as tt, RuleLevel as u, checkSplit as ut, ShapeKindSpec as v, Margin as vt, inputShapeLevel as w, Side as wt, ShapeSupport as x, Region as xt, ShapeLevel as y, Point as yt, LayoutGenerator as z, pointInRings as zt };
730
- //# sourceMappingURL=measures-J0yY_JvV.d.ts.map
742
+ export { CorpusEntry as $, shapeKindsOf as A, convexCorners as At, LayoutInput as B, pointPolylineDistance as Bt, checkShapes as C, SIDES as Ct, ruleLevel as D, boundsOf as Dt, itemShapeOf as E, SizedRect as Et, LayoutBox as F, grow as Ft, PairGap as G, regionPerimeter as Gt, PackInput as H, pointSegmentDistance as Ht, LayoutCell as I, marginSides as It, canonicalInput as J, segmentsCross as Jt, Port as K, ringCentroid as Kt, LayoutContainer as L, overlapOf as Lt, shapeSupportProblems as M, cornersInConvex as Mt, shapesOf as N, crossingPoint as Nt, shapeKindOf as O, boxCenterDistance as Ot, Item as P, dropIndex as Pt, ClaimBreak as Q, translate as Qt, LayoutEdge as R, pointInRing as Rt, boxArea as S, Ring as St, isShapeKind as T, Sides as Tt, PackInputOptions as U, rectCenter as Ut, Obstacle as V, pointRegionDistance as Vt, PackLink as W, regionArea as Wt, portPoint as X, toRect as Xt, packLinks as Y, snapRect as Yt, toPackInput as Z, toSizedRect as Zt, ShapeKind as _, splitFolds as _t, MeasureSpec as a, FamilyCell as at, ShapeLimit as b, Rect as bt, minEffectOf as c, SplitFold as ct, SHAPE_KINDS as d, corpusHashOf as dt, CorpusSplit as et, SHAPE_KIND_IDS as f, declaredClaimOf as ft, ShapeInput as g, splitFileName as gt, ShapeGeometry as h, leaveOneSeedOut as ht, JointMeasureId as i, FamilyBy as it, shapeLevel as j, convexOverlap as jt, shapeKindProblem as k, clipRing as kt, DEFAULT_SHAPES as l, checkDeclared as lt, ShapeCheck as m, familyOf as mt, JOINT_MEASURES as n, Declares as nt, Verdict as o, SPLIT_SCHEMA as ot, ShapeBound as p, declaredCounts as pt, Resize as q, scaleRect as qt, JOINT_MOVED_MIN as r, FAMILY_ANY_KIND as rt, compareMeasure as s, SplitCorpus as st, Direction as t, DeclaredClaim as tt, RuleLevel as u, checkSplit as ut, ShapeKindSpec as v, Margin as vt, inputShapeLevel as w, Side as wt, ShapeSupport as x, Region as xt, ShapeLevel as y, Point as yt, LayoutGenerator as z, pointInRings as zt };
743
+ //# sourceMappingURL=measures-B4oIewps.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"measures-B4oIewps.d.ts","names":[],"sources":["../src/geometry.ts","../src/corpus.ts","../src/input.ts","../src/shapes.ts","../src/measures.ts"],"mappings":";KAGY;;cAGC,gBAAgB;UAEZ;WACN;WACA;;;UAIM;WACN;WACA;WACA;WACA;;;;;;UAOM;WACN;WACA;WACA;WACA;;;iBAIK,OAAO,MAAM,YAAY;;iBAKzB,YAAY,MAAM,OAAO;;;;;iBAWzB,SAAS,MAAM,OAAO;;;;;;iBAWtB,UAAU,MAAM,MAAM,iBAAiB;;UAMtC;WACN;WACA;WACA;WACA;;;;;;KAOC;WACG;WAAuB;WAAoB;WAAoB;WAAoB;;WAEnF;WACA,QAAQ;WACR,iBAAiB;;WAEjB;WAAyB;WAAqB;WAAqB;;WACnE;WAA0B;WAAqB;WAAqB;WAAqB;;;KAG5F,kBAAkB;;iBAGd,YAAY,QAAQ,qBAAqB;;iBAOzC,KAAK,MAAM,MAAM,QAAQ,qBAAqB;;iBAM9C,SAAS,QAAQ,SAAS;;;;;iBA4B1B,WAAW,QAAQ;;;;;;;iBA8BnB,gBAAgB,QAAQ;;iBA+BxB,UAAU,QAAQ,QAAQ,YAAY,aAAa;;;;;iBAoBnD,UAAU,GAAG,MAAM,GAAG;WAAkB;WAAoB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;;iBAezD,eAAe,mBAAmB,kBAAkB,MAAM,KAAK,0CAA0C"}
package/build/text.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as MeasureSpec } from "./measures-J0yY_JvV.js";
1
+ import { a as MeasureSpec } from "./measures-B4oIewps.js";
2
2
  /**
3
3
  * The advance function of a host: the width of a run of text in a font, in pixels.
4
4
  * A browser host gives `canvasAdvance(context)`. A test or a server host gives a function of a font file.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/layout-contract",
4
- "version": "0.10.3",
4
+ "version": "0.10.5",
5
5
  "description": "The shared contract of the packing and highways layout engines: the input and record formats, the turn rule, margins, tolerances and hard rules.",
6
6
  "keywords": [
7
7
  "layout",
package/src/geometry.ts CHANGED
@@ -365,6 +365,18 @@ export function pointSegmentDistance(p: Point, a: Point, b: Point): number {
365
365
  return Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy));
366
366
  }
367
367
 
368
+ /**
369
+ * This function gives the shortest distance from `p` to a polyline. A polyline of one point is that point, and an empty polyline gives `Infinity`.
370
+ * The hit test of a route uses it with the polyline of `samplePath`.
371
+ */
372
+ export function pointPolylineDistance(p: Point, points: readonly Point[]): number {
373
+ const first = points[0];
374
+ if (first === undefined) return Infinity;
375
+ let best = Math.hypot(p.x - first.x, p.y - first.y);
376
+ for (let i = 1; i < points.length; i++) best = Math.min(best, pointSegmentDistance(p, points[i - 1]!, points[i]!));
377
+ return best;
378
+ }
379
+
368
380
  /** A ring of a polygon: its corners in order, as `[x, y]` pairs. The last corner connects to the first. */
369
381
  export type Ring = readonly (readonly [number, number])[];
370
382
 
@@ -389,6 +401,46 @@ export function pointInRings(x: number, y: number, rings: readonly Ring[]): bool
389
401
  return inside;
390
402
  }
391
403
 
404
+ /**
405
+ * This function gives the distance from `p` to a region. A point in the region gives 0, so a hit test compares the value with its slack.
406
+ * A hole of a polygon is not in the region. A polygon with no corner gives `Infinity`.
407
+ * The distance to an ellipse is along the line to its center. Thus the value is the shortest distance or more, and the two are equal on the axes.
408
+ */
409
+ export function pointRegionDistance(p: Point, region: Region): number {
410
+ switch (region.kind) {
411
+ case "rect":
412
+ return Math.hypot(Math.max(region.x - p.x, 0, p.x - region.x - region.w), Math.max(region.y - p.y, 0, p.y - region.y - region.h));
413
+ case "circle":
414
+ return Math.max(0, Math.hypot(p.x - region.cx, p.y - region.cy) - region.r);
415
+ case "ellipse": {
416
+ const dx = p.x - region.cx;
417
+ const dy = p.y - region.cy;
418
+ // An ellipse with no width or no height is a segment or a point.
419
+ if (!(region.rx > 0) || !(region.ry > 0)) {
420
+ const rx = Math.max(0, region.rx);
421
+ const ry = Math.max(0, region.ry);
422
+ return pointSegmentDistance(p, { x: region.cx - rx, y: region.cy - ry }, { x: region.cx + rx, y: region.cy + ry });
423
+ }
424
+ // The line from the center to `p` leaves the ellipse at the share 1 / `far` of its length.
425
+ const far = Math.hypot(dx / region.rx, dy / region.ry);
426
+ return far <= 1 ? 0 : Math.hypot(dx, dy) * (1 - 1 / far);
427
+ }
428
+ case "polygon": {
429
+ const rings = region.holes === undefined ? [region.points] : [region.points, ...region.holes];
430
+ if (pointInRings(p.x, p.y, rings)) return 0;
431
+ let best = Infinity;
432
+ for (const ring of rings) {
433
+ for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
434
+ const [ax, ay] = ring[j]!;
435
+ const [bx, by] = ring[i]!;
436
+ best = Math.min(best, pointSegmentDistance(p, { x: ax, y: ay }, { x: bx, y: by }));
437
+ }
438
+ }
439
+ return best;
440
+ }
441
+ }
442
+ }
443
+
392
444
  /**
393
445
  * This function gives the centroid of the area of a ring, by the shoelace formula. The order of the corners can be
394
446
  * clockwise or counterclockwise. A ring with the area 0 gives the mean of its corners. An empty ring is a `RangeError`.
@@ -440,6 +492,11 @@ export function clipRing(ring: Ring, a: number, b: number, c: number): Ring {
440
492
  return out;
441
493
  }
442
494
 
495
+ /** This function gives the middle of a rectangle. */
496
+ export function rectCenter(rect: Rect): Point {
497
+ return { x: rect.x + rect.w / 2, y: rect.y + rect.h / 2 };
498
+ }
499
+
443
500
  /** This function gives the distance between the centers of two rectangles. */
444
501
  export function boxCenterDistance(a: Rect, b: Rect): number {
445
502
  return Math.hypot(b.x + b.w / 2 - (a.x + a.w / 2), b.y + b.h / 2 - (a.y + a.h / 2));
package/src/index.ts CHANGED
@@ -15,6 +15,7 @@ export * from "./cell.ts";
15
15
  export * from "./frame.ts";
16
16
  export * from "./path.ts";
17
17
  export * from "./picture.ts";
18
+ export * from "./nest.ts";
18
19
  export * from "./strategy.ts";
19
20
  export * from "./random.ts";
20
21
  export * from "./edges.ts";
package/src/nest.ts ADDED
@@ -0,0 +1,233 @@
1
+ // The boxes in boxes of an input (`docs/NESTED.md`). The field `parent` of a box makes a tree of boxes.
2
+ // A layout of the children of one box reads the tree. A router of the top boxes reads a flat input.
3
+ import { rectCenter, type Point, type Rect, type Side } from "./geometry.ts";
4
+ import type { LayoutBox, LayoutEdge, LayoutInput, Port } from "./input.ts";
5
+
6
+ /** One box of a tree of boxes, with the boxes that it contains. */
7
+ export interface BoxNode {
8
+ readonly box: LayoutBox;
9
+ /** The boxes that have this box as their `parent`, in the order of the input. */
10
+ readonly children: readonly BoxNode[];
11
+ }
12
+
13
+ /** The facts of the tree of a list of boxes. */
14
+ interface Levels {
15
+ readonly roots: readonly BoxNode[];
16
+ /** The count of the boxes above each box. */
17
+ readonly depth: ReadonlyMap<string, number>;
18
+ /** The box with no parent that contains each box. */
19
+ readonly top: ReadonlyMap<string, string>;
20
+ }
21
+
22
+ /** This function gives the tree of a list of boxes, with the depth and the top box of each box. `name` is the function in the text of an error. */
23
+ function levelsOf(boxes: readonly LayoutBox[], name: string): Levels {
24
+ const nodes = new Map<string, { box: LayoutBox; children: BoxNode[] }>();
25
+ for (const box of boxes) {
26
+ if (nodes.has(box.id)) throw new RangeError(`${name}: the id ${box.id} is two times in the boxes.`);
27
+ nodes.set(box.id, { box, children: [] });
28
+ }
29
+ const roots: BoxNode[] = [];
30
+ for (const node of nodes.values()) {
31
+ const { id, parent } = node.box;
32
+ if (parent === undefined) {
33
+ roots.push(node);
34
+ continue;
35
+ }
36
+ const above = nodes.get(parent);
37
+ if (above === undefined) throw new RangeError(`${name}: the parent ${parent} of the box ${id} is not a box of the input.`);
38
+ above.children.push(node);
39
+ }
40
+ const depth = new Map<string, number>();
41
+ const top = new Map<string, string>();
42
+ for (const root of roots) {
43
+ const stack: (readonly [BoxNode, number])[] = [[root, 0]];
44
+ for (let next = stack.pop(); next !== undefined; next = stack.pop()) {
45
+ const [node, level] = next;
46
+ depth.set(node.box.id, level);
47
+ top.set(node.box.id, root.box.id);
48
+ for (const child of node.children) stack.push([child, level + 1]);
49
+ }
50
+ }
51
+ // A box in a loop of parents has no box with no parent above it.
52
+ if (depth.size < nodes.size) throw new RangeError(`${name}: the parents of the boxes make a loop.`);
53
+ return { roots, depth, top };
54
+ }
55
+
56
+ /**
57
+ * This function gives the tree of the boxes of an input. Each box with no `parent` is a root, in the order of the input.
58
+ * The children of a box are in the order of the input too. An adapter of a layout engine makes the nodes of the engine from this tree.
59
+ *
60
+ * A `RangeError` comes for an id that is two times in the list, and for a parent that is not in the list.
61
+ * It comes also for a loop of parents.
62
+ */
63
+ export function boxTree(boxes: readonly LayoutBox[]): BoxNode[] {
64
+ return [...levelsOf(boxes, "boxTree").roots];
65
+ }
66
+
67
+ /**
68
+ * This function gives the top box of each box of an input, by the id of the box. The top box of a box is the box with no `parent` that contains it.
69
+ * A box with no parent is its own top box.
70
+ *
71
+ * A `RangeError` comes for each list that `boxTree` refuses.
72
+ */
73
+ export function topBoxes(boxes: readonly LayoutBox[]): Map<string, string> {
74
+ return new Map(levelsOf(boxes, "topBoxes").top);
75
+ }
76
+
77
+ /**
78
+ * This function gives the edges of an input between boxes with the same parent. A layout of the children of one box reads them, for example as springs.
79
+ *
80
+ * - An edge between two boxes with the same parent stays as it is. Two boxes with no parent have the same parent.
81
+ * - Each other edge goes up the tree: its ends become the two boxes with the same parent that contain its ends.
82
+ * - An end that goes up loses its port. The edge keeps its id and its `data`.
83
+ * - An edge has no result if one end contains the other end, or if the two ends are one box.
84
+ * - An edge with an end that is not a box of the input has no result.
85
+ *
86
+ * The result has the order of the edges of the input. A `RangeError` comes for each list of boxes that `boxTree` refuses.
87
+ */
88
+ export function siblingEdges(input: Pick<LayoutInput, "boxes" | "edges">): LayoutEdge[] {
89
+ const { depth } = levelsOf(input.boxes, "siblingEdges");
90
+ const parent = new Map(input.boxes.map((box) => [box.id, box.parent]));
91
+ const out: LayoutEdge[] = [];
92
+ for (const edge of input.edges ?? []) {
93
+ let a = edge.source;
94
+ let b = edge.target;
95
+ let da = depth.get(a);
96
+ let db = depth.get(b);
97
+ if (da === undefined || db === undefined) continue;
98
+ for (; da > db; da--) a = parent.get(a)!;
99
+ for (; db > da; db--) b = parent.get(b)!;
100
+ // At the same depth, the same box means that one end contains the other end.
101
+ if (a === b) continue;
102
+ while (parent.get(a) !== parent.get(b)) {
103
+ a = parent.get(a)!;
104
+ b = parent.get(b)!;
105
+ }
106
+ out.push({
107
+ id: edge.id,
108
+ source: a,
109
+ target: b,
110
+ ...(a === edge.source && edge.sourcePort !== undefined ? { sourcePort: edge.sourcePort } : {}),
111
+ ...(b === edge.target && edge.targetPort !== undefined ? { targetPort: edge.targetPort } : {}),
112
+ ...(edge.data === undefined ? {} : { data: edge.data }),
113
+ });
114
+ }
115
+ return out;
116
+ }
117
+
118
+ /** The options of `flattenInput`. */
119
+ export interface FlattenOptions {
120
+ /**
121
+ * The sides of a top box that can hold the port of a box inside it. The default is `right` and `left`, for rows in a column.
122
+ * The first side of the list wins a tie. With an empty list, an edge of a box inside a top box goes to the top box with no port.
123
+ */
124
+ readonly sides?: readonly Side[];
125
+ }
126
+
127
+ /** The sides of `flattenInput` with no option: the two ends of a row. */
128
+ export const FLATTEN_SIDES: readonly Side[] = /* @__PURE__ */ Object.freeze(["right", "left"] as const);
129
+
130
+ /** The direction out of each side of a box. The y axis points down. */
131
+ const OUT: Readonly<Record<Side, Point>> = { top: { x: 0, y: -1 }, right: { x: 1, y: 0 }, bottom: { x: 0, y: 1 }, left: { x: -1, y: 0 } };
132
+
133
+ /** This function gives the rectangle of a placed box. A `RangeError` comes for a box with no place. */
134
+ function placeOf(box: LayoutBox): Rect {
135
+ if (box.x === undefined || box.y === undefined) throw new RangeError(`flattenInput: the box ${box.id} has no place, and the port of a box in a top box needs it.`);
136
+ return { x: box.x, y: box.y, w: box.w, h: box.h };
137
+ }
138
+
139
+ /** This function gives the id of the port that `flattenInput` makes for a box inside a top box, on a side of the top box. */
140
+ export function flatPortId(box: string, side: Side): string {
141
+ return `${box}:${side}`;
142
+ }
143
+
144
+ /** This function gives the share `part` of `whole`, from 0 to 1. A whole of 0 gives the middle. */
145
+ function shareOf(part: number, whole: number): number {
146
+ return whole > 0 ? Math.min(1, Math.max(0, part / whole)) : 0.5;
147
+ }
148
+
149
+ /**
150
+ * This function gives the input of the top boxes of an input, for a router that does not go into a box.
151
+ * The top boxes are the boxes with no `parent`. Each top box is one obstacle, and a box inside it becomes a port on its border.
152
+ *
153
+ * - An edge between two top boxes stays as it is.
154
+ * - An edge with an end inside a top box goes to that top box, at a port. The port is on the side that points most to the top box of the other end.
155
+ * - The port is at the middle of the inner box along that side. Its id comes from `flatPortId`. Only an end of an edge makes a port.
156
+ * - An end that moves to a top box loses the port that it had.
157
+ * - An edge has no result if its two ends are in one top box, or if an end is not a box of the input.
158
+ *
159
+ * Each edge keeps its id and its `data`. Thus a route of the flat input is the route of the edge with the same id in the input.
160
+ * `pictureOf` puts that route between the inner boxes.
161
+ *
162
+ * The other fields of the input stay. The result has no `hash`, because it is a different document, and no `pairGaps` entry of an inner box.
163
+ * A port needs the place of its inner box and of the two top boxes. A `RangeError` comes for a box with no place there.
164
+ * It comes also for a top box that has a port with the id of a new port. Each list of boxes that `boxTree` refuses gives one too.
165
+ */
166
+ export function flattenInput(input: LayoutInput, options: FlattenOptions = {}): LayoutInput {
167
+ const sides = options.sides ?? FLATTEN_SIDES;
168
+ const { top } = levelsOf(input.boxes, "flattenInput");
169
+ const byId = new Map(input.boxes.map((box) => [box.id, box]));
170
+ const ports = new Map<string, Port[]>();
171
+ const made = new Set<string>();
172
+
173
+ /** This function gives the end of an edge in the flat input: the top box of `id`, and its port. `other` is the top box of the other end. */
174
+ const endOf = (id: string, own: string, other: string, port: string | undefined): { readonly box: string; readonly port?: string } => {
175
+ if (own === id) return port === undefined ? { box: id } : { box: id, port };
176
+ if (sides.length === 0) return { box: own };
177
+ const card = byId.get(own)!;
178
+ const outer = placeOf(card);
179
+ const from = rectCenter(outer);
180
+ const to = rectCenter(placeOf(byId.get(other)!));
181
+ let side = sides[0]!;
182
+ let most = -Infinity;
183
+ for (const s of sides) {
184
+ const toward = (to.x - from.x) * OUT[s].x + (to.y - from.y) * OUT[s].y;
185
+ if (toward > most) {
186
+ most = toward;
187
+ side = s;
188
+ }
189
+ }
190
+ const name = flatPortId(id, side);
191
+ if (!made.has(name)) {
192
+ if (card.ports?.some((p) => p.id === name) === true) throw new RangeError(`flattenInput: the box ${own} has a port with the id ${name} of a new port.`);
193
+ const middle = rectCenter(placeOf(byId.get(id)!));
194
+ const along = side === "left" || side === "right" ? shareOf(middle.y - outer.y, outer.h) : shareOf(middle.x - outer.x, outer.w);
195
+ const list = ports.get(own);
196
+ if (list === undefined) ports.set(own, [{ id: name, side, along }]);
197
+ else list.push({ id: name, side, along });
198
+ made.add(name);
199
+ }
200
+ return { box: own, port: name };
201
+ };
202
+
203
+ const edges: LayoutEdge[] = [];
204
+ for (const edge of input.edges ?? []) {
205
+ const s = top.get(edge.source);
206
+ const t = top.get(edge.target);
207
+ if (s === undefined || t === undefined || s === t) continue;
208
+ const source = endOf(edge.source, s, t, edge.sourcePort);
209
+ const target = endOf(edge.target, t, s, edge.targetPort);
210
+ edges.push({
211
+ id: edge.id,
212
+ source: source.box,
213
+ target: target.box,
214
+ ...(source.port === undefined ? {} : { sourcePort: source.port }),
215
+ ...(target.port === undefined ? {} : { targetPort: target.port }),
216
+ ...(edge.data === undefined ? {} : { data: edge.data }),
217
+ });
218
+ }
219
+ const boxes = input.boxes
220
+ .filter((box) => box.parent === undefined)
221
+ .map((box): LayoutBox => {
222
+ const more = ports.get(box.id);
223
+ return more === undefined ? box : { ...box, ports: [...(box.ports ?? []), ...more] };
224
+ });
225
+ const { hash: _hash, pairGaps, ...rest } = input;
226
+ const gaps = pairGaps?.filter((pair) => top.get(pair.a) === pair.a && top.get(pair.b) === pair.b);
227
+ return {
228
+ ...rest,
229
+ ...(gaps === undefined ? {} : { pairGaps: gaps }),
230
+ boxes,
231
+ ...(input.edges === undefined ? {} : { edges }),
232
+ };
233
+ }
@@ -1 +0,0 @@
1
- {"version":3,"file":"measures-J0yY_JvV.d.ts","names":[],"sources":["../src/geometry.ts","../src/corpus.ts","../src/input.ts","../src/shapes.ts","../src/measures.ts"],"mappings":";KAGY;;cAGC,gBAAgB;UAEZ;WACN;WACA;;;UAIM;WACN;WACA;WACA;WACA;;;;;;UAOM;WACN;WACA;WACA;WACA;;;iBAIK,OAAO,MAAM,YAAY;;iBAKzB,YAAY,MAAM,OAAO;;;;;iBAWzB,SAAS,MAAM,OAAO;;;;;;iBAWtB,UAAU,MAAM,MAAM,iBAAiB;;UAMtC;WACN;WACA;WACA;WACA;;;;;;KAOC;WACG;WAAuB;WAAoB;WAAoB;WAAoB;;WAEnF;WACA,QAAQ;WACR,iBAAiB;;WAEjB;WAAyB;WAAqB;WAAqB;;WACnE;WAA0B;WAAqB;WAAqB;WAAqB;;;KAG5F,kBAAkB;;iBAGd,YAAY,QAAQ,qBAAqB;;iBAOzC,KAAK,MAAM,MAAM,QAAQ,qBAAqB;;iBAM9C,SAAS,QAAQ,SAAS;;;;;iBA4B1B,WAAW,QAAQ;;;;;;;iBA8BnB,gBAAgB,QAAQ;;iBA+BxB,UAAU,QAAQ,QAAQ,YAAY,aAAa;;;;;iBA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