@mark1russell7/layout-contract 0.9.9 → 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.
@@ -84,6 +84,13 @@ declare function boundsOf(region: Region): Rect;
84
84
  * A polygon gives the absolute value of the shoelace formula, less the area of each hole. A ring with fewer than 3 points has the area 0.
85
85
  */
86
86
  declare function regionArea(region: Region): number;
87
+ /**
88
+ * This function gives the perimeter of a region. A `rect` gives `2 * (w + h)`, and a circle gives `2 * PI * r`.
89
+ * A polygon gives the length of its outer ring plus the length of each hole. A ring with fewer than 2 points has the length 0.
90
+ *
91
+ * An ellipse has no closed form. It gives the second formula of Ramanujan, with a relative error below 5e-4 of the true perimeter. The error is largest for a flat ellipse.
92
+ */
93
+ declare function regionPerimeter(region: Region): number;
87
94
  /** This function gives the region moved by `dx` and `dy`. */
88
95
  declare function translate(region: Region, dx: number, dy: number): Region;
89
96
  /**
@@ -94,6 +101,24 @@ declare function overlapOf(a: Rect, b: Rect): {
94
101
  readonly x: number;
95
102
  readonly y: number;
96
103
  };
104
+ /**
105
+ * This function gives the corners of a convex region, or `undefined` for each other region.
106
+ * A `rect` gives its 4 corners. A `polygon` without holes gives its points when it has 3 or more corners, an area over 0, and each turn to the same side.
107
+ * The turns use exact signs. A corner on a straight side is permitted. A circle and an ellipse give `undefined`.
108
+ */
109
+ declare function convexCorners(region: Region): Ring | undefined;
110
+ /**
111
+ * This function gives the least overlap of two convex rings over the normals of their sides, in the units of the corners.
112
+ * By the separating axis theorem, a value of 0 or less tells that a line separates the rings. For two rectangles, the value is the lesser axis of `overlapOf`.
113
+ * A side of length 0 gives no normal. The rings come from `convexCorners`.
114
+ */
115
+ declare function convexOverlap(a: Ring, b: Ring): number;
116
+ /**
117
+ * This function tells if each corner of the ring `inner` is inside the convex ring `outer` made smaller by `inset`, with the tolerance `tolerance`.
118
+ * For a convex `outer`, this test is exact: a polygon is inside a convex region when each of its corners is inside.
119
+ * The ring `outer` comes from `convexCorners`, in either direction of its corners.
120
+ */
121
+ declare function cornersInConvex(inner: Ring, outer: Ring, inset?: number, tolerance?: number): boolean;
97
122
  /**
98
123
  * This function tells if the segments `ab` and `cd` cross at one point inside both of them.
99
124
  * Segments that only touch at an end, or that are collinear, do not cross. The test has no tolerance.
@@ -303,6 +328,11 @@ interface Resize {
303
328
  readonly minH?: number;
304
329
  readonly maxH?: number;
305
330
  readonly aspect?: "keep" | "free";
331
+ /**
332
+ * With `true`, the placement can give the box a shape (`Placement.shape`), for example the polygon cell of a Voronoi treemap.
333
+ * The bounds of the size also limit the bounds of that shape.
334
+ */
335
+ readonly reshape?: boolean;
306
336
  }
307
337
  /** A box of an input. In the packer, its name is item. */
