@mark1russell7/layout-contract 0.9.8 → 0.10.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/src/rules.ts CHANGED
@@ -1,7 +1,21 @@
1
- import { boundsOf, grow, marginSides, overlapOf, pointInRings, type Margin, type Point, type Rect, type Region } from "./geometry.ts";
1
+ import {
2
+ boundsOf,
3
+ convexCorners,
4
+ convexOverlap,
5
+ cornersInConvex,
6
+ grow,
7
+ marginSides,
8
+ overlapOf,
9
+ pointInRings,
10
+ type Margin,
11
+ type Point,
12
+ type Rect,
13
+ type Region,
14
+ type Ring,
15
+ } from "./geometry.ts";
2
16
  import type { LayoutBox, LayoutContainer, LayoutInput, Obstacle, PairGap, Port } from "./input.ts";
3
17
  import { applyPack, type PackOutput } from "./output.ts";
4
- import { resizeProblems, sizeFits } from "./resize.ts";
18
+ import { resizeProblems, shapeFits, sizeFits } from "./resize.ts";
5
19
  import { SHAPE_KIND_IDS, shapeKindProblem, type ShapeSupport } from "./shapes.ts";
6
20
  import { DEFAULT_TOLERANCE, EPS, RECORD_EPS } from "./tolerance.ts";
7
21
  import { turnBox } from "./turn.ts";
