@mark1russell7/layout-contract 0.10.2 → 0.10.3

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
@@ -1463,7 +1463,7 @@ function toLayoutRecord(input, run) {
1463
1463
  ...onlyRect ? {} : { shapes }
1464
1464
  };
1465
1465
  }
1466
- const isFields$1 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1466
+ const isFields$3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1467
1467
  const STAGES = [
1468
1468
  "pack",
1469
1469
  "route",
@@ -1504,17 +1504,17 @@ const ENV_STRINGS = [
1504
1504
  const ENV_OPTIONAL_STRINGS = ["mode", "context"];
1505
1505
  /** This function adds a problem for each value of a map that is not a number. */
1506
1506
  function numberMap(out, v, name) {
1507
- if (!isFields$1(v)) {
1507
+ if (!isFields$3(v)) {
1508
1508
  out.push(`${name} is not an object`);
1509
1509
  return;
1510
1510
  }
1511
1511
  for (const [key, n] of Object.entries(v)) if (typeof n !== "number") out.push(`${name}.${key} is not a number`);
1512
1512
  }
1513
1513
  /** This function tells if a value is an object whose values are strings. */
1514
- const isStringMap = (v) => isFields$1(v) && Object.values(v).every((s) => typeof s === "string");
1514
+ const isStringMap = (v) => isFields$3(v) && Object.values(v).every((s) => typeof s === "string");
1515
1515
  /** This function gives the problems of the field `carried.code` of a record. */
1516
1516
  function codeProblems(code) {
1517
- if (!isFields$1(code)) return ["carried.code is not an object"];
1517
+ if (!isFields$3(code)) return ["carried.code is not an object"];
1518
1518
  const out = [];
1519
1519
  for (const key of ["from", "to"]) if (typeof code[key] !== "string" || code[key] === "") out.push(`carried.code.${key} is not a commit`);
1520
1520
  if (out.length === 0 && code["from"] === code["to"]) out.push("carried.code.to is the commit of carried.code.from");
@@ -1525,7 +1525,7 @@ function codeProblems(code) {
1525
1525
  }
1526
1526
  /** This function gives the problems of the field `carried` of a record. */
1527
1527
  function carriedProblems(carried) {
1528
- if (!isFields$1(carried)) return ["carried is not an object"];
1528
+ if (!isFields$3(carried)) return ["carried is not an object"];
1529
1529
  const out = [];
1530
1530
  for (const key of [
1531
1531
  "from",
@@ -1545,7 +1545,7 @@ function carriedProblems(carried) {
1545
1545
  }
1546
1546
  /** This function gives the problems of the field `env` of a record. */
1547
1547
  function envProblems(env) {
1548
- if (!isFields$1(env)) return ["env is not an object"];
1548
+ if (!isFields$3(env)) return ["env is not an object"];
1549
1549
  const out = [];
1550
1550
  for (const key of ENV_STRINGS) if (typeof env[key] !== "string") out.push(`env.${key} is not a string`);
1551
1551
  if (typeof env["cpus"] !== "number") out.push("env.cpus is not a number");
@@ -1565,7 +1565,7 @@ function hardRuleOf(record) {
1565
1565
  * A record without `skipped` has a boolean, or `null` when it has `oneRun: true`. The check accepts fields that the format does not know.
1566
1566
  */
1567
1567
  function checkLayoutRecord(value) {
1568
- if (!isFields$1(value)) return ["the record is not an object"];
1568
+ if (!isFields$3(value)) return ["the record is not an object"];
1569
1569
  const out = [];
1570
1570
  const v = value;
1571
1571
  if (v["schema"] !== "layout-record/1") out.push("schema is not layout-record/1");
@@ -1573,7 +1573,7 @@ function checkLayoutRecord(value) {
1573
1573
  for (const key of RECORD_STRINGS) if (typeof v[key] !== "string") out.push(`${key} is not a string`);
1574
1574
  for (const key of RECORD_NUMBERS) if (typeof v[key] !== "number") out.push(`${key} is not a number`);
1575
1575
  for (const key of RECORD_OPTIONAL_STRINGS) if (v[key] !== void 0 && typeof v[key] !== "string") out.push(`${key} is not a string`);
1576
- if (!isFields$1(v["options"])) out.push("options is not an object");
1576
+ if (!isFields$3(v["options"])) out.push("options is not an object");
1577
1577
  numberMap(out, v["measures"], "measures");
1578
1578
  numberMap(out, v["hard"], "hard");
1579
1579
  if (v["tolerance"] !== void 0) numberMap(out, v["tolerance"], "tolerance");
@@ -3228,6 +3228,507 @@ function frameMove(a, b) {
3228
3228
  function fixedPointMove(start, run) {
3229
3229
  return frameMove(start, run(start));
3230
3230
  }
3231
+ // src/path.ts
3232
+ /** The kinds of the segments of a path. */
3233
+ const PATH_KINDS = [
3234
+ "move",
3235
+ "line",
3236
+ "cubic",
3237
+ "arc"
3238
+ ];
3239
+ /** The largest number of points that `samplePath` gives for one segment. */
3240
+ const MAX_STEPS = 1024;
3241
+ /** This function gives the path of a polyline: a `move` to the first point, then a line to each next point. A list with no point gives an empty path. */
3242
+ function pathOf(points) {
3243
+ return points.map((to, i) => i === 0 ? {
3244
+ kind: "move",
3245
+ to
3246
+ } : {
3247
+ kind: "line",
3248
+ to
3249
+ });
3250
+ }
3251
+ /**
3252
+ * This function gives a polyline that follows the path. The distance from each part of the path to the polyline is `tolerance` or less.
3253
+ * The polyline starts at the point of the `move` and goes through the end of each segment.
3254
+ * Hit tests, measures and renderers that draw only lines use this polyline.
3255
+ */
3256
+ function samplePath(segments, tolerance = .5) {
3257
+ const tol = Math.max(1e-6, tolerance);
3258
+ const out = [];
3259
+ let at;
3260
+ for (const s of segments) {
3261
+ if (s.kind === "move" || at === void 0) {
3262
+ out.push(s.to);
3263
+ at = s.to;
3264
+ continue;
3265
+ }
3266
+ if (s.kind === "cubic") {
3267
+ const d = Math.max(Math.hypot(at.x - 2 * s.c1.x + s.c2.x, at.y - 2 * s.c1.y + s.c2.y), Math.hypot(s.c1.x - 2 * s.c2.x + s.to.x, s.c1.y - 2 * s.c2.y + s.to.y));
3268
+ const n = Math.min(MAX_STEPS, Math.max(1, Math.ceil(Math.sqrt(3 * d / (4 * tol)))));
3269
+ for (let k = 1; k < n; k++) out.push(cubicAt(at, s.c1, s.c2, s.to, k / n));
3270
+ } else if (s.kind === "arc") {
3271
+ const step = s.radius <= tol ? Math.PI : 2 * Math.acos(1 - tol / s.radius);
3272
+ const n = Math.min(MAX_STEPS, Math.max(1, Math.ceil(Math.abs(s.sweep) / step)));
3273
+ for (let k = 1; k < n; k++) {
3274
+ const a = s.start + s.sweep * k / n;
3275
+ out.push({
3276
+ x: s.center.x + s.radius * Math.cos(a),
3277
+ y: s.center.y + s.radius * Math.sin(a)
3278
+ });
3279
+ }
3280
+ }
3281
+ out.push(s.to);
3282
+ at = s.to;
3283
+ }
3284
+ return out;
3285
+ }
3286
+ /** This function gives the point at the parameter `t` of the cubic Bezier curve with the control points `p0`, `p1`, `p2` and `p3`. */
3287
+ function cubicAt(p0, p1, p2, p3, t) {
3288
+ const u = 1 - t;
3289
+ const a = u * u * u;
3290
+ const b = 3 * u * u * t;
3291
+ const c = 3 * u * t * t;
3292
+ const d = t * t * t;
3293
+ return {
3294
+ x: a * p0.x + b * p1.x + c * p2.x + d * p3.x,
3295
+ y: a * p0.y + b * p1.y + c * p2.y + d * p3.y
3296
+ };
3297
+ }
3298
+ /**
3299
+ * This function writes the segments as the data of an SVG path: the commands `M`, `L`, `C` and `A`.
3300
+ * Each number has at most `digits` digits after the point.
3301
+ */
3302
+ function toSvgPath(segments, digits = 2) {
3303
+ const n = (v) => {
3304
+ const s = String(Number(v.toFixed(digits)));
3305
+ return s === "-0" ? "0" : s;
3306
+ };
3307
+ const p = (q) => `${n(q.x)} ${n(q.y)}`;
3308
+ const parts = [];
3309
+ for (const s of segments) if (s.kind === "move") parts.push(`M ${p(s.to)}`);
3310
+ else if (s.kind === "line") parts.push(`L ${p(s.to)}`);
3311
+ else if (s.kind === "cubic") parts.push(`C ${p(s.c1)} ${p(s.c2)} ${p(s.to)}`);
3312
+ else parts.push(`A ${n(s.radius)} ${n(s.radius)} 0 ${Math.abs(s.sweep) > Math.PI ? 1 : 0} ${s.sweep > 0 ? 1 : 0} ${p(s.to)}`);
3313
+ return parts.join(" ");
3314
+ }
3315
+ /** This function gives the parameters between 0 and 1 where `a·t² + b·t + c` is 0. The stable form of the roots keeps a small `a` correct. */
3316
+ function unitRoots(a, b, c) {
3317
+ const inside = (t) => t > 0 && t < 1;
3318
+ if (a === 0) return b !== 0 && inside(-c / b) ? [-c / b] : [];
3319
+ const disc = b * b - 4 * a * c;
3320
+ if (!(disc >= 0)) return [];
3321
+ const q = -(b + (b < 0 ? -1 : 1) * Math.sqrt(disc)) / 2;
3322
+ return (q === 0 ? [0] : [q / a, c / q]).filter(inside);
3323
+ }
3324
+ /**
3325
+ * This function gives the exact bounding box of a path. The box of a cubic curve has the points where the curve turns back on an axis.
3326
+ * The box of an arc has the points of its circle at each quarter turn that the arc goes through.
3327
+ * A path with no segment gives a `RangeError`.
3328
+ */
3329
+ function pathBounds(segments) {
3330
+ if (segments.length === 0) throw new RangeError("layout-path: a path with no segment has no bounds.");
3331
+ let x0 = Infinity;
3332
+ let y0 = Infinity;
3333
+ let x1 = -Infinity;
3334
+ let y1 = -Infinity;
3335
+ const add = (p) => {
3336
+ x0 = Math.min(x0, p.x);
3337
+ y0 = Math.min(y0, p.y);
3338
+ x1 = Math.max(x1, p.x);
3339
+ y1 = Math.max(y1, p.y);
3340
+ };
3341
+ let at;
3342
+ for (const s of segments) {
3343
+ add(s.to);
3344
+ const from = at;
3345
+ at = s.to;
3346
+ if (from === void 0) continue;
3347
+ if (s.kind === "cubic") for (const k of ["x", "y"]) {
3348
+ const a = s.to[k] - 3 * s.c2[k] + 3 * s.c1[k] - from[k];
3349
+ const b = 2 * (s.c2[k] - 2 * s.c1[k] + from[k]);
3350
+ const c = s.c1[k] - from[k];
3351
+ for (const t of unitRoots(a, b, c)) add(cubicAt(from, s.c1, s.c2, s.to, t));
3352
+ }
3353
+ else if (s.kind === "arc") {
3354
+ const quarter = Math.PI / 2;
3355
+ const lo = Math.min(s.start, s.start + s.sweep);
3356
+ const hi = Math.max(s.start, s.start + s.sweep);
3357
+ if (!Number.isFinite(lo) || !Number.isFinite(hi)) continue;
3358
+ const first = hi - lo >= 2 * Math.PI ? 0 : Math.ceil(lo / quarter);
3359
+ const last = hi - lo >= 2 * Math.PI ? 3 : Math.floor(hi / quarter);
3360
+ for (let k = first; k <= last; k++) {
3361
+ const turn = (k % 4 + 4) % 4;
3362
+ const ux = turn === 0 ? 1 : turn === 2 ? -1 : 0;
3363
+ const uy = turn === 1 ? 1 : turn === 3 ? -1 : 0;
3364
+ add({
3365
+ x: s.center.x + s.radius * ux,
3366
+ y: s.center.y + s.radius * uy
3367
+ });
3368
+ }
3369
+ }
3370
+ }
3371
+ return {
3372
+ x: x0,
3373
+ y: y0,
3374
+ w: x1 - x0,
3375
+ h: y1 - y0
3376
+ };
3377
+ }
3378
+ /** This function gives the unit vector of the vector `dx`, `dy`, or `undefined` for a vector with no length. */
3379
+ function unit(dx, dy) {
3380
+ const length = Math.hypot(dx, dy);
3381
+ return length > 0 && Number.isFinite(length) ? {
3382
+ x: dx / length,
3383
+ y: dy / length
3384
+ } : void 0;
3385
+ }
3386
+ /**
3387
+ * This function gives the direction of one segment at its start or at its end. `from` is the end of the segment before.
3388
+ * A segment with no length gives `undefined`. A cubic curve with a control point on its end uses the next control point.
3389
+ */
3390
+ function directionOf(from, s, atEnd) {
3391
+ if (s.kind === "move") return void 0;
3392
+ const chord = () => unit(s.to.x - from.x, s.to.y - from.y);
3393
+ if (s.kind === "cubic") return atEnd ? unit(s.to.x - s.c2.x, s.to.y - s.c2.y) ?? unit(s.to.x - s.c1.x, s.to.y - s.c1.y) ?? chord() : unit(s.c1.x - from.x, s.c1.y - from.y) ?? unit(s.c2.x - from.x, s.c2.y - from.y) ?? chord();
3394
+ if (s.kind === "arc" && s.radius > 0 && s.sweep !== 0) {
3395
+ const angle = atEnd ? s.start + s.sweep : s.start;
3396
+ const sign = s.sweep > 0 ? 1 : -1;
3397
+ return unit(-sign * Math.sin(angle), sign * Math.cos(angle));
3398
+ }
3399
+ return chord();
3400
+ }
3401
+ /**
3402
+ * This function gives the first point of a path and the direction in which the path leaves it.
3403
+ * The direction comes from the first segment that has a length. A path with no segment gives a `RangeError`.
3404
+ */
3405
+ function pathStart(segments) {
3406
+ const first = segments[0];
3407
+ if (first === void 0) throw new RangeError("layout-path: a path with no segment has no start.");
3408
+ for (let i = 1; i < segments.length; i++) {
3409
+ const direction = directionOf(segments[i - 1].to, segments[i], false);
3410
+ if (direction !== void 0) return {
3411
+ point: first.to,
3412
+ direction
3413
+ };
3414
+ }
3415
+ return {
3416
+ point: first.to,
3417
+ direction: {
3418
+ x: 0,
3419
+ y: 0
3420
+ }
3421
+ };
3422
+ }
3423
+ /**
3424
+ * This function gives the last point of a path and the direction in which the path comes to it. An arrow head at the end points along it.
3425
+ * The direction comes from the last segment that has a length. A path with no segment gives a `RangeError`.
3426
+ */
3427
+ function pathEnd(segments) {
3428
+ const last = segments[segments.length - 1];
3429
+ if (last === void 0) throw new RangeError("layout-path: a path with no segment has no end.");
3430
+ for (let i = segments.length - 1; i >= 1; i--) {
3431
+ const direction = directionOf(segments[i - 1].to, segments[i], true);
3432
+ if (direction !== void 0) return {
3433
+ point: last.to,
3434
+ direction
3435
+ };
3436
+ }
3437
+ return {
3438
+ point: last.to,
3439
+ direction: {
3440
+ x: 0,
3441
+ y: 0
3442
+ }
3443
+ };
3444
+ }
3445
+ const isFields$2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3446
+ const isPoint = (v) => isFields$2(v) && Number.isFinite(v["x"]) && Number.isFinite(v["y"]);
3447
+ /** The fields of each kind of segment that hold a point. */
3448
+ const POINT_FIELDS = {
3449
+ move: ["to"],
3450
+ line: ["to"],
3451
+ cubic: [
3452
+ "c1",
3453
+ "c2",
3454
+ "to"
3455
+ ],
3456
+ arc: ["center", "to"]
3457
+ };
3458
+ /**
3459
+ * This function gives the problems of a path. An empty list means a good path.
3460
+ * A good path starts with its one `move`, and each number of it is finite. An arc has a radius of 0 or more.
3461
+ * An arc starts at the end of the segment before, and it ends at its `to`, to 1e-6 of its radius plus 1.
3462
+ */
3463
+ function checkPath(value) {
3464
+ if (!Array.isArray(value)) return ["the path is not a list"];
3465
+ if (value.length === 0) return ["the path has no segment"];
3466
+ const out = [];
3467
+ let at;
3468
+ value.forEach((s, i) => {
3469
+ const from = at;
3470
+ at = void 0;
3471
+ if (!isFields$2(s)) {
3472
+ out.push(`segment ${i} is not an object`);
3473
+ return;
3474
+ }
3475
+ const kind = PATH_KINDS.find((k) => k === s["kind"]);
3476
+ if (kind === void 0) {
3477
+ out.push(`segment ${i}: the kind is not one of ${PATH_KINDS.join(", ")}`);
3478
+ return;
3479
+ }
3480
+ if (i === 0 && kind !== "move") out.push("segment 0 is not a move");
3481
+ if (i > 0 && kind === "move") out.push(`segment ${i} is a second move`);
3482
+ let good = true;
3483
+ for (const key of POINT_FIELDS[kind]) {
3484
+ if (isPoint(s[key])) continue;
3485
+ out.push(`segment ${i}: ${key} is not a point of two finite numbers`);
3486
+ good = false;
3487
+ }
3488
+ const to = s["to"];
3489
+ if (isPoint(to)) at = to;
3490
+ if (kind !== "arc") return;
3491
+ for (const key of [
3492
+ "radius",
3493
+ "start",
3494
+ "sweep"
3495
+ ]) {
3496
+ if (Number.isFinite(s[key])) continue;
3497
+ out.push(`segment ${i}: ${key} is not a finite number`);
3498
+ good = false;
3499
+ }
3500
+ if (!good) return;
3501
+ const arc = s;
3502
+ if (arc.radius < 0) {
3503
+ out.push(`segment ${i}: the radius is less than 0`);
3504
+ return;
3505
+ }
3506
+ const slack = 1e-6 * (arc.radius + 1);
3507
+ const on = (angle, p) => Math.hypot(arc.center.x + arc.radius * Math.cos(angle) - p.x, arc.center.y + arc.radius * Math.sin(angle) - p.y) <= slack;
3508
+ if (from !== void 0 && !on(arc.start, from)) out.push(`segment ${i}: the arc does not start at the end of the segment before`);
3509
+ if (!on(arc.start + arc.sweep, arc.to)) out.push(`segment ${i}: the arc does not end at its point to`);
3510
+ });
3511
+ return out;
3512
+ }
3513
+ // src/picture.ts
3514
+ /** The schema of a picture. */
3515
+ const PICTURE_SCHEMA = "layout-picture/1";
3516
+ /** The places of the lines of a label in its width. */
3517
+ const LABEL_ALIGNS = [
3518
+ "left",
3519
+ "center",
3520
+ "right"
3521
+ ];
3522
+ const isFields$1 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3523
+ const REGION_KINDS = [
3524
+ "rect",
3525
+ "polygon",
3526
+ "circle",
3527
+ "ellipse"
3528
+ ];
3529
+ /** This function gives the list `v`. A value that is not a list adds a problem and gives an empty list. */
3530
+ function listOf(out, v, name) {
3531
+ if (Array.isArray(v)) return v;
3532
+ out.push(`${name} is not a list`);
3533
+ return [];
3534
+ }
3535
+ /**
3536
+ * This function gives the fields and the name of record `i` of a list, or `undefined` for a record without a good id.
3537
+ * The name is the kind and the id, for the text of a problem. An id two times in the list adds a problem.
3538
+ */
3539
+ function recordOf(out, kind, v, i, seen) {
3540
+ if (!isFields$1(v)) {
3541
+ out.push(`${kind} ${i} is not an object`);
3542
+ return;
3543
+ }
3544
+ const id = v["id"];
3545
+ if (typeof id !== "string" || id === "") {
3546
+ out.push(`${kind} ${i}: the id is not a string with a character`);
3547
+ return;
3548
+ }
3549
+ if (seen.has(id)) out.push(`${kind} ${id}: the id is not unique`);
3550
+ return {
3551
+ fields: v,
3552
+ id,
3553
+ name: `${kind} ${id}`
3554
+ };
3555
+ }
3556
+ /** This function adds the problems of the rectangle of a record: a value that is not finite, or a size less than 0. */
3557
+ function rectProblems(out, name, v) {
3558
+ for (const key of [
3559
+ "x",
3560
+ "y",
3561
+ "w",
3562
+ "h"
3563
+ ]) {
3564
+ const n = v[key];
3565
+ if (typeof n !== "number" || !Number.isFinite(n)) out.push(`${name}: ${key} is not a finite number`);
3566
+ else if (n < 0 && (key === "w" || key === "h")) out.push(`${name}: ${key} is less than 0`);
3567
+ }
3568
+ }
3569
+ /** This function adds a problem for a field `data` that is not an object. */
3570
+ function dataProblems(out, name, v) {
3571
+ if (v["data"] !== void 0 && !isFields$1(v["data"])) out.push(`${name}: data is not an object`);
3572
+ }
3573
+ /**
3574
+ * This function gives the problems of one `layout-picture/1` value. An empty list means a good picture.
3575
+ * Each id occurs one time in its list, each number is finite, and a size is 0 or more. A parent is a box before its child in the list.
3576
+ * The source and the target of a route are boxes of the picture, and its path has no problem of `checkPath`.
3577
+ *
3578
+ * A label has lines of text, a line height above 0 and a font. Its `box` or its `route` is in the picture, and it does not have the two.
3579
+ * The check accepts fields that the format does not know.
3580
+ */
3581
+ function checkPicture(value) {
3582
+ if (!isFields$1(value)) return ["the picture is not an object"];
3583
+ const out = [];
3584
+ if (value["schema"] !== "layout-picture/1") out.push(`schema is not ${PICTURE_SCHEMA}`);
3585
+ if (value["id"] !== void 0 && typeof value["id"] !== "string") out.push("id is not a string");
3586
+ const boxIds = /* @__PURE__ */ new Set();
3587
+ listOf(out, value["boxes"], "boxes").forEach((v, i) => {
3588
+ const box = recordOf(out, "box", v, i, boxIds);
3589
+ if (box === void 0) return;
3590
+ rectProblems(out, box.name, box.fields);
3591
+ const parent = box.fields["parent"];
3592
+ if (parent !== void 0 && (typeof parent !== "string" || parent === box.id || !boxIds.has(parent))) out.push(`${box.name}: the parent ${String(parent)} is not a box before it in the list`);
3593
+ const shape = box.fields["shape"];
3594
+ if (shape !== void 0 && !(isFields$1(shape) && REGION_KINDS.includes(shape["kind"]))) out.push(`${box.name}: the shape is not a region`);
3595
+ dataProblems(out, box.name, box.fields);
3596
+ boxIds.add(box.id);
3597
+ });
3598
+ const routeIds = /* @__PURE__ */ new Set();
3599
+ listOf(out, value["routes"], "routes").forEach((v, i) => {
3600
+ const route = recordOf(out, "route", v, i, routeIds);
3601
+ if (route === void 0) return;
3602
+ for (const key of ["source", "target"]) {
3603
+ const end = route.fields[key];
3604
+ if (typeof end !== "string" || !boxIds.has(end)) out.push(`${route.name}: the ${key} ${String(end)} is not a box of the picture`);
3605
+ }
3606
+ for (const problem of checkPath(route.fields["path"])) out.push(`${route.name}: ${problem}`);
3607
+ dataProblems(out, route.name, route.fields);
3608
+ routeIds.add(route.id);
3609
+ });
3610
+ const labelIds = /* @__PURE__ */ new Set();
3611
+ listOf(out, value["labels"], "labels").forEach((v, i) => {
3612
+ const label = recordOf(out, "label", v, i, labelIds);
3613
+ if (label === void 0) return;
3614
+ const f = label.fields;
3615
+ rectProblems(out, label.name, f);
3616
+ if (f["box"] !== void 0 && f["route"] !== void 0) out.push(`${label.name}: the label has a box and a route`);
3617
+ if (f["box"] !== void 0 && (typeof f["box"] !== "string" || !boxIds.has(f["box"]))) out.push(`${label.name}: the box ${String(f["box"])} is not a box of the picture`);
3618
+ if (f["route"] !== void 0 && (typeof f["route"] !== "string" || !routeIds.has(f["route"]))) out.push(`${label.name}: the route ${String(f["route"])} is not a route of the picture`);
3619
+ const lines = f["lines"];
3620
+ if (!Array.isArray(lines) || !lines.every((line) => typeof line === "string")) out.push(`${label.name}: lines is not a list of strings`);
3621
+ const lineHeight = f["lineHeight"];
3622
+ if (typeof lineHeight !== "number" || !Number.isFinite(lineHeight) || lineHeight <= 0) out.push(`${label.name}: lineHeight is not a finite number above 0`);
3623
+ if (typeof f["font"] !== "string" || f["font"] === "") out.push(`${label.name}: font is not a string with a character`);
3624
+ if (f["align"] !== void 0 && !LABEL_ALIGNS.includes(f["align"])) out.push(`${label.name}: align is not one of ${LABEL_ALIGNS.join(", ")}`);
3625
+ dataProblems(out, label.name, f);
3626
+ labelIds.add(label.id);
3627
+ });
3628
+ return out;
3629
+ }
3630
+ /**
3631
+ * This function reads one `layout-picture/1` value, for example a parsed JSON document.
3632
+ * It throws a `TypeError` with the problems of `checkPicture`.
3633
+ */
3634
+ function parsePicture(value) {
3635
+ const problems = checkPicture(value);
3636
+ if (problems.length > 0) throw new TypeError(`The value is not a layout-picture/1: ${problems.join(", ")}.`);
3637
+ return value;
3638
+ }
3639
+ /** This function gives the box of a picture for a placed box of an input. */
3640
+ function pictureBox(box, x, y) {
3641
+ return {
3642
+ id: box.id,
3643
+ x,
3644
+ y,
3645
+ w: box.w,
3646
+ h: box.h,
3647
+ ...box.parent === void 0 ? {} : { parent: box.parent },
3648
+ ...box.shape === void 0 ? {} : { shape: box.shape },
3649
+ ...box.data === void 0 ? {} : { data: box.data }
3650
+ };
3651
+ }
3652
+ /**
3653
+ * This function makes the picture of a placed input. Each box with `x` and `y` is in the picture, and a box with no place is not.
3654
+ * The coordinates of each box are those of the input. The order is the order of the input, but each box comes immediately before its children.
3655
+ *
3656
+ * Each route gets the source, the target and the data of its edge in the input. A route with no `path` gets the polyline of its points.
3657
+ * The labels of `parts` go into the picture with no change.
3658
+ * A `RangeError` comes for a placed box below a box with no place, and for a loop of parents.
3659
+ * It comes also for a route with no edge in the input, and for each problem of `checkPicture`.
3660
+ */
3661
+ function pictureOf(input, parts = {}) {
3662
+ const placed = input.boxes.filter((b) => b.x !== void 0 && b.y !== void 0);
3663
+ const ids = new Set(placed.map((b) => b.id));
3664
+ const roots = [];
3665
+ const children = /* @__PURE__ */ new Map();
3666
+ for (const b of placed) {
3667
+ if (b.parent === void 0) {
3668
+ roots.push(b);
3669
+ continue;
3670
+ }
3671
+ if (!ids.has(b.parent)) throw new RangeError(`layout-picture: the box ${b.id} has a place, and its parent ${b.parent} has no place in the input.`);
3672
+ const list = children.get(b.parent);
3673
+ if (list === void 0) children.set(b.parent, [b]);
3674
+ else list.push(b);
3675
+ }
3676
+ const boxes = [];
3677
+ const stack = roots.reverse();
3678
+ for (let b = stack.pop(); b !== void 0; b = stack.pop()) {
3679
+ boxes.push(pictureBox(b, b.x, b.y));
3680
+ const list = children.get(b.id);
3681
+ if (list !== void 0) for (let i = list.length - 1; i >= 0; i--) stack.push(list[i]);
3682
+ }
3683
+ if (boxes.length < placed.length) throw new RangeError("layout-picture: the parents of the boxes of the input make a loop.");
3684
+ const edges = new Map((input.edges ?? []).map((e) => [e.id, e]));
3685
+ const routes = (parts.routes ?? []).map((r) => {
3686
+ const edge = edges.get(r.edge);
3687
+ if (edge === void 0) throw new RangeError(`layout-picture: the route ${r.edge} has no edge in the input.`);
3688
+ return {
3689
+ id: edge.id,
3690
+ source: edge.source,
3691
+ target: edge.target,
3692
+ path: r.path ?? pathOf(r.points),
3693
+ ...edge.data === void 0 ? {} : { data: edge.data }
3694
+ };
3695
+ });
3696
+ const picture = {
3697
+ schema: PICTURE_SCHEMA,
3698
+ id: input.id,
3699
+ boxes,
3700
+ routes,
3701
+ labels: [...parts.labels ?? []]
3702
+ };
3703
+ const problems = checkPicture(picture);
3704
+ if (problems.length > 0) throw new RangeError(`layout-picture: ${problems.join(", ")}.`);
3705
+ return picture;
3706
+ }
3707
+ /**
3708
+ * This function gives the bounding box of a picture: its boxes, the exact bounds of its paths and its labels.
3709
+ * A picture with no record gives `undefined`. The picture must be good (`checkPicture`).
3710
+ */
3711
+ function pictureBounds(picture) {
3712
+ let x0 = Infinity;
3713
+ let y0 = Infinity;
3714
+ let x1 = -Infinity;
3715
+ let y1 = -Infinity;
3716
+ const add = (r) => {
3717
+ x0 = Math.min(x0, r.x);
3718
+ y0 = Math.min(y0, r.y);
3719
+ x1 = Math.max(x1, r.x + r.w);
3720
+ y1 = Math.max(y1, r.y + r.h);
3721
+ };
3722
+ for (const b of picture.boxes) add(b);
3723
+ for (const r of picture.routes) add(pathBounds(r.path));
3724
+ for (const l of picture.labels) add(l);
3725
+ return x0 === Infinity ? void 0 : {
3726
+ x: x0,
3727
+ y: y0,
3728
+ w: x1 - x0,
3729
+ h: y1 - y0
3730
+ };
3731
+ }
3231
3732
  // src/random.ts
3232
3733
  /**
3233
3734
  * This function gives a generator of random numbers in [0, 1). It is `mulberry32`, as in `docs/FORMAT.md` of `packing`.
@@ -6388,6 +6889,6 @@ function surveyFindings(survey) {
6388
6889
  units
6389
6890
  };
6390
6891
  }
6391
- export { BALANCE_MEASURE_SUFFIXES, BALANCE_SIDE_DEPTH, CELL_MEASURE_SUFFIXES, CELL_SOURCE, CIRCLE_SCATTERED, CORPUS_DIMENSIONS, CORPUS_MANIFEST_SCHEMA, CURVE_MAX_SIDE, CURVE_SYMMETRIES, DEFAULT_FAMILY_BY, DEFAULT_RNG, DEFAULT_SHAPES, DEFAULT_TOLERANCE, EDGES_STEP, EDGE_DENSITY, EDGE_KEY_STEP, EDGE_KEY_STEP_VERSION, EDGE_STEP_VERSION, EPS, EPS_STEPS, FAMILY_ANY_KIND, FRAME_SCHEMA, FRAME_STATES, HARD_RULE_VERSION, HILBERT_CURVE, HILBERT_PATTERN, INVALIDATED_FIELD, JOINT_MEASURES, JOINT_MOVED_MIN, JOINT_SOURCE, MEASURE_REGISTRY, MEASURE_SURVEY_SCHEMA, MOORE_CURVE, MOORE_PATTERN, MORTON_CURVE, NODE_POSITIONS_DIMENSION, NOISE_KINDS, NO_FINITE_RANGE, NO_ROTATION3, NO_TRANSFORM3, NO_UNIT, ORIGIN3, OUTPUT_CLASS_MIN_INPUTS, OUTPUT_GRID_PROPERTIES, OUTPUT_NEAR_WHOLE, PACK_HARD_RULES, RECORD_EPS, RECORD_SCALE, RECT_SCATTERED, REFUSED_PROBE, SHAPE_KINDS, SHAPE_KIND_IDS, SHARE_UNIT, SIDES, SPLIT_SCHEMA, SQUARE_COMPACTNESS, STRATEGY_CATALOG_SCHEMA, STRATEGY_CATALOG_SCHEMAS, STRATEGY_SPACE_SCHEMA, VERDICT_DRAWS, VERDICT_EXACT_CAP, VERDICT_EXACT_MAX, VERDICT_RUNS, VERDICT_SEED, addPoints3, applyPack, applySymmetry, balanceMeasureSpecs, balanceMeasures, balanceOf, boundsOf, boundsOf3, box3Center, box3Corners, box3Volume, boxArea, boxCenterDistance, canonicalConfig, canonicalInput, canonicalJson, carryRecord, catalogChoices, catalogDefaults, catalogKey, catalogOptions, cellMeasureEntries, cellMeasureSpecs, cellMeasures, cellsOf, checkCatalog, checkConfig, checkDeclared, checkInput, checkLayoutRecord, checkOptions, checkRegistry, checkSchema, checkShapes, checkSpace, checkSplit, checkSurvey, circleOverlaps, circlesOutside, clampOptions, clipRing, compareMeasure, composeFamily, composeRotations3, composeTransforms3, configId, convexCorners, convexOverlap, cornersInConvex, corpusHashOf, corpusManifestText, countLinksThroughShapes, countObstacleHits, countOutside, countOverlaps, countPortsOffBorder, countResizeBreaks, createFamilyRegistry, cross3, crossingPoint, curveCell, curveCells, curveIndex, declarationIssues, declaredClaimOf, declaredCounts, decodeOptionValue, defaultNormalize, dimensionAt, dimensionSupports, dimensionUnit, distance3, documentHash, dot3, dropIndex, edgeKeyStep, edgeStep, encodeOptionValue, enumerateSpace, exercised, familyKind, familyOf, fingerprintOf, fixedPointMove, fnv1a32, frameAt, frameMove, frameOf, grow, hardRuleOf, hilbertCell, hilbertIndex, inputShapeLevel, inverseRotation3, inverseSymmetry, inverseTransform3, isShapeKind, itemShapeOf, joinConfigs, leaveOneSeedOut, length3, levelsOf, lineJson, listOptions, manifestText, marginSides, measureEntry, minEffectOf, mooreCell, mooreIndex, mortonCell, mortonIndex, mulberry32, nameAfterStage, nearestGaps, normalizeMeasure, normalizeRotation3, optionDefaults, optionIssue, outputGridClass, outputGroups, outputHash, outputOf, overlapOf, overlapOf3, ownerDimension, packHard, packLinks, packOutputForm, paramActive, paramAt, paramLevels, paramProblem, paramUnit, paramValue, parseLayoutRecord, parseStrategyCatalog, perChange, pickMoves, placedCircle, placedConvex, placedRect, pointInRing, pointInRings, pointSegmentDistance, portPoint, portfolio, probeHash, procrustesOf, productSpace, randomInt, rectInRegion, regionArea, regionHitsRect, regionPerimeter, resizeBox, resizeProblems, resolveDimensions, ringCentroid, rotatePoint3, rotationAbout, ruleLevel, scalePoint3, scaleRect, segmentThroughShape, segmentsCross, selectBest, sha256Hex, shapeFits, shapeKindOf, shapeKindProblem, shapeKindsOf, shapeLevel, shapeSupportProblems, shapesOf, shapesOverlap, sharedDimension, sizeBoundsOf, sizeFits, snapRect, spaceShapeKinds, spaceSize, splitConfig, splitFileName, splitFolds, stepRandom, subtractPoints3, surveyFindings, sweepGrid, sweepOf, sweepValues, toLayoutRecord, toPackInput, toRect, toSizedRect, transformMatrix4, transformPoint3, transformedBounds3, translate, turnBox, turnMargin, turnPoint, turnPort, turnRegion, turnResize, turnSide, unitFault, verdict, writeStrategyCatalog };
6892
+ export { BALANCE_MEASURE_SUFFIXES, BALANCE_SIDE_DEPTH, CELL_MEASURE_SUFFIXES, CELL_SOURCE, CIRCLE_SCATTERED, CORPUS_DIMENSIONS, CORPUS_MANIFEST_SCHEMA, CURVE_MAX_SIDE, CURVE_SYMMETRIES, DEFAULT_FAMILY_BY, DEFAULT_RNG, DEFAULT_SHAPES, DEFAULT_TOLERANCE, EDGES_STEP, EDGE_DENSITY, EDGE_KEY_STEP, EDGE_KEY_STEP_VERSION, EDGE_STEP_VERSION, EPS, EPS_STEPS, FAMILY_ANY_KIND, FRAME_SCHEMA, FRAME_STATES, HARD_RULE_VERSION, HILBERT_CURVE, HILBERT_PATTERN, INVALIDATED_FIELD, JOINT_MEASURES, JOINT_MOVED_MIN, JOINT_SOURCE, LABEL_ALIGNS, MEASURE_REGISTRY, MEASURE_SURVEY_SCHEMA, MOORE_CURVE, MOORE_PATTERN, MORTON_CURVE, NODE_POSITIONS_DIMENSION, NOISE_KINDS, NO_FINITE_RANGE, NO_ROTATION3, NO_TRANSFORM3, NO_UNIT, ORIGIN3, OUTPUT_CLASS_MIN_INPUTS, OUTPUT_GRID_PROPERTIES, OUTPUT_NEAR_WHOLE, PACK_HARD_RULES, PATH_KINDS, PICTURE_SCHEMA, RECORD_EPS, RECORD_SCALE, RECT_SCATTERED, REFUSED_PROBE, SHAPE_KINDS, SHAPE_KIND_IDS, SHARE_UNIT, SIDES, SPLIT_SCHEMA, SQUARE_COMPACTNESS, STRATEGY_CATALOG_SCHEMA, STRATEGY_CATALOG_SCHEMAS, STRATEGY_SPACE_SCHEMA, VERDICT_DRAWS, VERDICT_EXACT_CAP, VERDICT_EXACT_MAX, VERDICT_RUNS, VERDICT_SEED, addPoints3, applyPack, applySymmetry, balanceMeasureSpecs, balanceMeasures, balanceOf, boundsOf, boundsOf3, box3Center, box3Corners, box3Volume, boxArea, boxCenterDistance, canonicalConfig, canonicalInput, canonicalJson, carryRecord, catalogChoices, catalogDefaults, catalogKey, catalogOptions, cellMeasureEntries, cellMeasureSpecs, cellMeasures, cellsOf, checkCatalog, checkConfig, checkDeclared, checkInput, checkLayoutRecord, checkOptions, checkPath, checkPicture, checkRegistry, checkSchema, checkShapes, checkSpace, checkSplit, checkSurvey, circleOverlaps, circlesOutside, clampOptions, clipRing, compareMeasure, composeFamily, composeRotations3, composeTransforms3, configId, convexCorners, convexOverlap, cornersInConvex, corpusHashOf, corpusManifestText, countLinksThroughShapes, countObstacleHits, countOutside, countOverlaps, countPortsOffBorder, countResizeBreaks, createFamilyRegistry, cross3, crossingPoint, cubicAt, curveCell, curveCells, curveIndex, declarationIssues, declaredClaimOf, declaredCounts, decodeOptionValue, defaultNormalize, dimensionAt, dimensionSupports, dimensionUnit, distance3, documentHash, dot3, dropIndex, edgeKeyStep, edgeStep, encodeOptionValue, enumerateSpace, exercised, familyKind, familyOf, fingerprintOf, fixedPointMove, fnv1a32, frameAt, frameMove, frameOf, grow, hardRuleOf, hilbertCell, hilbertIndex, inputShapeLevel, inverseRotation3, inverseSymmetry, inverseTransform3, isShapeKind, itemShapeOf, joinConfigs, leaveOneSeedOut, length3, levelsOf, lineJson, listOptions, manifestText, marginSides, measureEntry, minEffectOf, mooreCell, mooreIndex, mortonCell, mortonIndex, mulberry32, nameAfterStage, nearestGaps, normalizeMeasure, normalizeRotation3, optionDefaults, optionIssue, outputGridClass, outputGroups, outputHash, outputOf, overlapOf, overlapOf3, ownerDimension, packHard, packLinks, packOutputForm, paramActive, paramAt, paramLevels, paramProblem, paramUnit, paramValue, parseLayoutRecord, parsePicture, parseStrategyCatalog, pathBounds, pathEnd, pathOf, pathStart, perChange, pickMoves, pictureBounds, pictureOf, placedCircle, placedConvex, placedRect, pointInRing, pointInRings, pointSegmentDistance, portPoint, portfolio, probeHash, procrustesOf, productSpace, randomInt, rectInRegion, regionArea, regionHitsRect, regionPerimeter, resizeBox, resizeProblems, resolveDimensions, ringCentroid, rotatePoint3, rotationAbout, ruleLevel, samplePath, scalePoint3, scaleRect, segmentThroughShape, segmentsCross, selectBest, sha256Hex, shapeFits, shapeKindOf, shapeKindProblem, shapeKindsOf, shapeLevel, shapeSupportProblems, shapesOf, shapesOverlap, sharedDimension, sizeBoundsOf, sizeFits, snapRect, spaceShapeKinds, spaceSize, splitConfig, splitFileName, splitFolds, stepRandom, subtractPoints3, surveyFindings, sweepGrid, sweepOf, sweepValues, toLayoutRecord, toPackInput, toRect, toSizedRect, toSvgPath, transformMatrix4, transformPoint3, transformedBounds3, translate, turnBox, turnMargin, turnPoint, turnPort, turnRegion, turnResize, turnSide, unitFault, verdict, writeStrategyCatalog };
6392
6893
 
6393
6894
  //# sourceMappingURL=index.js.map