@mark1russell7/layout-contract 0.5.5 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/text.d.ts CHANGED
@@ -44,7 +44,7 @@ export interface CanvasTextContext {
44
44
  }
45
45
  /** 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. */
46
46
  export declare function canvasAdvance(context: CanvasTextContext): AdvanceFn;
47
- /** This function gives the grapheme clusters of a text. Without `Intl.Segmenter`, it gives the code points. */
47
+ /** This function gives the grapheme clusters of a text by UAX #29 (`graphemes` of `@mark1russell7/typeset`), with no locale. */
48
48
  export declare function graphemesOf(text: string): string[];
49
49
  /** The digits, as a value for `createTextCharset`. */
50
50
  export declare const DIGITS = "0123456789";
@@ -1 +1 @@
1
- {"version":3,"file":"text.d.ts","names":[],"sources":["../src/text.ts"],"mappings":";;;;;YAOY,aAAa,cAAc;;qBAG1B;;iBAGI;WACN;WACA;WACA;;;iBAIM;;EAEf,QAAQ,iBAAiB;;EAEzB,SAAS;;EAET;;EAEA;;;iBAIe;;WAEN;;;wBAIK,QAAQ;;;;;wBAQR,eAAe,SAAS,WAAW,UAAS,kBAAuB;;iBAwClE;EACf;EACA,YAAY;aAA0B;;;;wBAIxB,cAAc,SAAS,oBAAoB;;wBAwE3C,YAAY;;qBAOf;;qBAGA;;iBAYI;;;;;WAKN;;;iBAIM;WACN;;EAET,OAAO;;;;;;EAMP,KAAK,cAAc,UAAU;;;;;;;wBAQf,kBAAkB,oBAAoB,UAAS,qBAA0B;;YA6C7E;;iBAGK;WACN;WACA,UAAU;;WAEV;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;;;;WAKA;;;;;WAKA;;;;;;WAMA,SAAS;;WAET,UAAU;;;iBAIJ;WACN;;WAEA;WACA;;WAEA;WACA;;WAEA;;WAEA;;WAEA;;;;;;;;;;;wBA+BK,WAAW,cAAc,SAAS,oBAAoB;;iBAiHrD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
1
1
  import { breakers, linesOf } from "@mark1russell7/typeset/breaking";
2
+ import { graphemes, lineBreaks, wordBreaks } from "@mark1russell7/typeset/segmentation";
3
+ // src/word-parts.ts
4
+ /** This function gives the word segments of one word, with one call of `wordBreaks`. */
5
+ function partsOfWord(word) {
6
+ const parts = [];
7
+ let from = 0;
8
+ for (const end of wordBreaks(word)) {
9
+ parts.push(word.slice(from, end));
10
+ from = end;
11
+ }
12
+ return parts;
13
+ }
14
+ /**
15
+ * This function gives the word segments of each word, with one call of `wordBreaks` on the words joined by line feeds.
16
+ * UAX #29 puts a break before and after a line feed (WB3a, WB3b), and no rule looks across it.
17
+ * So each word gets the segments of a call on the word alone.
18
+ * A word that ends with a carriage return has no break before the next line feed (WB3).
19
+ * When a break of a line feed is absent, the function gives the segments of one call for each word.
20
+ */
21
+ function partsOfWords(words) {
22
+ if (words.length === 0) return [];
23
+ if (words.length === 1) return [partsOfWord(words[0])];
24
+ const parts = words.map(() => []);
25
+ const joined = words.join("\n");
26
+ let w = 0;
27
+ let from = 0;
28
+ let end = words[0].length;
29
+ for (const offset of wordBreaks(joined)) {
30
+ if (from === end) {
31
+ if (offset !== end + 1 || w + 1 >= words.length) return words.map(partsOfWord);
32
+ w += 1;
33
+ from = offset;
34
+ end = offset + words[w].length;
35
+ continue;
36
+ }
37
+ if (offset > end) return words.map(partsOfWord);
38
+ parts[w].push(joined.slice(from, offset));
39
+ from = offset;
40
+ }
41
+ if (w !== words.length - 1 || from !== end) return words.map(partsOfWord);
42
+ return parts;
43
+ }
2
44
  // src/text.ts
3
45
  /** 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. */
4
46
  const TEXT_UNITS = 64;
@@ -63,22 +105,20 @@ function canvasAdvance(context) {
63
105
  return context.measureText(text).width;
64
106
  };
65
107
  }
