@mark1russell7/layout-contract 0.3.11 → 0.4.0

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.
package/build/index.js CHANGED
@@ -177,7 +177,7 @@ function pointSegmentDistance(p, a, b) {
177
177
  // src/shapes.ts
178
178
  /**
179
179
  * The declared shape kinds, in their order. Only `rect` has all of its geometry.
180
- * `polygon` and `circle` have their bounding box and their exact area. `free` has its bounding box only.
180
+ * `polygon` and `circle` have their bounding box and their exact area. A `circle` also has the overlap test of two circles. `free` has its bounding box only.
181
181
  */
182
182
  const SHAPE_KINDS = /* @__PURE__ */ Object.freeze([
183
183
  {
@@ -214,7 +214,7 @@ const SHAPE_KINDS = /* @__PURE__ */ Object.freeze([
214
214
  bounds: true,
215
215
  area: true,
216
216
  contains: false,
217
- overlap: false
217
+ overlap: true
218
218
  }
219
219
  },
220
220
  {
@@ -256,14 +256,35 @@ function shapeLevel(use, kind) {
256
256
  if (level !== "none") return level;
257
257
  return use.bound?.shapes.includes(kind) === true ? "bound" : "none";
258
258
  }
259
+ /** This function tells if a limit names an input. An input without a circle box is not in a limit. */
260
+ function inLimit(limit, input) {
261
+ const kinds = shapeKindsOf(input);
262
+ if (!kinds.includes("circle")) return false;
263
+ if (limit.reads === "neighbours") return kinds.length > 1 || (input.obstacles?.length ?? 0) > 0;
264
+ const shape = input.container?.shape?.kind;
265
+ return shape === "polygon" || shape === "ellipse";
266
+ }
267
+ /**
268
+ * This function gives the level of a measure or a rule on a shape kind for one input. It is `shapeLevel` with the `limit` of the rule.
269
+ * When the limit names the input, the level `exact` becomes `safe`. Each other level does not change.
270
+ */
271
+ function inputShapeLevel(use, kind, input) {
272
+ const level = shapeLevel(use, kind);
273
+ return level === "exact" && use.limit !== void 0 && inLimit(use.limit, input) ? "safe" : level;
274
+ }
259
275
  /**
260
276
  * This function gives the problems of a list of measures and rules. An empty list tells that the list is good.
261
277
  * It refuses an unknown kind, a kind two times in one list, and a kind in more than one of `shapesOf`, `safe` and `bound.shapes`.
262
278
  * It also refuses a `bound` without a list of kinds, and a `side` that is not `upper` or `lower`.
279
+ * It also refuses a `limit` with a bad `reads` or a bad `until`.
263
280
  */
264
281
  function shapeSupportProblems(uses) {
265
282
  const out = [];
266
283
  for (const use of uses) {
284
+ if (use.limit !== void 0) {
285
+ if (use.limit.reads !== "neighbours" && use.limit.reads !== "container") out.push(`${use.id}: the limit reads ${String(use.limit.reads)}, not neighbours or container`);
286
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(String(use.limit.until))) out.push(`${use.id}: the limit date ${String(use.limit.until)} is not YYYY-MM-DD`);
287
+ }
267
288
  const bound = use.bound;
268
289
  const isBound = typeof bound === "object" && bound !== null && !Array.isArray(bound);
269
290
  if (bound !== void 0 && !isBound) out.push(`${use.id}: the bound value is not an object with shapes and a side`);
@@ -364,7 +385,7 @@ function checkShapes(input, uses, options = {}) {
364
385
  for (const use of uses) {
365
386
  const shapes = shapesOf(use);
366
387
  for (const kind of kinds) {
367
- const level = shapeLevel(use, kind);
388
+ const level = inputShapeLevel(use, kind, input);
368
389
  if (level === "exact" || level === "safe" && (options.level === "safe" || options.level === "bound") || level === "bound" && options.level === "bound") continue;
369
390
  const ids = input.boxes.filter((b) => shapeKindOf(b) === kind).map((b) => b.id);
370
391
  const shown = ids.slice(0, 5).join(", ") + (ids.length > 5 ? `, and ${ids.length - 5} more` : "");
@@ -664,7 +685,11 @@ const RECORD_OPTIONAL_STRINGS = [
664
685
  "skipped",
665
686
  "commit"
666
687
  ];
667
- const RECORD_OPTIONAL_NUMBERS = ["budgetMs", "msAtLeast"];
688
+ const RECORD_OPTIONAL_NUMBERS = [
689
+ "budgetMs",
690
+ "msAtLeast",
691
+ "hardRule"
692
+ ];
668
693
  const ENV_STRINGS = [
669
694
  "node",
670
695
  "os",
@@ -691,6 +716,13 @@ function envProblems(env) {
691
716
  return out;
692
717
  }
693
718
  /**
719
+ * This function gives the version of the rules that made the counts of `hard` of a record. A record without `hardRule` has version 1.
720
+ * On version 1, a count on a circle is by its bounding box. So it is an upper bound, and a count over 0 proves nothing.
721
+ */
722
+ function hardRuleOf(record) {
723
+ return record.hardRule ?? 1;
724
+ }
725
+ /**
694
726
  * This function gives the problems of one `layout-record/1` value. An empty list means a good record.
695
727
  * A record that has `skipped` has `deterministic: null`. An old skipped record with a boolean is also correct.
696
728
  * A record without `skipped` has a boolean. The check accepts fields that the format does not know.
@@ -756,45 +788,136 @@ function placedRect(box) {
756
788
  };
757
789
  }
758
790
  /**
759
- * This function counts the pairs of placed boxes whose insides, with their margins, overlap by more than `tolerance` on each axis.
760
- * A box with a shape counts as its bounding box. That area is larger, thus the count is safe.
791
+ * The version of the rules that count `no-overlap` and `in-container`. A record states it in `LayoutRecord.hardRule`.
761
792
  *
762
- * A pair of `pairGaps`, in either order, uses its `gap` in place of the two margins. One box grows by the gap, and the other box does not grow.
763
- * Thus the pair breaks the rule only when the boxes are nearer than the gap on each axis. The other pairs do not change.
793
+ * - Version 1 counts each shape by its bounding box. On a circle, that count is an upper bound. A count over 0 proves nothing.
794
+ * - Version 2 counts two circles, and a circle in a circle container, by the distance of the centers. The other pairs stay on the bounding box.
764
795
  */
765
- function countOverlaps(boxes, tolerance = DEFAULT_TOLERANCE.overlap, pairGaps) {
766
- if (pairGaps === void 0 || pairGaps.length === 0) return marginOverlaps(boxes, tolerance, void 0);
796
+ const HARD_RULE_VERSION = 2;
797
+ /** This function gives the circle of a placed box. A box without a position, or with another shape, gives `undefined`. */
798
+ function placedCircle(box) {
799
+ if (box.shape?.kind !== "circle" || box.x === void 0 || box.y === void 0) return void 0;
800
+ return {
801
+ cx: box.x + box.shape.cx,
802
+ cy: box.y + box.shape.cy,
803
+ r: box.shape.r
804
+ };
805
+ }
806
+ /** This function gives the largest side of a margin. A circle has one distance to the things near it, so its margin is this side. */
807
+ function marginReach(margin) {
808
+ const m = marginSides(margin);
809
+ return Math.max(m.top, m.right, m.bottom, m.left);
810
+ }
811
+ /** This function tells if the centers of two circles are nearer than `need`. It compares the squares, so it does not take a root. */
812
+ function nearerThan(a, b, need) {
813
+ if (need <= 0) return false;
814
+ const dx = a.cx - b.cx;
815
+ const dy = a.cy - b.cy;
816
+ return dx * dx + dy * dy < need * need;
817
+ }
818
+ /**
819
+ * This function tells if two placed boxes break `no-overlap`. It is the rule for one pair of `countOverlaps`.
820
+ *
821
+ * - Two circles break the rule when their centers are nearer than the two radii and the two margins, less `tolerance`. The margin of a circle is the largest side of its margin.
822
+ * - Another pair breaks the rule when the bounding boxes with their margins overlap by more than `tolerance` on each axis. With a shape that is not a rectangle, this test is an upper bound.
823
+ * - With `gap`, the gap replaces the two margins. Two circles are then apart by the two radii and the gap. For another pair, one box grows by the gap.
824
+ * - A box without a position does not overlap.
825
+ */
826
+ function shapesOverlap(a, b, tolerance = DEFAULT_TOLERANCE.overlap, gap) {
827
+ const ca = placedCircle(a);
828
+ const cb = placedCircle(b);
829
+ if (ca !== void 0 && cb !== void 0) return nearerThan(ca, cb, ca.r + cb.r + (gap ?? marginReach(a.margin) + marginReach(b.margin)) - tolerance);
830
+ const ra = placedRect(a);
831
+ const rb = placedRect(b);
832
+ if (ra === void 0 || rb === void 0) return false;
833
+ const o = gap === void 0 ? overlapOf(grow(ra, a.margin), grow(rb, b.margin)) : overlapOf(grow(ra, gap), rb);
834
+ return o.x > tolerance && o.y > tolerance;
835
+ }
836
+ /** This function gives the gap of each pair of `pairGaps` by `pairKey`. The first entry of a pair wins. A pair of one box has no gap. */
837
+ function gapsOf(pairGaps) {
767
838
  const gaps = /* @__PURE__ */ new Map();
768
- for (const p of pairGaps) {
839
+ for (const p of pairGaps ?? []) {
769
840
  const key = pairKey(p.a, p.b);
770
841
  if (p.a !== p.b && !gaps.has(key)) gaps.set(key, p.gap);
771
842
  }
843
+ return gaps;
844
+ }
845
+ /**
846
+ * This function counts the pairs of placed boxes that break `no-overlap`. `shapesOverlap` is the rule for one pair.
847
+ * Two circles count by the distance of their centers. Each other pair counts by the bounding boxes, so a circle beside another shape is an upper bound (roadmap item L107).
848
+ *
849
+ * A pair of `pairGaps`, in either order, uses its `gap` in place of the two margins. One box grows by the gap, and the other box does not grow.
850
+ * Thus the pair breaks the rule only when the boxes are nearer than the gap on each axis. The other pairs do not change.
851
+ */
852
+ function countOverlaps(boxes, tolerance = DEFAULT_TOLERANCE.overlap, pairGaps) {
853
+ const circles = circleOverlaps(boxes, tolerance, pairGaps);
854
+ if (pairGaps === void 0 || pairGaps.length === 0) return circles + marginOverlaps(boxes, tolerance, void 0);
855
+ const gaps = gapsOf(pairGaps);
772
856
  const raw = /* @__PURE__ */ new Map();
773
- for (const box of boxes) {
774
- const r = placedRect(box);
775
- if (r !== void 0 && !raw.has(box.id)) raw.set(box.id, r);
776
- }
777
- let count = marginOverlaps(boxes, tolerance, gaps);
857
+ for (const box of boxes) if (placedRect(box) !== void 0 && !raw.has(box.id)) raw.set(box.id, box);
858
+ let count = circles + marginOverlaps(boxes, tolerance, gaps);
778
859
  for (const [key, gap] of gaps) {
779
860
  const [a, b] = JSON.parse(key);
780
- const ra = raw.get(a);
781
- const rb = raw.get(b);
782
- if (ra === void 0 || rb === void 0) continue;
783
- const o = overlapOf(grow(ra, gap), rb);
784
- if (o.x > tolerance && o.y > tolerance) count++;
861
+ const ba = raw.get(a);
862
+ const bb = raw.get(b);
863
+ if (ba === void 0 || bb === void 0) continue;
864
+ if (placedCircle(ba) !== void 0 && placedCircle(bb) !== void 0) continue;
865
+ if (shapesOverlap(ba, bb, tolerance, gap)) count++;
785
866
  }
786
867
  return count;
787
868
  }
788
869
  /** This function gives the key of a pair of box ids, with the same key for each order. */
789
870
  const pairKey = (a, b) => JSON.stringify(a < b ? [a, b] : [b, a]);
790
- /** This function counts the overlaps of the boxes with their margins. It skips the pairs of `skip`. Without `skip`, it is the rule of 0.2.13. */
871
+ /**
872
+ * This function counts the pairs of placed circles that break `no-overlap`, by the distance of their centers. Each other box does not count.
873
+ *
874
+ * - Two circles break the rule when their centers are nearer than the two radii, the two margins and `gap`, less `tolerance`.
875
+ * - The margin of a circle is the largest side of its margin.
876
+ * - A pair of `pairGaps` is apart by the two radii and its gap, in place of the margins and `gap`.
877
+ * - `gap` has the default 0. The rule `no-overlap` does not read `LayoutInput.gap`, so `countOverlaps` gives no value. An engine that keeps the gap between circles gives it here.
878
+ */
879
+ function circleOverlaps(boxes, tolerance = DEFAULT_TOLERANCE.overlap, pairGaps, gap = 0) {
880
+ const gaps = gapsOf(pairGaps);
881
+ const discs = [];
882
+ const first = /* @__PURE__ */ new Map();
883
+ for (const box of boxes) {
884
+ const c = placedCircle(box);
885
+ if (c === void 0) continue;
886
+ discs.push({
887
+ id: box.id,
888
+ c,
889
+ reach: c.r + marginReach(box.margin) + gap / 2
890
+ });
891
+ if (!first.has(box.id)) first.set(box.id, c);
892
+ }
893
+ discs.sort((a, b) => a.c.cx - a.reach - (b.c.cx - b.reach));
894
+ let count = 0;
895
+ for (let i = 0; i < discs.length; i++) {
896
+ const a = discs[i];
897
+ for (let j = i + 1; j < discs.length; j++) {
898
+ const b = discs[j];
899
+ if (b.c.cx - b.reach >= a.c.cx + a.reach - tolerance) break;
900
+ if (gaps.has(pairKey(a.id, b.id))) continue;
901
+ if (nearerThan(a.c, b.c, a.reach + b.reach - tolerance)) count++;
902
+ }
903
+ }
904
+ for (const [key, g] of gaps) {
905
+ const [a, b] = JSON.parse(key);
906
+ const ca = first.get(a);
907
+ const cb = first.get(b);
908
+ if (ca !== void 0 && cb !== void 0 && nearerThan(ca, cb, ca.r + cb.r + g - tolerance)) count++;
909
+ }
910
+ return count;
911
+ }
912
+ /** This function counts the overlaps by the bounding boxes with their margins. It skips the pairs of `skip` and the pairs of two circles. */
791
913
  function marginOverlaps(boxes, tolerance, skip) {
792
914
  const rects = [];
793
915
  for (const box of boxes) {
794
916
  const r = placedRect(box);
795
917
  if (r !== void 0) rects.push({
796
918
  id: box.id,
797
- r: grow(r, box.margin)
919
+ r: grow(r, box.margin),
920
+ circle: box.shape?.kind === "circle"
798
921
  });
799
922
  }
800
923
  rects.sort((a, b) => a.r.x - b.r.x);
@@ -804,6 +927,7 @@ function marginOverlaps(boxes, tolerance, skip) {
804
927
  for (let j = i + 1; j < rects.length; j++) {
805
928
  const b = rects[j].r;
806
929
  if (b.x >= a.x + a.w - tolerance) break;
930
+ if (rects[i].circle && rects[j].circle) continue;
807
931
  if (skip !== void 0 && skip.has(pairKey(rects[i].id, rects[j].id))) continue;
808
932
  const o = overlapOf(a, b);
809
933
  if (o.x > tolerance && o.y > tolerance) count++;
@@ -811,18 +935,61 @@ function marginOverlaps(boxes, tolerance, skip) {
811
935
  }
812
936
  return count;
813
937
  }
938
+ /** This function gives the circle of a circle container. A free size reads its radius from `w`, and the corner of the shape stays. Another container, or a free size without `w`, gives `undefined`. */
939
+ function containerCircle(c) {
940
+ const s = c.shape;
941
+ if (s?.kind !== "circle") return void 0;
942
+ if (c.fixed === "size") return s;
943
+ if (c.w === void 0) return void 0;
944
+ const r = c.w / 2;
945
+ return {
946
+ cx: s.cx - s.r + r,
947
+ cy: s.cy - s.r + r,
948
+ r
949
+ };
950
+ }
951
+ /** This function tells if a circle goes out of a circle container. The reach is the center distance, the radius and `extra`. It compares the squares. */
952
+ function circleOutside(disc, extra, ring, tolerance) {
953
+ const room = ring.r + tolerance - disc.r - extra;
954
+ if (room < 0) return true;
955
+ const dx = disc.cx - ring.cx;
956
+ const dy = disc.cy - ring.cy;
957
+ return dx * dx + dy * dy > room * room;
958
+ }
959
+ /**
960
+ * This function counts the placed circles that go out of a circle container, by the distance of the centers.
961
+ *
962
+ * - The reach of a circle is the sum of the center distance, the radius, the largest side of the margin and the inset.
963
+ * - A circle breaks the rule when its reach is more than the container radius plus `tolerance`.
964
+ * - A container with a free size reads its radius from `w`, and its center is the corner of the shape plus that radius. `applyPack` writes that `w`.
965
+ * - Each other box does not count. The function throws a `RangeError` for a container that is not a circle.
966
+ */
967
+ function circlesOutside(input, tolerance = DEFAULT_TOLERANCE.overlap) {
968
+ const c = input.container;
969
+ const ring = c === void 0 ? void 0 : containerCircle(c);
970
+ if (c === void 0 || ring === void 0) throw new RangeError("The function circlesOutside needs a circle container, with w when its size is free.");
971
+ let count = 0;
972
+ for (const box of input.boxes) {
973
+ const disc = placedCircle(box);
974
+ if (disc !== void 0 && circleOutside(disc, marginReach(box.margin) + (c.inset ?? 0), ring, tolerance)) count++;
975
+ }
976
+ return count;
977
+ }
814
978
  /**
815
979
  * This function counts the placed boxes that go out of the container.
816
980
  * Each box with its margin must stay inside the container made smaller by `inset`. Only the fixed sides of the size count. A shaped container counts as its bounding box.
817
981
  *
818
- * With `exactContainer`, a box of a shaped container with the size `fixed` also counts when `rectInRegion` tells that it is not inside the shape.
982
+ * With `exactContainer`, the default, a box of a shaped container with the size `fixed` also counts when it is not inside the shape, by `rectInRegion`.
819
983
  * For that test, the box grows by `inset` and becomes smaller by `tolerance` on each side. A shaped container with a free side keeps the bounding test only.
984
+ * A circle in a circle container does not use `rectInRegion`. It counts by distance, as in `circlesOutside`, also when the size is free.
820
985
  * An input without a container gives 0.
821
986
  */
822
987
  function countOutside(input, tolerance = DEFAULT_TOLERANCE.overlap, options = {}) {
823
988
  const c = input.container;
824
989
  if (c === void 0) return 0;
825
- const shape = options.exactContainer === true && c.fixed === "size" ? c.shape : void 0;
990
+ const exact = options.exactContainer !== false;
991
+ const shape = exact && c.fixed === "size" ? c.shape : void 0;
992
+ const ring = exact ? containerCircle(c) : void 0;
826
993
  const area = c.shape === void 0 ? {
827
994
  x: 0,
828
995
  y: 0,
@@ -839,8 +1006,11 @@ function countOutside(input, tolerance = DEFAULT_TOLERANCE.overlap, options = {}
839
1006
  const r = grow(r0, box.margin);
840
1007
  const outX = r.x < area.x + inset - tolerance || r.x + r.w > area.x + area.w - inset + tolerance;
841
1008
  const outY = r.y < area.y + inset - tolerance || r.y + r.h > area.y + area.h - inset + tolerance;
1009
+ const disc = ring === void 0 ? void 0 : placedCircle(box);
842
1010
  if (fixW && outX || fixH && outY) count++;
843
- else if (shape !== void 0 && !rectInRegion(shape, shrink(grow(r, inset), tolerance))) count++;
1011
+ else if (ring !== void 0 && disc !== void 0) {
1012
+ if (circleOutside(disc, marginReach(box.margin) + inset, ring, tolerance)) count++;
1013
+ } else if (shape !== void 0 && !rectInRegion(shape, shrink(grow(r, inset), tolerance))) count++;
844
1014
  }
845
1015
  return count;
846
1016
  }
@@ -863,28 +1033,30 @@ function countPortsOffBorder(boxes, eps = RECORD_EPS) {
863
1033
  }
864
1034
  /**
865
1035
  * The hard rules of a pack, with the shape kinds that each rule supports.
866
- * `no-overlap` and `in-container` test the bounding box of a shape. That count is exact only for a `rect`.
867
- * For the other kinds, the count is safe: a shape is inside its bounding box, so the count is an upper bound. A count of 0 tells that the rule has no break.
1036
+ * `no-overlap` and `in-container` are exact for a `rect` and a `circle`. `limit` tells the inputs where the count of a circle is only safe (roadmap item L107).
1037
+ * For the other kinds, these rules test the bounding box. The count is safe: a shape is inside its bounding box, so the count is an upper bound. A count of 0 tells that the rule has no break.
868
1038
  * `locked-kept` and `complete` read only the positions and the ids, so they support each kind.
869
1039
  */
870
1040
  const PACK_HARD_RULES = /* @__PURE__ */ Object.freeze([
871
1041
  {
872
1042
  id: "no-overlap",
873
- shapes: ["rect"],
874
- safe: [
875
- "polygon",
876
- "circle",
877
- "free"
878
- ]
1043
+ shapes: ["rect", "circle"],
1044
+ safe: ["polygon", "free"],
1045
+ limit: {
1046
+ reads: "neighbours",
1047
+ because: "A circle beside another shape kind or an obstacle counts by its bounding box.",
1048
+ until: "2026-11-28"
1049
+ }
879
1050
  },
880
1051
  {
881
1052
  id: "in-container",
882
- shapes: ["rect"],
883
- safe: [
884
- "polygon",
885
- "circle",
886
- "free"
887
- ]
1053
+ shapes: ["rect", "circle"],
1054
+ safe: ["polygon", "free"],
1055
+ limit: {
1056
+ reads: "container",
1057
+ because: "A circle in a polygon or an ellipse container counts by its bounding box.",
1058
+ until: "2026-11-28"
1059
+ }
888
1060
  },
889
1061
  {
890
1062
  id: "locked-kept",
@@ -1050,7 +1222,7 @@ function countObstacleHits(boxes, obstacles, tolerance = DEFAULT_TOLERANCE.overl
1050
1222
  /**
1051
1223
  * This function gives the count of each hard rule of the output of a packer.
1052
1224
  * It applies the output with `applyPack`. Only the placed boxes and the locked boxes count for the overlaps and the container.
1053
- * `no-overlap` counts the pairs of boxes and the pairs of a box and an obstacle. A pair of `pairGaps` uses its gap in place of the margins.
1225
+ * `no-overlap` counts the pairs of boxes and the pairs of a box and an obstacle. A pair of `pairGaps` uses its gap in place of the margins. `HARD_RULE_VERSION` tells the version of these counts.
1054
1226
  *
1055
1227
  * A locked box without a placement, or with a move of more than `RECORD_EPS`, breaks `locked-kept`.
1056
1228
  * A locked box without a position in the input is a bad input, not a break. `checkInput` finds it.
@@ -1641,6 +1813,8 @@ const EDGE_DENSITY = /* @__PURE__ */ Object.freeze({
1641
1813
  });
1642
1814
  /** The version of `edgeStep`. A change of its output gives a new version. */
1643
1815
  const EDGE_STEP_VERSION = 1;
1816
+ /** The version of `edgeKeyStep`. A change of its output gives a new version. */
1817
+ const EDGE_KEY_STEP_VERSION = 1;
1644
1818
  const CLUSTER = 8;
1645
1819
  const CHAIN = 32;
1646
1820
  const INSIDE = .85;
@@ -1653,6 +1827,23 @@ const COLLECTIONS = [
1653
1827
  "events"
1654
1828
  ];
1655
1829
  const round3 = (x) => Math.round(x * 1e3) / 1e3;
1830
+ /** This function gives the shuffled order of `n` boxes, from the first numbers of the stream `edges`. */
1831
+ function shuffledBoxes(n, r) {
1832
+ const perm = Array.from({ length: n }, (_, i) => i);
1833
+ for (let i = n - 1; i > 0; i--) {
1834
+ const j = randomInt(r, 0, i);
1835
+ [perm[i], perm[j]] = [perm[j], perm[i]];
1836
+ }
1837
+ return perm;
1838
+ }
1839
+ /** This function gives the cluster of each box from the shuffled order: each cluster has `CLUSTER` boxes. */
1840
+ function clustersOf(perm) {
1841
+ const clusterOf = new Array(perm.length);
1842
+ perm.forEach((box, p) => clusterOf[box] = Math.floor(p / CLUSTER));
1843
+ return clusterOf;
1844
+ }
1845
+ /** This function gives the key of the boxes of one cluster. */
1846
+ const clusterKey = (c) => `${COLLECTIONS[c % COLLECTIONS.length]}-${c}`;
1656
1847
  /**
1657
1848
  * This function gives the input with edges, groups and ports from its topology alone: a joint input has no positions before the pack.
1658
1849
  * The random numbers come from the steps `edges` and `ports` of `seed`. The function appends its stamp to `steps`, and removes the old `hash`.
@@ -1668,16 +1859,11 @@ function edgeStep(input, params, seed = input.seed ?? 0) {
1668
1859
  };
1669
1860
  const n = input.boxes.length;
1670
1861
  const r = stepRandom(seed, "edges");
1671
- const perm = input.boxes.map((_, i) => i);
1672
- for (let i = n - 1; i > 0; i--) {
1673
- const j = randomInt(r, 0, i);
1674
- [perm[i], perm[j]] = [perm[j], perm[i]];
1675
- }
1676
- const clusterOf = new Array(n);
1677
- perm.forEach((box, p) => clusterOf[box] = Math.floor(p / CLUSTER));
1862
+ const perm = shuffledBoxes(n, r);
1863
+ const clusterOf = clustersOf(perm);
1678
1864
  const clusters = Math.ceil(n / CLUSTER);
1679
1865
  const members = (c) => perm.slice(c * CLUSTER, (c + 1) * CLUSTER);
1680
- const collectionOf = full.edgeShape === "bundled" ? clusterOf.map((c) => `${COLLECTIONS[c % COLLECTIONS.length]}-${c}`) : input.boxes.map(() => COLLECTIONS[randomInt(r, 0, COLLECTIONS.length - 1)]);
1866
+ const collectionOf = full.edgeShape === "bundled" ? clusterOf.map(clusterKey) : input.boxes.map(() => COLLECTIONS[randomInt(r, 0, COLLECTIONS.length - 1)]);
1681
1867
  const area = (i) => input.boxes[i].w * input.boxes[i].h;
1682
1868
  const rank = full.hubBy === "area" ? input.boxes.map((_, i) => i).sort((a, b) => area(b) - area(a) || a - b) : perm;
1683
1869
  const pairs = [];
@@ -1828,6 +2014,52 @@ function edgeStep(input, params, seed = input.seed ?? 0) {
1828
2014
  steps: [...input.steps ?? [], stamp]
1829
2015
  };
1830
2016
  }
2017
+ /**
2018
+ * This function gives the input with a stated key on each edge. The edges stay the same in all but `data.collection`, so the 3 values of `edgeKey` read one factor.
2019
+ * The key of an edge depends on its target box, as in `edgeStep`.
2020
+ * The value `cluster` uses the clusters of `edgeStep` with the same seed and box order, so this step comes directly after `edgeStep`. On the shape `bundled` it gives the keys of `edgeStep`.
2021
+ * The value `random` uses the stream `edge-key`, so it does not change the numbers of `edgeStep`. The function appends its stamp to `steps`, and removes the old `hash`.
2022
+ * It throws a `RangeError` for an edge with an unknown target.
2023
+ */
2024
+ function edgeKeyStep(input, params, seed = input.seed ?? 0) {
2025
+ const n = input.boxes.length;
2026
+ const keys = () => {
2027
+ if (params.edgeKey === "cluster") return clustersOf(shuffledBoxes(n, stepRandom(seed, "edges"))).map(clusterKey);
2028
+ const r = stepRandom(seed, "edge-key");
2029
+ return input.boxes.map(() => COLLECTIONS[randomInt(r, 0, COLLECTIONS.length - 1)]);
2030
+ };
2031
+ const keyOf = params.edgeKey === "none" ? [] : keys();
2032
+ const indexOf = new Map(input.boxes.map((box, i) => [box.id, i]));
2033
+ const edges = input.edges?.map((edge) => {
2034
+ const { data: oldData, ...plain } = edge;
2035
+ const { collection: _old, ...data } = oldData ?? {};
2036
+ if (params.edgeKey === "none") return Object.keys(data).length === 0 ? plain : {
2037
+ ...plain,
2038
+ data
2039
+ };
2040
+ const target = indexOf.get(edge.target);
2041
+ if (target === void 0) throw new RangeError(`edgeKeyStep: the edge "${edge.id}" has the unknown target "${edge.target}".`);
2042
+ return {
2043
+ ...plain,
2044
+ data: {
2045
+ ...data,
2046
+ collection: keyOf[target]
2047
+ }
2048
+ };
2049
+ });
2050
+ const stamp = {
2051
+ name: "edge-key",
2052
+ version: 1,
2053
+ params: { edgeKey: params.edgeKey },
2054
+ seed
2055
+ };
2056
+ const { hash: _oldHash, edges: _oldEdges, ...rest } = input;
2057
+ return {
2058
+ ...rest,
2059
+ ...edges === void 0 ? {} : { edges },
2060
+ steps: [...input.steps ?? [], stamp]
2061
+ };
2062
+ }
1831
2063
  // src/hash.ts
1832
2064
  /** The round constants of SHA-256. */
1833
2065
  const K = [
@@ -4832,6 +5064,11 @@ const CORPUS_DIMENSIONS = /* @__PURE__ */ Object.freeze({
4832
5064
  "sides",
4833
5065
  "fixed"
4834
5066
  ], "free", "The ports of the edges: free, a side for each end, or fixed ports.", [H, J]),
5067
+ edgeKey: /* @__PURE__ */ choice("edgeKey", [
5068
+ "none",
5069
+ "random",
5070
+ "cluster"
5071
+ ], "none", "The key of each edge in `data.collection`: absent, a random name for each target box, or a name for each cluster of boxes.", [H, J]),
4835
5072
  hubBy: /* @__PURE__ */ withWhen(/* @__PURE__ */ choice("hubBy", ["area", "random"], "area", "The order of the hubs of the shapes hubs and tree: the largest item first, or random.", [J]), /* @__PURE__ */ Object.freeze({
4836
5073
  param: "edgeShape",
4837
5074
  in: /* @__PURE__ */ Object.freeze(["hubs", "tree"])
@@ -5398,6 +5635,29 @@ const EDGES_STEP = /* @__PURE__ */ Object.freeze({
5398
5635
  familyPart: (d) => `e-${d["edgeDensity"]}.${d["edgeShape"]}.${d["groups"]}.${d["ports"]}${d["hubBy"] === "random" ? ".hub-random" : ""}`,
5399
5636
  apply: (input, seed, d) => edgeStep(input, edgeParams(d), seed)
5400
5637
  });
5638
+ /** The dimension of `EDGE_KEY_STEP`, from the shared table. */
5639
+ const EDGE_KEY_DIMENSIONS = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ ["edgeKey"].map((n) => CORPUS_DIMENSIONS[n]));
5640
+ /** This function gives the value of `edgeKey`. It throws a `RangeError` for a missing or a bad value. */
5641
+ function edgeKeyOf(d) {
5642
+ const value = Object.hasOwn(d, "edgeKey") ? d["edgeKey"] : void 0;
5643
+ const bad = value === void 0 ? "the value is missing" : paramProblem(EDGE_KEY_DIMENSIONS[0], value);
5644
+ if (bad !== void 0) throw new RangeError(`EDGE_KEY_STEP: the dimension "edgeKey" is bad: ${bad}.`);
5645
+ return value;
5646
+ }
5647
+ /**
5648
+ * The step `edge-key` of `edgeKeyStep` (version 1), as a corpus step. It comes directly after `EDGES_STEP`. Its family part is `key-<edgeKey>`.
5649
+ */
5650
+ const EDGE_KEY_STEP = /* @__PURE__ */ Object.freeze({
5651
+ name: "edge-key",
5652
+ version: 1,
5653
+ owner: "layout-contract",
5654
+ meaning: "The key of each edge: absent, with no meaning, or with the meaning of a cluster of boxes.",
5655
+ dimensions: EDGE_KEY_DIMENSIONS,
5656
+ seeding: "stepRandom(seed, step) for the value random. The value cluster reads the stream edges again, as edgeStep does.",
5657
+ crossEngine: "exact",
5658
+ familyPart: (d) => `key-${d["edgeKey"]}`,
5659
+ apply: (input, seed, d) => edgeKeyStep(input, { edgeKey: edgeKeyOf(d) }, seed)
5660
+ });
5401
5661
  /** The set of `RECT_SCATTERED` when the caller gives no set. */
5402
5662
  const XCHECK_SET = "xcheck-v1";
5403
5663
  /**
@@ -5477,6 +5737,6 @@ const RECT_SCATTERED = /* @__PURE__ */ Object.freeze({
5477
5737
  };
5478
5738
  }
5479
5739
  });
5480
- export { BALANCE_MEASURE_SUFFIXES, BALANCE_SIDE_DEPTH, CORPUS_DIMENSIONS, DEFAULT_FAMILY_BY, DEFAULT_RNG, DEFAULT_SHAPES, DEFAULT_TOLERANCE, EDGES_STEP, EDGE_DENSITY, EDGE_STEP_VERSION, EPS, FAMILY_ANY_KIND, INVALIDATED_FIELD, JOINT_MEASURES, JOINT_MOVED_MIN, NODE_POSITIONS_DIMENSION, PACK_HARD_RULES, RECORD_EPS, RECORD_SCALE, RECT_SCATTERED, SHAPE_KINDS, SHAPE_KIND_IDS, SIDES, SPLIT_SCHEMA, STRATEGY_CATALOG_SCHEMA, STRATEGY_SPACE_SCHEMA, VERDICT_DRAWS, VERDICT_EXACT_CAP, VERDICT_EXACT_MAX, VERDICT_RUNS, VERDICT_SEED, applyPack, balanceMeasureSpecs, balanceMeasures, balanceOf, boundsOf, boxArea, canonicalConfig, canonicalInput, canonicalJson, catalogChoices, catalogDefaults, catalogKey, catalogOptions, checkCatalog, checkConfig, checkDeclared, checkInput, checkLayoutRecord, checkOptions, checkSchema, checkShapes, checkSpace, checkSplit, clampOptions, compareMeasure, composeFamily, configId, corpusHashOf, countObstacleHits, countOutside, countOverlaps, countPortsOffBorder, createFamilyRegistry, declarationIssues, declaredClaimOf, declaredCounts, decodeOptionValue, dimensionAt, dimensionSupports, dimensionUnit, documentHash, edgeStep, encodeOptionValue, enumerateSpace, exercised, familyKind, familyOf, fnv1a32, grow, isShapeKind, itemShapeOf, joinConfigs, leaveOneSeedOut, levelsOf, listOptions, marginSides, minEffectOf, mulberry32, nearestGaps, optionDefaults, optionIssue, outputGroups, outputHash, overlapOf, ownerDimension, packHard, packLinks, paramActive, paramLevels, paramProblem, paramValue, parseLayoutRecord, parseStrategyCatalog, perChange, pickMoves, placedRect, pointSegmentDistance, portPoint, portfolio, procrustesOf, productSpace, randomInt, rectInRegion, regionArea, regionHitsRect, resolveDimensions, ruleLevel, segmentsCross, selectBest, sha256Hex, shapeKindOf, shapeKindProblem, shapeKindsOf, shapeLevel, shapeSupportProblems, shapesOf, sharedDimension, spaceShapeKinds, spaceSize, splitConfig, splitFileName, splitFolds, stepRandom, sweepGrid, sweepOf, sweepValues, toLayoutRecord, toPackInput, toRect, toSizedRect, translate, turnBox, turnMargin, turnPoint, turnPort, turnRegion, turnSide, verdict, writeStrategyCatalog };
5740
+ export { BALANCE_MEASURE_SUFFIXES, BALANCE_SIDE_DEPTH, CORPUS_DIMENSIONS, DEFAULT_FAMILY_BY, DEFAULT_RNG, DEFAULT_SHAPES, DEFAULT_TOLERANCE, EDGES_STEP, EDGE_DENSITY, EDGE_KEY_STEP, EDGE_KEY_STEP_VERSION, EDGE_STEP_VERSION, EPS, FAMILY_ANY_KIND, HARD_RULE_VERSION, INVALIDATED_FIELD, JOINT_MEASURES, JOINT_MOVED_MIN, NODE_POSITIONS_DIMENSION, PACK_HARD_RULES, RECORD_EPS, RECORD_SCALE, RECT_SCATTERED, SHAPE_KINDS, SHAPE_KIND_IDS, SIDES, SPLIT_SCHEMA, STRATEGY_CATALOG_SCHEMA, STRATEGY_SPACE_SCHEMA, VERDICT_DRAWS, VERDICT_EXACT_CAP, VERDICT_EXACT_MAX, VERDICT_RUNS, VERDICT_SEED, applyPack, balanceMeasureSpecs, balanceMeasures, balanceOf, boundsOf, boxArea, canonicalConfig, canonicalInput, canonicalJson, catalogChoices, catalogDefaults, catalogKey, catalogOptions, checkCatalog, checkConfig, checkDeclared, checkInput, checkLayoutRecord, checkOptions, checkSchema, checkShapes, checkSpace, checkSplit, circleOverlaps, circlesOutside, clampOptions, compareMeasure, composeFamily, configId, corpusHashOf, countObstacleHits, countOutside, countOverlaps, countPortsOffBorder, createFamilyRegistry, declarationIssues, declaredClaimOf, declaredCounts, decodeOptionValue, dimensionAt, dimensionSupports, dimensionUnit, documentHash, edgeKeyStep, edgeStep, encodeOptionValue, enumerateSpace, exercised, familyKind, familyOf, fnv1a32, grow, hardRuleOf, inputShapeLevel, isShapeKind, itemShapeOf, joinConfigs, leaveOneSeedOut, levelsOf, listOptions, marginSides, minEffectOf, mulberry32, nearestGaps, optionDefaults, optionIssue, outputGroups, outputHash, overlapOf, ownerDimension, packHard, packLinks, paramActive, paramLevels, paramProblem, paramValue, parseLayoutRecord, parseStrategyCatalog, perChange, pickMoves, placedCircle, placedRect, pointSegmentDistance, portPoint, portfolio, procrustesOf, productSpace, randomInt, rectInRegion, regionArea, regionHitsRect, resolveDimensions, ruleLevel, segmentsCross, selectBest, sha256Hex, shapeKindOf, shapeKindProblem, shapeKindsOf, shapeLevel, shapeSupportProblems, shapesOf, shapesOverlap, sharedDimension, spaceShapeKinds, spaceSize, splitConfig, splitFileName, splitFolds, stepRandom, sweepGrid, sweepOf, sweepValues, toLayoutRecord, toPackInput, toRect, toSizedRect, translate, turnBox, turnMargin, turnPoint, turnPort, turnRegion, turnSide, verdict, writeStrategyCatalog };
5481
5741
 
5482
5742
  //# sourceMappingURL=index.js.map