@mark1russell7/layout-contract 0.3.5 → 0.3.6
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/README.md +1 -1
- package/build/text.d.ts +45 -1
- package/build/text.d.ts.map +1 -1
- package/build/text.js +105 -21
- package/build/text.js.map +1 -1
- package/package.json +5 -4
- package/src/text.ts +144 -20
package/README.md
CHANGED
|
@@ -16,7 +16,7 @@ The package has one runtime dependency: `@mark1russell7/rigor-generators`, the h
|
|
|
16
16
|
| The strategies | `StrategyInfo` |
|
|
17
17
|
| The measures | `MeasureSpec`, `Direction`, `JointMeasureId`, `JOINT_MEASURES`, `JOINT_MOVED_MIN`, `Verdict`, `compareMeasure`, `minEffectOf` |
|
|
18
18
|
| The balance and stability measures | `balanceOf`, `Balance`, `nearestGaps`, `procrustesOf`, `ProcrustesOptions`, `perChange`, `balanceMeasures`, `balanceMeasureSpecs`, `BALANCE_MEASURE_SUFFIXES`, `BalanceMeasureSuffix`, `BALANCE_SIDE_DEPTH`, `PlacedBox` |
|
|
19
|
-
| Text layout, in the subpath `/text` | `layoutText`, `TextLayout`, `TextLayoutOptions`, `createTextLayoutCache`, `TextLayoutCache`, `TextLayoutCacheOptions`, `TextLayoutCacheStats`, `createMeasurer`, `TextMeasurer`, `canvasAdvance`, `AdvanceFn`, `fontKey`, `graphemesOf`, `textMeasures`, `TEXT_MEASURES`, `TEXT_UNITS` |
|
|
19
|
+
| Text layout, in the subpath `/text` | `layoutText`, `TextLayout`, `TextLayoutOptions`, `TextSizing`, `createTextCharset`, `TextCharset`, `TextCharsetOptions`, `DIGITS`, `PRINTABLE_ASCII`, `createTextLayoutCache`, `TextLayoutCache`, `TextLayoutCacheOptions`, `TextLayoutCacheStats`, `createMeasurer`, `TextMeasurer`, `canvasAdvance`, `AdvanceFn`, `fontKey`, `graphemesOf`, `textMeasures`, `TEXT_MEASURES`, `TEXT_UNITS` |
|
|
20
20
|
| The edges step | `edgeStep`, `EdgeShape`, `EdgeStepParams`, `EDGE_DENSITY`, `EDGE_STEP_VERSION` |
|
|
21
21
|
| The random numbers | `mulberry32`, `fnv1a32`, `stepRandom`, `randomInt` |
|
|
22
22
|
| The hashes | `sha256Hex`, `canonicalJson`, `documentHash`, `outputHash`, `HashOptions` |
|
package/build/text.d.ts
CHANGED
|
@@ -46,6 +46,38 @@ export interface CanvasTextContext {
|
|
|
46
46
|
export declare function canvasAdvance(context: CanvasTextContext): AdvanceFn;
|
|
47
47
|
/** This function gives the grapheme clusters of a text. Without `Intl.Segmenter`, it gives the code points. */
|
|
48
48
|
export declare function graphemesOf(text: string): string[];
|
|
49
|
+
/** The digits, as a value for `createTextCharset`. */
|
|
50
|
+
export declare const DIGITS = "0123456789";
|
|
51
|
+
/** The printable characters of ASCII with the space, as a value for `createTextCharset`. */
|
|
52
|
+
export declare const PRINTABLE_ASCII = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
|
|
53
|
+
/** The options of `createTextCharset`. */
|
|
54
|
+
export interface TextCharsetOptions {
|
|
55
|
+
/**
|
|
56
|
+
* 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.
|
|
57
|
+
* A kerning pair that is narrower adds no width. Give a value for a font with kerning pairs or ligatures that are wider.
|
|
58
|
+
*/
|
|
59
|
+
readonly pairMargin?: number;
|
|
60
|
+
}
|
|
61
|
+
/** A declared character set. A caller asks for it with `createTextCharset`. It is frozen, so `createTextLayoutCache` can use its identity as a key. */
|
|
62
|
+
export interface TextCharset {
|
|
63
|
+
readonly characters: string;
|
|
64
|
+
/** This function tells if each code point of the text is a member of the set. */
|
|
65
|
+
covers(text: string): boolean;
|
|
66
|
+
/**
|
|
67
|
+
* This function gives the bound of one UTF-16 code unit of a member in the font, in units of 1/`TEXT_UNITS` pixel.
|
|
68
|
+
* It measures each member once for a measurer with `generation`, and again after a `reset`. It measures on each call for a different measurer.
|
|
69
|
+
* It gives `undefined` when a member has no positive finite advance: that is a gap in the font.
|
|
70
|
+
*/
|
|
71
|
+
unit(font: string, measurer: TextMeasurer): number | undefined;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* This function gives a declared character set. A member is one code point with a plain advance.
|
|
75
|
+
* 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`.
|
|
76
|
+
* 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.
|
|
77
|
+
*/
|
|
78
|
+
export declare function createTextCharset(characters: string, options?: TextCharsetOptions): TextCharset;
|
|
79
|
+
/** The source of the width of a label. The option `sizing` of `layoutText` tells each value. */
|
|
80
|
+
export type TextSizing = "exact" | "bound-first" | "bound";
|
|
49
81
|
/** The options of `layoutText`. All lengths are in pixels. */
|
|
50
82
|
export interface TextLayoutOptions {
|
|
51
83
|
readonly font: string;
|
|
@@ -76,6 +108,14 @@ export interface TextLayoutOptions {
|
|
|
76
108
|
* makes the lines more equal. `balanced` keeps the greedy line count with the least width.
|
|
77
109
|
*/
|
|
78
110
|
readonly breaker?: "greedy" | "total-fit" | "balanced";
|
|
111
|
+
/**
|
|
112
|
+
* The source of the width of a label. `exact` (the default) measures each label.
|
|
113
|
+
* `bound-first` keeps a label of `charset` on one line with no measure when its bound fits. It measures each other label.
|
|
114
|
+
* `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.
|
|
115
|
+
*/
|
|
116
|
+
readonly sizing?: TextSizing;
|
|
117
|
+
/** The declared character set of `sizing`. `bound-first` and `bound` need it, and `exact` does not read it. */
|
|
118
|
+
readonly charset?: TextCharset;
|
|
79
119
|
}
|
|
80
120
|
/** The layout of a text: its lines and its box. */
|
|
81
121
|
export interface TextLayout {
|
|
@@ -90,6 +130,8 @@ export interface TextLayout {
|
|
|
90
130
|
readonly wrapWidth?: number;
|
|
91
131
|
/** `true` when `maxChars` or `maxLines` cut the text. */
|
|
92
132
|
readonly truncated: boolean;
|
|
133
|
+
/** `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. */
|
|
134
|
+
readonly bounded?: true;
|
|
93
135
|
}
|
|
94
136
|
/**
|
|
95
137
|
* 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`.
|
|
@@ -97,6 +139,8 @@ export interface TextLayout {
|
|
|
97
139
|
* The breaker comes from `@mark1russell7/typeset`. The default is greedy, as a browser with `white-space: normal`.
|
|
98
140
|
* It collapses each run of white space to one space, and a line does not count its last space.
|
|
99
141
|
* 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.
|
|
142
|
+
*
|
|
143
|
+
* 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.
|
|
100
144
|
*/
|
|
101
145
|
export declare function layoutText(text: string, options: TextLayoutOptions): TextLayout;
|
|
102
146
|
/** The counts of a `TextLayoutCache`. `calls` is the count of the `layoutText` calls, and `size` is the count of the entries. */
|
|
@@ -121,7 +165,7 @@ export interface TextLayoutCache {
|
|
|
121
165
|
reset(): void;
|
|
122
166
|
}
|
|
123
167
|
/**
|
|
124
|
-
* This function gives a bounded cache of `layoutText` results, keyed by the text, the options and the
|
|
168
|
+
* This function gives a bounded cache of `layoutText` results, keyed by the text, the options, the measurer and the character set.
|
|
125
169
|
* 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.
|
|
126
170
|
* The key holds the raw font string, because a host can give two spellings of a font two different advances.
|
|
127
171
|
* 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.
|
package/build/text.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"text.d.ts","names":[],"sources":["../src/text.ts"],"mappings":";;;;;YAOY,aAAa,cAAc;;qBAG1B;;iBAGI;WACN;WACA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112,64 @@ function graphemesOf(text) {
|
|
|
112
112
|
if (segmenter !== null) return Array.from(segmenter.segment(text), (s) => s.segment);
|
|
113
113
|
return Array.from(text);
|
|
114
114
|
}
|
|
115
|
+
/** The digits, as a value for `createTextCharset`. */
|
|
116
|
+
const DIGITS = "0123456789";
|
|
117
|
+
/** The printable characters of ASCII with the space, as a value for `createTextCharset`. */
|
|
118
|
+
const PRINTABLE_ASCII = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
|
|
119
|
+
/** 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. */
|
|
120
|
+
const SIMPLE_SCRIPT = /^[\p{Script=Common}\p{Script=Latin}\p{Script=Greek}\p{Script=Cyrillic}\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]$/u;
|
|
121
|
+
/** The characters that are not plain advances: marks, control and format characters, emoji parts, and each white space but the space. */
|
|
122
|
+
const NOT_AN_ADVANCE = /[\p{M}\p{C}\p{Extended_Pictographic}\p{Emoji_Modifier}\p{Regional_Indicator}]|[^\S ]/u;
|
|
123
|
+
/** The largest count of fonts in the memo of a character set for one measurer. */
|
|
124
|
+
const CHARSET_FONTS = 64;
|
|
125
|
+
/**
|
|
126
|
+
* This function gives a declared character set. A member is one code point with a plain advance.
|
|
127
|
+
* 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`.
|
|
128
|
+
* 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.
|
|
129
|
+
*/
|
|
130
|
+
function createTextCharset(characters, options = {}) {
|
|
131
|
+
const pairMargin = options.pairMargin ?? 0;
|
|
132
|
+
if (!(Number.isFinite(pairMargin) && pairMargin >= 0)) throw new RangeError(`createTextCharset: pairMargin is a finite number of 0 or more, not ${pairMargin}.`);
|
|
133
|
+
const members = new Set(characters);
|
|
134
|
+
if (members.size === 0) throw new RangeError("createTextCharset: the set has no character.");
|
|
135
|
+
for (const c of members) 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.`);
|
|
136
|
+
/** 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. */
|
|
137
|
+
const scan = (font, measurer) => {
|
|
138
|
+
let largest = 0;
|
|
139
|
+
for (const c of members) {
|
|
140
|
+
const units = measurer.advance(c, font);
|
|
141
|
+
if (!(Number.isFinite(units) && units > 0)) return void 0;
|
|
142
|
+
largest = Math.max(largest, units);
|
|
143
|
+
}
|
|
144
|
+
return Math.ceil((largest + 1) * (1 + pairMargin));
|
|
145
|
+
};
|
|
146
|
+
const memo = /* @__PURE__ */ new WeakMap();
|
|
147
|
+
return Object.freeze({
|
|
148
|
+
characters,
|
|
149
|
+
covers(text) {
|
|
150
|
+
for (const c of text) if (!members.has(c)) return false;
|
|
151
|
+
return true;
|
|
152
|
+
},
|
|
153
|
+
unit(font, measurer) {
|
|
154
|
+
const generation = measurer.generation?.();
|
|
155
|
+
if (generation === void 0) return scan(font, measurer);
|
|
156
|
+
let fonts = memo.get(measurer);
|
|
157
|
+
if (fonts === void 0) {
|
|
158
|
+
fonts = /* @__PURE__ */ new Map();
|
|
159
|
+
memo.set(measurer, fonts);
|
|
160
|
+
}
|
|
161
|
+
const known = fonts.get(font);
|
|
162
|
+
if (known?.generation === generation) return known.unit;
|
|
163
|
+
const unit = scan(font, measurer);
|
|
164
|
+
if (fonts.size >= CHARSET_FONTS) fonts.delete(fonts.keys().next().value);
|
|
165
|
+
fonts.set(font, {
|
|
166
|
+
generation,
|
|
167
|
+
unit
|
|
168
|
+
});
|
|
169
|
+
return unit;
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
}
|
|
115
173
|
/** A forced break: a penalty with no text, no width and the cost `-Infinity`. */
|
|
116
174
|
const FORCED = {
|
|
117
175
|
type: "penalty",
|
|
@@ -121,6 +179,10 @@ const FORCED = {
|
|
|
121
179
|
flagged: false
|
|
122
180
|
};
|
|
123
181
|
/** This function gives the box of a part of a word. */
|
|
182
|
+
/** 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
|
+
function advanceOf(segment, font, measurer, bound) {
|
|
184
|
+
return bound === void 0 ? measurer.advance(segment, font) : segment.length * bound;
|
|
185
|
+
}
|
|
124
186
|
function boxOf(part) {
|
|
125
187
|
return {
|
|
126
188
|
type: "box",
|
|
@@ -134,6 +196,8 @@ function boxOf(part) {
|
|
|
134
196
|
* The breaker comes from `@mark1russell7/typeset`. The default is greedy, as a browser with `white-space: normal`.
|
|
135
197
|
* It collapses each run of white space to one space, and a line does not count its last space.
|
|
136
198
|
* 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.
|
|
199
|
+
*
|
|
200
|
+
* 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.
|
|
137
201
|
*/
|
|
138
202
|
function layoutText(text, options) {
|
|
139
203
|
const { font, measurer, lineHeight } = options;
|
|
@@ -144,6 +208,10 @@ function layoutText(text, options) {
|
|
|
144
208
|
const name = options.breaker ?? "greedy";
|
|
145
209
|
if (!Object.hasOwn(breakers, name)) throw new RangeError(`layoutText: breaker is "greedy", "total-fit" or "balanced", not ${String(name)}.`);
|
|
146
210
|
const breaker = breakers[name];
|
|
211
|
+
const sizing = options.sizing ?? "exact";
|
|
212
|
+
if (sizing !== "exact" && sizing !== "bound-first" && sizing !== "bound") throw new RangeError(`layoutText: sizing is "exact", "bound-first" or "bound", not ${String(sizing)}.`);
|
|
213
|
+
const charset = sizing === "exact" ? void 0 : options.charset;
|
|
214
|
+
if (sizing !== "exact" && charset === void 0) throw new RangeError(`layoutText: sizing "${sizing}" needs a charset from createTextCharset.`);
|
|
147
215
|
let truncated = false;
|
|
148
216
|
let source = text;
|
|
149
217
|
if (options.maxChars !== void 0) {
|
|
@@ -155,21 +223,12 @@ function layoutText(text, options) {
|
|
|
155
223
|
}
|
|
156
224
|
}
|
|
157
225
|
const words = wordsOf(source);
|
|
158
|
-
const space = measurer.advance(" ", font);
|
|
159
|
-
const width = (w) => w.parts.reduce((s, p) => s + measurer.advance(p, font), 0);
|
|
160
|
-
const lineUnits = (line) => {
|
|
161
|
-
const ws = wordsOf(line);
|
|
162
|
-
return ws.reduce((s, w) => s + width(w), 0) + space * Math.max(0, ws.length - 1);
|
|
163
|
-
};
|
|
164
|
-
const widths = words.map(width);
|
|
165
|
-
const natural = widths.reduce((s, w) => s + w, 0) + space * Math.max(0, words.length - 1);
|
|
166
226
|
const maxWidth = options.maxWidth ?? (options.wrapWidth === void 0 ? Infinity : options.wrapWidth + padding);
|
|
167
|
-
const
|
|
168
|
-
if (options.wrapWidth === void 0 || fits) {
|
|
227
|
+
const oneLine = (natural, bounded) => {
|
|
169
228
|
const one = words.map((w) => w.text).join(" ");
|
|
170
229
|
const px = natural / 64;
|
|
171
230
|
const box = Math.min(maxWidth, Math.max(options.minWidth ?? 0, px + padding));
|
|
172
|
-
|
|
231
|
+
const layout = {
|
|
173
232
|
lines: [one],
|
|
174
233
|
widths: [px],
|
|
175
234
|
lineCount: 1,
|
|
@@ -177,7 +236,27 @@ function layoutText(text, options) {
|
|
|
177
236
|
height: lineHeight,
|
|
178
237
|
truncated
|
|
179
238
|
};
|
|
239
|
+
return bounded ? {
|
|
240
|
+
...layout,
|
|
241
|
+
bounded
|
|
242
|
+
} : layout;
|
|
243
|
+
};
|
|
244
|
+
const unit = charset?.covers(source) === true ? charset.unit(font, measurer) : void 0;
|
|
245
|
+
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;
|
|
247
|
+
if (options.wrapWidth === void 0 || natural / 64 + padding <= maxWidth) return oneLine(natural, true);
|
|
180
248
|
}
|
|
249
|
+
const bound = sizing === "bound" ? unit : void 0;
|
|
250
|
+
const space = advanceOf(" ", font, measurer, bound);
|
|
251
|
+
const width = (w) => w.parts.reduce((s, p) => s + advanceOf(p, font, measurer, bound), 0);
|
|
252
|
+
const lineUnits = (line) => {
|
|
253
|
+
const ws = wordsOf(line);
|
|
254
|
+
return ws.reduce((s, w) => s + width(w), 0) + space * Math.max(0, ws.length - 1);
|
|
255
|
+
};
|
|
256
|
+
const widths = words.map(width);
|
|
257
|
+
const natural = widths.reduce((s, w) => s + w, 0) + space * Math.max(0, words.length - 1);
|
|
258
|
+
const fits = natural / 64 + padding <= maxWidth;
|
|
259
|
+
if (options.wrapWidth === void 0 || fits) return oneLine(natural, bound !== void 0);
|
|
181
260
|
const limit = Math.round(options.wrapWidth * 64);
|
|
182
261
|
const items = [];
|
|
183
262
|
/** 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. */
|
|
@@ -185,7 +264,7 @@ function layoutText(text, options) {
|
|
|
185
264
|
if (items.length > 0) items.push(FORCED);
|
|
186
265
|
let cur;
|
|
187
266
|
for (const g of graphemesOf(word.text)) {
|
|
188
|
-
const w =
|
|
267
|
+
const w = advanceOf(g, font, measurer, bound);
|
|
189
268
|
if (cur !== void 0 && cur.width + w > limit) {
|
|
190
269
|
items.push(boxOf(cur), FORCED);
|
|
191
270
|
cur = void 0;
|
|
@@ -238,7 +317,7 @@ function layoutText(text, options) {
|
|
|
238
317
|
last.units = lineUnits(kept) + tail;
|
|
239
318
|
truncated = true;
|
|
240
319
|
}
|
|
241
|
-
|
|
320
|
+
const layout = {
|
|
242
321
|
lines: lines.map((l) => l.text),
|
|
243
322
|
widths: lines.map((l) => l.units / 64),
|
|
244
323
|
lineCount: lines.length,
|
|
@@ -247,6 +326,10 @@ function layoutText(text, options) {
|
|
|
247
326
|
wrapWidth: options.wrapWidth,
|
|
248
327
|
truncated
|
|
249
328
|
};
|
|
329
|
+
return bound === void 0 ? layout : {
|
|
330
|
+
...layout,
|
|
331
|
+
bounded: true
|
|
332
|
+
};
|
|
250
333
|
}
|
|
251
334
|
/** This function gives the key text of a number. It keeps -0, because `layoutText` can give -0 back in a result. */
|
|
252
335
|
function numberKey(value) {
|
|
@@ -257,14 +340,14 @@ function numberKey(value) {
|
|
|
257
340
|
* A number has no comma. The two lengths mark the end of the font and of the ellipsis.
|
|
258
341
|
*/
|
|
259
342
|
function optionsKey(o) {
|
|
260
|
-
return `${`${numberKey(o.lineHeight)},${numberKey(o.wrapWidth)},${numberKey(o.maxLines)},${numberKey(o.maxChars)},${numberKey(o.padding)},${numberKey(o.minWidth)},${numberKey(o.maxWidth)}`},${(o.wordBreak ?? "keep") === "keep"},${o.breaker},${o.font.length},${o.ellipsis?.length},${o.font}${o.ellipsis ?? ""}`;
|
|
343
|
+
return `${`${numberKey(o.lineHeight)},${numberKey(o.wrapWidth)},${numberKey(o.maxLines)},${numberKey(o.maxChars)},${numberKey(o.padding)},${numberKey(o.minWidth)},${numberKey(o.maxWidth)}`},${(o.wordBreak ?? "keep") === "keep"},${o.breaker},${o.sizing ?? "exact"},${o.font.length},${o.ellipsis?.length},${o.font}${o.ellipsis ?? ""}`;
|
|
261
344
|
}
|
|
262
345
|
/** 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. */
|
|
263
346
|
function sameOptions(a, b) {
|
|
264
|
-
return a.font === b.font && a.measurer === b.measurer && Object.is(a.lineHeight, b.lineHeight) && Object.is(a.wrapWidth, b.wrapWidth) && Object.is(a.maxLines, b.maxLines) && Object.is(a.maxChars, b.maxChars) && Object.is(a.padding, b.padding) && Object.is(a.minWidth, b.minWidth) && Object.is(a.maxWidth, b.maxWidth) && a.ellipsis === b.ellipsis && a.wordBreak === b.wordBreak && a.breaker === b.breaker;
|
|
347
|
+
return a.font === b.font && a.measurer === b.measurer && Object.is(a.lineHeight, b.lineHeight) && Object.is(a.wrapWidth, b.wrapWidth) && Object.is(a.maxLines, b.maxLines) && Object.is(a.maxChars, b.maxChars) && Object.is(a.padding, b.padding) && Object.is(a.minWidth, b.minWidth) && Object.is(a.maxWidth, b.maxWidth) && a.ellipsis === b.ellipsis && a.wordBreak === b.wordBreak && a.breaker === b.breaker && a.sizing === b.sizing && a.charset === b.charset;
|
|
265
348
|
}
|
|
266
349
|
/**
|
|
267
|
-
* This function gives a bounded cache of `layoutText` results, keyed by the text, the options and the
|
|
350
|
+
* This function gives a bounded cache of `layoutText` results, keyed by the text, the options, the measurer and the character set.
|
|
268
351
|
* 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.
|
|
269
352
|
* The key holds the raw font string, because a host can give two spellings of a font two different advances.
|
|
270
353
|
* 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.
|
|
@@ -280,17 +363,18 @@ function createTextLayoutCache(options = {}) {
|
|
|
280
363
|
let requests = 0;
|
|
281
364
|
let hits = 0;
|
|
282
365
|
let calls = 0;
|
|
283
|
-
const idOf = (
|
|
284
|
-
let id = ids.get(
|
|
366
|
+
const idOf = (item) => {
|
|
367
|
+
let id = ids.get(item);
|
|
285
368
|
if (id === void 0) {
|
|
286
369
|
id = nextId++;
|
|
287
|
-
ids.set(
|
|
370
|
+
ids.set(item, id);
|
|
288
371
|
}
|
|
289
372
|
return id;
|
|
290
373
|
};
|
|
291
374
|
/** This function finds the layouts of a set of options, and it makes that set the most recently used. */
|
|
292
375
|
const open = (layoutOptions, generation) => {
|
|
293
|
-
const
|
|
376
|
+
const charset = layoutOptions.charset === void 0 ? "" : idOf(layoutOptions.charset);
|
|
377
|
+
const key = `${idOf(layoutOptions.measurer)},${generation},${charset},${optionsKey(layoutOptions)}`;
|
|
294
378
|
const layouts = groups.get(key) ?? /* @__PURE__ */ new Map();
|
|
295
379
|
if (groups.delete(key)) groups.set(key, layouts);
|
|
296
380
|
return {
|
|
@@ -417,6 +501,6 @@ function textMeasures(layout, stats) {
|
|
|
417
501
|
...stats === void 0 ? {} : { "text.cacheHit": stats.requests === 0 ? 0 : stats.hits / stats.requests }
|
|
418
502
|
};
|
|
419
503
|
}
|
|
420
|
-
export { TEXT_MEASURES, TEXT_UNITS, canvasAdvance, createMeasurer, createTextLayoutCache, fontKey, graphemesOf, layoutText, textMeasures };
|
|
504
|
+
export { DIGITS, PRINTABLE_ASCII, TEXT_MEASURES, TEXT_UNITS, canvasAdvance, createMeasurer, createTextCharset, createTextLayoutCache, fontKey, graphemesOf, layoutText, textMeasures };
|
|
421
505
|
|
|
422
506
|
//# sourceMappingURL=text.js.map
|
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 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\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}\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. */\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 */\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 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 space = measurer.advance(\" \", font);\n const width = (w: Word): number => w.parts.reduce((s, p) => s + measurer.advance(p, font), 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 maxWidth = options.maxWidth ?? (options.wrapWidth === undefined ? Infinity : options.wrapWidth + padding);\n const fits = natural / TEXT_UNITS + padding <= maxWidth;\n if (options.wrapWidth === undefined || fits) {\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 return { lines: [one], widths: [px], lineCount: 1, width: box, height: lineHeight, truncated };\n }\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 = measurer.advance(g, font);\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 return {\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}\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.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 );\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 and the measurer.\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 is an object. It gets a number here, so a key does not keep the measurer alive.\n const ids = new WeakMap<TextMeasurer, 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 = (measurer: TextMeasurer): number => {\n let id = ids.get(measurer);\n if (id === undefined) {\n id = nextId++;\n ids.set(measurer, 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 key = `${idOf(layoutOptions.measurer)},${generation},${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,EAAE,KAAK,KAAK,GAA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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"}
|
|
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,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AI,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.3.
|
|
4
|
+
"version": "0.3.6",
|
|
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",
|
|
@@ -52,10 +52,11 @@
|
|
|
52
52
|
"@mark1russell7/cue": "^1.0.2",
|
|
53
53
|
"@types/node": "^26.6.4",
|
|
54
54
|
"esbuild": "^0.28.2",
|
|
55
|
-
"
|
|
56
|
-
"
|
|
55
|
+
"fast-check": "^4.10.2",
|
|
56
|
+
"layout-contract-0221": "npm:@mark1russell7/layout-contract@0.2.21",
|
|
57
57
|
"tsdown": "^0.23.1",
|
|
58
|
-
"
|
|
58
|
+
"typescript": "^7.0.2",
|
|
59
|
+
"vitest": "^5.0.3"
|
|
59
60
|
},
|
|
60
61
|
"dependencies": {
|
|
61
62
|
"@mark1russell7/rigor-generators": "^0.1.0",
|
package/src/text.ts
CHANGED
|
@@ -168,6 +168,95 @@ export function graphemesOf(text: string): string[] {
|
|
|
168
168
|
return Array.from(text);
|
|
169
169
|
}
|
|
170
170
|
|
|
171
|
+
/** The digits, as a value for `createTextCharset`. */
|
|
172
|
+
export const DIGITS = "0123456789";
|
|
173
|
+
|
|
174
|
+
/** The printable characters of ASCII with the space, as a value for `createTextCharset`. */
|
|
175
|
+
export const PRINTABLE_ASCII = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
|
|
176
|
+
|
|
177
|
+
/** 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. */
|
|
178
|
+
const SIMPLE_SCRIPT = /^[\p{Script=Common}\p{Script=Latin}\p{Script=Greek}\p{Script=Cyrillic}\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]$/u;
|
|
179
|
+
|
|
180
|
+
/** The characters that are not plain advances: marks, control and format characters, emoji parts, and each white space but the space. */
|
|
181
|
+
const NOT_AN_ADVANCE = /[\p{M}\p{C}\p{Extended_Pictographic}\p{Emoji_Modifier}\p{Regional_Indicator}]|[^\S ]/u;
|
|
182
|
+
|
|
183
|
+
/** The largest count of fonts in the memo of a character set for one measurer. */
|
|
184
|
+
const CHARSET_FONTS = 64;
|
|
185
|
+
|
|
186
|
+
/** The options of `createTextCharset`. */
|
|
187
|
+
export interface TextCharsetOptions {
|
|
188
|
+
/**
|
|
189
|
+
* 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.
|
|
190
|
+
* A kerning pair that is narrower adds no width. Give a value for a font with kerning pairs or ligatures that are wider.
|
|
191
|
+
*/
|
|
192
|
+
readonly pairMargin?: number;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** A declared character set. A caller asks for it with `createTextCharset`. It is frozen, so `createTextLayoutCache` can use its identity as a key. */
|
|
196
|
+
export interface TextCharset {
|
|
197
|
+
readonly characters: string;
|
|
198
|
+
/** This function tells if each code point of the text is a member of the set. */
|
|
199
|
+
covers(text: string): boolean;
|
|
200
|
+
/**
|
|
201
|
+
* This function gives the bound of one UTF-16 code unit of a member in the font, in units of 1/`TEXT_UNITS` pixel.
|
|
202
|
+
* It measures each member once for a measurer with `generation`, and again after a `reset`. It measures on each call for a different measurer.
|
|
203
|
+
* It gives `undefined` when a member has no positive finite advance: that is a gap in the font.
|
|
204
|
+
*/
|
|
205
|
+
unit(font: string, measurer: TextMeasurer): number | undefined;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* This function gives a declared character set. A member is one code point with a plain advance.
|
|
210
|
+
* 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`.
|
|
211
|
+
* 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.
|
|
212
|
+
*/
|
|
213
|
+
export function createTextCharset(characters: string, options: TextCharsetOptions = {}): TextCharset {
|
|
214
|
+
const pairMargin = options.pairMargin ?? 0;
|
|
215
|
+
if (!(Number.isFinite(pairMargin) && pairMargin >= 0)) throw new RangeError(`createTextCharset: pairMargin is a finite number of 0 or more, not ${pairMargin}.`);
|
|
216
|
+
const members = new Set(characters);
|
|
217
|
+
if (members.size === 0) throw new RangeError("createTextCharset: the set has no character.");
|
|
218
|
+
for (const c of members) {
|
|
219
|
+
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.`);
|
|
220
|
+
}
|
|
221
|
+
/** 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. */
|
|
222
|
+
const scan = (font: string, measurer: TextMeasurer): number | undefined => {
|
|
223
|
+
let largest = 0;
|
|
224
|
+
for (const c of members) {
|
|
225
|
+
const units = measurer.advance(c, font);
|
|
226
|
+
if (!(Number.isFinite(units) && units > 0)) return undefined;
|
|
227
|
+
largest = Math.max(largest, units);
|
|
228
|
+
}
|
|
229
|
+
return Math.ceil((largest + 1) * (1 + pairMargin));
|
|
230
|
+
};
|
|
231
|
+
const memo = new WeakMap<TextMeasurer, Map<string, { readonly generation: number; readonly unit: number | undefined }>>();
|
|
232
|
+
return Object.freeze({
|
|
233
|
+
characters,
|
|
234
|
+
covers(text: string): boolean {
|
|
235
|
+
for (const c of text) if (!members.has(c)) return false;
|
|
236
|
+
return true;
|
|
237
|
+
},
|
|
238
|
+
unit(font: string, measurer: TextMeasurer): number | undefined {
|
|
239
|
+
const generation = measurer.generation?.();
|
|
240
|
+
// A measurer without `generation` does not tell of a change of its advances, so a memo can keep a low bound.
|
|
241
|
+
if (generation === undefined) return scan(font, measurer);
|
|
242
|
+
let fonts = memo.get(measurer);
|
|
243
|
+
if (fonts === undefined) {
|
|
244
|
+
fonts = new Map();
|
|
245
|
+
memo.set(measurer, fonts);
|
|
246
|
+
}
|
|
247
|
+
const known = fonts.get(font);
|
|
248
|
+
if (known?.generation === generation) return known.unit;
|
|
249
|
+
const unit = scan(font, measurer);
|
|
250
|
+
if (fonts.size >= CHARSET_FONTS) fonts.delete(fonts.keys().next().value!);
|
|
251
|
+
fonts.set(font, { generation, unit });
|
|
252
|
+
return unit;
|
|
253
|
+
},
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** The source of the width of a label. The option `sizing` of `layoutText` tells each value. */
|
|
258
|
+
export type TextSizing = "exact" | "bound-first" | "bound";
|
|
259
|
+
|
|
171
260
|
/** The options of `layoutText`. All lengths are in pixels. */
|
|
172
261
|
export interface TextLayoutOptions {
|
|
173
262
|
readonly font: string;
|
|
@@ -198,6 +287,14 @@ export interface TextLayoutOptions {
|
|
|
198
287
|
* makes the lines more equal. `balanced` keeps the greedy line count with the least width.
|
|
199
288
|
*/
|
|
200
289
|
readonly breaker?: "greedy" | "total-fit" | "balanced";
|
|
290
|
+
/**
|
|
291
|
+
* The source of the width of a label. `exact` (the default) measures each label.
|
|
292
|
+
* `bound-first` keeps a label of `charset` on one line with no measure when its bound fits. It measures each other label.
|
|
293
|
+
* `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.
|
|
294
|
+
*/
|
|
295
|
+
readonly sizing?: TextSizing;
|
|
296
|
+
/** The declared character set of `sizing`. `bound-first` and `bound` need it, and `exact` does not read it. */
|
|
297
|
+
readonly charset?: TextCharset;
|
|
201
298
|
}
|
|
202
299
|
|
|
203
300
|
/** The layout of a text: its lines and its box. */
|
|
@@ -213,12 +310,19 @@ export interface TextLayout {
|
|
|
213
310
|
readonly wrapWidth?: number;
|
|
214
311
|
/** `true` when `maxChars` or `maxLines` cut the text. */
|
|
215
312
|
readonly truncated: boolean;
|
|
313
|
+
/** `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. */
|
|
314
|
+
readonly bounded?: true;
|
|
216
315
|
}
|
|
217
316
|
|
|
218
317
|
/** A forced break: a penalty with no text, no width and the cost `-Infinity`. */
|
|
219
318
|
const FORCED: Penalty = { type: "penalty", text: "", width: 0, cost: -Infinity, flagged: false };
|
|
220
319
|
|
|
221
320
|
/** This function gives the box of a part of a word. */
|
|
321
|
+
/** This function gives the units of a segment: the bound for one character times the length, or a measure when there is no bound. */
|
|
322
|
+
function advanceOf(segment: string, font: string, measurer: TextMeasurer, bound: number | undefined): number {
|
|
323
|
+
return bound === undefined ? measurer.advance(segment, font) : segment.length * bound;
|
|
324
|
+
}
|
|
325
|
+
|
|
222
326
|
function boxOf(part: { readonly text: string; readonly width: number }): Box {
|
|
223
327
|
return { type: "box", text: part.text, width: part.width };
|
|
224
328
|
}
|
|
@@ -235,6 +339,8 @@ interface Line {
|
|
|
235
339
|
* The breaker comes from `@mark1russell7/typeset`. The default is greedy, as a browser with `white-space: normal`.
|
|
236
340
|
* It collapses each run of white space to one space, and a line does not count its last space.
|
|
237
341
|
* 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.
|
|
342
|
+
*
|
|
343
|
+
* 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.
|
|
238
344
|
*/
|
|
239
345
|
export function layoutText(text: string, options: TextLayoutOptions): TextLayout {
|
|
240
346
|
const { font, measurer, lineHeight } = options;
|
|
@@ -245,6 +351,10 @@ export function layoutText(text: string, options: TextLayoutOptions): TextLayout
|
|
|
245
351
|
const name = options.breaker ?? "greedy";
|
|
246
352
|
if (!Object.hasOwn(breakers, name)) throw new RangeError(`layoutText: breaker is "greedy", "total-fit" or "balanced", not ${String(name)}.`);
|
|
247
353
|
const breaker = breakers[name];
|
|
354
|
+
const sizing = options.sizing ?? "exact";
|
|
355
|
+
if (sizing !== "exact" && sizing !== "bound-first" && sizing !== "bound") throw new RangeError(`layoutText: sizing is "exact", "bound-first" or "bound", not ${String(sizing)}.`);
|
|
356
|
+
const charset = sizing === "exact" ? undefined : options.charset;
|
|
357
|
+
if (sizing !== "exact" && charset === undefined) throw new RangeError(`layoutText: sizing "${sizing}" needs a charset from createTextCharset.`);
|
|
248
358
|
let truncated = false;
|
|
249
359
|
|
|
250
360
|
let source = text;
|
|
@@ -258,8 +368,24 @@ export function layoutText(text: string, options: TextLayoutOptions): TextLayout
|
|
|
258
368
|
}
|
|
259
369
|
|
|
260
370
|
const words = wordsOf(source);
|
|
261
|
-
const
|
|
262
|
-
const
|
|
371
|
+
const maxWidth = options.maxWidth ?? (options.wrapWidth === undefined ? Infinity : options.wrapWidth + padding);
|
|
372
|
+
const oneLine = (natural: number, bounded: boolean): TextLayout => {
|
|
373
|
+
const one = words.map((w) => w.text).join(" ");
|
|
374
|
+
const px = natural / TEXT_UNITS;
|
|
375
|
+
const box = Math.min(maxWidth, Math.max(options.minWidth ?? 0, px + padding));
|
|
376
|
+
const layout: TextLayout = { lines: [one], widths: [px], lineCount: 1, width: box, height: lineHeight, truncated };
|
|
377
|
+
return bounded ? { ...layout, bounded } : layout;
|
|
378
|
+
};
|
|
379
|
+
|
|
380
|
+
// The raw text, not its words: the check sees a tab or a line break before they collapse.
|
|
381
|
+
const unit = charset?.covers(source) === true ? charset.unit(font, measurer) : undefined;
|
|
382
|
+
if (sizing === "bound-first" && unit !== undefined) {
|
|
383
|
+
const natural = words.reduce((s, w) => s + w.text.length, Math.max(0, words.length - 1)) * unit;
|
|
384
|
+
if (options.wrapWidth === undefined || natural / TEXT_UNITS + padding <= maxWidth) return oneLine(natural, true);
|
|
385
|
+
}
|
|
386
|
+
const bound = sizing === "bound" ? unit : undefined;
|
|
387
|
+
const space = advanceOf(" ", font, measurer, bound);
|
|
388
|
+
const width = (w: Word): number => w.parts.reduce((s, p) => s + advanceOf(p, font, measurer, bound), 0);
|
|
263
389
|
const lineUnits = (line: string): number => {
|
|
264
390
|
const ws = wordsOf(line);
|
|
265
391
|
return ws.reduce((s, w) => s + width(w), 0) + space * Math.max(0, ws.length - 1);
|
|
@@ -267,14 +393,8 @@ export function layoutText(text: string, options: TextLayoutOptions): TextLayout
|
|
|
267
393
|
const widths = words.map(width);
|
|
268
394
|
const natural = widths.reduce((s, w) => s + w, 0) + space * Math.max(0, words.length - 1);
|
|
269
395
|
|
|
270
|
-
const maxWidth = options.maxWidth ?? (options.wrapWidth === undefined ? Infinity : options.wrapWidth + padding);
|
|
271
396
|
const fits = natural / TEXT_UNITS + padding <= maxWidth;
|
|
272
|
-
if (options.wrapWidth === undefined || fits)
|
|
273
|
-
const one = words.map((w) => w.text).join(" ");
|
|
274
|
-
const px = natural / TEXT_UNITS;
|
|
275
|
-
const box = Math.min(maxWidth, Math.max(options.minWidth ?? 0, px + padding));
|
|
276
|
-
return { lines: [one], widths: [px], lineCount: 1, width: box, height: lineHeight, truncated };
|
|
277
|
-
}
|
|
397
|
+
if (options.wrapWidth === undefined || fits) return oneLine(natural, bound !== undefined);
|
|
278
398
|
|
|
279
399
|
const limit = Math.round(options.wrapWidth * TEXT_UNITS);
|
|
280
400
|
// The items of the breaker: a box for each word, and glue of one space between two words.
|
|
@@ -284,7 +404,7 @@ export function layoutText(text: string, options: TextLayoutOptions): TextLayout
|
|
|
284
404
|
if (items.length > 0) items.push(FORCED);
|
|
285
405
|
let cur: { text: string; width: number } | undefined;
|
|
286
406
|
for (const g of graphemesOf(word.text)) {
|
|
287
|
-
const w =
|
|
407
|
+
const w = advanceOf(g, font, measurer, bound);
|
|
288
408
|
if (cur !== undefined && cur.width + w > limit) {
|
|
289
409
|
items.push(boxOf(cur), FORCED);
|
|
290
410
|
cur = undefined;
|
|
@@ -322,7 +442,7 @@ export function layoutText(text: string, options: TextLayoutOptions): TextLayout
|
|
|
322
442
|
truncated = true;
|
|
323
443
|
}
|
|
324
444
|
|
|
325
|
-
|
|
445
|
+
const layout: TextLayout = {
|
|
326
446
|
lines: lines.map((l) => l.text),
|
|
327
447
|
widths: lines.map((l) => l.units / TEXT_UNITS),
|
|
328
448
|
lineCount: lines.length,
|
|
@@ -331,6 +451,7 @@ export function layoutText(text: string, options: TextLayoutOptions): TextLayout
|
|
|
331
451
|
wrapWidth: options.wrapWidth,
|
|
332
452
|
truncated,
|
|
333
453
|
};
|
|
454
|
+
return bound === undefined ? layout : { ...layout, bounded: true };
|
|
334
455
|
}
|
|
335
456
|
|
|
336
457
|
/** The counts of a `TextLayoutCache`. `calls` is the count of the `layoutText` calls, and `size` is the count of the entries. */
|
|
@@ -368,7 +489,7 @@ function numberKey(value: number | undefined): string {
|
|
|
368
489
|
*/
|
|
369
490
|
function optionsKey(o: TextLayoutOptions): string {
|
|
370
491
|
const numbers = `${numberKey(o.lineHeight)},${numberKey(o.wrapWidth)},${numberKey(o.maxLines)},${numberKey(o.maxChars)},${numberKey(o.padding)},${numberKey(o.minWidth)},${numberKey(o.maxWidth)}`;
|
|
371
|
-
return `${numbers},${(o.wordBreak ?? "keep") === "keep"},${o.breaker},${o.font.length},${o.ellipsis?.length},${o.font}${o.ellipsis ?? ""}`;
|
|
492
|
+
return `${numbers},${(o.wordBreak ?? "keep") === "keep"},${o.breaker},${o.sizing ?? "exact"},${o.font.length},${o.ellipsis?.length},${o.font}${o.ellipsis ?? ""}`;
|
|
372
493
|
}
|
|
373
494
|
|
|
374
495
|
/** 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. */
|
|
@@ -385,7 +506,9 @@ function sameOptions(a: TextLayoutOptions, b: TextLayoutOptions): boolean {
|
|
|
385
506
|
Object.is(a.maxWidth, b.maxWidth) &&
|
|
386
507
|
a.ellipsis === b.ellipsis &&
|
|
387
508
|
a.wordBreak === b.wordBreak &&
|
|
388
|
-
a.breaker === b.breaker
|
|
509
|
+
a.breaker === b.breaker &&
|
|
510
|
+
a.sizing === b.sizing &&
|
|
511
|
+
a.charset === b.charset
|
|
389
512
|
);
|
|
390
513
|
}
|
|
391
514
|
|
|
@@ -399,7 +522,7 @@ interface CurrentOptions {
|
|
|
399
522
|
}
|
|
400
523
|
|
|
401
524
|
/**
|
|
402
|
-
* This function gives a bounded cache of `layoutText` results, keyed by the text, the options and the
|
|
525
|
+
* This function gives a bounded cache of `layoutText` results, keyed by the text, the options, the measurer and the character set.
|
|
403
526
|
* 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.
|
|
404
527
|
* The key holds the raw font string, because a host can give two spellings of a font two different advances.
|
|
405
528
|
* 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.
|
|
@@ -409,25 +532,26 @@ export function createTextLayoutCache(options: TextLayoutCacheOptions = {}): Tex
|
|
|
409
532
|
if (!(Number.isInteger(max) && max >= 0)) throw new RangeError(`createTextLayoutCache: maxEntries is an integer of 0 or more, not ${max}.`);
|
|
410
533
|
// 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.
|
|
411
534
|
const groups = new Map<string, Map<string, TextLayout>>();
|
|
412
|
-
// A measurer
|
|
413
|
-
const ids = new WeakMap<
|
|
535
|
+
// A measurer and a character set are objects. Each gets a number here, so a key does not keep it alive.
|
|
536
|
+
const ids = new WeakMap<object, number>();
|
|
414
537
|
let nextId = 0;
|
|
415
538
|
let current: CurrentOptions | undefined;
|
|
416
539
|
let size = 0;
|
|
417
540
|
let requests = 0;
|
|
418
541
|
let hits = 0;
|
|
419
542
|
let calls = 0;
|
|
420
|
-
const idOf = (
|
|
421
|
-
let id = ids.get(
|
|
543
|
+
const idOf = (item: object): number => {
|
|
544
|
+
let id = ids.get(item);
|
|
422
545
|
if (id === undefined) {
|
|
423
546
|
id = nextId++;
|
|
424
|
-
ids.set(
|
|
547
|
+
ids.set(item, id);
|
|
425
548
|
}
|
|
426
549
|
return id;
|
|
427
550
|
};
|
|
428
551
|
/** This function finds the layouts of a set of options, and it makes that set the most recently used. */
|
|
429
552
|
const open = (layoutOptions: TextLayoutOptions, generation: number | undefined): CurrentOptions => {
|
|
430
|
-
const
|
|
553
|
+
const charset = layoutOptions.charset === undefined ? "" : idOf(layoutOptions.charset);
|
|
554
|
+
const key = `${idOf(layoutOptions.measurer)},${generation},${charset},${optionsKey(layoutOptions)}`;
|
|
431
555
|
const layouts = groups.get(key) ?? new Map<string, TextLayout>();
|
|
432
556
|
if (groups.delete(key)) groups.set(key, layouts);
|
|
433
557
|
return { options: { ...layoutOptions }, generation, key, layouts };
|