66
- const SPACE = /^\s+$/u;
67
- /** The segmenters of the module. A new `Intl.Segmenter` loads the data of the locale, so the module makes each granularity only once. */
68
- const segmenters = /* @__PURE__ */ new Map();
69
- /** This function gives the segmenter of a granularity, or `null` without `Intl.Segmenter`. */
70
- function segmenterOf(granularity) {
71
- let s = segmenters.get(granularity);
72
- if (s === void 0) {
73
- s = typeof Intl !== "undefined" && typeof Intl.Segmenter === "function" ? new Intl.Segmenter(void 0, { granularity }) : null;
74
- segmenters.set(granularity, s);
75
- }
76
- return s;
77
- }
108
+ /**
109
+ * 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.
110
+ * A no-break space or an ideographic space stays in its word, as in CSS.
111
+ */
112
+ const SPACES = /[ \t\n\v\f\r\u0085\u2028\u2029]+/gu;
113
+ /** The white space of `SPACES` at the end of a text. */
114
+ const TRAILING_SPACE = /[ \t\n\v\f\r\u0085\u2028\u2029]+$/u;
78
115
  /** The largest count of texts in the memo of `wordsOf`. A page often asks for the same labels many times. */
79
116
  const WORDS_MEMO = 4096;
80
117
  const wordsMemo = /* @__PURE__ */ new Map();
