@mark1russell7/layout-contract 0.2.19 → 0.2.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/text.ts ADDED
@@ -0,0 +1,311 @@
1
+ import type { MeasureSpec } from "./measures.ts";
2
+
3
+ /**
4
+ * The advance function of a host: the width of a run of text in a font, in pixels.
5
+ * A browser host gives `canvasAdvance(context)`. A test or a server host gives a function of a font file.
6
+ */
7
+ export type AdvanceFn = (text: string, font: string) => number;
8
+
9
+ /** 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. */
10
+ export const TEXT_UNITS = 64;
11
+
12
+ /** The counts of a measurer: the requests, the cache hits and the calls of the advance function. */
13
+ export interface MeasurerStats {
14
+ readonly requests: number;
15
+ readonly hits: number;
16
+ readonly calls: number;
17
+ }
18
+
19
+ /** A measurer: the advance of a segment in a font, in whole units of 1/`TEXT_UNITS` pixel, with a cache. */
20
+ export interface TextMeasurer {
21
+ /** This function gives the advance of the segment in the font, in units. */
22
+ advance(segment: string, font: string): number;
23
+ /** This function gives the counts since the start or since the last `reset`. */
24
+ stats(): MeasurerStats;
25
+ /** This function clears the cache and the counts. */
26
+ reset(): void;
27
+ }
28
+
29
+ /** The options of `createMeasurer`. */
30
+ export interface MeasurerOptions {
31
+ /** The count of the cache entries. The default is 10000. With 0, the measurer has no cache. */
32
+ readonly maxEntries?: number;
33
+ }
34
+
35
+ /** This function gives the key of a font: the font string with its white space collapsed and trimmed. */
36
+ export function fontKey(font: string): string {
37
+ return font.trim().replace(/\s+/g, " ");
38
+ }
39
+
40
+ /**
41
+ * This function gives a measurer with a cache keyed by the font and the segment.
42
+ * The cache removes its oldest entry when it is full. The advance function rounds each width to whole units.
43
+ */
44
+ export function createMeasurer(measure: AdvanceFn, options: MeasurerOptions = {}): TextMeasurer {
45
+ const max = options.maxEntries ?? 10000;
46
+ if (!(Number.isInteger(max) && max >= 0)) throw new RangeError(`createMeasurer: maxEntries is an integer of 0 or more, not ${max}.`);
47
+ const cache = new Map<string, number>();
48
+ let requests = 0;
49
+ let hits = 0;
50
+ let calls = 0;
51
+ return {
52
+ advance(segment, font) {
53
+ requests++;
54
+ const key = `${fontKey(font)}\u0000${segment}`;
55
+ const known = cache.get(key);
56
+ if (known !== undefined) {
57
+ hits++;
58
+ return known;
59
+ }
60
+ calls++;
61
+ const px = measure(segment, font);
62
+ 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.`);
63
+ const units = Math.round(px * TEXT_UNITS);
64
+ if (max > 0) {
65
+ if (cache.size >= max) cache.delete(cache.keys().next().value!);
66
+ cache.set(key, units);
67
+ }
68
+ return units;
69
+ },
70
+ stats: () => ({ requests, hits, calls }),
71
+ reset() {
72
+ cache.clear();
73
+ requests = 0;
74
+ hits = 0;
75
+ calls = 0;
76
+ },
77
+ };
78
+ }
79
+
80
+ /** The part of a canvas context that `canvasAdvance` uses. */
81
+ export interface CanvasTextContext {
82
+ font: string;
83
+ measureText(text: string): { readonly width: number };
84
+ }
85
+
86
+ /** 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. */
87
+ export function canvasAdvance(context: CanvasTextContext): AdvanceFn {
88
+ let current: string | undefined;
89
+ return (text, font) => {
90
+ if (font !== current) {
91
+ context.font = font;
92
+ current = font;
93
+ }
94
+ return context.measureText(text).width;
95
+ };
96
+ }
97
+
98
+ /** A word of a text: its segments, which the measurer measures and caches one by one. */
99
+ interface Word {
100
+ readonly text: string;
101
+ readonly parts: readonly string[];
102
+ }
103
+
104
+ const SPACE = /^\s+$/u;
105
+
106
+ /** 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. */
107
+ function wordsOf(text: string): Word[] {
108
+ const words: Word[] = [];
109
+ let parts: string[] = [];
110
+ const flush = (): void => {
111
+ if (parts.length > 0) words.push({ text: parts.join(""), parts });
112
+ parts = [];
113
+ };
114
+ if (typeof Intl !== "undefined" && typeof Intl.Segmenter === "function") {
115
+ for (const s of new Intl.Segmenter(undefined, { granularity: "word" }).segment(text)) {
116
+ if (SPACE.test(s.segment)) flush();
117
+ else parts.push(s.segment);
118
+ }
119
+ } else {
120
+ for (const s of text.split(/(\s+)/u)) {
121
+ if (s === "" || SPACE.test(s)) flush();
122
+ else parts.push(s);
123
+ }
124
+ }
125
+ flush();
126
+ return words;
127
+ }
128
+
129
+ /** This function gives the grapheme clusters of a text. Without `Intl.Segmenter`, it gives the code points. */
130
+ export function graphemesOf(text: string): string[] {
131
+ if (typeof Intl !== "undefined" && typeof Intl.Segmenter === "function") return Array.from(new Intl.Segmenter(undefined, { granularity: "grapheme" }).segment(text), (s) => s.segment);
132
+ return Array.from(text);
133
+ }
134
+
135
+ /** The options of `layoutText`. All lengths are in pixels. */
136
+ export interface TextLayoutOptions {
137
+ readonly font: string;
138
+ readonly measurer: TextMeasurer;
139
+ /** The line height. A finite number above 0. */
140
+ readonly lineHeight: number;
141
+ /** The width of the lines of a text that does not fit on one line. Without it, the text stays on one line. */
142
+ readonly wrapWidth?: number;
143
+ /** The count of the lines. The last line that stays gets the ellipsis. The default is no limit. */
144
+ readonly maxLines?: number;
145
+ /** The count of the grapheme clusters. A longer text keeps `maxChars` clusters with the ellipsis at the end. The default is no limit. */
146
+ readonly maxChars?: number;
147
+ /** The text at the end of a cut text. The default is "…". */
148
+ readonly ellipsis?: string;
149
+ /** The space that the box adds to the width of the text. The default is 0. */
150
+ readonly padding?: number;
151
+ /** The smallest width of a box with one line. The default is 0. */
152
+ readonly minWidth?: number;
153
+ /** 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`. */
154
+ readonly maxWidth?: number;
155
+ /**
156
+ * The break of a word that is wider than a line. `keep` (the default) keeps the word whole, and the line overflows.
157
+ * `anywhere` breaks it between two grapheme clusters, as the CSS `overflow-wrap: anywhere`.
158
+ */
159
+ readonly wordBreak?: "keep" | "anywhere";
160
+ }
161
+
162
+ /** The layout of a text: its lines and its box. */
163
+ export interface TextLayout {
164
+ readonly lines: readonly string[];
165
+ /** The width of each line, in pixels. Each width is a whole number of units of 1/`TEXT_UNITS` pixel. */
166
+ readonly widths: readonly number[];
167
+ readonly lineCount: number;
168
+ /** The width of the box: the text and the padding. */
169
+ readonly width: number;
170
+ readonly height: number;
171
+ /** The width of the lines, or `undefined` for a text on one line. */
172
+ readonly wrapWidth?: number;
173
+ /** `true` when `maxChars` or `maxLines` cut the text. */
174
+ readonly truncated: boolean;
175
+ }
176
+
177
+ /** A line of a layout, with its width in units. */
178
+ interface Line {
179
+ text: string;
180
+ units: number;
181
+ }
182
+
183
+ /**
184
+ * 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`.
185
+ *
186
+ * The breaker is greedy, as a browser with `white-space: normal`. It collapses each run of white space to one space, and a line does not count its last space.
187
+ * 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.
188
+ */
189
+ export function layoutText(text: string, options: TextLayoutOptions): TextLayout {
190
+ const { font, measurer, lineHeight } = options;
191
+ if (!(Number.isFinite(lineHeight) && lineHeight > 0)) throw new RangeError(`layoutText: lineHeight is a finite number above 0, not ${lineHeight}.`);
192
+ const ellipsis = options.ellipsis ?? "…";
193
+ const padding = options.padding ?? 0;
194
+ const keep = (options.wordBreak ?? "keep") === "keep";
195
+ let truncated = false;
196
+
197
+ let source = text;
198
+ if (options.maxChars !== undefined) {
199
+ const clusters = graphemesOf(source);
200
+ if (clusters.length > options.maxChars) {
201
+ const room = Math.max(0, options.maxChars - graphemesOf(ellipsis).length);
202
+ source = clusters.slice(0, room).join("") + ellipsis;
203
+ truncated = true;
204
+ }
205
+ }
206
+
207
+ const words = wordsOf(source);
208
+ const space = measurer.advance(" ", font);
209
+ const width = (w: Word): number => w.parts.reduce((s, p) => s + measurer.advance(p, font), 0);
210
+ const lineUnits = (line: string): number => {
211
+ const ws = wordsOf(line);
212
+ return ws.reduce((s, w) => s + width(w), 0) + space * Math.max(0, ws.length - 1);
213
+ };
214
+ const widths = words.map(width);
215
+ const natural = widths.reduce((s, w) => s + w, 0) + space * Math.max(0, words.length - 1);
216
+
217
+ const maxWidth = options.maxWidth ?? (options.wrapWidth === undefined ? Infinity : options.wrapWidth + padding);
218
+ const fits = natural / TEXT_UNITS + padding <= maxWidth;
219
+ if (options.wrapWidth === undefined || fits) {
220
+ const one = words.map((w) => w.text).join(" ");
221
+ const px = natural / TEXT_UNITS;
222
+ const box = Math.min(maxWidth, Math.max(options.minWidth ?? 0, px + padding));
223
+ return { lines: [one], widths: [px], lineCount: 1, width: box, height: lineHeight, truncated };
224
+ }
225
+
226
+ const limit = Math.round(options.wrapWidth * TEXT_UNITS);
227
+ const lines: Line[] = [];
228
+ let cur: Line | undefined;
229
+ const push = (): void => {
230
+ if (cur !== undefined) lines.push(cur);
231
+ cur = undefined;
232
+ };
233
+ /** This function puts a word that is wider than a line on new lines, with a break between grapheme clusters. */
234
+ const split = (word: Word): void => {
235
+ for (const g of graphemesOf(word.text)) {
236
+ const w = measurer.advance(g, font);
237
+ if (cur !== undefined && cur.units + w > limit) push();
238
+ if (cur === undefined) cur = { text: g, units: w };
239
+ else {
240
+ cur.text += g;
241
+ cur.units += w;
242
+ }
243
+ }
244
+ };
245
+ words.forEach((word, i) => {
246
+ const w = widths[i]!;
247
+ if (cur !== undefined && cur.units + space + w <= limit) {
248
+ cur.text += ` ${word.text}`;
249
+ cur.units += space + w;
250
+ return;
251
+ }
252
+ push();
253
+ if (w > limit && !keep) split(word);
254
+ else cur = { text: word.text, units: w };
255
+ });
256
+ push();
257
+ if (lines.length === 0) lines.push({ text: "", units: 0 });
258
+
259
+ const maxLines = options.maxLines ?? Infinity;
260
+ if (lines.length > maxLines) {
261
+ lines.length = Math.max(1, maxLines);
262
+ const last = lines[lines.length - 1]!;
263
+ const tail = measurer.advance(ellipsis, font);
264
+ const clusters = graphemesOf(last.text);
265
+ while (clusters.length > 0 && lineUnits(clusters.join("")) + tail > limit) clusters.pop();
266
+ const kept = clusters.join("").replace(/\s+$/u, "");
267
+ last.text = kept + ellipsis;
268
+ last.units = lineUnits(kept) + tail;
269
+ truncated = true;
270
+ }
271
+
272
+ return {
273
+ lines: lines.map((l) => l.text),
274
+ widths: lines.map((l) => l.units / TEXT_UNITS),
275
+ lineCount: lines.length,
276
+ width: options.wrapWidth + padding,
277
+ height: lines.length * lineHeight,
278
+ wrapWidth: options.wrapWidth,
279
+ truncated,
280
+ };
281
+ }
282
+
283
+ /** The id of a text measure. `docs/TEXT.md` gives the definitions. */
284
+ export type TextMeasureId = "text.lines" | "text.raggedness" | "text.overflow" | "text.cacheHit" | "text.ms";
285
+
286
+ /** The specs of the text measures. */
287
+ export const TEXT_MEASURES: readonly MeasureSpec<TextMeasureId>[] = Object.freeze([
288
+ { id: "text.lines", unit: "count", direction: "lower", min: 1, max: Infinity, minEffect: 0, family: "text" },
289
+ { id: "text.raggedness", unit: "0 to 1", direction: "lower", min: 0, max: 1, minEffect: 0.005, family: "text" },
290
+ { 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" },
291
+ { id: "text.cacheHit", unit: "0 to 1", direction: "higher", min: 0, max: 1, family: "text", role: "diagnostic" },
292
+ { id: "text.ms", unit: "milliseconds", direction: "lower", min: 0, max: Infinity, family: "text", role: "time" },
293
+ ] as const);
294
+
295
+ /**
296
+ * 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.
297
+ * `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.
298
+ * With `stats`, the measures also hold `text.cacheHit`: the hits divided by the requests.
299
+ */
300
+ export function textMeasures(layout: TextLayout, stats?: MeasurerStats): Partial<Record<TextMeasureId, number>> {
301
+ const w = layout.wrapWidth;
302
+ const body = layout.widths.slice(0, -1);
303
+ const raggedness = w === undefined || body.length === 0 ? 0 : body.reduce((s, x) => s + (Math.max(0, w - x) / w) ** 2, 0) / body.length;
304
+ const overflow = w === undefined ? 0 : Math.max(0, ...layout.widths.map((x) => (x - w) / w));
305
+ return {
306
+ "text.lines": layout.lineCount,
307
+ "text.raggedness": raggedness,
308
+ "text.overflow": overflow,
309
+ ...(stats === undefined ? {} : { "text.cacheHit": stats.requests === 0 ? 0 : stats.hits / stats.requests }),
310
+ };
311
+ }