@@ -19,8 +33,10 @@ export function placedRect(box: LayoutBox): Rect | undefined {
19
33
  *
20
34
  * - Version 1 counts each shape by its bounding box. On a circle, that count is an upper bound. A count over 0 proves nothing.
21
35
  * - 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.
36
+ * - Version 3 counts a pair with a convex polygon by the separating axis theorem. The other box is a rectangle or a convex polygon, and neither box has a margin.
37
+ * A convex polygon without a margin in a convex container counts by its corners. The counts of the other inputs do not change.
22
38
  */
23
- export const HARD_RULE_VERSION = 2;
39
+ export const HARD_RULE_VERSION = 3;
24
40
 
25
41
  /** A circle at its place on the board: its center and its radius, without a margin. */
26
42
  export interface PlacedCircle {
@@ -35,6 +51,20 @@ export function placedCircle(box: LayoutBox): PlacedCircle | undefined {
35
51
  return { cx: box.x + box.shape.cx, cy: box.y + box.shape.cy, r: box.shape.r };
36
52
  }
37
53
 
54
+ /**
55
+ * This function gives the corners of a placed box on the board, when its outline is convex and it has no margin. Each other box gives `undefined`.
56
+ * A box without a shape is its rectangle. A box with a shape gives `convexCorners` of the shape at the position of the box.
57
+ */
58
+ export function placedConvex(box: LayoutBox): Ring | undefined {
59
+ if (box.x === undefined || box.y === undefined) return undefined;
60
+ const m = marginSides(box.margin);
61
+ if (m.top !== 0 || m.right !== 0 || m.bottom !== 0 || m.left !== 0) return undefined;
62
+ const corners = convexCorners(box.shape ?? { kind: "rect", x: 0, y: 0, w: box.w, h: box.h });
63
+ if (corners === undefined) return undefined;
64
+ const { x, y } = box;
65
+ return corners.map(([cx, cy]) => [cx + x, cy + y] as const);
66
+ }
67
+
38
68
  /** 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. */
39
69
  function marginReach(margin: Margin | undefined): number {
40
70
  const m = marginSides(margin);
@@ -54,6 +84,7 @@ function nearerThan(a: PlacedCircle, b: PlacedCircle, need: number): boolean {
54
84
  *
55
85
  * - 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.
56
86
  * - 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.
87
+ * - A pair with a convex polygon and no margin also needs an overlap over `tolerance` on the normal of each side (`convexOverlap`). Thus that pair is exact.
57
88
  * - 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.
58
89
  * - A box without a position does not overlap.
59
90
  */
@@ -65,7 +96,19 @@ export function shapesOverlap(a: LayoutBox, b: LayoutBox, tolerance: number = DE
65
96
  const rb = placedRect(b);
66
97
  if (ra === undefined || rb === undefined) return false;
67
98
  const o = gap === undefined ? overlapOf(grow(ra, a.margin), grow(rb, b.margin)) : overlapOf(grow(ra, gap), rb);
68
- return o.x > tolerance && o.y > tolerance;
99
+ if (!(o.x > tolerance && o.y > tolerance)) return false;
100
+ return gap !== undefined || !convexApart(a, b, tolerance);
101
+ }
102
+
103
+ /**
104
+ * This function tells if the separating axis theorem puts two placed boxes apart, for `no-overlap` of version 3.
105
+ * Only a pair with a box of a `polygon` shape is tested, and both boxes need `placedConvex`. Each other pair gives `false`, so its count does not change.
106
+ */
107
+ function convexApart(a: LayoutBox, b: LayoutBox, tolerance: number): boolean {
108
+ if (a.shape?.kind !== "polygon" && b.shape?.kind !== "polygon") return false;
109
+ const ca = placedConvex(a);
110
+ const cb = placedConvex(b);
111
+ return ca !== undefined && cb !== undefined && convexOverlap(ca, cb) <= tolerance;
69
112
  }
70
113
 
71
114
  /** 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. */
@@ -81,6 +124,7 @@ function gapsOf(pairGaps: readonly PairGap[] | undefined): Map<string, number> {
81
124
  /**
82
125
  * This function counts the pairs of placed boxes that break `no-overlap`. `shapesOverlap` is the rule for one pair.
83
126
  * 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).
127
+ * A pair with a convex polygon and no margin also needs an overlap on the normal of each side, so it is exact (version 3).
84
128
  *
85
129
  * 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.
86
130
  * Thus the pair breaks the rule only when the boxes are nearer than the gap on each axis. The other pairs do not change.
@@ -146,12 +190,15 @@ export function circleOverlaps(boxes: readonly LayoutBox[], tolerance: number =
146
190
  return count;
147
191
  }
148
192
 
149
- /** This function counts the overlaps by the bounding boxes with their margins. It skips the pairs of `skip` and the pairs of two circles. */
193
+ /**
194
+ * This function counts the overlaps by the bounding boxes with their margins. It skips the pairs of `skip` and the pairs of two circles.
195
+ * A pair that `convexApart` puts apart does not count.
196
+ */
150
197
  function marginOverlaps(boxes: readonly LayoutBox[], tolerance: number, skip: ReadonlyMap<string, number> | undefined): number {
151
- const rects: { readonly id: string; readonly r: Rect; readonly circle: boolean }[] = [];
198
+ const rects: { readonly box: LayoutBox; readonly id: string; readonly r: Rect; readonly circle: boolean }[] = [];
152
199
  for (const box of boxes) {
153
200
  const r = placedRect(box);
154
- if (r !== undefined) rects.push({ id: box.id, r: grow(r, box.margin), circle: box.shape?.kind === "circle" });
201
+ if (r !== undefined) rects.push({ box, id: box.id, r: grow(r, box.margin), circle: box.shape?.kind === "circle" });
155
202
  }
156
203
  rects.sort((a, b) => a.r.x - b.r.x);
157
204
  let count = 0;
@@ -163,7 +210,7 @@ function marginOverlaps(boxes: readonly LayoutBox[], tolerance: number, skip: Re
163
210
  if (rects[i]!.circle && rects[j]!.circle) continue;
164
211
  if (skip !== undefined && skip.has(pairKey(rects[i]!.id, rects[j]!.id))) continue;
165
212
  const o = overlapOf(a, b);
166
- if (o.x > tolerance && o.y > tolerance) count++;
213
+ if (o.x > tolerance && o.y > tolerance && !convexApart(rects[i]!.box, rects[j]!.box, tolerance)) count++;
167
214
  }
168
215
  }
169
216
  return count;
@@ -326,8 +373,10 @@ export function countLinksThroughShapes(boxes: readonly LayoutBox[], links: read
326
373
  *
327
374
  * 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`.
328
375
  * 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.
329
- * A circle in a circle container does not use `rectInRegion`. It counts by distance, as in `circlesOutside`, also when the size is free.
330
376
  * An input without a container gives 0.
377
+ *
378
+ * A circle in a circle container does not use `rectInRegion`. It counts by distance, as in `circlesOutside`, also when the size is free.
379
+ * A box of a `polygon` shape with `placedConvex` in a convex shape does not use `rectInRegion`. It counts by its corners (`cornersInConvex`), so the count is exact (version 3).
331
380
  */
332
381
  export function countOutside(input: LayoutInput, tolerance: number = DEFAULT_TOLERANCE.overlap, options: ContainerTest = {}): number {
333
382
  const c = input.container;
@@ -350,11 +399,19 @@ export function countOutside(input: LayoutInput, tolerance: number = DEFAULT_TOL
350
399
  if ((fixW && outX) || (fixH && outY)) count++;
351
400
  else if (ring !== undefined && disc !== undefined) {
352
401
  if (circleOutside(disc, marginReach(box.margin) + inset, ring, tolerance)) count++;
353
- } else if (shape !== undefined && !rectInRegion(shape, shrink(grow(r, inset), tolerance))) count++;
402
+ } else if (shape !== undefined && !inShape(box, shape, r, inset, tolerance)) count++;
354
403
  }
355
404
  return count;
356
405
  }
357
406
 
407
+ /** This function tells if a placed box is inside a container shape for `countOutside`. A convex polygon box in a convex shape counts by its corners. */
408
+ function inShape(box: LayoutBox, shape: Region, r: Rect, inset: number, tolerance: number): boolean {
409
+ const inner = box.shape?.kind === "polygon" ? placedConvex(box) : undefined;
410
+ const outer = inner === undefined ? undefined : convexCorners(shape);
411
+ if (inner !== undefined && outer !== undefined) return cornersInConvex(inner, outer, inset, tolerance);
412
+ return rectInRegion(shape, shrink(grow(r, inset), tolerance));
413
+ }
414
+
358
415
  /** This function counts the fixed ports that are not on the border of their box, with the epsilon of a written file. A port without a side does not count. */
359
416
  export function countPortsOffBorder(boxes: readonly LayoutBox[], eps: number = RECORD_EPS): number {
360
417
  let count = 0;
@@ -377,8 +434,8 @@ export interface PackHard {
377
434
  readonly "locked-kept": number;
378
435
  readonly complete: number;
379
436
  /**
380
- * The count of the placements whose size is not in the bounds of their box (`countResizeBreaks`).
381
- * `packHard` gives it only when a box of the input has `resize` or a placement has `w` or `h`. Thus the counts of the other inputs do not change.
437
+ * The count of the placements whose size or shape does not fit their box (`countResizeBreaks`).
438
+ * `packHard` gives it only when a box of the input has `resize` or a placement has `w`, `h` or `shape`. Thus the counts of the other inputs do not change.
382
439
  */
383
440
  readonly "size-kept"?: number;
384
441
  }
@@ -388,6 +445,9 @@ export interface PackHard {
388
445
  * `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).
389
446
  * 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.
390
447
  * `locked-kept` and `complete` read only the positions and the ids, so they support each kind.
448
+ *
449
+ * A convex `polygon` without a margin is exact beside a rectangle or a convex polygon, and in a convex container (version 3).
450
+ * The kind `polygon` stays `safe`, because a concave polygon is not exact.
391
451
  */
392
452
  export const PACK_HARD_RULES: readonly ShapeSupport<keyof PackHard>[] = /* @__PURE__ */ Object.freeze([
393
453
  {
@@ -561,19 +621,23 @@ export function countObstacleHits(
561
621
  }
562
622
 
563
623
  /**
564
- * This function gives the count of the placements whose size is not in the bounds of their box (`sizeFits`).
624
+ * This function counts the placements with a size outside the bounds of their box (`sizeFits`), or with a shape that does not fit (`shapeFits`).
565
625
  * The bounds are in the axes of the placed box: a turned box has the turned bounds. A placement without `w` or `h` keeps that size of the box.
626
+ * A placement with a shape on a box without `resize.reshape` counts. A placement counts one time, also when its size and its shape both break.
566
627
  * A placement of an id that is not in the input does not count.
567
628
  */
568
629
  export function countResizeBreaks(input: LayoutInput, output: PackOutput): number {
569
630
  const was = new Map(input.boxes.map((b) => [b.id, b]));
570
631
  let count = 0;
571
632
  for (const p of output.placements) {
572
- if (p.w === undefined && p.h === undefined) continue;
633
+ if (p.w === undefined && p.h === undefined && p.shape === undefined) continue;
573
634
  const box = was.get(p.id);
574
635
  if (box === undefined) continue;
575
636
  const placed = p.turn === 90 ? turnBox(box) : box;
576
- if (!sizeFits(placed, p.w ?? placed.w, p.h ?? placed.h)) count++;
637
+ const w = p.w ?? placed.w;
638
+ const h = p.h ?? placed.h;
639
+ const sized = (p.w === undefined && p.h === undefined) || sizeFits(placed, w, h);
640
+ if (!sized || (p.shape !== undefined && !shapeFits(placed, p.shape, w, h))) count++;
577
641
  }
578
642
  return count;
579
643
  }
@@ -586,7 +650,7 @@ export function countResizeBreaks(input: LayoutInput, output: PackOutput): numbe
586
650
  * A locked box without a placement, or with a move of more than `RECORD_EPS`, breaks `locked-kept`.
587
651
  * A locked box without a position in the input is a bad input, not a break. `checkInput` finds it.
588
652
  * Another box without a placement that is not in `overflow` breaks `complete`.
589
- * `size-kept` is in the result only when a box has `resize` or a placement has `w` or `h` (`countResizeBreaks`).
653
+ * `size-kept` is in the result only when a box has `resize` or a placement has `w`, `h` or `shape` (`countResizeBreaks`).
590
654
  *
591
655
  * `options` goes to `countOutside` for `in-container`.
592
656
  */
@@ -620,9 +684,9 @@ export function packHard(input: LayoutInput, output: PackOutput, tolerance: numb
620
684
  };
621
685
  }
622
686
 
623
- /** This function tells if a box of the input has `resize` or a placement of the output has `w` or `h`. */
687
+ /** This function tells if a box of the input has `resize` or a placement of the output has `w`, `h` or `shape`. */
624
688
  function resizes(input: LayoutInput, output: PackOutput): boolean {
625
- return input.boxes.some((b) => b.resize !== undefined) || output.placements.some((p) => p.w !== undefined || p.h !== undefined);
689
+ return input.boxes.some((b) => b.resize !== undefined) || output.placements.some((p) => p.w !== undefined || p.h !== undefined || p.shape !== undefined);
626
690
  }
627
691
 
628
692
  /**
package/src/text.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { breakers, linesOf, type Box, type Item, type Penalty } from "@mark1russell7/typeset/breaking";
1
+ import { adjustmentRatios, breakers, linesOf, type Box, type Glue, type Item, type Penalty } from "@mark1russell7/typeset/breaking";
2
2
  import { graphemes, lineBreaks } from "@mark1russell7/typeset/segmentation";
3
3
  import { partsOfWords } from "./word-parts.ts";
4
4
  import type { MeasureSpec } from "./measures.ts";
@@ -313,6 +313,26 @@ export interface TextLayoutOptions {
313
313
  readonly sizing?: TextSizing;
314
314
  /** The declared character set of `sizing`. `bound-first` and `bound` need it, and `exact` does not read it. */
315
315
  readonly charset?: TextCharset;
316
+ /**
317
+ * The stretch and the shrink of each space of a text that wraps, as a share of the width of a space. TeX uses a stretch of 0.5 and a shrink of 1/3.
318
+ * With this option, `total-fit` chooses the lines with the adjustment ratio, and the layout gives the ratio of each line in `ratios`.
319
+ * Without it, a space does not stretch or shrink.
320
+ */
321
+ readonly justify?: TextJustify;
322
+ /**
323
+ * The hyphenation hook of `paragraphOf` of `@mark1russell7/typeset`. It gives the offsets in a word where a break with a hyphen is possible.
324
+ * A line that ends at such an offset ends with "-". The subpaths `./hyphen/<language>` of typeset give a hook for each language.
325
+ * layout-contract imports no pattern set. Without the option, a word does not break at a hyphen.
326
+ */
327
+ readonly hyphenate?: (word: string) => readonly number[];
328
+ }
329
+
330
+ /** The stretch and the shrink of each space of a justified layout, as a share of the width of a space. */
331
+ export interface TextJustify {
332
+ /** A finite number of 0 or more. */
333
+ readonly stretch: number;
334
+ /** A finite number from 0 to 1, because a space cannot be narrower than 0. */
335
+ readonly shrink: number;
316
336
  }
317
337
 
318
338
  /** The layout of a text: its lines and its box. */
@@ -330,6 +350,13 @@ export interface TextLayout {
330
350
  readonly truncated: boolean;
331
351
  /** `true` when the widths and the box come from the bound of a character set. Each width is then at or above the measured width. A measured layout does not have this field. */
332
352
  readonly bounded?: true;
353
+ /**
354
+ * The adjustment ratio of each line of a text that wraps with the option `justify`. A renderer adds `ratio × stretch × space` to each space of the
355
+ * line, or `ratio × shrink × space` when the ratio is negative. The last line does not stretch, so its ratio is not more than 0.
356
+ * The ratio is infinite for a line with free space and no space to stretch.
357
+ * A layout without `justify`, or a text that fits on one line at its natural width, does not have this field.
358
+ */
359
+ readonly ratios?: readonly number[];
333
360
  }
334
361
 
335
362
  /** A forced break: a penalty with no text, no width and the cost `-Infinity`. */
@@ -338,6 +365,21 @@ const FORCED: Penalty = { type: "penalty", text: "", width: 0, cost: -Infinity,
338
365
  /** The glue between two words with no white space between them, for example after a hyphen or between two CJK characters. A line can end there. */
339
366
  const NO_GAP: Item = { type: "glue", text: "", width: 0 };
340
367
 
368
+ /** The cost of a break at a hyphen: 50, as in TeX and in `paragraphOf` of typeset. */
369
+ const HYPHEN_COST = 50;
370
+
371
+ /**
372
+ * This function gives the hyphen places of a word from the hook, sorted, with no repeat.
373
+ * It keeps only the offsets between two grapheme clusters, so a place inside a surrogate pair or before a mark does not split a cluster.
374
+ */
375
+ function hyphenPlaces(word: string, hyphenate: (word: string) => readonly number[]): number[] {
376
+ const edges = new Set<number>();
377
+ let at = 0;
378
+ for (const cluster of graphemesOf(word)) edges.add((at += cluster.length));
379
+ const places = hyphenate(word).filter((o) => o > 0 && o < word.length && edges.has(o));
380
+ return [...new Set(places)].sort((a, b) => a - b);
381
+ }
382
+
341
383
  /** This function gives the box of a part of a word. */
342
384
  /** This function gives the units of a segment: the bound for one character times the length, or a measure when there is no bound. */
343
385
  function advanceOf(segment: string, font: string, measurer: TextMeasurer, bound: number | undefined): number {
@@ -375,6 +417,10 @@ export function layoutText(text: string, options: TextLayoutOptions): TextLayout
375
417
  const sizing = options.sizing ?? "exact";
376
418
  if (sizing !== "exact" && sizing !== "bound-first" && sizing !== "bound") throw new RangeError(`layoutText: sizing is "exact", "bound-first" or "bound", not ${String(sizing)}.`);
377
419
  const charset = sizing === "exact" ? undefined : options.charset;
420
+ const { justify, hyphenate } = options;
421
+ if (justify !== undefined && !(Number.isFinite(justify.stretch) && justify.stretch >= 0 && Number.isFinite(justify.shrink) && justify.shrink >= 0 && justify.shrink <= 1)) {
422
+ throw new RangeError(`layoutText: justify has a finite stretch of 0 or more and a shrink from 0 to 1, not ${String(justify.stretch)} and ${String(justify.shrink)}.`);
423
+ }
378
424
  if (sizing !== "exact" && charset === undefined) throw new RangeError(`layoutText: sizing "${sizing}" needs a charset from createTextCharset.`);
379
425
  let truncated = false;
380
426
 
@@ -438,17 +484,45 @@ export function layoutText(text: string, options: TextLayoutOptions): TextLayout
438
484
  }
439
485
  if (cur !== undefined) items.push(boxOf(cur));
440
486
  };
487
+ const gap: Glue = justify === undefined ? { type: "glue", text: " ", width: space } : { type: "glue", text: " ", width: space, stretch: space * justify.stretch, shrink: space * justify.shrink };
488
+ const hyphen: Penalty | undefined = hyphenate === undefined ? undefined : { type: "penalty", text: "-", width: advanceOf("-", font, measurer, bound), cost: HYPHEN_COST, flagged: true };
489
+ /**
490
+ * This function puts the parts of a word between its hyphen places, with a hyphen penalty between two parts. A word with no place stays one box.
491
+ * The last part gets the width of the word minus the earlier parts. Thus the parts have the width of the whole word, also with kerning.
492
+ */
493
+ const hyphenated = (word: Word, w: number): void => {
494
+ const places = hyphen === undefined ? [] : hyphenPlaces(word.text, hyphenate!);
495
+ if (places.length === 0) {
496
+ items.push({ type: "box", text: word.text, width: w });
497
+ return;
498
+ }
499
+ let start = 0;
500
+ let rest = w;
501
+ for (const end of [...places, word.text.length]) {
502
+ if (start > 0) items.push(hyphen!);
503
+ const part = word.text.slice(start, end);
504
+ const units = end === word.text.length ? rest : advanceOf(part, font, measurer, bound);
505
+ items.push({ type: "box", text: part, width: units });
506
+ rest -= units;
507
+ start = end;
508
+ }
509
+ };
441
510
  words.forEach((word, i) => {
442
511
  const w = widths[i]!;
443
512
  if (w > limit && !keep) split(word);
444
513
  else {
445
- if (items.length > 0) items.push(words[i - 1]!.spaced ? { type: "glue", text: " ", width: space } : NO_GAP);
446
- items.push({ type: "box", text: word.text, width: w });
514
+ if (items.length > 0) items.push(words[i - 1]!.spaced ? gap : NO_GAP);
515
+ hyphenated(word, w);
447
516
  }
448
517
  });
449
518
  const paragraph = { items };
450
- const lines: Line[] = linesOf(paragraph, breaker.breaks(paragraph, limit)).map((l) => ({ text: l.text, units: l.width }));
451
- if (lines.length === 0) lines.push({ text: "", units: 0 });
519
+ const broken = linesOf(paragraph, breaker.breaks(paragraph, limit));
520
+ const lines: Line[] = broken.map((l) => ({ text: l.text, units: l.width }));
521
+ const ratios = justify === undefined ? undefined : adjustmentRatios(paragraph, broken, limit);
522
+ if (lines.length === 0) {
523
+ lines.push({ text: "", units: 0 });
524
+ ratios?.push(0);
525
+ }
452
526
 
453
527
  const maxLines = options.maxLines ?? Infinity;
454
528
  if (lines.length > maxLines) {
@@ -461,6 +535,11 @@ export function layoutText(text: string, options: TextLayoutOptions): TextLayout
461
535
  last.text = kept + ellipsis;
462
536
  last.units = lineUnits(kept) + tail;
463
537
  truncated = true;
538
+ // The cut line is the last line, so it does not stretch. The cut makes it fit, so it does not shrink.
539
+ if (ratios !== undefined) {
540
+ ratios.length = lines.length;
541
+ ratios[lines.length - 1] = 0;
542
+ }
464
543
  }
465
544
 
466
545
  const layout: TextLayout = {
@@ -471,6 +550,7 @@ export function layoutText(text: string, options: TextLayoutOptions): TextLayout
471
550
  height: lines.length * lineHeight,
472
551
  wrapWidth: options.wrapWidth,
473
552
  truncated,
553
+ ...(ratios === undefined ? {} : { ratios }),
474
554
  };
475
555
  return bound === undefined ? layout : { ...layout, bounded: true };
476
556
  }
@@ -509,7 +589,7 @@ function numberKey(value: number | undefined): string {
509
589
  * A number has no comma. The two lengths mark the end of the font and of the ellipsis.
510
590
  */
511
591
  function optionsKey(o: TextLayoutOptions): string {
512
- const numbers = `${numberKey(o.lineHeight)},${numberKey(o.wrapWidth)},${numberKey(o.maxLines)},${numberKey(o.maxChars)},${numberKey(o.padding)},${numberKey(o.minWidth)},${numberKey(o.maxWidth)}`;
592
+ const numbers = `${numberKey(o.lineHeight)},${numberKey(o.wrapWidth)},${numberKey(o.maxLines)},${numberKey(o.maxChars)},${numberKey(o.padding)},${numberKey(o.minWidth)},${numberKey(o.maxWidth)},${numberKey(o.justify?.stretch)},${numberKey(o.justify?.shrink)}`;
513
593
  return `${numbers},${(o.wordBreak ?? "keep") === "keep"},${o.breaker},${o.sizing ?? "exact"},${o.font.length},${o.ellipsis?.length},${o.font}${o.ellipsis ?? ""}`;
514
594
  }
515
595
 
@@ -529,7 +609,10 @@ function sameOptions(a: TextLayoutOptions, b: TextLayoutOptions): boolean {
529
609
  a.wordBreak === b.wordBreak &&
530
610
  a.breaker === b.breaker &&
531
611
  a.sizing === b.sizing &&
532
- a.charset === b.charset
612
+ a.charset === b.charset &&
613
+ a.hyphenate === b.hyphenate &&
614
+ Object.is(a.justify?.stretch, b.justify?.stretch) &&
615
+ Object.is(a.justify?.shrink, b.justify?.shrink)
533
616
  );
534
617
  }
535
618
 
@@ -543,7 +626,7 @@ interface CurrentOptions {
543
626
  }
544
627
 
545
628
  /**
546
- * This function gives a bounded cache of `layoutText` results, keyed by the text, the options, the measurer and the character set.
629
+ * This function gives a bounded cache of `layoutText` results, keyed by the text, the options, the measurer, the character set and the hyphenation hook.
547
630
  * A full cache removes one entry. It takes the set of options that a caller used least recently, and in it the text that a caller used least recently.
548
631
  * The key holds the raw font string, because a host can give two spellings of a font two different advances.
549
632
  * A measurer with `generation` starts a new set of keys after each `reset`. For a different measurer, start `reset` of the cache after a change of the advances.
@@ -572,10 +655,13 @@ export function createTextLayoutCache(options: TextLayoutCacheOptions = {}): Tex
572
655
  /** This function finds the layouts of a set of options, and it makes that set the most recently used. */
573
656
  const open = (layoutOptions: TextLayoutOptions, generation: number | undefined): CurrentOptions => {
574
657
  const charset = layoutOptions.charset === undefined ? "" : idOf(layoutOptions.charset);
575
- const key = `${idOf(layoutOptions.measurer)},${generation},${charset},${optionsKey(layoutOptions)}`;
658
+ const hyphenate = layoutOptions.hyphenate === undefined ? "" : idOf(layoutOptions.hyphenate);
659
+ const key = `${idOf(layoutOptions.measurer)},${generation},${charset},${hyphenate},${optionsKey(layoutOptions)}`;
576
660
  const layouts = groups.get(key) ?? new Map<string, TextLayout>();
577
661
  if (groups.delete(key)) groups.set(key, layouts);
578
- return { options: { ...layoutOptions }, generation, key, layouts };
662
+ // The copy of `justify` keeps its values, so a later change of the object of the caller does not touch the key.
663
+ const copy = layoutOptions.justify === undefined ? { ...layoutOptions } : { ...layoutOptions, justify: { ...layoutOptions.justify } };
664
+ return { options: copy, generation, key, layouts };
579
665
  };
580
666
  /** This function removes one entry. */
581
667
  const evict = (): void => {
@@ -603,6 +689,7 @@ export function createTextLayoutCache(options: TextLayoutCacheOptions = {}): Tex
603
689
  // The callers share this object, so it is frozen also when the cache does not keep it.
604
690
  Object.freeze(layout.lines);
605
691
  Object.freeze(layout.widths);
692
+ if (layout.ratios !== undefined) Object.freeze(layout.ratios);
606
693
  Object.freeze(layout);
607
694
  if (max > 0) {
608
695
  if (size >= max) evict();
@@ -630,9 +717,9 @@ export type TextMeasureId = "text.lines" | "text.raggedness" | "text.overflow" |
630
717
  /** The specs of the text measures. */
631
718
  export const TEXT_MEASURES: readonly MeasureSpec<TextMeasureId>[] = /* @__PURE__ */ Object.freeze([
632
719
  { id: "text.lines", unit: "count", direction: "lower", min: 1, max: Infinity, minEffect: 0, family: "text" },
633
- { id: "text.raggedness", unit: "0 to 1", direction: "lower", min: 0, max: 1, minEffect: 0.005, family: "text" },
634
- { id: "text.overflow", unit: "share of the wrap width", direction: "lower", min: 0, max: Infinity, floor: 0, tol: 0, minEffect: 0, family: "text", role: "guard" },
635
- { id: "text.cacheHit", unit: "0 to 1", direction: "higher", min: 0, max: 1, family: "text", role: "diagnostic" },
720
+ { id: "text.raggedness", unit: "share", direction: "lower", min: 0, max: 1, minEffect: 0.005, family: "text" },
721
+ { id: "text.overflow", unit: "wrap widths", direction: "lower", min: 0, max: Infinity, floor: 0, tol: 0, minEffect: 0, family: "text", role: "guard" },
722
+ { id: "text.cacheHit", unit: "share", direction: "higher", min: 0, max: 1, family: "text", role: "diagnostic" },
636
723
  { id: "text.ms", unit: "milliseconds", direction: "lower", min: 0, max: Infinity, family: "text", role: "time" },
637
724
  ] as const);
638
725
 
@@ -1 +0,0 @@
1
- {"version":3,"file":"measures-CJZw-Y3H.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;W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