81
- /** This function splits the text into words at white space. Each word holds its word segments (`Intl.Segmenter`), so words that share segments share the cache. */
118
+ /**
119
+ * This function splits the text into words at the break places of UAX #14 (`lineBreaks` of `@mark1russell7/typeset`).
120
+ * Each word holds its word segments, so words that share segments share the cache.
121
+ */
82
122
  function wordsOf(text) {
83
123
  const known = wordsMemo.get(text);
84
124
  if (known !== void 0) return known;
@@ -87,30 +127,51 @@ function wordsOf(text) {
87
127
  wordsMemo.set(text, words);
88
128
  return words;
89
129
  }
90
- /** This function gives the words of `wordsOf` with no memo. */
130
+ /**
131
+ * This function gives the words of `wordsOf` with no memo.
132
+ * 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.
133
+ * White space inside a piece, for example before a closing bracket, collapses to one space, as `white-space: normal` in CSS.
134
+ * 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.
135
+ */
91
136
  function splitWords(text) {
92
137
  const words = [];
93
- let parts = [];
94
- const flush = () => {
95
- if (parts.length > 0) words.push({
96
- text: parts.join(""),
97
- parts
138
+ let start = 0;
139
+ for (const place of lineBreaks(text)) {
140
+ const piece = text.slice(start, place.offset);
141
+ start = place.offset;
142
+ const body = piece.replace(TRAILING_SPACE, "").replace(SPACES, " ");
143
+ const spaced = body.length < piece.length;
144
+ const word = body.startsWith(" ") ? body.slice(1) : body;
145
+ if (word.length < body.length || body === "") {
146
+ const last = words[words.length - 1];
147
+ if (last !== void 0) last.spaced = true;
148
+ }
149
+ if (word === "") continue;
150
+ words.push({
151
+ text: word,
152
+ spaced
98
153
  });
99
- parts = [];
100
- };
101
- const segmenter = segmenterOf("word");
102
- if (segmenter !== null) for (const s of segmenter.segment(text)) if (SPACE.test(s.segment)) flush();
103
- else parts.push(s.segment);
104
- else for (const s of text.split(/(\s+)/u)) if (s === "" || SPACE.test(s)) flush();
105
- else parts.push(s);
106
- flush();
107
- return words;
154
+ }
155
+ const parts = partsOfWords(words.map((w) => w.text));
156
+ return words.map((w, i) => ({
157
+ text: w.text,
158
+ parts: parts[i],
159
+ spaced: w.spaced
160
+ }));
108
161
  }
109
- /** This function gives the grapheme clusters of a text. Without `Intl.Segmenter`, it gives the code points. */
162
+ /** This function gives the grapheme clusters of a text by UAX #29 (`graphemes` of `@mark1russell7/typeset`), with no locale. */
110
163
  function graphemesOf(text) {
111
- const segmenter = segmenterOf("grapheme");
112
- if (segmenter !== null) return Array.from(segmenter.segment(text), (s) => s.segment);
113
- return Array.from(text);
164
+ return [...graphemes(text)];
165
+ }
166
+ /** This function gives the count of the gaps of one space between the words: one after each spaced word but the last. */
167
+ function spacesOf(words) {
168
+ let count = 0;
169
+ for (let i = 0; i < words.length - 1; i++) if (words[i].spaced) count++;
170
+ return count;
171
+ }
172
+ /** This function joins the words with their gaps: one space after a spaced word, and nothing after another word. */
173
+ function joinWords(words) {
174
+ return words.map((w, i) => i < words.length - 1 && w.spaced ? `${w.text} ` : w.text).join("");
114
175
  }
115
176
  /** The digits, as a value for `createTextCharset`. */
116
177
  const DIGITS = "0123456789";
@@ -178,6 +239,12 @@ const FORCED = {
178
239
  cost: -Infinity,
179
240
  flagged: false
180
241
  };
242
+ /** 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. */
243
+ const NO_GAP = {
244
+ type: "glue",
245
+ text: "",
246
+ width: 0
247
+ };
181
248
  /** This function gives the box of a part of a word. */
182
249
  /** This function gives the units of a segment: the bound for one character times the length, or a measure when there is no bound. */
183
250
  function advanceOf(segment, font, measurer, bound) {
@@ -225,7 +292,7 @@ function layoutText(text, options) {
225
292
  const words = wordsOf(source);
226
293
  const maxWidth = options.maxWidth ?? (options.wrapWidth === void 0 ? Infinity : options.wrapWidth + padding);
227
294
  const oneLine = (natural, bounded) => {
228
- const one = words.map((w) => w.text).join(" ");
295
+ const one = joinWords(words);
229
296
  const px = natural / 64;
230
297
  const box = Math.min(maxWidth, Math.max(options.minWidth ?? 0, px + padding));
231
298
  const layout = {
@@ -243,7 +310,7 @@ function layoutText(text, options) {
243
310
  };
244
311
  const unit = charset?.covers(source) === true ? charset.unit(font, measurer) : void 0;
245
312
  if (sizing === "bound-first" && unit !== void 0) {
246
- const natural = words.reduce((s, w) => s + w.text.length, Math.max(0, words.length - 1)) * unit;
313
+ const natural = words.reduce((s, w) => s + w.text.length, spacesOf(words)) * unit;
247
314
  if (options.wrapWidth === void 0 || natural / 64 + padding <= maxWidth) return oneLine(natural, true);
248
315
  }
249
316
  const bound = sizing === "bound" ? unit : void 0;
@@ -251,10 +318,10 @@ function layoutText(text, options) {
251
318
  const width = (w) => w.parts.reduce((s, p) => s + advanceOf(p, font, measurer, bound), 0);
252
319
  const lineUnits = (line) => {
253
320
  const ws = wordsOf(line);
254
- return ws.reduce((s, w) => s + width(w), 0) + space * Math.max(0, ws.length - 1);
321
+ return ws.reduce((s, w) => s + width(w), 0) + space * spacesOf(ws);
255
322
  };
256
323
  const widths = words.map(width);
257
- const natural = widths.reduce((s, w) => s + w, 0) + space * Math.max(0, words.length - 1);
324
+ const natural = widths.reduce((s, w) => s + w, 0) + space * spacesOf(words);
258
325
  const fits = natural / 64 + padding <= maxWidth;
259
326
  if (options.wrapWidth === void 0 || fits) return oneLine(natural, bound !== void 0);
260
327
  const limit = Math.round(options.wrapWidth * 64);
@@ -284,11 +351,11 @@ function layoutText(text, options) {
284
351
  const w = widths[i];
285
352
  if (w > limit && !keep) split(word);
286
353
  else {
287
- if (items.length > 0) items.push({
354
+ if (items.length > 0) items.push(words[i - 1].spaced ? {
288
355
  type: "glue",
289
356
  text: " ",
290
357
  width: space
291
- });
358
+ } : NO_GAP);
292
359
  items.push({
293
360
  type: "box",
294
361
  text: word.text,
package/build/text.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"text.js","names":[],"sources":["../src/text.ts"],"sourcesContent":["import { breakers, linesOf, type Box, type Item, type Penalty } from \"@mark1russell7/typeset/breaking\";\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/** A word of a text: its segments, which the measurer measures and caches one by one. */\ninterface Word {\n readonly text: string;\n readonly parts: readonly string[];\n}\n\nconst SPACE = /^\\s+$/u;\n\n/** The segmenters of the module. A new `Intl.Segmenter` loads the data of the locale, so the module makes each granularity only once. */\nconst segmenters = /* @__PURE__ */ new Map<\"word\" | \"grapheme\", Intl.Segmenter | null>();\n\n/** This function gives the segmenter of a granularity, or `null` without `Intl.Segmenter`. */\nfunction segmenterOf(granularity: \"word\" | \"grapheme\"): Intl.Segmenter | null {\n let s = segmenters.get(granularity);\n if (s === undefined) {\n s = typeof Intl !== \"undefined\" && typeof Intl.Segmenter === \"function\" ? new Intl.Segmenter(undefined, { granularity }) : null;\n segmenters.set(granularity, s);\n }\n return s;\n}\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/** This function splits the text into words at white space. Each word holds its word segments (`Intl.Segmenter`), so words that share segments share the cache. */\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/** This function gives the words of `wordsOf` with no memo. */\nfunction splitWords(text: string): Word[] {\n const words: Word[] = [];\n let parts: string[] = [];\n const flush = (): void => {\n if (parts.length > 0) words.push({ text: parts.join(\"\"), parts });\n parts = [];\n };\n const segmenter = segmenterOf(\"word\");\n if (segmenter !== null) {\n for (const s of segmenter.segment(text)) {\n if (SPACE.test(s.segment)) flush();\n else parts.push(s.segment);\n }\n } else {\n for (const s of text.split(/(\\s+)/u)) {\n if (s === \"\" || SPACE.test(s)) flush();\n else parts.push(s);\n }\n }\n flush();\n return words;\n}\n\n/** This function gives the grapheme clusters of a text. Without `Intl.Segmenter`, it gives the code points. */\nexport function graphemesOf(text: string): string[] {\n const segmenter = segmenterOf(\"grapheme\");\n if (segmenter !== null) return Array.from(segmenter.segment(text), (s) => s.segment);\n return Array.from(text);\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\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\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/** 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 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 = words.map((w) => w.text).join(\" \");\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, Math.max(0, words.length - 1)) * 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 * Math.max(0, ws.length - 1);\n };\n const widths = words.map(width);\n const natural = widths.reduce((s, w) => s + w, 0) + space * Math.max(0, words.length - 1);\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 of one space between two words.\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 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({ type: \"glue\", text: \" \", width: space });\n items.push({ type: \"box\", text: word.text, width: w });\n }\n });\n const paragraph = { items };\n const lines: Line[] = linesOf(paragraph, breaker.breaks(paragraph, limit)).map((l) => ({ text: l.text, units: l.width }));\n if (lines.length === 0) lines.push({ text: \"\", units: 0 });\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 }\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 };\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)}`;\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 );\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 and the character set.\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 key = `${idOf(layoutOptions.measurer)},${generation},${charset},${optionsKey(layoutOptions)}`;\n const layouts = groups.get(key) ?? new Map<string, TextLayout>();\n if (groups.delete(key)) groups.set(key, layouts);\n return { options: { ...layoutOptions }, 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 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":";;;AAUA,MAAa,aAAa;;AA4B1B,SAAgB,QAAQ,MAAsB;CAC5C,OAAO,KAAK,KAAK,CAAC,CAAC,QAAQ,QAAQ,GAAG;AACxC;;;;;AAMA,SAAgB,eAAe,SAAoB,UAA2B,CAAC,GAAiB;CAC9F,MAAM,MAAM,QAAQ,cAAc;CAClC,IAAI,EAAE,OAAO,UAAU,GAAG,KAAK,OAAO,IAAI,MAAM,IAAI,WAAW,8DAA8D,IAAI,EAAE;CACnI,MAAM,wBAAQ,IAAI,IAAoB;CACtC,IAAI,WAAW;CACf,IAAI,OAAO;CACX,IAAI,QAAQ;CACZ,IAAI,aAAa;CACjB,OAAO;EACL,QAAQ,SAAS,MAAM;GACrB;GACA,MAAM,MAAM,GAAG,QAAQ,IAAI,EAAE,QAAQ;GACrC,MAAM,QAAQ,MAAM,IAAI,GAAG;GAC3B,IAAI,UAAU,KAAA,GAAW;IACvB;IACA,OAAO;GACT;GACA;GACA,MAAM,KAAK,QAAQ,SAAS,IAAI;GAChC,IAAI,CAAC,OAAO,SAAS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":"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 { breakers, linesOf, type Box, 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\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\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/** 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 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 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 ? { type: \"glue\", text: \" \", width: space } : NO_GAP);\n items.push({ type: \"box\", text: word.text, width: w });\n }\n });\n const paragraph = { items };\n const lines: Line[] = linesOf(paragraph, breaker.breaks(paragraph, limit)).map((l) => ({ text: l.text, units: l.width }));\n if (lines.length === 0) lines.push({ text: \"\", units: 0 });\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 }\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 };\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)}`;\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 );\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 and the character set.\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 key = `${idOf(layoutOptions.measurer)},${generation},${charset},${optionsKey(layoutOptions)}`;\n const layouts = groups.get(key) ?? new Map<string, TextLayout>();\n if (groups.delete(key)) groups.set(key, layouts);\n return { options: { ...layoutOptions }, 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 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,M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K;EAAU,WAAW;EAAG,QAAQ;CAAO;CAC3G;EAAE,IAAI;EAAmB,MAAM;EAAU,WAAW;EAAS,KAAK;EAAG,KAAK;EAAG,WAAW;EAAO,QAAQ;CAAO;CAC9G;EAAE,IAAI;EAAiB,MAAM;EAA2B,WAAW;EAAS,KAAK;EAAG,KAAK;EAAU,OAAO;EAAG,KAAK;EAAG,WAAW;EAAG,QAAQ;EAAQ,MAAM;CAAQ;CACjK;EAAE,IAAI;EAAiB,MAAM;EAAU,WAAW;EAAU,KAAK;EAAG,KAAK;EAAG,QAAQ;EAAQ,MAAM;CAAa;CAC/G;EAAE,IAAI;EAAW,MAAM;EAAgB,WAAW;EAAS,KAAK;EAAG,KAAK;EAAU,QAAQ;EAAQ,MAAM;CAAO;AACjH,CAAU;;;;;;AAOV,SAAgB,aAAa,QAAoB,OAA+D;CAC9G,MAAM,IAAI,OAAO;CACjB,MAAM,OAAO,OAAO,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"}
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.5.5",
4
+ "version": "0.6.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",
@@ -60,7 +60,7 @@
60
60
  },
61
61
  "dependencies": {
62
62
  "@mark1russell7/rigor-generators": "^0.1.0",
63
- "@mark1russell7/typeset": "^0.1.0"
63
+ "@mark1russell7/typeset": "^0.1.8"
64
64
  },
65
65
  "scripts": {
66
66
  "build": "tsdown",
@@ -5,10 +5,13 @@ import { type AnyOption, declarationIssues, type ListItem, type NoDefaultReason,
5
5
  import type { ParamValue, StrategySpace } from "./strategy-space.ts";
6
6
 
7
7
  /** The newest schema of a strategy catalog. A new field is a new version of the schema. */
8
- export const STRATEGY_CATALOG_SCHEMA = "strategy-catalog/2";
8
+ export const STRATEGY_CATALOG_SCHEMA = "strategy-catalog/3";
9
9
 
10
- /** The schemas that `parseStrategyCatalog` reads, oldest first. Schema 2 adds the field `output` of an entry. */
11
- export const STRATEGY_CATALOG_SCHEMAS: readonly ["strategy-catalog/1", "strategy-catalog/2"] = ["strategy-catalog/1", STRATEGY_CATALOG_SCHEMA];
10
+ /** The schemas that `parseStrategyCatalog` reads, oldest first. Schema 2 adds the field `output` of an entry, and schema 3 adds the field `fingerprint`. */
11
+ export const STRATEGY_CATALOG_SCHEMAS: readonly ["strategy-catalog/1", "strategy-catalog/2", "strategy-catalog/3"] = ["strategy-catalog/1", "strategy-catalog/2", STRATEGY_CATALOG_SCHEMA];
12
+
13
+ /** The form of the field `fingerprint` of an entry: the 16 lowercase hex digits that `fingerprintOf` gives. */
14
+ const FINGERPRINT = /^[0-9a-f]{16}$/u;
12
15
 
13
16
  /** The name of one schema of a strategy catalog. */
14
17
  export type StrategyCatalogSchema = (typeof STRATEGY_CATALOG_SCHEMAS)[number];
@@ -113,6 +116,8 @@ export interface CatalogEntry {
113
116
  readonly baseline?: true;
114
117
  /** The reads of the output of the strategy. A file with this field has the schema 2. */
115
118
  readonly output?: readonly OutputRow[];
119
+ /** The fingerprint of the outputs of the strategy on the probes of its engine, from `fingerprintOf`. A file with this field has the schema 3. */
120
+ readonly fingerprint?: string;
116
121
  /** The declarations of the options, in the order of a form. */
117
122
  readonly options: Readonly<Record<string, AnyOption>>;
118
123
  }
@@ -210,7 +215,7 @@ const STRATEGY_KINDS: readonly string[] = ["single", "composite", "shape"];
210
215
  const NO_DEFAULT_REASONS: readonly NoDefaultReason[] = ["unset", "required", "derived", "function"];
211
216
  const SCALES: readonly OptionScale[] = ["linear", "log"];
212
217
  const TOP_FIELDS: readonly string[] = ["schema", "engine", "version", "strategies"];
213
- const ENTRY_FIELDS: readonly string[] = ["key", "id", "step", "family", "kind", "describe", "supports", "limits", "deterministic", "determinismNote", "optIn", "baseline", "output", "options"];
218
+ const ENTRY_FIELDS: readonly string[] = ["key", "id", "step", "family", "kind", "describe", "supports", "limits", "deterministic", "determinismNote", "optIn", "baseline", "output", "fingerprint", "options"];
214
219
  const COMMON_FIELDS: readonly string[] = ["type", "describe", "default", "noDefault", "when"];
215
220
  const NUMBER_FIELDS: readonly string[] = [...COMMON_FIELDS, "min", "max", "step", "scale", "special", "marks", "values"];
216
221
  const ENUM_FIELDS: readonly string[] = [...COMMON_FIELDS, "values", "custom"];
@@ -479,7 +484,7 @@ function checkEvidence(at: string, property: unknown, rowClass: unknown, raw: un
479
484
 
480
485
  /** This function adds the faults of the field `output` of one entry. */
481
486
  function checkOutput(at: string, raw: unknown, schema: unknown, faults: string[]): void {
482
- if (schema === STRATEGY_CATALOG_SCHEMAS[0]) faults.push(`${at}: the field "output" needs the schema ${STRATEGY_CATALOG_SCHEMA}.`);
487
+ if (schema === STRATEGY_CATALOG_SCHEMAS[0]) faults.push(`${at}: the field "output" needs the schema ${STRATEGY_CATALOG_SCHEMAS[1]} or a newer schema.`);
483
488
  if (!Array.isArray(raw) || raw.length === 0) {
484
489
  faults.push(`${at}: "output" is not a list with rows.`);
485
490
  return;
@@ -519,6 +524,10 @@ function readEntry(at: string, raw: unknown, schema: unknown, faults: string[]):
519
524
  if (!isFields(raw["supports"]) || !Object.values(raw["supports"]).every(isTextList)) faults.push(`${at}: "supports" is not a record of text lists.`);
520
525
  checkLimits(at, raw["limits"], faults);
521
526
  if (raw["output"] !== undefined) checkOutput(at, raw["output"], schema, faults);
527
+ if (raw["fingerprint"] !== undefined) {
528
+ if (schema !== STRATEGY_CATALOG_SCHEMAS[2]) faults.push(`${at}: the field "fingerprint" needs the schema ${STRATEGY_CATALOG_SCHEMAS[2]}.`);
529
+ if (!isText(raw["fingerprint"]) || !FINGERPRINT.test(raw["fingerprint"])) faults.push(`${at}: "fingerprint" is not 16 lowercase hex digits.`);
530
+ }
522
531
  if (isText(raw["id"]) && raw["key"] !== catalogKey(raw["id"], raw["step"] as string | undefined)) faults.push(`${at}: the key does not follow from "step" and "id".`);
523
532
  if (!isFields(raw["options"])) {
524
533
  faults.push(`${at}: "options" is not an object.`);
@@ -552,6 +561,7 @@ function readEntry(at: string, raw: unknown, schema: unknown, faults: string[]):
552
561
  optIn: raw["optIn"] as boolean,
553
562
  ...(raw["baseline"] === true ? { baseline: true as const } : {}),
554
563
  ...(raw["output"] === undefined ? {} : { output: raw["output"] as readonly OutputRow[] }),
564
+ ...(raw["fingerprint"] === undefined ? {} : { fingerprint: raw["fingerprint"] as string }),
555
565
  options,
556
566
  };
557
567
  }
@@ -726,6 +736,7 @@ function writeEntry(e: CatalogEntry): Fields {
726
736
  optIn: e.optIn,
727
737
  ...(e.baseline === true ? { baseline: true } : {}),
728
738
  ...(e.output === undefined ? {} : { output: e.output.map(writeRow) }),
739
+ ...(e.fingerprint === undefined ? {} : { fingerprint: e.fingerprint }),
729
740
  options,
730
741
  };
731
742
  }
@@ -741,12 +752,14 @@ function unsafeValues(v: unknown, at: string): string[] {
741
752
 
742
753
  /**
743
754
  * This function gives the text of the catalog file, sorted by key. The same source and version give the same bytes.
744
- * The file has the oldest schema that holds it, so a catalog with no `output` stays valid for a reader of the schema 1.
755
+ * The file has the oldest schema that holds it. A catalog with no `output` and no `fingerprint` stays valid for a reader of the schema 1.
756
+ * A catalog with no `fingerprint` stays valid for a reader of the schema 2.
745
757
  * The caller gives the version from `package.json`. The function throws an error if the file breaks a rule of the format.
746
758
  */
747
759
  export function writeStrategyCatalog(source: StrategyCatalogSource, version: string): string {
748
760
  const strategies = [...source.strategies].sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0)).map(writeEntry);
749
- const schema = source.strategies.some((e) => e.output !== undefined) ? STRATEGY_CATALOG_SCHEMA : STRATEGY_CATALOG_SCHEMAS[0];
761
+ const has = (field: "output" | "fingerprint"): boolean => source.strategies.some((e) => e[field] !== undefined);
762
+ const schema = has("fingerprint") ? STRATEGY_CATALOG_SCHEMAS[2] : has("output") ? STRATEGY_CATALOG_SCHEMAS[1] : STRATEGY_CATALOG_SCHEMAS[0];
750
763
  const doc = { schema, engine: source.engine, version, strategies };
751
764
  const unsafe = unsafeValues(doc, "catalog");
752
765
  if (unsafe.length > 0) throw new Error(`The catalog of ${source.engine} has values that JSON cannot hold: ${unsafe.join(" ")}`);