308
338
  interface LayoutBox {
@@ -696,5 +726,5 @@ declare function minEffectOf(spec: Pick<MeasureSpec, "minEffect">, a?: number, b
696
726
  * Two equal values are a tie, also two infinite values. A value `NaN` is an error.
697
727
  */
698
728
  declare function compareMeasure(candidate: number, baseline: number, spec: Pick<MeasureSpec, "direction" | "minEffect">): Verdict;
699
- export { CorpusEntry as $, shapeKindsOf as A, crossingPoint as At, LayoutInput as B, scaleRect as Bt, checkShapes as C, SIDES as Ct, ruleLevel as D, boundsOf as Dt, itemShapeOf as E, SizedRect as Et, LayoutBox as F, pointInRing as Ft, PairGap as G, translate as Gt, PackInput as H, snapRect as Ht, LayoutCell as I, pointInRings as It, canonicalInput as J, Port as K, LayoutContainer as L, pointSegmentDistance as Lt, shapeSupportProblems as M, grow as Mt, shapesOf as N, marginSides as Nt, shapeKindOf as O, boxCenterDistance as Ot, Item as P, overlapOf as Pt, ClaimBreak as Q, LayoutEdge as R, regionArea as Rt, boxArea as S, Ring as St, isShapeKind as T, Sides as Tt, PackInputOptions as U, toRect as Ut, Obstacle as V, segmentsCross as Vt, PackLink as W, toSizedRect as Wt, portPoint as X, packLinks as Y, toPackInput as Z, ShapeKind as _, splitFolds as _t, MeasureSpec as a, FamilyCell as at, ShapeLimit as b, Rect as bt, minEffectOf as c, SplitFold as ct, SHAPE_KINDS as d, corpusHashOf as dt, CorpusSplit as et, SHAPE_KIND_IDS as f, declaredClaimOf as ft, ShapeInput as g, splitFileName as gt, ShapeGeometry as h, leaveOneSeedOut as ht, JointMeasureId as i, FamilyBy as it, shapeLevel as j, dropIndex as jt, shapeKindProblem as k, clipRing as kt, DEFAULT_SHAPES as l, checkDeclared as lt, ShapeCheck as m, familyOf as mt, JOINT_MEASURES as n, Declares as nt, Verdict as o, SPLIT_SCHEMA as ot, ShapeBound as p, declaredCounts as pt, Resize as q, JOINT_MOVED_MIN as r, FAMILY_ANY_KIND as rt, compareMeasure as s, SplitCorpus as st, Direction as t, DeclaredClaim as tt, RuleLevel as u, checkSplit as ut, ShapeKindSpec as v, Margin as vt, inputShapeLevel as w, Side as wt, ShapeSupport as x, Region as xt, ShapeLevel as y, Point as yt, LayoutGenerator as z, ringCentroid as zt };
700
- //# sourceMappingURL=measures-CJZw-Y3H.d.ts.map
729
+ export { CorpusEntry as $, shapeKindsOf as A, convexCorners as At, LayoutInput as B, pointSegmentDistance as Bt, checkShapes as C, SIDES as Ct, ruleLevel as D, boundsOf as Dt, itemShapeOf as E, SizedRect as Et, LayoutBox as F, grow as Ft, PairGap as G, segmentsCross as Gt, PackInput as H, regionPerimeter as Ht, LayoutCell as I, marginSides as It, canonicalInput as J, toSizedRect as Jt, Port as K, snapRect as Kt, LayoutContainer as L, overlapOf as Lt, shapeSupportProblems as M, cornersInConvex as Mt, shapesOf as N, crossingPoint as Nt, shapeKindOf as O, boxCenterDistance as Ot, Item as P, dropIndex as Pt, ClaimBreak as Q, LayoutEdge as R, pointInRing as Rt, boxArea as S, Ring as St, isShapeKind as T, Sides as Tt, PackInputOptions as U, ringCentroid as Ut, Obstacle as V, regionArea as Vt, PackLink as W, scaleRect as Wt, portPoint as X, packLinks as Y, translate as Yt, toPackInput as Z, ShapeKind as _, splitFolds as _t, MeasureSpec as a, FamilyCell as at, ShapeLimit as b, Rect as bt, minEffectOf as c, SplitFold as ct, SHAPE_KINDS as d, corpusHashOf as dt, CorpusSplit as et, SHAPE_KIND_IDS as f, declaredClaimOf as ft, ShapeInput as g, splitFileName as gt, ShapeGeometry as h, leaveOneSeedOut as ht, JointMeasureId as i, FamilyBy as it, shapeLevel as j, convexOverlap as jt, shapeKindProblem as k, clipRing as kt, DEFAULT_SHAPES as l, checkDeclared as lt, ShapeCheck as m, familyOf as mt, JOINT_MEASURES as n, Declares as nt, Verdict as o, SPLIT_SCHEMA as ot, ShapeBound as p, declaredCounts as pt, Resize as q, toRect as qt, JOINT_MOVED_MIN as r, FAMILY_ANY_KIND as rt, compareMeasure as s, SplitCorpus as st, Direction as t, DeclaredClaim as tt, RuleLevel as u, checkSplit as ut, ShapeKindSpec as v, Margin as vt, inputShapeLevel as w, Side as wt, ShapeSupport as x, Region as xt, ShapeLevel as y, Point as yt, LayoutGenerator as z, pointInRings as zt };
730
+ //# sourceMappingURL=measures-J0yY_JvV.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"measures-J0yY_JvV.d.ts","names":[],"sources":["../src/geometry.ts","../src/corpus.ts","../src/input.ts","../src/shapes.ts","../src/measures.ts"],"mappings":";KAGY;;cAGC,gBAAgB;UAEZ;WACN;WACA;;;UAIM;WACN;WACA;WACA;WACA;;;;;;UAOM;WACN;WACA;WACA;WACA;;;iBAIK,OAAO,MAAM,YAAY;;iBAKzB,YAAY,MAAM,OAAO;;;;;iBAWzB,SAAS,MAAM,OAAO;;;;;;iBAWtB,UAAU,MAAM,MAAM,iBAAiB;;UAMtC;WACN;WACA;WACA;WACA;;;;;;KAOC;WACG;WAAuB;WAAoB;WAAoB;WAAoB;;WAEnF;WACA,QAAQ;WACR,iBAAiB;;WAEjB;WAAyB;WAAqB;WAAqB;;WACnE;WAA0B;WAAqB;WAAqB;WAAqB;;;KAG5F,kBAAkB;;iBAGd,YAAY,QAAQ,qBAAqB;;iBAOzC,KAAK,MAAM,MAAM,QAAQ,qBAAqB;;iBAM9C,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C;;KAGD;;;;;;iBAOI,YAAY,MAAM,KAAK,2BAA2B,YAAO;;;;;;;iBAezD,eAAe,mBAAmB,kBAAkB,MAAM,KAAK,0CAA0C"}
package/build/text.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as MeasureSpec } from "./measures-CJZw-Y3H.js";
1
+ import { a as MeasureSpec } from "./measures-J0yY_JvV.js";
2
2
  /**
3
3
  * The advance function of a host: the width of a run of text in a font, in pixels.
4
4
  * A browser host gives `canvasAdvance(context)`. A test or a server host gives a function of a font file.
package/build/text.js CHANGED
@@ -582,7 +582,7 @@ const TEXT_MEASURES = /* @__PURE__ */ Object.freeze([
582
582
  },
583
583
  {
584
584
  id: "text.raggedness",
585
- unit: "0 to 1",
585
+ unit: "share",
586
586
  direction: "lower",
587
587
  min: 0,
588
588
  max: 1,
@@ -591,7 +591,7 @@ const TEXT_MEASURES = /* @__PURE__ */ Object.freeze([
591
591
  },
592
592
  {
593
593
  id: "text.overflow",
594
- unit: "share of the wrap width",
594
+ unit: "wrap widths",
595
595
  direction: "lower",
596
596
  min: 0,
597
597
  max: Infinity,
@@ -603,7 +603,7 @@ const TEXT_MEASURES = /* @__PURE__ */ Object.freeze([
603
603
  },
604
604
  {
605
605
  id: "text.cacheHit",
606
- unit: "0 to 1",
606
+ unit: "share",
607
607
  direction: "higher",
608
608
  min: 0,
609
609
  max: 1,
package/build/text.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"text.js","names":[],"sources":["../src/word-parts.ts","../src/text.ts"],"sourcesContent":["// The word segments (UAX #29) of the words of a text, with one call of `wordBreaks` for all the words.\n// This module is internal: the package root and `./text` do not export it.\nimport { wordBreaks } from \"@mark1russell7/typeset/segmentation\";\n\n/** This function gives the word segments of one word, with one call of `wordBreaks`. */\nexport function partsOfWord(word: string): string[] {\n const parts: string[] = [];\n let from = 0;\n for (const end of wordBreaks(word)) {\n parts.push(word.slice(from, end));\n from = end;\n }\n return parts;\n}\n\n/**\n * This function gives the word segments of each word, with one call of `wordBreaks` on the words joined by line feeds.\n * UAX #29 puts a break before and after a line feed (WB3a, WB3b), and no rule looks across it.\n * So each word gets the segments of a call on the word alone.\n * A word that ends with a carriage return has no break before the next line feed (WB3).\n * When a break of a line feed is absent, the function gives the segments of one call for each word.\n */\nexport function partsOfWords(words: readonly string[]): string[][] {\n if (words.length === 0) return [];\n if (words.length === 1) return [partsOfWord(words[0]!)];\n const parts: string[][] = words.map(() => []);\n const joined = words.join(\"\\n\");\n let w = 0;\n let from = 0;\n let end = words[0]!.length;\n for (const offset of wordBreaks(joined)) {\n if (from === end) {\n // The segment from `end` is the line feed after word `w`.\n if (offset !== end + 1 || w + 1 >= words.length) return words.map(partsOfWord);\n w += 1;\n from = offset;\n end = offset + words[w]!.length;\n continue;\n }\n if (offset > end) return words.map(partsOfWord);\n parts[w]!.push(joined.slice(from, offset));\n from = offset;\n }\n if (w !== words.length - 1 || from !== end) return words.map(partsOfWord);\n return parts;\n}\n","import { adjustmentRatios, breakers, linesOf, type Box, type Glue, type Item, type Penalty } from \"@mark1russell7/typeset/breaking\";\nimport { graphemes, lineBreaks } from \"@mark1russell7/typeset/segmentation\";\nimport { partsOfWords } from \"./word-parts.ts\";\nimport type { MeasureSpec } from \"./measures.ts\";\n\n/**\n * The advance function of a host: the width of a run of text in a font, in pixels.\n * A browser host gives `canvasAdvance(context)`. A test or a server host gives a function of a font file.\n */\nexport type AdvanceFn = (text: string, font: string) => number;\n\n/** The count of the units in one pixel. Each advance is a whole number of units, so each sum is exact and each port gets the same pixels. */\nexport const TEXT_UNITS = 64;\n\n/** The counts of a measurer: the requests, the cache hits and the calls of the advance function. */\nexport interface MeasurerStats {\n readonly requests: number;\n readonly hits: number;\n readonly calls: number;\n}\n\n/** A measurer: the advance of a segment in a font, in whole units of 1/`TEXT_UNITS` pixel, with a cache. */\nexport interface TextMeasurer {\n /** This function gives the advance of the segment in the font, in units. */\n advance(segment: string, font: string): number;\n /** This function gives the counts since the start or since the last `reset`. */\n stats(): MeasurerStats;\n /** This function clears the cache and the counts. */\n reset(): void;\n /** This function gives the count of the `reset` calls. A `TextLayoutCache` reads it, and it does not give a layout from before a reset. */\n generation?(): number;\n}\n\n/** The options of `createMeasurer`. */\nexport interface MeasurerOptions {\n /** The count of the cache entries. The default is 10000. With 0, the measurer has no cache. */\n readonly maxEntries?: number;\n}\n\n/** This function gives the key of a font: the font string with its white space collapsed and trimmed. */\nexport function fontKey(font: string): string {\n return font.trim().replace(/\\s+/g, \" \");\n}\n\n/**\n * This function gives a measurer with a cache keyed by the font and the segment.\n * The cache removes its oldest entry when it is full. The advance function rounds each width to whole units.\n */\nexport function createMeasurer(measure: AdvanceFn, options: MeasurerOptions = {}): TextMeasurer {\n const max = options.maxEntries ?? 10000;\n if (!(Number.isInteger(max) && max >= 0)) throw new RangeError(`createMeasurer: maxEntries is an integer of 0 or more, not ${max}.`);\n const cache = new Map<string, number>();\n let requests = 0;\n let hits = 0;\n let calls = 0;\n let generation = 0;\n return {\n advance(segment, font) {\n requests++;\n const key = `${fontKey(font)}\\u0000${segment}`;\n const known = cache.get(key);\n if (known !== undefined) {\n hits++;\n return known;\n }\n calls++;\n const px = measure(segment, font);\n if (!Number.isFinite(px) || px < 0) throw new RangeError(`The advance of \"${segment}\" in \"${font}\" is ${px}, not a finite number of 0 or more.`);\n const units = Math.round(px * TEXT_UNITS);\n if (max > 0) {\n if (cache.size >= max) cache.delete(cache.keys().next().value!);\n cache.set(key, units);\n }\n return units;\n },\n stats: () => ({ requests, hits, calls }),\n reset() {\n cache.clear();\n requests = 0;\n hits = 0;\n calls = 0;\n generation++;\n },\n generation: () => generation,\n };\n}\n\n/** The part of a canvas context that `canvasAdvance` uses. */\nexport interface CanvasTextContext {\n font: string;\n measureText(text: string): { readonly width: number };\n}\n\n/** This function gives the advance function of a canvas context. It sets `font` only when the font changes, because a browser parses each new font string. */\nexport function canvasAdvance(context: CanvasTextContext): AdvanceFn {\n let current: string | undefined;\n return (text, font) => {\n if (font !== current) {\n context.font = font;\n current = font;\n }\n return context.measureText(text).width;\n };\n}\n\n/**\n * A word of a text: the text from one break place of UAX #14 to the next, with no white space at its end.\n * Its parts are its word segments (UAX #29), which the measurer measures and caches one by one.\n */\ninterface Word {\n readonly text: string;\n readonly parts: readonly string[];\n /** This value is `true` when white space follows the word in the text. Then one space comes after the word. Else the gap has no width. */\n readonly spaced: boolean;\n}\n\n/**\n * A run of the white space that collapses: the white space of CSS (space, tab, line feed, form feed, carriage return) and the other mandatory breaks of UAX #14.\n * A no-break space or an ideographic space stays in its word, as in CSS.\n */\nconst SPACES = /[ \\t\\n\\v\\f\\r\\u0085\\u2028\\u2029]+/gu;\n\n/** The white space of `SPACES` at the end of a text. */\nconst TRAILING_SPACE = /[ \\t\\n\\v\\f\\r\\u0085\\u2028\\u2029]+$/u;\n\n/** The largest count of texts in the memo of `wordsOf`. A page often asks for the same labels many times. */\nconst WORDS_MEMO = 4096;\nconst wordsMemo = /* @__PURE__ */ new Map<string, readonly Word[]>();\n\n/**\n * This function splits the text into words at the break places of UAX #14 (`lineBreaks` of `@mark1russell7/typeset`).\n * Each word holds its word segments, so words that share segments share the cache.\n */\nfunction wordsOf(text: string): readonly Word[] {\n const known = wordsMemo.get(text);\n if (known !== undefined) return known;\n const words = splitWords(text);\n // The memo forgets its oldest text when it is full.\n if (wordsMemo.size >= WORDS_MEMO) wordsMemo.delete(wordsMemo.keys().next().value!);\n wordsMemo.set(text, words);\n return words;\n}\n\n/**\n * This function gives the words of `wordsOf` with no memo.\n * A break place of UAX #14 comes after a run of white space, so the white space of a piece is at its end. That white space goes, and the word records it.\n * White space inside a piece, for example before a closing bracket, collapses to one space, as `white-space: normal` in CSS.\n * A mandatory break inside the text, for example at a line feed, is white space as in CSS. Only the end of the text ends the last line.\n */\nfunction splitWords(text: string): Word[] {\n const words: { text: string; spaced: boolean }[] = [];\n let start = 0;\n for (const place of lineBreaks(text)) {\n const piece = text.slice(start, place.offset);\n start = place.offset;\n const body = piece.replace(TRAILING_SPACE, \"\").replace(SPACES, \" \");\n const spaced = body.length < piece.length;\n // White space at the start of a piece, for example after a line feed, is the gap after the word before it. A piece of only white space adds no word.\n const word = body.startsWith(\" \") ? body.slice(1) : body;\n if (word.length < body.length || body === \"\") {\n const last = words[words.length - 1];\n if (last !== undefined) last.spaced = true;\n }\n if (word === \"\") continue;\n words.push({ text: word, spaced });\n }\n // One call of `wordBreaks` gives the segments of all the words of the text.\n const parts = partsOfWords(words.map((w) => w.text));\n return words.map((w, i) => ({ text: w.text, parts: parts[i]!, spaced: w.spaced }));\n}\n\n/** This function gives the grapheme clusters of a text by UAX #29 (`graphemes` of `@mark1russell7/typeset`), with no locale. */\nexport function graphemesOf(text: string): string[] {\n return [...graphemes(text)];\n}\n\n/** This function gives the count of the gaps of one space between the words: one after each spaced word but the last. */\nfunction spacesOf(words: readonly Word[]): number {\n let count = 0;\n for (let i = 0; i < words.length - 1; i++) if (words[i]!.spaced) count++;\n return count;\n}\n\n/** This function joins the words with their gaps: one space after a spaced word, and nothing after another word. */\nfunction joinWords(words: readonly Word[]): string {\n return words.map((w, i) => (i < words.length - 1 && w.spaced ? `${w.text} ` : w.text)).join(\"\");\n}\n\n/** The digits, as a value for `createTextCharset`. */\nexport const DIGITS = \"0123456789\";\n\n/** The printable characters of ASCII with the space, as a value for `createTextCharset`. */\nexport const PRINTABLE_ASCII = \" !\\\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\";\n\n/** The scripts of a member of a character set. The characters of other scripts can join or change their shape, so their advances do not add. */\nconst SIMPLE_SCRIPT = /^[\\p{Script=Common}\\p{Script=Latin}\\p{Script=Greek}\\p{Script=Cyrillic}\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}]$/u;\n\n/** The characters that are not plain advances: marks, control and format characters, emoji parts, and each white space but the space. */\nconst NOT_AN_ADVANCE = /[\\p{M}\\p{C}\\p{Extended_Pictographic}\\p{Emoji_Modifier}\\p{Regional_Indicator}]|[^\\S ]/u;\n\n/** The largest count of fonts in the memo of a character set for one measurer. */\nconst CHARSET_FONTS = 64;\n\n/** The options of `createTextCharset`. */\nexport interface TextCharsetOptions {\n /**\n * The largest width that two neighbor characters add to the sum of their advances, as a share of the largest advance. The default is 0.\n * A kerning pair that is narrower adds no width. Give a value for a font with kerning pairs or ligatures that are wider.\n */\n readonly pairMargin?: number;\n}\n\n/** A declared character set. A caller asks for it with `createTextCharset`. It is frozen, so `createTextLayoutCache` can use its identity as a key. */\nexport interface TextCharset {\n readonly characters: string;\n /** This function tells if each code point of the text is a member of the set. */\n covers(text: string): boolean;\n /**\n * This function gives the bound of one UTF-16 code unit of a member in the font, in units of 1/`TEXT_UNITS` pixel.\n * It measures each member once for a measurer with `generation`, and again after a `reset`. It measures on each call for a different measurer.\n * It gives `undefined` when a member has no positive finite advance: that is a gap in the font.\n */\n unit(font: string, measurer: TextMeasurer): number | undefined;\n}\n\n/**\n * This function gives a declared character set. A member is one code point with a plain advance.\n * A tab, a line break, a soft hyphen, a zero-width character, a combining mark, an emoji part or a bidirectional control gives a `RangeError`.\n * A letter of a script that joins or changes its shape, for example Arabic or Devanagari, also gives a `RangeError`. A label with this letter gets a measure.\n */\nexport function createTextCharset(characters: string, options: TextCharsetOptions = {}): TextCharset {\n const pairMargin = options.pairMargin ?? 0;\n if (!(Number.isFinite(pairMargin) && pairMargin >= 0)) throw new RangeError(`createTextCharset: pairMargin is a finite number of 0 or more, not ${pairMargin}.`);\n const members = new Set(characters);\n if (members.size === 0) throw new RangeError(\"createTextCharset: the set has no character.\");\n for (const c of members) {\n if (NOT_AN_ADVANCE.test(c) || !SIMPLE_SCRIPT.test(c)) throw new RangeError(`createTextCharset: U+${c.codePointAt(0)!.toString(16).toUpperCase()} is not a plain advance.`);\n }\n /** This function gives the bound of one character. The added unit holds the rounding of each advance, so a sum of rounded segments stays under the bound. */\n const scan = (font: string, measurer: TextMeasurer): number | undefined => {\n let largest = 0;\n for (const c of members) {\n const units = measurer.advance(c, font);\n if (!(Number.isFinite(units) && units > 0)) return undefined;\n largest = Math.max(largest, units);\n }\n return Math.ceil((largest + 1) * (1 + pairMargin));\n };\n const memo = new WeakMap<TextMeasurer, Map<string, { readonly generation: number; readonly unit: number | undefined }>>();\n return Object.freeze({\n characters,\n covers(text: string): boolean {\n for (const c of text) if (!members.has(c)) return false;\n return true;\n },\n unit(font: string, measurer: TextMeasurer): number | undefined {\n const generation = measurer.generation?.();\n // A measurer without `generation` does not tell of a change of its advances, so a memo can keep a low bound.\n if (generation === undefined) return scan(font, measurer);\n let fonts = memo.get(measurer);\n if (fonts === undefined) {\n fonts = new Map();\n memo.set(measurer, fonts);\n }\n const known = fonts.get(font);\n if (known?.generation === generation) return known.unit;\n const unit = scan(font, measurer);\n if (fonts.size >= CHARSET_FONTS) fonts.delete(fonts.keys().next().value!);\n fonts.set(font, { generation, unit });\n return unit;\n },\n });\n}\n\n/** The source of the width of a label. The option `sizing` of `layoutText` tells each value. */\nexport type TextSizing = \"exact\" | \"bound-first\" | \"bound\";\n\n/** The options of `layoutText`. All lengths are in pixels. */\nexport interface TextLayoutOptions {\n readonly font: string;\n readonly measurer: TextMeasurer;\n /** The line height. A finite number above 0. */\n readonly lineHeight: number;\n /** The width of the lines of a text that does not fit on one line. Without it, the text stays on one line. */\n readonly wrapWidth?: number;\n /** The count of the lines. The last line that stays gets the ellipsis. The default is no limit. */\n readonly maxLines?: number;\n /** The count of the grapheme clusters. A longer text keeps `maxChars` clusters with the ellipsis at the end. The default is no limit. */\n readonly maxChars?: number;\n /** The text at the end of a cut text. The default is \"…\". */\n readonly ellipsis?: string;\n /** The space that the box adds to the width of the text. The default is 0. */\n readonly padding?: number;\n /** The smallest width of a box with one line. The default is 0. */\n readonly minWidth?: number;\n /** The largest width of a box with one line. A text that does not fit wraps at `wrapWidth`. The default is `wrapWidth` plus the padding, or no limit without `wrapWidth`. */\n readonly maxWidth?: number;\n /**\n * The break of a word that is wider than a line. `keep` (the default) keeps the word whole, and the line overflows.\n * `anywhere` breaks it between two grapheme clusters, as the CSS `overflow-wrap: anywhere`.\n */\n readonly wordBreak?: \"keep\" | \"anywhere\";\n /**\n * The line breaker of `@mark1russell7/typeset`. `greedy` (the default) fills each line, as a browser. `total-fit` (Knuth and Plass)\n * makes the lines more equal. `balanced` keeps the greedy line count with the least width.\n */\n readonly breaker?: \"greedy\" | \"total-fit\" | \"balanced\";\n /**\n * The source of the width of a label. `exact` (the default) measures each label.\n * `bound-first` keeps a label of `charset` on one line with no measure when its bound fits. It measures each other label.\n * `bound` sizes each label of `charset` from its bound, also when the label wraps. A label that has a character out of `charset` gets a measure in all modes.\n */\n readonly sizing?: TextSizing;\n /** The declared character set of `sizing`. `bound-first` and `bound` need it, and `exact` does not read it. */\n readonly charset?: TextCharset;\n /**\n * 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.\n * With this option, `total-fit` chooses the lines with the adjustment ratio, and the layout gives the ratio of each line in `ratios`.\n * Without it, a space does not stretch or shrink.\n */\n readonly justify?: TextJustify;\n /**\n * The hyphenation hook of `paragraphOf` of `@mark1russell7/typeset`. It gives the offsets in a word where a break with a hyphen is possible.\n * A line that ends at such an offset ends with \"-\". The subpaths `./hyphen/<language>` of typeset give a hook for each language.\n * layout-contract imports no pattern set. Without the option, a word does not break at a hyphen.\n */\n readonly hyphenate?: (word: string) => readonly number[];\n}\n\n/** The stretch and the shrink of each space of a justified layout, as a share of the width of a space. */\nexport interface TextJustify {\n /** A finite number of 0 or more. */\n readonly stretch: number;\n /** A finite number from 0 to 1, because a space cannot be narrower than 0. */\n readonly shrink: number;\n}\n\n/** The layout of a text: its lines and its box. */\nexport interface TextLayout {\n readonly lines: readonly string[];\n /** The width of each line, in pixels. Each width is a whole number of units of 1/`TEXT_UNITS` pixel. */\n readonly widths: readonly number[];\n readonly lineCount: number;\n /** The width of the box: the text and the padding. */\n readonly width: number;\n readonly height: number;\n /** The width of the lines, or `undefined` for a text on one line. */\n readonly wrapWidth?: number;\n /** `true` when `maxChars` or `maxLines` cut the text. */\n readonly truncated: boolean;\n /** `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. */\n readonly bounded?: true;\n /**\n * 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\n * line, or `ratio × shrink × space` when the ratio is negative. The last line does not stretch, so its ratio is not more than 0.\n * The ratio is infinite for a line with free space and no space to stretch.\n * A layout without `justify`, or a text that fits on one line at its natural width, does not have this field.\n */\n readonly ratios?: readonly number[];\n}\n\n/** A forced break: a penalty with no text, no width and the cost `-Infinity`. */\nconst FORCED: Penalty = { type: \"penalty\", text: \"\", width: 0, cost: -Infinity, flagged: false };\n\n/** 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. */\nconst NO_GAP: Item = { type: \"glue\", text: \"\", width: 0 };\n\n/** The cost of a break at a hyphen: 50, as in TeX and in `paragraphOf` of typeset. */\nconst HYPHEN_COST = 50;\n\n/**\n * This function gives the hyphen places of a word from the hook, sorted, with no repeat.\n * 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.\n */\nfunction hyphenPlaces(word: string, hyphenate: (word: string) => readonly number[]): number[] {\n const edges = new Set<number>();\n let at = 0;\n for (const cluster of graphemesOf(word)) edges.add((at += cluster.length));\n const places = hyphenate(word).filter((o) => o > 0 && o < word.length && edges.has(o));\n return [...new Set(places)].sort((a, b) => a - b);\n}\n\n/** This function gives the box of a part of a word. */\n/** This function gives the units of a segment: the bound for one character times the length, or a measure when there is no bound. */\nfunction advanceOf(segment: string, font: string, measurer: TextMeasurer, bound: number | undefined): number {\n return bound === undefined ? measurer.advance(segment, font) : segment.length * bound;\n}\n\nfunction boxOf(part: { readonly text: string; readonly width: number }): Box {\n return { type: \"box\", text: part.text, width: part.width };\n}\n\n/** A line of a layout, with its width in units. */\ninterface Line {\n text: string;\n units: number;\n}\n\n/**\n * This function lays out a text. It cuts the text to `maxChars`. It keeps the text on one line when it fits in `maxWidth`. Else it breaks the text into lines of `wrapWidth`.\n *\n * The breaker comes from `@mark1russell7/typeset`. The default is greedy, as a browser with `white-space: normal`.\n * It collapses each run of white space to one space, and a line does not count its last space.\n * The width of a word is the sum of the advances of its segments. `docs/TEXT.md` gives the rules and the error of this sum.\n *\n * The option `sizing` replaces a measure with the bound of a declared character set. A caller that does not set it gets each measured result.\n */\nexport function layoutText(text: string, options: TextLayoutOptions): TextLayout {\n const { font, measurer, lineHeight } = options;\n if (!(Number.isFinite(lineHeight) && lineHeight > 0)) throw new RangeError(`layoutText: lineHeight is a finite number above 0, not ${lineHeight}.`);\n const ellipsis = options.ellipsis ?? \"…\";\n const padding = options.padding ?? 0;\n const keep = (options.wordBreak ?? \"keep\") === \"keep\";\n const name = options.breaker ?? \"greedy\";\n if (!Object.hasOwn(breakers, name)) throw new RangeError(`layoutText: breaker is \"greedy\", \"total-fit\" or \"balanced\", not ${String(name)}.`);\n const breaker = breakers[name];\n const sizing = options.sizing ?? \"exact\";\n if (sizing !== \"exact\" && sizing !== \"bound-first\" && sizing !== \"bound\") throw new RangeError(`layoutText: sizing is \"exact\", \"bound-first\" or \"bound\", not ${String(sizing)}.`);\n const charset = sizing === \"exact\" ? undefined : options.charset;\n const { justify, hyphenate } = options;\n if (justify !== undefined && !(Number.isFinite(justify.stretch) && justify.stretch >= 0 && Number.isFinite(justify.shrink) && justify.shrink >= 0 && justify.shrink <= 1)) {\n 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)}.`);\n }\n if (sizing !== \"exact\" && charset === undefined) throw new RangeError(`layoutText: sizing \"${sizing}\" needs a charset from createTextCharset.`);\n let truncated = false;\n\n let source = text;\n if (options.maxChars !== undefined) {\n const clusters = graphemesOf(source);\n if (clusters.length > options.maxChars) {\n const room = Math.max(0, options.maxChars - graphemesOf(ellipsis).length);\n source = clusters.slice(0, room).join(\"\") + ellipsis;\n truncated = true;\n }\n }\n\n const words = wordsOf(source);\n const maxWidth = options.maxWidth ?? (options.wrapWidth === undefined ? Infinity : options.wrapWidth + padding);\n const oneLine = (natural: number, bounded: boolean): TextLayout => {\n const one = joinWords(words);\n const px = natural / TEXT_UNITS;\n const box = Math.min(maxWidth, Math.max(options.minWidth ?? 0, px + padding));\n const layout: TextLayout = { lines: [one], widths: [px], lineCount: 1, width: box, height: lineHeight, truncated };\n return bounded ? { ...layout, bounded } : layout;\n };\n\n // The raw text, not its words: the check sees a tab or a line break before they collapse.\n const unit = charset?.covers(source) === true ? charset.unit(font, measurer) : undefined;\n if (sizing === \"bound-first\" && unit !== undefined) {\n const natural = words.reduce((s, w) => s + w.text.length, spacesOf(words)) * unit;\n if (options.wrapWidth === undefined || natural / TEXT_UNITS + padding <= maxWidth) return oneLine(natural, true);\n }\n const bound = sizing === \"bound\" ? unit : undefined;\n const space = advanceOf(\" \", font, measurer, bound);\n const width = (w: Word): number => w.parts.reduce((s, p) => s + advanceOf(p, font, measurer, bound), 0);\n const lineUnits = (line: string): number => {\n const ws = wordsOf(line);\n return ws.reduce((s, w) => s + width(w), 0) + space * spacesOf(ws);\n };\n const widths = words.map(width);\n const natural = widths.reduce((s, w) => s + w, 0) + space * spacesOf(words);\n\n const fits = natural / TEXT_UNITS + padding <= maxWidth;\n if (options.wrapWidth === undefined || fits) return oneLine(natural, bound !== undefined);\n\n const limit = Math.round(options.wrapWidth * TEXT_UNITS);\n // The items of the breaker: a box for each word, and glue between two words. The glue is one space after a spaced word, else it has no width.\n const items: Item[] = [];\n /** This function puts a word that is wider than a line on new lines, with a break between grapheme clusters. Each forced penalty ends a line. */\n const split = (word: Word): void => {\n if (items.length > 0) items.push(FORCED);\n let cur: { text: string; width: number } | undefined;\n for (const g of graphemesOf(word.text)) {\n const w = advanceOf(g, font, measurer, bound);\n if (cur !== undefined && cur.width + w > limit) {\n items.push(boxOf(cur), FORCED);\n cur = undefined;\n }\n if (cur === undefined) cur = { text: g, width: w };\n else {\n cur.text += g;\n cur.width += w;\n }\n }\n if (cur !== undefined) items.push(boxOf(cur));\n };\n const gap: Glue = justify === undefined ? { type: \"glue\", text: \" \", width: space } : { type: \"glue\", text: \" \", width: space, stretch: space * justify.stretch, shrink: space * justify.shrink };\n const hyphen: Penalty | undefined = hyphenate === undefined ? undefined : { type: \"penalty\", text: \"-\", width: advanceOf(\"-\", font, measurer, bound), cost: HYPHEN_COST, flagged: true };\n /**\n * 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.\n * 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.\n */\n const hyphenated = (word: Word, w: number): void => {\n const places = hyphen === undefined ? [] : hyphenPlaces(word.text, hyphenate!);\n if (places.length === 0) {\n items.push({ type: \"box\", text: word.text, width: w });\n return;\n }\n let start = 0;\n let rest = w;\n for (const end of [...places, word.text.length]) {\n if (start > 0) items.push(hyphen!);\n const part = word.text.slice(start, end);\n const units = end === word.text.length ? rest : advanceOf(part, font, measurer, bound);\n items.push({ type: \"box\", text: part, width: units });\n rest -= units;\n start = end;\n }\n };\n words.forEach((word, i) => {\n const w = widths[i]!;\n if (w > limit && !keep) split(word);\n else {\n if (items.length > 0) items.push(words[i - 1]!.spaced ? gap : NO_GAP);\n hyphenated(word, w);\n }\n });\n const paragraph = { items };\n const broken = linesOf(paragraph, breaker.breaks(paragraph, limit));\n const lines: Line[] = broken.map((l) => ({ text: l.text, units: l.width }));\n const ratios = justify === undefined ? undefined : adjustmentRatios(paragraph, broken, limit);\n if (lines.length === 0) {\n lines.push({ text: \"\", units: 0 });\n ratios?.push(0);\n }\n\n const maxLines = options.maxLines ?? Infinity;\n if (lines.length > maxLines) {\n lines.length = Math.max(1, maxLines);\n const last = lines[lines.length - 1]!;\n const tail = measurer.advance(ellipsis, font);\n const clusters = graphemesOf(last.text);\n while (clusters.length > 0 && lineUnits(clusters.join(\"\")) + tail > limit) clusters.pop();\n const kept = clusters.join(\"\").replace(/\\s+$/u, \"\");\n last.text = kept + ellipsis;\n last.units = lineUnits(kept) + tail;\n truncated = true;\n // The cut line is the last line, so it does not stretch. The cut makes it fit, so it does not shrink.\n if (ratios !== undefined) {\n ratios.length = lines.length;\n ratios[lines.length - 1] = 0;\n }\n }\n\n const layout: TextLayout = {\n lines: lines.map((l) => l.text),\n widths: lines.map((l) => l.units / TEXT_UNITS),\n lineCount: lines.length,\n width: options.wrapWidth + padding,\n height: lines.length * lineHeight,\n wrapWidth: options.wrapWidth,\n truncated,\n ...(ratios === undefined ? {} : { ratios }),\n };\n return bound === undefined ? layout : { ...layout, bounded: true };\n}\n\n/** The counts of a `TextLayoutCache`. `calls` is the count of the `layoutText` calls, and `size` is the count of the entries. */\nexport interface TextLayoutCacheStats extends MeasurerStats {\n readonly size: number;\n}\n\n/** The options of `createTextLayoutCache`. */\nexport interface TextLayoutCacheOptions {\n /** The largest count of the entries. The default is 4096. With 0, the cache keeps no entry. */\n readonly maxEntries?: number;\n}\n\n/** A cache of `layoutText` results. A caller asks for it with `createTextLayoutCache`. `layoutText` itself has no cache of results. */\nexport interface TextLayoutCache {\n /**\n * This function gives the result of `layoutText` for the text and the options.\n * The result is deeply frozen. Equal arguments give the same object until the cache removes the entry.\n */\n layout(text: string, options: TextLayoutOptions): TextLayout;\n /** This function gives the counts since the start or since the last `reset`. */\n stats(): TextLayoutCacheStats;\n /** This function clears the entries and the counts. */\n reset(): void;\n}\n\n/** This function gives the key text of a number. It keeps -0, because `layoutText` can give -0 back in a result. */\nfunction numberKey(value: number | undefined): string {\n return Object.is(value, -0) ? \"-0\" : String(value);\n}\n\n/**\n * This function gives the key of a set of options, without the text and the measurer. Two different sets do not give one key.\n * A number has no comma. The two lengths mark the end of the font and of the ellipsis.\n */\nfunction optionsKey(o: TextLayoutOptions): string {\n 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)}`;\n return `${numbers},${(o.wordBreak ?? \"keep\") === \"keep\"},${o.breaker},${o.sizing ?? \"exact\"},${o.font.length},${o.ellipsis?.length},${o.font}${o.ellipsis ?? \"\"}`;\n}\n\n/** This function tells if two sets of options are the same. It uses `Object.is`, so 0 and -0 are different. It makes no string, so it is cheap on each hit. */\nfunction sameOptions(a: TextLayoutOptions, b: TextLayoutOptions): boolean {\n return (\n a.font === b.font &&\n a.measurer === b.measurer &&\n Object.is(a.lineHeight, b.lineHeight) &&\n Object.is(a.wrapWidth, b.wrapWidth) &&\n Object.is(a.maxLines, b.maxLines) &&\n Object.is(a.maxChars, b.maxChars) &&\n Object.is(a.padding, b.padding) &&\n Object.is(a.minWidth, b.minWidth) &&\n Object.is(a.maxWidth, b.maxWidth) &&\n a.ellipsis === b.ellipsis &&\n a.wordBreak === b.wordBreak &&\n a.breaker === b.breaker &&\n a.sizing === b.sizing &&\n a.charset === b.charset &&\n a.hyphenate === b.hyphenate &&\n Object.is(a.justify?.stretch, b.justify?.stretch) &&\n Object.is(a.justify?.shrink, b.justify?.shrink)\n );\n}\n\n/** The set of options of the last call of a cache, with its layouts by text. */\ninterface CurrentOptions {\n /** A copy of the options, so a later change of the object of the caller does not touch it. */\n readonly options: TextLayoutOptions;\n readonly generation: number | undefined;\n readonly key: string;\n readonly layouts: Map<string, TextLayout>;\n}\n\n/**\n * This function gives a bounded cache of `layoutText` results, keyed by the text, the options, the measurer, the character set and the hyphenation hook.\n * 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.\n * The key holds the raw font string, because a host can give two spellings of a font two different advances.\n * 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.\n */\nexport function createTextLayoutCache(options: TextLayoutCacheOptions = {}): TextLayoutCache {\n const max = options.maxEntries ?? 4096;\n if (!(Number.isInteger(max) && max >= 0)) throw new RangeError(`createTextLayoutCache: maxEntries is an integer of 0 or more, not ${max}.`);\n // Each Map keeps the order of insertion, so its first key is the least recently used. A set of options is here only while it has an entry.\n const groups = new Map<string, Map<string, TextLayout>>();\n // A measurer and a character set are objects. Each gets a number here, so a key does not keep it alive.\n const ids = new WeakMap<object, number>();\n let nextId = 0;\n let current: CurrentOptions | undefined;\n let size = 0;\n let requests = 0;\n let hits = 0;\n let calls = 0;\n const idOf = (item: object): number => {\n let id = ids.get(item);\n if (id === undefined) {\n id = nextId++;\n ids.set(item, id);\n }\n return id;\n };\n /** This function finds the layouts of a set of options, and it makes that set the most recently used. */\n const open = (layoutOptions: TextLayoutOptions, generation: number | undefined): CurrentOptions => {\n const charset = layoutOptions.charset === undefined ? \"\" : idOf(layoutOptions.charset);\n const hyphenate = layoutOptions.hyphenate === undefined ? \"\" : idOf(layoutOptions.hyphenate);\n const key = `${idOf(layoutOptions.measurer)},${generation},${charset},${hyphenate},${optionsKey(layoutOptions)}`;\n const layouts = groups.get(key) ?? new Map<string, TextLayout>();\n if (groups.delete(key)) groups.set(key, layouts);\n // The copy of `justify` keeps its values, so a later change of the object of the caller does not touch the key.\n const copy = layoutOptions.justify === undefined ? { ...layoutOptions } : { ...layoutOptions, justify: { ...layoutOptions.justify } };\n return { options: copy, generation, key, layouts };\n };\n /** This function removes one entry. */\n const evict = (): void => {\n const [key, layouts] = groups.entries().next().value!;\n layouts.delete(layouts.keys().next().value!);\n size--;\n if (layouts.size === 0) groups.delete(key);\n };\n return {\n layout(text, layoutOptions) {\n requests++;\n const generation = layoutOptions.measurer.generation?.();\n if (current === undefined || generation !== current.generation || !sameOptions(current.options, layoutOptions)) current = open(layoutOptions, generation);\n const { key, layouts } = current;\n const known = layouts.get(text);\n if (known !== undefined) {\n hits++;\n // This moves the text to the end of the order.\n layouts.delete(text);\n layouts.set(text, known);\n return known;\n }\n calls++;\n const layout = layoutText(text, layoutOptions);\n // The callers share this object, so it is frozen also when the cache does not keep it.\n Object.freeze(layout.lines);\n Object.freeze(layout.widths);\n if (layout.ratios !== undefined) Object.freeze(layout.ratios);\n Object.freeze(layout);\n if (max > 0) {\n if (size >= max) evict();\n if (layouts.size === 0) groups.set(key, layouts);\n layouts.set(text, layout);\n size++;\n }\n return layout;\n },\n stats: () => ({ requests, hits, calls, size }),\n reset() {\n groups.clear();\n current = undefined;\n size = 0;\n requests = 0;\n hits = 0;\n calls = 0;\n },\n };\n}\n\n/** The id of a text measure. `docs/TEXT.md` gives the definitions. */\nexport type TextMeasureId = \"text.lines\" | \"text.raggedness\" | \"text.overflow\" | \"text.cacheHit\" | \"text.ms\";\n\n/** The specs of the text measures. */\nexport const TEXT_MEASURES: readonly MeasureSpec<TextMeasureId>[] = /* @__PURE__ */ Object.freeze([\n { id: \"text.lines\", unit: \"count\", direction: \"lower\", min: 1, max: Infinity, minEffect: 0, family: \"text\" },\n { id: \"text.raggedness\", unit: \"0 to 1\", direction: \"lower\", min: 0, max: 1, minEffect: 0.005, family: \"text\" },\n { 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\" },\n { id: \"text.cacheHit\", unit: \"0 to 1\", direction: \"higher\", min: 0, max: 1, family: \"text\", role: \"diagnostic\" },\n { id: \"text.ms\", unit: \"milliseconds\", direction: \"lower\", min: 0, max: Infinity, family: \"text\", role: \"time\" },\n] as const);\n\n/**\n * This function gives the measures of a layout. `text.raggedness` is the mean of `((wrapWidth - width) / wrapWidth)^2` over the lines before the last line.\n * `text.overflow` is the largest excess of a line over `wrapWidth`, as a share of `wrapWidth`. A text on one line gives 0 for the two values.\n * With `stats`, the measures also hold `text.cacheHit`: the hits divided by the requests.\n */\nexport function textMeasures(layout: TextLayout, stats?: MeasurerStats): Partial<Record<TextMeasureId, number>> {\n const w = layout.wrapWidth;\n const body = layout.widths.slice(0, -1);\n const raggedness = w === undefined || body.length === 0 ? 0 : body.reduce((s, x) => s + (Math.max(0, w - x) / w) ** 2, 0) / body.length;\n const overflow = w === undefined ? 0 : Math.max(0, ...layout.widths.map((x) => (x - w) / w));\n return {\n \"text.lines\": layout.lineCount,\n \"text.raggedness\": raggedness,\n \"text.overflow\": overflow,\n ...(stats === undefined ? {} : { \"text.cacheHit\": stats.requests === 0 ? 0 : stats.hits / stats.requests }),\n };\n}\n"],"mappings":";;;;AAKA,SAAgB,YAAY,MAAwB;CAClD,MAAM,QAAkB,CAAC;CACzB,IAAI,OAAO;CACX,KAAK,MAAM,OAAO,WAAW,IAAI,GAAG;EAClC,MAAM,KAAK,KAAK,MAAM,MAAM,GAAG,CAAC;EAChC,OAAO;CACT;CACA,OAAO;AACT;;;;;;;;AASA,SAAgB,aAAa,OAAsC;CACjE,IAAI,MAAM,WAAW,GAAG,OAAO,CAAC;CAChC,IAAI,MAAM,WAAW,GAAG,OAAO,CAAC,YAAY,MAAM,EAAG,CAAC;CACtD,MAAM,QAAoB,MAAM,UAAU,CAAC,CAAC;CAC5C,MAAM,SAAS,MAAM,KAAK,IAAI;CAC9B,IAAI,IAAI;CACR,IAAI,OAAO;CACX,IAAI,MAAM,MAAM,EAAE,CAAE;CACpB,KAAK,MAAM,UAAU,WAAW,MAAM,GAAG;EACvC,IAAI,SAAS,KAAK;GAEhB,IAAI,WAAW,MAAM,KAAK,IAAI,KAAK,MAAM,QAAQ,OAAO,MAAM,IAAI,WAAW;GAC7E,KAAK;GACL,OAAO;GACP,MAAM,SAAS,MAAM,EAAE,CAAE;GACzB;EACF;EACA,IAAI,SAAS,KAAK,OAAO,MAAM,IAAI,WAAW;EAC9C,MAAM,EAAE,CAAE,KAAK,OAAO,MAAM,MAAM,MAAM,CAAC;EACzC,OAAO;CACT;CACA,IAAI,MAAM,MAAM,SAAS,KAAK,SAAS,KAAK,OAAO,MAAM,IAAI,WAAW;CACxE,OAAO;AACT;;;ACjCA,MAAa,aAAa;;AA4B1B,SAAgB,QAAQ,MAAsB;CAC5C,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AAO,OAAO,MAAM,GAAG,EAAE;CACtC,MAAM,aAAa,MAAM,KAAA,KAAa,KAAK,WAAW,IAAI,IAAI,KAAK,QAAQ,GAAG,MAAM,KAAK,KAAK,IAAI,GAAG,IAAI,CAAC,IAAI,MAAM,GAAG,CAAC,IAAI,KAAK;CACjI,MAAM,WAAW,MAAM,KAAA,IAAY,IAAI,KAAK,IAAI,GAAG,GAAG,OAAO,OAAO,KAAK,OAAO,IAAI,KAAK,CAAC,CAAC;CAC3F,OAAO;EACL,cAAc,OAAO;EACrB,mBAAmB;EACnB,iBAAiB;EACjB,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,iBAAiB,MAAM,aAAa,IAAI,IAAI,MAAM,OAAO,MAAM,SAAS;CAC3G;AACF"}
1
+ {"version":3,"file":"text.js","names":[],"sources":["../src/word-parts.ts","../src/text.ts"],"sourcesContent":["// The word segments (UAX #29) of the words of a text, with one call of `wordBreaks` for all the words.\n// This module is internal: the package root and `./text` do not export it.\nimport { wordBreaks } from \"@mark1russell7/typeset/segmentation\";\n\n/** This function gives the word segments of one word, with one call of `wordBreaks`. */\nexport function partsOfWord(word: string): string[] {\n const parts: string[] = [];\n let from = 0;\n for (const end of wordBreaks(word)) {\n parts.push(word.slice(from, end));\n from = end;\n }\n return parts;\n}\n\n/**\n * This function gives the word segments of each word, with one call of `wordBreaks` on the words joined by line feeds.\n * UAX #29 puts a break before and after a line feed (WB3a, WB3b), and no rule looks across it.\n * So each word gets the segments of a call on the word alone.\n * A word that ends with a carriage return has no break before the next line feed (WB3).\n * When a break of a line feed is absent, the function gives the segments of one call for each word.\n */\nexport function partsOfWords(words: readonly string[]): string[][] {\n if (words.length === 0) return [];\n if (words.length === 1) return [partsOfWord(words[0]!)];\n const parts: string[][] = words.map(() => []);\n const joined = words.join(\"\\n\");\n let w = 0;\n let from = 0;\n let end = words[0]!.length;\n for (const offset of wordBreaks(joined)) {\n if (from === end) {\n // The segment from `end` is the line feed after word `w`.\n if (offset !== end + 1 || w + 1 >= words.length) return words.map(partsOfWord);\n w += 1;\n from = offset;\n end = offset + words[w]!.length;\n continue;\n }\n if (offset > end) return words.map(partsOfWord);\n parts[w]!.push(joined.slice(from, offset));\n from = offset;\n }\n if (w !== words.length - 1 || from !== end) return words.map(partsOfWord);\n return parts;\n}\n","import { adjustmentRatios, breakers, linesOf, type Box, type Glue, type Item, type Penalty } from \"@mark1russell7/typeset/breaking\";\nimport { graphemes, lineBreaks } from \"@mark1russell7/typeset/segmentation\";\nimport { partsOfWords } from \"./word-parts.ts\";\nimport type { MeasureSpec } from \"./measures.ts\";\n\n/**\n * The advance function of a host: the width of a run of text in a font, in pixels.\n * A browser host gives `canvasAdvance(context)`. A test or a server host gives a function of a font file.\n */\nexport type AdvanceFn = (text: string, font: string) => number;\n\n/** The count of the units in one pixel. Each advance is a whole number of units, so each sum is exact and each port gets the same pixels. */\nexport const TEXT_UNITS = 64;\n\n/** The counts of a measurer: the requests, the cache hits and the calls of the advance function. */\nexport interface MeasurerStats {\n readonly requests: number;\n readonly hits: number;\n readonly calls: number;\n}\n\n/** A measurer: the advance of a segment in a font, in whole units of 1/`TEXT_UNITS` pixel, with a cache. */\nexport interface TextMeasurer {\n /** This function gives the advance of the segment in the font, in units. */\n advance(segment: string, font: string): number;\n /** This function gives the counts since the start or since the last `reset`. */\n stats(): MeasurerStats;\n /** This function clears the cache and the counts. */\n reset(): void;\n /** This function gives the count of the `reset` calls. A `TextLayoutCache` reads it, and it does not give a layout from before a reset. */\n generation?(): number;\n}\n\n/** The options of `createMeasurer`. */\nexport interface MeasurerOptions {\n /** The count of the cache entries. The default is 10000. With 0, the measurer has no cache. */\n readonly maxEntries?: number;\n}\n\n/** This function gives the key of a font: the font string with its white space collapsed and trimmed. */\nexport function fontKey(font: string): string {\n return font.trim().replace(/\\s+/g, \" \");\n}\n\n/**\n * This function gives a measurer with a cache keyed by the font and the segment.\n * The cache removes its oldest entry when it is full. The advance function rounds each width to whole units.\n */\nexport function createMeasurer(measure: AdvanceFn, options: MeasurerOptions = {}): TextMeasurer {\n const max = options.maxEntries ?? 10000;\n if (!(Number.isInteger(max) && max >= 0)) throw new RangeError(`createMeasurer: maxEntries is an integer of 0 or more, not ${max}.`);\n const cache = new Map<string, number>();\n let requests = 0;\n let hits = 0;\n let calls = 0;\n let generation = 0;\n return {\n advance(segment, font) {\n requests++;\n const key = `${fontKey(font)}\\u0000${segment}`;\n const known = cache.get(key);\n if (known !== undefined) {\n hits++;\n return known;\n }\n calls++;\n const px = measure(segment, font);\n if (!Number.isFinite(px) || px < 0) throw new RangeError(`The advance of \"${segment}\" in \"${font}\" is ${px}, not a finite number of 0 or more.`);\n const units = Math.round(px * TEXT_UNITS);\n if (max > 0) {\n if (cache.size >= max) cache.delete(cache.keys().next().value!);\n cache.set(key, units);\n }\n return units;\n },\n stats: () => ({ requests, hits, calls }),\n reset() {\n cache.clear();\n requests = 0;\n hits = 0;\n calls = 0;\n generation++;\n },\n generation: () => generation,\n };\n}\n\n/** The part of a canvas context that `canvasAdvance` uses. */\nexport interface CanvasTextContext {\n font: string;\n measureText(text: string): { readonly width: number };\n}\n\n/** This function gives the advance function of a canvas context. It sets `font` only when the font changes, because a browser parses each new font string. */\nexport function canvasAdvance(context: CanvasTextContext): AdvanceFn {\n let current: string | undefined;\n return (text, font) => {\n if (font !== current) {\n context.font = font;\n current = font;\n }\n return context.measureText(text).width;\n };\n}\n\n/**\n * A word of a text: the text from one break place of UAX #14 to the next, with no white space at its end.\n * Its parts are its word segments (UAX #29), which the measurer measures and caches one by one.\n */\ninterface Word {\n readonly text: string;\n readonly parts: readonly string[];\n /** This value is `true` when white space follows the word in the text. Then one space comes after the word. Else the gap has no width. */\n readonly spaced: boolean;\n}\n\n/**\n * A run of the white space that collapses: the white space of CSS (space, tab, line feed, form feed, carriage return) and the other mandatory breaks of UAX #14.\n * A no-break space or an ideographic space stays in its word, as in CSS.\n */\nconst SPACES = /[ \\t\\n\\v\\f\\r\\u0085\\u2028\\u2029]+/gu;\n\n/** The white space of `SPACES` at the end of a text. */\nconst TRAILING_SPACE = /[ \\t\\n\\v\\f\\r\\u0085\\u2028\\u2029]+$/u;\n\n/** The largest count of texts in the memo of `wordsOf`. A page often asks for the same labels many times. */\nconst WORDS_MEMO = 4096;\nconst wordsMemo = /* @__PURE__ */ new Map<string, readonly Word[]>();\n\n/**\n * This function splits the text into words at the break places of UAX #14 (`lineBreaks` of `@mark1russell7/typeset`).\n * Each word holds its word segments, so words that share segments share the cache.\n */\nfunction wordsOf(text: string): readonly Word[] {\n const known = wordsMemo.get(text);\n if (known !== undefined) return known;\n const words = splitWords(text);\n // The memo forgets its oldest text when it is full.\n if (wordsMemo.size >= WORDS_MEMO) wordsMemo.delete(wordsMemo.keys().next().value!);\n wordsMemo.set(text, words);\n return words;\n}\n\n/**\n * This function gives the words of `wordsOf` with no memo.\n * A break place of UAX #14 comes after a run of white space, so the white space of a piece is at its end. That white space goes, and the word records it.\n * White space inside a piece, for example before a closing bracket, collapses to one space, as `white-space: normal` in CSS.\n * A mandatory break inside the text, for example at a line feed, is white space as in CSS. Only the end of the text ends the last line.\n */\nfunction splitWords(text: string): Word[] {\n const words: { text: string; spaced: boolean }[] = [];\n let start = 0;\n for (const place of lineBreaks(text)) {\n const piece = text.slice(start, place.offset);\n start = place.offset;\n const body = piece.replace(TRAILING_SPACE, \"\").replace(SPACES, \" \");\n const spaced = body.length < piece.length;\n // White space at the start of a piece, for example after a line feed, is the gap after the word before it. A piece of only white space adds no word.\n const word = body.startsWith(\" \") ? body.slice(1) : body;\n if (word.length < body.length || body === \"\") {\n const last = words[words.length - 1];\n if (last !== undefined) last.spaced = true;\n }\n if (word === \"\") continue;\n words.push({ text: word, spaced });\n }\n // One call of `wordBreaks` gives the segments of all the words of the text.\n const parts = partsOfWords(words.map((w) => w.text));\n return words.map((w, i) => ({ text: w.text, parts: parts[i]!, spaced: w.spaced }));\n}\n\n/** This function gives the grapheme clusters of a text by UAX #29 (`graphemes` of `@mark1russell7/typeset`), with no locale. */\nexport function graphemesOf(text: string): string[] {\n return [...graphemes(text)];\n}\n\n/** This function gives the count of the gaps of one space between the words: one after each spaced word but the last. */\nfunction spacesOf(words: readonly Word[]): number {\n let count = 0;\n for (let i = 0; i < words.length - 1; i++) if (words[i]!.spaced) count++;\n return count;\n}\n\n/** This function joins the words with their gaps: one space after a spaced word, and nothing after another word. */\nfunction joinWords(words: readonly Word[]): string {\n return words.map((w, i) => (i < words.length - 1 && w.spaced ? `${w.text} ` : w.text)).join(\"\");\n}\n\n/** The digits, as a value for `createTextCharset`. */\nexport const DIGITS = \"0123456789\";\n\n/** The printable characters of ASCII with the space, as a value for `createTextCharset`. */\nexport const PRINTABLE_ASCII = \" !\\\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\";\n\n/** The scripts of a member of a character set. The characters of other scripts can join or change their shape, so their advances do not add. */\nconst SIMPLE_SCRIPT = /^[\\p{Script=Common}\\p{Script=Latin}\\p{Script=Greek}\\p{Script=Cyrillic}\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}]$/u;\n\n/** The characters that are not plain advances: marks, control and format characters, emoji parts, and each white space but the space. */\nconst NOT_AN_ADVANCE = /[\\p{M}\\p{C}\\p{Extended_Pictographic}\\p{Emoji_Modifier}\\p{Regional_Indicator}]|[^\\S ]/u;\n\n/** The largest count of fonts in the memo of a character set for one measurer. */\nconst CHARSET_FONTS = 64;\n\n/** The options of `createTextCharset`. */\nexport interface TextCharsetOptions {\n /**\n * The largest width that two neighbor characters add to the sum of their advances, as a share of the largest advance. The default is 0.\n * A kerning pair that is narrower adds no width. Give a value for a font with kerning pairs or ligatures that are wider.\n */\n readonly pairMargin?: number;\n}\n\n/** A declared character set. A caller asks for it with `createTextCharset`. It is frozen, so `createTextLayoutCache` can use its identity as a key. */\nexport interface TextCharset {\n readonly characters: string;\n /** This function tells if each code point of the text is a member of the set. */\n covers(text: string): boolean;\n /**\n * This function gives the bound of one UTF-16 code unit of a member in the font, in units of 1/`TEXT_UNITS` pixel.\n * It measures each member once for a measurer with `generation`, and again after a `reset`. It measures on each call for a different measurer.\n * It gives `undefined` when a member has no positive finite advance: that is a gap in the font.\n */\n unit(font: string, measurer: TextMeasurer): number | undefined;\n}\n\n/**\n * This function gives a declared character set. A member is one code point with a plain advance.\n * A tab, a line break, a soft hyphen, a zero-width character, a combining mark, an emoji part or a bidirectional control gives a `RangeError`.\n * A letter of a script that joins or changes its shape, for example Arabic or Devanagari, also gives a `RangeError`. A label with this letter gets a measure.\n */\nexport function createTextCharset(characters: string, options: TextCharsetOptions = {}): TextCharset {\n const pairMargin = options.pairMargin ?? 0;\n if (!(Number.isFinite(pairMargin) && pairMargin >= 0)) throw new RangeError(`createTextCharset: pairMargin is a finite number of 0 or more, not ${pairMargin}.`);\n const members = new Set(characters);\n if (members.size === 0) throw new RangeError(\"createTextCharset: the set has no character.\");\n for (const c of members) {\n if (NOT_AN_ADVANCE.test(c) || !SIMPLE_SCRIPT.test(c)) throw new RangeError(`createTextCharset: U+${c.codePointAt(0)!.toString(16).toUpperCase()} is not a plain advance.`);\n }\n /** This function gives the bound of one character. The added unit holds the rounding of each advance, so a sum of rounded segments stays under the bound. */\n const scan = (font: string, measurer: TextMeasurer): number | undefined => {\n let largest = 0;\n for (const c of members) {\n const units = measurer.advance(c, font);\n if (!(Number.isFinite(units) && units > 0)) return undefined;\n largest = Math.max(largest, units);\n }\n return Math.ceil((largest + 1) * (1 + pairMargin));\n };\n const memo = new WeakMap<TextMeasurer, Map<string, { readonly generation: number; readonly unit: number | undefined }>>();\n return Object.freeze({\n characters,\n covers(text: string): boolean {\n for (const c of text) if (!members.has(c)) return false;\n return true;\n },\n unit(font: string, measurer: TextMeasurer): number | undefined {\n const generation = measurer.generation?.();\n // A measurer without `generation` does not tell of a change of its advances, so a memo can keep a low bound.\n if (generation === undefined) return scan(font, measurer);\n let fonts = memo.get(measurer);\n if (fonts === undefined) {\n fonts = new Map();\n memo.set(measurer, fonts);\n }\n const known = fonts.get(font);\n if (known?.generation === generation) return known.unit;\n const unit = scan(font, measurer);\n if (fonts.size >= CHARSET_FONTS) fonts.delete(fonts.keys().next().value!);\n fonts.set(font, { generation, unit });\n return unit;\n },\n });\n}\n\n/** The source of the width of a label. The option `sizing` of `layoutText` tells each value. */\nexport type TextSizing = \"exact\" | \"bound-first\" | \"bound\";\n\n/** The options of `layoutText`. All lengths are in pixels. */\nexport interface TextLayoutOptions {\n readonly font: string;\n readonly measurer: TextMeasurer;\n /** The line height. A finite number above 0. */\n readonly lineHeight: number;\n /** The width of the lines of a text that does not fit on one line. Without it, the text stays on one line. */\n readonly wrapWidth?: number;\n /** The count of the lines. The last line that stays gets the ellipsis. The default is no limit. */\n readonly maxLines?: number;\n /** The count of the grapheme clusters. A longer text keeps `maxChars` clusters with the ellipsis at the end. The default is no limit. */\n readonly maxChars?: number;\n /** The text at the end of a cut text. The default is \"…\". */\n readonly ellipsis?: string;\n /** The space that the box adds to the width of the text. The default is 0. */\n readonly padding?: number;\n /** The smallest width of a box with one line. The default is 0. */\n readonly minWidth?: number;\n /** The largest width of a box with one line. A text that does not fit wraps at `wrapWidth`. The default is `wrapWidth` plus the padding, or no limit without `wrapWidth`. */\n readonly maxWidth?: number;\n /**\n * The break of a word that is wider than a line. `keep` (the default) keeps the word whole, and the line overflows.\n * `anywhere` breaks it between two grapheme clusters, as the CSS `overflow-wrap: anywhere`.\n */\n readonly wordBreak?: \"keep\" | \"anywhere\";\n /**\n * The line breaker of `@mark1russell7/typeset`. `greedy` (the default) fills each line, as a browser. `total-fit` (Knuth and Plass)\n * makes the lines more equal. `balanced` keeps the greedy line count with the least width.\n */\n readonly breaker?: \"greedy\" | \"total-fit\" | \"balanced\";\n /**\n * The source of the width of a label. `exact` (the default) measures each label.\n * `bound-first` keeps a label of `charset` on one line with no measure when its bound fits. It measures each other label.\n * `bound` sizes each label of `charset` from its bound, also when the label wraps. A label that has a character out of `charset` gets a measure in all modes.\n */\n readonly sizing?: TextSizing;\n /** The declared character set of `sizing`. `bound-first` and `bound` need it, and `exact` does not read it. */\n readonly charset?: TextCharset;\n /**\n * 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.\n * With this option, `total-fit` chooses the lines with the adjustment ratio, and the layout gives the ratio of each line in `ratios`.\n * Without it, a space does not stretch or shrink.\n */\n readonly justify?: TextJustify;\n /**\n * The hyphenation hook of `paragraphOf` of `@mark1russell7/typeset`. It gives the offsets in a word where a break with a hyphen is possible.\n * A line that ends at such an offset ends with \"-\". The subpaths `./hyphen/<language>` of typeset give a hook for each language.\n * layout-contract imports no pattern set. Without the option, a word does not break at a hyphen.\n */\n readonly hyphenate?: (word: string) => readonly number[];\n}\n\n/** The stretch and the shrink of each space of a justified layout, as a share of the width of a space. */\nexport interface TextJustify {\n /** A finite number of 0 or more. */\n readonly stretch: number;\n /** A finite number from 0 to 1, because a space cannot be narrower than 0. */\n readonly shrink: number;\n}\n\n/** The layout of a text: its lines and its box. */\nexport interface TextLayout {\n readonly lines: readonly string[];\n /** The width of each line, in pixels. Each width is a whole number of units of 1/`TEXT_UNITS` pixel. */\n readonly widths: readonly number[];\n readonly lineCount: number;\n /** The width of the box: the text and the padding. */\n readonly width: number;\n readonly height: number;\n /** The width of the lines, or `undefined` for a text on one line. */\n readonly wrapWidth?: number;\n /** `true` when `maxChars` or `maxLines` cut the text. */\n readonly truncated: boolean;\n /** `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. */\n readonly bounded?: true;\n /**\n * 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\n * line, or `ratio × shrink × space` when the ratio is negative. The last line does not stretch, so its ratio is not more than 0.\n * The ratio is infinite for a line with free space and no space to stretch.\n * A layout without `justify`, or a text that fits on one line at its natural width, does not have this field.\n */\n readonly ratios?: readonly number[];\n}\n\n/** A forced break: a penalty with no text, no width and the cost `-Infinity`. */\nconst FORCED: Penalty = { type: \"penalty\", text: \"\", width: 0, cost: -Infinity, flagged: false };\n\n/** 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. */\nconst NO_GAP: Item = { type: \"glue\", text: \"\", width: 0 };\n\n/** The cost of a break at a hyphen: 50, as in TeX and in `paragraphOf` of typeset. */\nconst HYPHEN_COST = 50;\n\n/**\n * This function gives the hyphen places of a word from the hook, sorted, with no repeat.\n * 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.\n */\nfunction hyphenPlaces(word: string, hyphenate: (word: string) => readonly number[]): number[] {\n const edges = new Set<number>();\n let at = 0;\n for (const cluster of graphemesOf(word)) edges.add((at += cluster.length));\n const places = hyphenate(word).filter((o) => o > 0 && o < word.length && edges.has(o));\n return [...new Set(places)].sort((a, b) => a - b);\n}\n\n/** This function gives the box of a part of a word. */\n/** This function gives the units of a segment: the bound for one character times the length, or a measure when there is no bound. */\nfunction advanceOf(segment: string, font: string, measurer: TextMeasurer, bound: number | undefined): number {\n return bound === undefined ? measurer.advance(segment, font) : segment.length * bound;\n}\n\nfunction boxOf(part: { readonly text: string; readonly width: number }): Box {\n return { type: \"box\", text: part.text, width: part.width };\n}\n\n/** A line of a layout, with its width in units. */\ninterface Line {\n text: string;\n units: number;\n}\n\n/**\n * This function lays out a text. It cuts the text to `maxChars`. It keeps the text on one line when it fits in `maxWidth`. Else it breaks the text into lines of `wrapWidth`.\n *\n * The breaker comes from `@mark1russell7/typeset`. The default is greedy, as a browser with `white-space: normal`.\n * It collapses each run of white space to one space, and a line does not count its last space.\n * The width of a word is the sum of the advances of its segments. `docs/TEXT.md` gives the rules and the error of this sum.\n *\n * The option `sizing` replaces a measure with the bound of a declared character set. A caller that does not set it gets each measured result.\n */\nexport function layoutText(text: string, options: TextLayoutOptions): TextLayout {\n const { font, measurer, lineHeight } = options;\n if (!(Number.isFinite(lineHeight) && lineHeight > 0)) throw new RangeError(`layoutText: lineHeight is a finite number above 0, not ${lineHeight}.`);\n const ellipsis = options.ellipsis ?? \"…\";\n const padding = options.padding ?? 0;\n const keep = (options.wordBreak ?? \"keep\") === \"keep\";\n const name = options.breaker ?? \"greedy\";\n if (!Object.hasOwn(breakers, name)) throw new RangeError(`layoutText: breaker is \"greedy\", \"total-fit\" or \"balanced\", not ${String(name)}.`);\n const breaker = breakers[name];\n const sizing = options.sizing ?? \"exact\";\n if (sizing !== \"exact\" && sizing !== \"bound-first\" && sizing !== \"bound\") throw new RangeError(`layoutText: sizing is \"exact\", \"bound-first\" or \"bound\", not ${String(sizing)}.`);\n const charset = sizing === \"exact\" ? undefined : options.charset;\n const { justify, hyphenate } = options;\n if (justify !== undefined && !(Number.isFinite(justify.stretch) && justify.stretch >= 0 && Number.isFinite(justify.shrink) && justify.shrink >= 0 && justify.shrink <= 1)) {\n 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)}.`);\n }\n if (sizing !== \"exact\" && charset === undefined) throw new RangeError(`layoutText: sizing \"${sizing}\" needs a charset from createTextCharset.`);\n let truncated = false;\n\n let source = text;\n if (options.maxChars !== undefined) {\n const clusters = graphemesOf(source);\n if (clusters.length > options.maxChars) {\n const room = Math.max(0, options.maxChars - graphemesOf(ellipsis).length);\n source = clusters.slice(0, room).join(\"\") + ellipsis;\n truncated = true;\n }\n }\n\n const words = wordsOf(source);\n const maxWidth = options.maxWidth ?? (options.wrapWidth === undefined ? Infinity : options.wrapWidth + padding);\n const oneLine = (natural: number, bounded: boolean): TextLayout => {\n const one = joinWords(words);\n const px = natural / TEXT_UNITS;\n const box = Math.min(maxWidth, Math.max(options.minWidth ?? 0, px + padding));\n const layout: TextLayout = { lines: [one], widths: [px], lineCount: 1, width: box, height: lineHeight, truncated };\n return bounded ? { ...layout, bounded } : layout;\n };\n\n // The raw text, not its words: the check sees a tab or a line break before they collapse.\n const unit = charset?.covers(source) === true ? charset.unit(font, measurer) : undefined;\n if (sizing === \"bound-first\" && unit !== undefined) {\n const natural = words.reduce((s, w) => s + w.text.length, spacesOf(words)) * unit;\n if (options.wrapWidth === undefined || natural / TEXT_UNITS + padding <= maxWidth) return oneLine(natural, true);\n }\n const bound = sizing === \"bound\" ? unit : undefined;\n const space = advanceOf(\" \", font, measurer, bound);\n const width = (w: Word): number => w.parts.reduce((s, p) => s + advanceOf(p, font, measurer, bound), 0);\n const lineUnits = (line: string): number => {\n const ws = wordsOf(line);\n return ws.reduce((s, w) => s + width(w), 0) + space * spacesOf(ws);\n };\n const widths = words.map(width);\n const natural = widths.reduce((s, w) => s + w, 0) + space * spacesOf(words);\n\n const fits = natural / TEXT_UNITS + padding <= maxWidth;\n if (options.wrapWidth === undefined || fits) return oneLine(natural, bound !== undefined);\n\n const limit = Math.round(options.wrapWidth * TEXT_UNITS);\n // The items of the breaker: a box for each word, and glue between two words. The glue is one space after a spaced word, else it has no width.\n const items: Item[] = [];\n /** This function puts a word that is wider than a line on new lines, with a break between grapheme clusters. Each forced penalty ends a line. */\n const split = (word: Word): void => {\n if (items.length > 0) items.push(FORCED);\n let cur: { text: string; width: number } | undefined;\n for (const g of graphemesOf(word.text)) {\n const w = advanceOf(g, font, measurer, bound);\n if (cur !== undefined && cur.width + w > limit) {\n items.push(boxOf(cur), FORCED);\n cur = undefined;\n }\n if (cur === undefined) cur = { text: g, width: w };\n else {\n cur.text += g;\n cur.width += w;\n }\n }\n if (cur !== undefined) items.push(boxOf(cur));\n };\n const gap: Glue = justify === undefined ? { type: \"glue\", text: \" \", width: space } : { type: \"glue\", text: \" \", width: space, stretch: space * justify.stretch, shrink: space * justify.shrink };\n const hyphen: Penalty | undefined = hyphenate === undefined ? undefined : { type: \"penalty\", text: \"-\", width: advanceOf(\"-\", font, measurer, bound), cost: HYPHEN_COST, flagged: true };\n /**\n * 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.\n * 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.\n */\n const hyphenated = (word: Word, w: number): void => {\n const places = hyphen === undefined ? [] : hyphenPlaces(word.text, hyphenate!);\n if (places.length === 0) {\n items.push({ type: \"box\", text: word.text, width: w });\n return;\n }\n let start = 0;\n let rest = w;\n for (const end of [...places, word.text.length]) {\n if (start > 0) items.push(hyphen!);\n const part = word.text.slice(start, end);\n const units = end === word.text.length ? rest : advanceOf(part, font, measurer, bound);\n items.push({ type: \"box\", text: part, width: units });\n rest -= units;\n start = end;\n }\n };\n words.forEach((word, i) => {\n const w = widths[i]!;\n if (w > limit && !keep) split(word);\n else {\n if (items.length > 0) items.push(words[i - 1]!.spaced ? gap : NO_GAP);\n hyphenated(word, w);\n }\n });\n const paragraph = { items };\n const broken = linesOf(paragraph, breaker.breaks(paragraph, limit));\n const lines: Line[] = broken.map((l) => ({ text: l.text, units: l.width }));\n const ratios = justify === undefined ? undefined : adjustmentRatios(paragraph, broken, limit);\n if (lines.length === 0) {\n lines.push({ text: \"\", units: 0 });\n ratios?.push(0);\n }\n\n const maxLines = options.maxLines ?? Infinity;\n if (lines.length > maxLines) {\n lines.length = Math.max(1, maxLines);\n const last = lines[lines.length - 1]!;\n const tail = measurer.advance(ellipsis, font);\n const clusters = graphemesOf(last.text);\n while (clusters.length > 0 && lineUnits(clusters.join(\"\")) + tail > limit) clusters.pop();\n const kept = clusters.join(\"\").replace(/\\s+$/u, \"\");\n last.text = kept + ellipsis;\n last.units = lineUnits(kept) + tail;\n truncated = true;\n // The cut line is the last line, so it does not stretch. The cut makes it fit, so it does not shrink.\n if (ratios !== undefined) {\n ratios.length = lines.length;\n ratios[lines.length - 1] = 0;\n }\n }\n\n const layout: TextLayout = {\n lines: lines.map((l) => l.text),\n widths: lines.map((l) => l.units / TEXT_UNITS),\n lineCount: lines.length,\n width: options.wrapWidth + padding,\n height: lines.length * lineHeight,\n wrapWidth: options.wrapWidth,\n truncated,\n ...(ratios === undefined ? {} : { ratios }),\n };\n return bound === undefined ? layout : { ...layout, bounded: true };\n}\n\n/** The counts of a `TextLayoutCache`. `calls` is the count of the `layoutText` calls, and `size` is the count of the entries. */\nexport interface TextLayoutCacheStats extends MeasurerStats {\n readonly size: number;\n}\n\n/** The options of `createTextLayoutCache`. */\nexport interface TextLayoutCacheOptions {\n /** The largest count of the entries. The default is 4096. With 0, the cache keeps no entry. */\n readonly maxEntries?: number;\n}\n\n/** A cache of `layoutText` results. A caller asks for it with `createTextLayoutCache`. `layoutText` itself has no cache of results. */\nexport interface TextLayoutCache {\n /**\n * This function gives the result of `layoutText` for the text and the options.\n * The result is deeply frozen. Equal arguments give the same object until the cache removes the entry.\n */\n layout(text: string, options: TextLayoutOptions): TextLayout;\n /** This function gives the counts since the start or since the last `reset`. */\n stats(): TextLayoutCacheStats;\n /** This function clears the entries and the counts. */\n reset(): void;\n}\n\n/** This function gives the key text of a number. It keeps -0, because `layoutText` can give -0 back in a result. */\nfunction numberKey(value: number | undefined): string {\n return Object.is(value, -0) ? \"-0\" : String(value);\n}\n\n/**\n * This function gives the key of a set of options, without the text and the measurer. Two different sets do not give one key.\n * A number has no comma. The two lengths mark the end of the font and of the ellipsis.\n */\nfunction optionsKey(o: TextLayoutOptions): string {\n 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)}`;\n return `${numbers},${(o.wordBreak ?? \"keep\") === \"keep\"},${o.breaker},${o.sizing ?? \"exact\"},${o.font.length},${o.ellipsis?.length},${o.font}${o.ellipsis ?? \"\"}`;\n}\n\n/** This function tells if two sets of options are the same. It uses `Object.is`, so 0 and -0 are different. It makes no string, so it is cheap on each hit. */\nfunction sameOptions(a: TextLayoutOptions, b: TextLayoutOptions): boolean {\n return (\n a.font === b.font &&\n a.measurer === b.measurer &&\n Object.is(a.lineHeight, b.lineHeight) &&\n Object.is(a.wrapWidth, b.wrapWidth) &&\n Object.is(a.maxLines, b.maxLines) &&\n Object.is(a.maxChars, b.maxChars) &&\n Object.is(a.padding, b.padding) &&\n Object.is(a.minWidth, b.minWidth) &&\n Object.is(a.maxWidth, b.maxWidth) &&\n a.ellipsis === b.ellipsis &&\n a.wordBreak === b.wordBreak &&\n a.breaker === b.breaker &&\n a.sizing === b.sizing &&\n a.charset === b.charset &&\n a.hyphenate === b.hyphenate &&\n Object.is(a.justify?.stretch, b.justify?.stretch) &&\n Object.is(a.justify?.shrink, b.justify?.shrink)\n );\n}\n\n/** The set of options of the last call of a cache, with its layouts by text. */\ninterface CurrentOptions {\n /** A copy of the options, so a later change of the object of the caller does not touch it. */\n readonly options: TextLayoutOptions;\n readonly generation: number | undefined;\n readonly key: string;\n readonly layouts: Map<string, TextLayout>;\n}\n\n/**\n * This function gives a bounded cache of `layoutText` results, keyed by the text, the options, the measurer, the character set and the hyphenation hook.\n * 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.\n * The key holds the raw font string, because a host can give two spellings of a font two different advances.\n * 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.\n */\nexport function createTextLayoutCache(options: TextLayoutCacheOptions = {}): TextLayoutCache {\n const max = options.maxEntries ?? 4096;\n if (!(Number.isInteger(max) && max >= 0)) throw new RangeError(`createTextLayoutCache: maxEntries is an integer of 0 or more, not ${max}.`);\n // Each Map keeps the order of insertion, so its first key is the least recently used. A set of options is here only while it has an entry.\n const groups = new Map<string, Map<string, TextLayout>>();\n // A measurer and a character set are objects. Each gets a number here, so a key does not keep it alive.\n const ids = new WeakMap<object, number>();\n let nextId = 0;\n let current: CurrentOptions | undefined;\n let size = 0;\n let requests = 0;\n let hits = 0;\n let calls = 0;\n const idOf = (item: object): number => {\n let id = ids.get(item);\n if (id === undefined) {\n id = nextId++;\n ids.set(item, id);\n }\n return id;\n };\n /** This function finds the layouts of a set of options, and it makes that set the most recently used. */\n const open = (layoutOptions: TextLayoutOptions, generation: number | undefined): CurrentOptions => {\n const charset = layoutOptions.charset === undefined ? \"\" : idOf(layoutOptions.charset);\n const hyphenate = layoutOptions.hyphenate === undefined ? \"\" : idOf(layoutOptions.hyphenate);\n const key = `${idOf(layoutOptions.measurer)},${generation},${charset},${hyphenate},${optionsKey(layoutOptions)}`;\n const layouts = groups.get(key) ?? new Map<string, TextLayout>();\n if (groups.delete(key)) groups.set(key, layouts);\n // The copy of `justify` keeps its values, so a later change of the object of the caller does not touch the key.\n const copy = layoutOptions.justify === undefined ? { ...layoutOptions } : { ...layoutOptions, justify: { ...layoutOptions.justify } };\n return { options: copy, generation, key, layouts };\n };\n /** This function removes one entry. */\n const evict = (): void => {\n const [key, layouts] = groups.entries().next().value!;\n layouts.delete(layouts.keys().next().value!);\n size--;\n if (layouts.size === 0) groups.delete(key);\n };\n return {\n layout(text, layoutOptions) {\n requests++;\n const generation = layoutOptions.measurer.generation?.();\n if (current === undefined || generation !== current.generation || !sameOptions(current.options, layoutOptions)) current = open(layoutOptions, generation);\n const { key, layouts } = current;\n const known = layouts.get(text);\n if (known !== undefined) {\n hits++;\n // This moves the text to the end of the order.\n layouts.delete(text);\n layouts.set(text, known);\n return known;\n }\n calls++;\n const layout = layoutText(text, layoutOptions);\n // The callers share this object, so it is frozen also when the cache does not keep it.\n Object.freeze(layout.lines);\n Object.freeze(layout.widths);\n if (layout.ratios !== undefined) Object.freeze(layout.ratios);\n Object.freeze(layout);\n if (max > 0) {\n if (size >= max) evict();\n if (layouts.size === 0) groups.set(key, layouts);\n layouts.set(text, layout);\n size++;\n }\n return layout;\n },\n stats: () => ({ requests, hits, calls, size }),\n reset() {\n groups.clear();\n current = undefined;\n size = 0;\n requests = 0;\n hits = 0;\n calls = 0;\n },\n };\n}\n\n/** The id of a text measure. `docs/TEXT.md` gives the definitions. */\nexport type TextMeasureId = \"text.lines\" | \"text.raggedness\" | \"text.overflow\" | \"text.cacheHit\" | \"text.ms\";\n\n/** The specs of the text measures. */\nexport const TEXT_MEASURES: readonly MeasureSpec<TextMeasureId>[] = /* @__PURE__ */ Object.freeze([\n { id: \"text.lines\", unit: \"count\", direction: \"lower\", min: 1, max: Infinity, minEffect: 0, family: \"text\" },\n { id: \"text.raggedness\", unit: \"share\", direction: \"lower\", min: 0, max: 1, minEffect: 0.005, family: \"text\" },\n { id: \"text.overflow\", unit: \"wrap widths\", direction: \"lower\", min: 0, max: Infinity, floor: 0, tol: 0, minEffect: 0, family: \"text\", role: \"guard\" },\n { id: \"text.cacheHit\", unit: \"share\", direction: \"higher\", min: 0, max: 1, family: \"text\", role: \"diagnostic\" },\n { id: \"text.ms\", unit: \"milliseconds\", direction: \"lower\", min: 0, max: Infinity, family: \"text\", role: \"time\" },\n] as const);\n\n/**\n * This function gives the measures of a layout. `text.raggedness` is the mean of `((wrapWidth - width) / wrapWidth)^2` over the lines before the last line.\n * `text.overflow` is the largest excess of a line over `wrapWidth`, as a share of `wrapWidth`. A text on one line gives 0 for the two values.\n * With `stats`, the measures also hold `text.cacheHit`: the hits divided by the requests.\n */\nexport function textMeasures(layout: TextLayout, stats?: MeasurerStats): Partial<Record<TextMeasureId, number>> {\n const w = layout.wrapWidth;\n const body = layout.widths.slice(0, -1);\n const raggedness = w === undefined || body.length === 0 ? 0 : body.reduce((s, x) => s + (Math.max(0, w - x) / w) ** 2, 0) / body.length;\n const overflow = w === undefined ? 0 : Math.max(0, ...layout.widths.map((x) => (x - w) / w));\n return {\n \"text.lines\": layout.lineCount,\n \"text.raggedness\": raggedness,\n \"text.overflow\": overflow,\n ...(stats === undefined ? {} : { \"text.cacheHit\": stats.requests === 0 ? 0 : stats.hits / stats.requests }),\n };\n}\n"],"mappings":";;;;AAKA,SAAgB,YAAY,MAAwB;CAClD,MAAM,QAAkB,CAAC;CACzB,IAAI,OAAO;CACX,KAAK,MAAM,OAAO,WAAW,IAAI,GAAG;EAClC,MAAM,KAAK,KAAK,MAAM,MAAM,GAAG,CAAC;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MAAM,aAAa,IAAI,IAAI,MAAM,OAAO,MAAM,SAAS;CAC3G;AACF"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/layout-contract",
4
- "version": "0.9.9",
4
+ "version": "0.10.0",
5
5
  "description": "The shared contract of the packing and highways layout engines: the input and record formats, the turn rule, margins, tolerances and hard rules.",
6
6
  "keywords": [
7
7
  "layout",
package/src/balance.ts CHANGED
@@ -11,6 +11,8 @@ export interface PlacedBox extends Rect {
11
11
  export interface Balance {
12
12
  /** The standard deviation of the nearest-neighbour gaps divided by their mean. */
13
13
  readonly gapCv: number;
14
+ /** The mean of the nearest-neighbour gaps, in layout units. With fewer than 2 boxes, the value is 0. */
15
+ readonly gapMean: number;
14
16
  /** The distance from the centroid of the free area to the center of the container, as a share of the half-diagonal. */
15
17
  readonly centroidOffset: number;
16
18
  /** The empty share of the strip at each side of the container. */
@@ -25,6 +27,7 @@ export const BALANCE_SIDE_DEPTH = 0.25;
25
27
  /** A suffix of a balance or stability measure. A stage adds its prefix, for example `pack.balance.gapCv`. */
26
28
  export type BalanceMeasureSuffix =
27
29
  | "balance.gapCv"
30
+ | "balance.gapMean"
28
31
  | "balance.centroidOffset"
29
32
  | "balance.side.top"
30
33
  | "balance.side.right"
@@ -37,6 +40,7 @@ export type BalanceMeasureSuffix =
37
40
  /** The suffixes of the balance and stability measures, in the order of `docs/BALANCE.md`. */
38
41
  export const BALANCE_MEASURE_SUFFIXES: readonly BalanceMeasureSuffix[] = /* @__PURE__ */ Object.freeze([
39
42
  "balance.gapCv",
43
+ "balance.gapMean",
40
44
  "balance.centroidOffset",
41
45
  "balance.side.top",
42
46
  "balance.side.right",
@@ -141,7 +145,7 @@ export function balanceOf(boxes: readonly Rect[], container: Rect): Balance {
141
145
  side[s] = stripArea > 0 ? Math.min(1, Math.max(0, 1 - filled / stripArea)) : 0;
142
146
  }
143
147
  const values = SIDES.map((s) => side[s]);
144
- return { gapCv, centroidOffset, side, sideRange: Math.max(...values) - Math.min(...values) };
148
+ return { gapCv, gapMean: mean, centroidOffset, side, sideRange: Math.max(...values) - Math.min(...values) };
145
149
  }
146
150
 
147
151
  /** The options of `procrustesOf`. */
@@ -207,6 +211,7 @@ export function perChange(move: number, changed: number, count: number): number
207
211
  export function balanceMeasures<S extends string>(stage: S, balance: Balance): Record<`${S}.${BalanceMeasureSuffix}`, number> {
208
212
  const m: Record<string, number> = {
209
213
  [`${stage}.balance.gapCv`]: balance.gapCv,
214
+ [`${stage}.balance.gapMean`]: balance.gapMean,
210
215
  [`${stage}.balance.centroidOffset`]: balance.centroidOffset,
211
216
  [`${stage}.balance.sideRange`]: balance.sideRange,
212
217
  };
@@ -217,6 +222,7 @@ export function balanceMeasures<S extends string>(stage: S, balance: Balance): R
217
222
  /**
218
223
  * This function gives the specs of the balance and stability measures, with the prefix of the stage.
219
224
  * The balance measures read the area of each box, so they support only `rect`. The stability measures read only the centers.
225
+ * `balance.gapMean` has no better side. An objective gives it a target, so its role is `diagnostic`, and the joint selector does not rank by it.
220
226
  */
221
227
  export function balanceMeasureSpecs<S extends string>(stage: S): readonly MeasureSpec<`${S}.${BalanceMeasureSuffix}`>[] {
222
228
  const id = (suffix: BalanceMeasureSuffix): `${S}.${BalanceMeasureSuffix}` => `${stage}.${suffix}`;
@@ -224,9 +230,10 @@ export function balanceMeasureSpecs<S extends string>(stage: S): readonly Measur
224
230
  const centers = SHAPE_KIND_IDS;
225
231
  return Object.freeze([
226
232
  { id: id("balance.gapCv"), unit: "ratio", direction: "lower", min: 0, max: Infinity, minEffect: 0.01, family: "balance", shapes: rect },
227
- { id: id("balance.centroidOffset"), unit: "0 to 1", direction: "lower", min: 0, max: 1, minEffect: 0.01, family: "balance", shapes: rect },
228
- ...SIDES.map((s) => ({ id: id(`balance.side.${s}`), unit: "0 to 1", direction: "lower" as const, min: 0, max: 1, family: "balance", role: "diagnostic" as const, shapes: rect })),
229
- { id: id("balance.sideRange"), unit: "0 to 1", direction: "lower", min: 0, max: 1, minEffect: 0.02, family: "balance", shapes: rect },
233
+ { id: id("balance.gapMean"), unit: "layout units", direction: "higher", min: 0, max: Infinity, family: "balance", role: "diagnostic", shapes: rect },
234
+ { id: id("balance.centroidOffset"), unit: "share", direction: "lower", min: 0, max: 1, minEffect: 0.01, family: "balance", shapes: rect },
235
+ ...SIDES.map((s) => ({ id: id(`balance.side.${s}`), unit: "share", direction: "lower" as const, min: 0, max: 1, family: "balance", role: "diagnostic" as const, shapes: rect })),
236
+ { id: id("balance.sideRange"), unit: "share", direction: "lower", min: 0, max: 1, minEffect: 0.02, family: "balance", shapes: rect },
230
237
  { id: id("stability.procrustes"), unit: "W for each change share", direction: "lower", min: 0, max: Infinity, floor: 0, tol: 0.005, minEffect: 0.005, family: "stability", role: "change-guard", shapes: centers },
231
238
  { id: id("stability.seed"), unit: "W", direction: "lower", min: 0, max: Infinity, floor: 0, tol: 0.005, minEffect: 0.005, family: "stability", shapes: centers },
232
239
  ]);
package/src/cell.ts ADDED
@@ -0,0 +1,104 @@
1
+ import { regionArea, regionPerimeter, type Region } from "./geometry.ts";
2
+ import { measureEntry, type MeasureEntry } from "./measure-registry.ts";
3
+ import type { MeasureSpec } from "./measures.ts";
4
+ import type { ShapeKind } from "./shapes.ts";
5
+
6
+ /** One placed item for the cell measures: the area that the item asks for, and the region that it got. */
7
+ export interface CellItem {
8
+ /**
9
+ * The weight of the item, for example the area `w` by `h` of its box in the input. It is a finite number above 0.
10
+ * The targets do not need a sum of 1, because `cellsOf` divides each target by the sum of the targets.
11
+ */
12
+ readonly target: number;
13
+ /** The region that the item got, in any frame. A box without a shape gives its rectangle. */
14
+ readonly cell: Region;
15
+ }
16
+
17
+ /** The cell measures of a set of items: `docs/CELLS.md` gives the definitions. */
18
+ export interface Cells {
19
+ /** Half the sum of the differences of the cell share and the target share, from 0 to 1. */
20
+ readonly areaError: number;
21
+ /** The mean of the perimeter squared over 4 PI times the area of each cell, 1 or more. */
22
+ readonly compactness: number;
23
+ }
24
+
25
+ /** The suffix of a cell measure id. The id is the stage, a point and the suffix, for example `pack.cell.areaError`. */
26
+ export type CellMeasureSuffix = "cell.areaError" | "cell.compactness";
27
+
28
+ /** The suffixes of the cell measures, in the order of `cellMeasureSpecs`. */
29
+ export const CELL_MEASURE_SUFFIXES: readonly CellMeasureSuffix[] = /* @__PURE__ */ Object.freeze(["cell.areaError", "cell.compactness"] as const);
30
+
31
+ /** The compactness of a square: 4 over PI. */
32
+ export const SQUARE_COMPACTNESS: number = 4 / Math.PI;
33
+
34
+ /**
35
+ * This function gives the cell measures of the placed items in a container of the area `containerArea`.
36
+ *
37
+ * - The cell share of an item is the area of its cell over `containerArea`. The target share is its `target` over the sum of the targets.
38
+ * - `containerArea` is the area of the container region. For a container with a shape, give `regionArea` of the shape, not `w` by `h`.
39
+ * - `areaError` is half the sum of the absolute differences of the two shares. Cells that fill the container in the target shares give 0.
40
+ * Cells that overlap or go out of the container can give a sum over 1. Those cells break the hard rules, and the value stops at 1.
41
+ * - `compactness` is the mean of `P * P / (4 * PI * A)` over the cells, for the perimeter `P` and the area `A` of each cell.
42
+ * A circle gives 1, and a square gives 4 over PI. A cell with the area 0 gives `Infinity`.
43
+ * - No items give the best values: an `areaError` of 0 and a `compactness` of 1. The hard rule `complete` counts the items that are not placed.
44
+ *
45
+ * A target that is not a finite number above 0, and a container area that is not a finite number above 0, give a `RangeError`.
46
+ */
47
+ export function cellsOf(items: readonly CellItem[], containerArea: number): Cells {
48
+ if (!(Number.isFinite(containerArea) && containerArea > 0)) throw new RangeError(`cellsOf: the container area is a finite number above 0, not ${containerArea}.`);
49
+ if (items.length === 0) return { areaError: 0, compactness: 1 };
50
+ let targets = 0;
51
+ for (const item of items) {
52
+ if (!(Number.isFinite(item.target) && item.target > 0)) throw new RangeError(`cellsOf: a target is a finite number above 0, not ${item.target}.`);
53
+ targets += item.target;
54
+ }
55
+ let error = 0;
56
+ let compact = 0;
57
+ for (const item of items) {
58
+ const area = regionArea(item.cell);
59
+ error += Math.abs(area / containerArea - item.target / targets);
60
+ const p = regionPerimeter(item.cell);
61
+ compact += area > 0 ? (p * p) / (4 * Math.PI * area) : Infinity;
62
+ }
63
+ return { areaError: Math.min(1, error / 2), compactness: compact / items.length };
64
+ }
65
+
66
+ /** This function gives the cell values as measures, with the prefix of the stage, for example `pack.cell.areaError`. */
67
+ export function cellMeasures<S extends string>(stage: S, cells: Cells): Record<`${S}.${CellMeasureSuffix}`, number> {
68
+ return {
69
+ [`${stage}.cell.areaError`]: cells.areaError,
70
+ [`${stage}.cell.compactness`]: cells.compactness,
71
+ } as Record<`${S}.${CellMeasureSuffix}`, number>;
72
+ }
73
+
74
+ /**
75
+ * This function gives the specs of the cell measures, with the prefix of the stage. The family is `cell`.
76
+ * The measures read the exact area and perimeter of each cell, so they support `rect`, `polygon` and `circle`. A `free` box has only its bounding box, so it is not supported.
77
+ */
78
+ export function cellMeasureSpecs<S extends string>(stage: S): readonly MeasureSpec<`${S}.${CellMeasureSuffix}`>[] {
79
+ const shapes: readonly ShapeKind[] = ["rect", "polygon", "circle"];
80
+ return Object.freeze([
81
+ { id: `${stage}.cell.areaError`, unit: "share", direction: "lower", min: 0, max: 1, floor: 0, tol: 1e-9, minEffect: 0.01, family: "cell", shapes },
82
+ { id: `${stage}.cell.compactness`, unit: "ratio", direction: "lower", min: 1, max: Infinity, minEffect: 0.01, family: "cell", shapes },
83
+ ] as MeasureSpec<`${S}.${CellMeasureSuffix}`>[]);
84
+ }
85
+
86
+ /** The npm name of the package that computes the cell measures. */
87
+ export const CELL_SOURCE = "@mark1russell7/layout-contract";
88
+
89
+ /**
90
+ * This function gives the registry entries of the cell measures, with the prefix of the stage.
91
+ * `areaError` uses the rule `range`. `compactness` uses the rule `scale`: a square has the loss 0.5.
92
+ * The cost of each is `n`. Each makes one pass over the corners of the cells. The cells of a Voronoi diagram have a count of corners in the order of `n`.
93
+ */
94
+ export function cellMeasureEntries<S extends string>(stage: S): readonly MeasureEntry<`${S}.${CellMeasureSuffix}`>[] {
95
+ const [area, compact] = cellMeasureSpecs(stage);
96
+ return Object.freeze([
97
+ measureEntry(area!, { source: CELL_SOURCE, cost: "n" }),
98
+ measureEntry(compact!, {
99
+ source: CELL_SOURCE,
100
+ cost: "n",
101
+ normalize: { kind: "scale", half: SQUARE_COMPACTNESS - 1, reason: "A square cell has the loss 0.5, and a circle has the loss 0." },
102
+ }),
103
+ ]);
104
+ }