@mark1russell7/layout-contract 0.3.4 → 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 +74 -0
- package/build/text.d.ts.map +1 -1
- package/build/text.js +203 -15
- package/build/text.js.map +1 -1
- package/package.json +5 -4
- package/src/text.ts +286 -11
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`, `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
|
@@ -20,6 +20,8 @@ export interface TextMeasurer {
|
|
|
20
20
|
stats(): MeasurerStats;
|
|
21
21
|
/** This function clears the cache and the counts. */
|
|
22
22
|
reset(): void;
|
|
23
|
+
/** This function gives the count of the `reset` calls. A `TextLayoutCache` reads it, and it does not give a layout from before a reset. */
|
|
24
|
+
generation?(): number;
|
|
23
25
|
}
|
|
24
26
|
/** The options of `createMeasurer`. */
|
|
25
27
|
export interface MeasurerOptions {
|
|
@@ -44,6 +46,38 @@ export interface CanvasTextContext {
|
|
|
44
46
|
export declare function canvasAdvance(context: CanvasTextContext): AdvanceFn;
|
|
45
47
|
/** This function gives the grapheme clusters of a text. Without `Intl.Segmenter`, it gives the code points. */
|
|
46
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";
|
|
47
81
|
/** The options of `layoutText`. All lengths are in pixels. */
|
|
48
82
|
export interface TextLayoutOptions {
|
|
49
83
|
readonly font: string;
|
|
@@ -74,6 +108,14 @@ export interface TextLayoutOptions {
|
|
|
74
108
|
* makes the lines more equal. `balanced` keeps the greedy line count with the least width.
|
|
75
109
|
*/
|
|
76
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;
|
|
77
119
|
}
|
|
78
120
|
/** The layout of a text: its lines and its box. */
|
|
79
121
|
export interface TextLayout {
|
|
@@ -88,6 +130,8 @@ export interface TextLayout {
|
|
|
88
130
|
readonly wrapWidth?: number;
|
|
89
131
|
/** `true` when `maxChars` or `maxLines` cut the text. */
|
|
90
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;
|
|
91
135
|
}
|
|
92
136
|
/**
|
|
93
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`.
|
|
@@ -95,8 +139,38 @@ export interface TextLayout {
|
|
|
95
139
|
* The breaker comes from `@mark1russell7/typeset`. The default is greedy, as a browser with `white-space: normal`.
|
|
96
140
|
* It collapses each run of white space to one space, and a line does not count its last space.
|
|
97
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.
|
|
98
144
|
*/
|
|
99
145
|
export declare function layoutText(text: string, options: TextLayoutOptions): TextLayout;
|
|
146
|
+
/** The counts of a `TextLayoutCache`. `calls` is the count of the `layoutText` calls, and `size` is the count of the entries. */
|
|
147
|
+
export interface TextLayoutCacheStats extends MeasurerStats {
|
|
148
|
+
readonly size: number;
|
|
149
|
+
}
|
|
150
|
+
/** The options of `createTextLayoutCache`. */
|
|
151
|
+
export interface TextLayoutCacheOptions {
|
|
152
|
+
/** The largest count of the entries. The default is 4096. With 0, the cache keeps no entry. */
|
|
153
|
+
readonly maxEntries?: number;
|
|
154
|
+
}
|
|
155
|
+
/** A cache of `layoutText` results. A caller asks for it with `createTextLayoutCache`. `layoutText` itself has no cache of results. */
|
|
156
|
+
export interface TextLayoutCache {
|
|
157
|
+
/**
|
|
158
|
+
* This function gives the result of `layoutText` for the text and the options.
|
|
159
|
+
* The result is deeply frozen. Equal arguments give the same object until the cache removes the entry.
|
|
160
|
+
*/
|
|
161
|
+
layout(text: string, options: TextLayoutOptions): TextLayout;
|
|
162
|
+
/** This function gives the counts since the start or since the last `reset`. */
|
|
163
|
+
stats(): TextLayoutCacheStats;
|
|
164
|
+
/** This function clears the entries and the counts. */
|
|
165
|
+
reset(): void;
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* This function gives a bounded cache of `layoutText` results, keyed by the text, the options, the measurer and the character set.
|
|
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.
|
|
170
|
+
* The key holds the raw font string, because a host can give two spellings of a font two different advances.
|
|
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.
|
|
172
|
+
*/
|
|
173
|
+
export declare function createTextLayoutCache(options?: TextLayoutCacheOptions): TextLayoutCache;
|
|
100
174
|
/** The id of a text measure. `docs/TEXT.md` gives the definitions. */
|
|
101
175
|
export type TextMeasureId = "text.lines" | "text.raggedness" | "text.overflow" | "text.cacheHit" | "text.ms";
|
|
102
176
|
/** The specs of the text measures. */
|
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;WACA;;;iBAIM;;EAEf,QAAQ,iBAAiB;;EAEzB,SAAS;;EAET;;;iBAIe;;WAEN;;;wBAIK,QAAQ;;;;;wBAQR,eAAe,SAAS,WAAW,UAAS,kBAAuB;;
|
|
1
|
+
{"version":3,"file":"text.d.ts","names":[],"sources":["../src/text.ts"],"mappings":";;;;;YAOY,aAAa,cAAc;;qBAG1B;;iBAGI;WACN;WACA;WACA;;;iBAIM;;EAEf,QAAQ,iBAAiB;;EAEzB,SAAS;;EAET;;EAEA;;;iBAIe;;WAEN;;;wBAIK,QAAQ;;;;;wBAQR,eAAe,SAAS,WAAW,UAAS,kBAAuB;;iBAwClE;EACf;EACA,YAAY;aAA0B;;;;wBAIxB,cAAc,SAAS,oBAAoB;;wBAwE3C,YAAY;;qBAOf;;qBAGA;;iBAYI;;;;;WAKN;;;iBAIM;WACN;;EAET,OAAO;;;;;;EAMP,KAAK,cAAc,UAAU;;;;;;;wBAQf,kBAAkB,oBAAoB,UAAS,qBAA0B;;YA6C7E;;iBAGK;WACN;WACA,UAAU;;WAEV;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;;;;WAKA;;;;;WAKA;;;;;;WAMA,SAAS;;WAET,UAAU;;;iBAIJ;WACN;;WAEA;WACA;;WAEA;WACA;;WAEA;;WAEA;;WAEA;;;;;;;;;;;wBA+BK,WAAW,cAAc,SAAS,oBAAoB;;iBAiHrD,6BAA6B;WACnC;;;iBAIM;;WAEN;;;iBAIM;;;;;EAKf,OAAO,cAAc,SAAS,oBAAoB;;EAElD,SAAS;;EAET;;;;;;;;wBAoDc,sBAAsB,UAAS,yBAA8B;;YA6EjE;;qBAGC,wBAAwB,YAAY;;;;;;wBAajC,aAAa,QAAQ,YAAY,QAAQ,gBAAgB,QAAQ,OAAO"}
|
package/build/text.js
CHANGED
|
@@ -17,6 +17,7 @@ function createMeasurer(measure, options = {}) {
|
|
|
17
17
|
let requests = 0;
|
|
18
18
|
let hits = 0;
|
|
19
19
|
let calls = 0;
|
|
20
|
+
let generation = 0;
|
|
20
21
|
return {
|
|
21
22
|
advance(segment, font) {
|
|
22
23
|
requests++;
|
|
@@ -46,7 +47,9 @@ function createMeasurer(measure, options = {}) {
|
|
|
46
47
|
requests = 0;
|
|
47
48
|
hits = 0;
|
|
48
49
|
calls = 0;
|
|
49
|
-
|
|
50
|
+
generation++;
|
|
51
|
+
},
|
|
52
|
+
generation: () => generation
|
|
50
53
|
};
|
|
51
54
|
}
|
|
52
55
|
/** 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. */
|
|
@@ -109,6 +112,64 @@ function graphemesOf(text) {
|
|
|
109
112
|
if (segmenter !== null) return Array.from(segmenter.segment(text), (s) => s.segment);
|
|
110
113
|
return Array.from(text);
|
|
111
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
|
+
}
|
|
112
173
|
/** A forced break: a penalty with no text, no width and the cost `-Infinity`. */
|
|
113
174
|
const FORCED = {
|
|
114
175
|
type: "penalty",
|
|
@@ -118,6 +179,10 @@ const FORCED = {
|
|
|
118
179
|
flagged: false
|
|
119
180
|
};
|
|
120
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
|
+
}
|
|
121
186
|
function boxOf(part) {
|
|
122
187
|
return {
|
|
123
188
|
type: "box",
|
|
@@ -131,6 +196,8 @@ function boxOf(part) {
|
|
|
131
196
|
* The breaker comes from `@mark1russell7/typeset`. The default is greedy, as a browser with `white-space: normal`.
|
|
132
197
|
* It collapses each run of white space to one space, and a line does not count its last space.
|
|
133
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.
|
|
134
201
|
*/
|
|
135
202
|
function layoutText(text, options) {
|
|
136
203
|
const { font, measurer, lineHeight } = options;
|
|
@@ -141,6 +208,10 @@ function layoutText(text, options) {
|
|
|
141
208
|
const name = options.breaker ?? "greedy";
|
|
142
209
|
if (!Object.hasOwn(breakers, name)) throw new RangeError(`layoutText: breaker is "greedy", "total-fit" or "balanced", not ${String(name)}.`);
|
|
143
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.`);
|
|
144
215
|
let truncated = false;
|
|
145
216
|
let source = text;
|
|
146
217
|
if (options.maxChars !== void 0) {
|
|
@@ -152,21 +223,12 @@ function layoutText(text, options) {
|
|
|
152
223
|
}
|
|
153
224
|
}
|
|
154
225
|
const words = wordsOf(source);
|
|
155
|
-
const space = measurer.advance(" ", font);
|
|
156
|
-
const width = (w) => w.parts.reduce((s, p) => s + measurer.advance(p, font), 0);
|
|
157
|
-
const lineUnits = (line) => {
|
|
158
|
-
const ws = wordsOf(line);
|
|
159
|
-
return ws.reduce((s, w) => s + width(w), 0) + space * Math.max(0, ws.length - 1);
|
|
160
|
-
};
|
|
161
|
-
const widths = words.map(width);
|
|
162
|
-
const natural = widths.reduce((s, w) => s + w, 0) + space * Math.max(0, words.length - 1);
|
|
163
226
|
const maxWidth = options.maxWidth ?? (options.wrapWidth === void 0 ? Infinity : options.wrapWidth + padding);
|
|
164
|
-
const
|
|
165
|
-
if (options.wrapWidth === void 0 || fits) {
|
|
227
|
+
const oneLine = (natural, bounded) => {
|
|
166
228
|
const one = words.map((w) => w.text).join(" ");
|
|
167
229
|
const px = natural / 64;
|
|
168
230
|
const box = Math.min(maxWidth, Math.max(options.minWidth ?? 0, px + padding));
|
|
169
|
-
|
|
231
|
+
const layout = {
|
|
170
232
|
lines: [one],
|
|
171
233
|
widths: [px],
|
|
172
234
|
lineCount: 1,
|
|
@@ -174,7 +236,27 @@ function layoutText(text, options) {
|
|
|
174
236
|
height: lineHeight,
|
|
175
237
|
truncated
|
|
176
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);
|
|
177
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);
|
|
178
260
|
const limit = Math.round(options.wrapWidth * 64);
|
|
179
261
|
const items = [];
|
|
180
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. */
|
|
@@ -182,7 +264,7 @@ function layoutText(text, options) {
|
|
|
182
264
|
if (items.length > 0) items.push(FORCED);
|
|
183
265
|
let cur;
|
|
184
266
|
for (const g of graphemesOf(word.text)) {
|
|
185
|
-
const w =
|
|
267
|
+
const w = advanceOf(g, font, measurer, bound);
|
|
186
268
|
if (cur !== void 0 && cur.width + w > limit) {
|
|
187
269
|
items.push(boxOf(cur), FORCED);
|
|
188
270
|
cur = void 0;
|
|
@@ -235,7 +317,7 @@ function layoutText(text, options) {
|
|
|
235
317
|
last.units = lineUnits(kept) + tail;
|
|
236
318
|
truncated = true;
|
|
237
319
|
}
|
|
238
|
-
|
|
320
|
+
const layout = {
|
|
239
321
|
lines: lines.map((l) => l.text),
|
|
240
322
|
widths: lines.map((l) => l.units / 64),
|
|
241
323
|
lineCount: lines.length,
|
|
@@ -244,6 +326,112 @@ function layoutText(text, options) {
|
|
|
244
326
|
wrapWidth: options.wrapWidth,
|
|
245
327
|
truncated
|
|
246
328
|
};
|
|
329
|
+
return bound === void 0 ? layout : {
|
|
330
|
+
...layout,
|
|
331
|
+
bounded: true
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
/** This function gives the key text of a number. It keeps -0, because `layoutText` can give -0 back in a result. */
|
|
335
|
+
function numberKey(value) {
|
|
336
|
+
return Object.is(value, -0) ? "-0" : String(value);
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* This function gives the key of a set of options, without the text and the measurer. Two different sets do not give one key.
|
|
340
|
+
* A number has no comma. The two lengths mark the end of the font and of the ellipsis.
|
|
341
|
+
*/
|
|
342
|
+
function optionsKey(o) {
|
|
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 ?? ""}`;
|
|
344
|
+
}
|
|
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. */
|
|
346
|
+
function sameOptions(a, b) {
|
|
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;
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* This function gives a bounded cache of `layoutText` results, keyed by the text, the options, the measurer and the character set.
|
|
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.
|
|
352
|
+
* The key holds the raw font string, because a host can give two spellings of a font two different advances.
|
|
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.
|
|
354
|
+
*/
|
|
355
|
+
function createTextLayoutCache(options = {}) {
|
|
356
|
+
const max = options.maxEntries ?? 4096;
|
|
357
|
+
if (!(Number.isInteger(max) && max >= 0)) throw new RangeError(`createTextLayoutCache: maxEntries is an integer of 0 or more, not ${max}.`);
|
|
358
|
+
const groups = /* @__PURE__ */ new Map();
|
|
359
|
+
const ids = /* @__PURE__ */ new WeakMap();
|
|
360
|
+
let nextId = 0;
|
|
361
|
+
let current;
|
|
362
|
+
let size = 0;
|
|
363
|
+
let requests = 0;
|
|
364
|
+
let hits = 0;
|
|
365
|
+
let calls = 0;
|
|
366
|
+
const idOf = (item) => {
|
|
367
|
+
let id = ids.get(item);
|
|
368
|
+
if (id === void 0) {
|
|
369
|
+
id = nextId++;
|
|
370
|
+
ids.set(item, id);
|
|
371
|
+
}
|
|
372
|
+
return id;
|
|
373
|
+
};
|
|
374
|
+
/** This function finds the layouts of a set of options, and it makes that set the most recently used. */
|
|
375
|
+
const open = (layoutOptions, generation) => {
|
|
376
|
+
const charset = layoutOptions.charset === void 0 ? "" : idOf(layoutOptions.charset);
|
|
377
|
+
const key = `${idOf(layoutOptions.measurer)},${generation},${charset},${optionsKey(layoutOptions)}`;
|
|
378
|
+
const layouts = groups.get(key) ?? /* @__PURE__ */ new Map();
|
|
379
|
+
if (groups.delete(key)) groups.set(key, layouts);
|
|
380
|
+
return {
|
|
381
|
+
options: { ...layoutOptions },
|
|
382
|
+
generation,
|
|
383
|
+
key,
|
|
384
|
+
layouts
|
|
385
|
+
};
|
|
386
|
+
};
|
|
387
|
+
/** This function removes one entry. */
|
|
388
|
+
const evict = () => {
|
|
389
|
+
const [key, layouts] = groups.entries().next().value;
|
|
390
|
+
layouts.delete(layouts.keys().next().value);
|
|
391
|
+
size--;
|
|
392
|
+
if (layouts.size === 0) groups.delete(key);
|
|
393
|
+
};
|
|
394
|
+
return {
|
|
395
|
+
layout(text, layoutOptions) {
|
|
396
|
+
requests++;
|
|
397
|
+
const generation = layoutOptions.measurer.generation?.();
|
|
398
|
+
if (current === void 0 || generation !== current.generation || !sameOptions(current.options, layoutOptions)) current = open(layoutOptions, generation);
|
|
399
|
+
const { key, layouts } = current;
|
|
400
|
+
const known = layouts.get(text);
|
|
401
|
+
if (known !== void 0) {
|
|
402
|
+
hits++;
|
|
403
|
+
layouts.delete(text);
|
|
404
|
+
layouts.set(text, known);
|
|
405
|
+
return known;
|
|
406
|
+
}
|
|
407
|
+
calls++;
|
|
408
|
+
const layout = layoutText(text, layoutOptions);
|
|
409
|
+
Object.freeze(layout.lines);
|
|
410
|
+
Object.freeze(layout.widths);
|
|
411
|
+
Object.freeze(layout);
|
|
412
|
+
if (max > 0) {
|
|
413
|
+
if (size >= max) evict();
|
|
414
|
+
if (layouts.size === 0) groups.set(key, layouts);
|
|
415
|
+
layouts.set(text, layout);
|
|
416
|
+
size++;
|
|
417
|
+
}
|
|
418
|
+
return layout;
|
|
419
|
+
},
|
|
420
|
+
stats: () => ({
|
|
421
|
+
requests,
|
|
422
|
+
hits,
|
|
423
|
+
calls,
|
|
424
|
+
size
|
|
425
|
+
}),
|
|
426
|
+
reset() {
|
|
427
|
+
groups.clear();
|
|
428
|
+
current = void 0;
|
|
429
|
+
size = 0;
|
|
430
|
+
requests = 0;
|
|
431
|
+
hits = 0;
|
|
432
|
+
calls = 0;
|
|
433
|
+
}
|
|
434
|
+
};
|
|
247
435
|
}
|
|
248
436
|
/** The specs of the text measures. */
|
|
249
437
|
const TEXT_MEASURES = /* @__PURE__ */ Object.freeze([
|
|
@@ -313,6 +501,6 @@ function textMeasures(layout, stats) {
|
|
|
313
501
|
...stats === void 0 ? {} : { "text.cacheHit": stats.requests === 0 ? 0 : stats.hits / stats.requests }
|
|
314
502
|
};
|
|
315
503
|
}
|
|
316
|
-
export { TEXT_MEASURES, TEXT_UNITS, canvasAdvance, createMeasurer, fontKey, graphemesOf, layoutText, textMeasures };
|
|
504
|
+
export { DIGITS, PRINTABLE_ASCII, TEXT_MEASURES, TEXT_UNITS, canvasAdvance, createMeasurer, createTextCharset, createTextLayoutCache, fontKey, graphemesOf, layoutText, textMeasures };
|
|
317
505
|
|
|
318
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}\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 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 },\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 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;;AA0B1B,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,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AAK;EAAG,WAAW;EAAO,QAAQ;CAAO;CAC9G;EAAE,IAAI;EAAiB,MAAM;EAA2B,WAAW;EAAS,KAAK;EAAG,KAAK;EAAU,OAAO;EAAG,KAAK;EAAG,WAAW;EAAG,QAAQ;EAAQ,MAAM;CAAQ;CACjK;EAAE,IAAI;EAAiB,MAAM;EAAU,WAAW;EAAU,KAAK;EAAG,KAAK;EAAG,QAAQ;EAAQ,MAAM;CAAa;CAC/G;EAAE,IAAI;EAAW,MAAM;EAAgB,WAAW;EAAS,KAAK;EAAG,KAAK;EAAU,QAAQ;EAAQ,MAAM;CAAO;AACjH,CAAU;;;;;;AAOV,SAAgB,aAAa,QAAoB,OAA+D;CAC9G,MAAM,IAAI,OAAO;CACjB,MAAM,OAAO,OAAO,OAAO,MAAM,GAAG,EAAE;CACtC,MAAM,aAAa,MAAM,KAAA,KAAa,KAAK,WAAW,IAAI,IAAI,KAAK,QAAQ,GAAG,MAAM,KAAK,KAAK,IAAI,GAAG,IAAI,CAAC,IAAI,MAAM,GAAG,CAAC,IAAI,KAAK;CACjI,MAAM,WAAW,MAAM,KAAA,IAAY,IAAI,KAAK,IAAI,GAAG,GAAG,OAAO,OAAO,KAAK,OAAO,IAAI,KAAK,CAAC,CAAC;CAC3F,OAAO;EACL,cAAc,OAAO;EACrB,mBAAmB;EACnB,iBAAiB;EACjB,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,iBAAiB,MAAM,aAAa,IAAI,IAAI,MAAM,OAAO,MAAM,SAAS;CAC3G;AACF"}
|
|
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;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;CAC9G,MAAM,IAAI,OAAO;CACjB,MAAM,OAAO,OAAO,OAAO,MAAM,GAAG,EAAE;CACtC,MAAM,aAAa,MAAM,KAAA,KAAa,KAAK,WAAW,IAAI,IAAI,KAAK,QAAQ,GAAG,MAAM,KAAK,KAAK,IAAI,GAAG,IAAI,CAAC,IAAI,MAAM,GAAG,CAAC,IAAI,KAAK;CACjI,MAAM,WAAW,MAAM,KAAA,IAAY,IAAI,KAAK,IAAI,GAAG,GAAG,OAAO,OAAO,KAAK,OAAO,IAAI,KAAK,CAAC,CAAC;CAC3F,OAAO;EACL,cAAc,OAAO;EACrB,mBAAmB;EACnB,iBAAiB;EACjB,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,iBAAiB,MAAM,aAAa,IAAI,IAAI,MAAM,OAAO,MAAM,SAAS;CAC3G;AACF"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package",
|
|
3
3
|
"name": "@mark1russell7/layout-contract",
|
|
4
|
-
"version": "0.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
|
@@ -25,6 +25,8 @@ export interface TextMeasurer {
|
|
|
25
25
|
stats(): MeasurerStats;
|
|
26
26
|
/** This function clears the cache and the counts. */
|
|
27
27
|
reset(): void;
|
|
28
|
+
/** This function gives the count of the `reset` calls. A `TextLayoutCache` reads it, and it does not give a layout from before a reset. */
|
|
29
|
+
generation?(): number;
|
|
28
30
|
}
|
|
29
31
|
|
|
30
32
|
/** The options of `createMeasurer`. */
|
|
@@ -49,6 +51,7 @@ export function createMeasurer(measure: AdvanceFn, options: MeasurerOptions = {}
|
|
|
49
51
|
let requests = 0;
|
|
50
52
|
let hits = 0;
|
|
51
53
|
let calls = 0;
|
|
54
|
+
let generation = 0;
|
|
52
55
|
return {
|
|
53
56
|
advance(segment, font) {
|
|
54
57
|
requests++;
|
|
@@ -74,7 +77,9 @@ export function createMeasurer(measure: AdvanceFn, options: MeasurerOptions = {}
|
|
|
74
77
|
requests = 0;
|
|
75
78
|
hits = 0;
|
|
76
79
|
calls = 0;
|
|
80
|
+
generation++;
|
|
77
81
|
},
|
|
82
|
+
generation: () => generation,
|
|
78
83
|
};
|
|
79
84
|
}
|
|
80
85
|
|
|
@@ -163,6 +168,95 @@ export function graphemesOf(text: string): string[] {
|
|
|
163
168
|
return Array.from(text);
|
|
164
169
|
}
|
|
165
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
|
+
|
|
166
260
|
/** The options of `layoutText`. All lengths are in pixels. */
|
|
167
261
|
export interface TextLayoutOptions {
|
|
168
262
|
readonly font: string;
|
|
@@ -193,6 +287,14 @@ export interface TextLayoutOptions {
|
|
|
193
287
|
* makes the lines more equal. `balanced` keeps the greedy line count with the least width.
|
|
194
288
|
*/
|
|
195
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;
|
|
196
298
|
}
|
|
197
299
|
|
|
198
300
|
/** The layout of a text: its lines and its box. */
|
|
@@ -208,12 +310,19 @@ export interface TextLayout {
|
|
|
208
310
|
readonly wrapWidth?: number;
|
|
209
311
|
/** `true` when `maxChars` or `maxLines` cut the text. */
|
|
210
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;
|
|
211
315
|
}
|
|
212
316
|
|
|
213
317
|
/** A forced break: a penalty with no text, no width and the cost `-Infinity`. */
|
|
214
318
|
const FORCED: Penalty = { type: "penalty", text: "", width: 0, cost: -Infinity, flagged: false };
|
|
215
319
|
|
|
216
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
|
+
|
|
217
326
|
function boxOf(part: { readonly text: string; readonly width: number }): Box {
|
|
218
327
|
return { type: "box", text: part.text, width: part.width };
|
|
219
328
|
}
|
|
@@ -230,6 +339,8 @@ interface Line {
|
|
|
230
339
|
* The breaker comes from `@mark1russell7/typeset`. The default is greedy, as a browser with `white-space: normal`.
|
|
231
340
|
* It collapses each run of white space to one space, and a line does not count its last space.
|
|
232
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.
|
|
233
344
|
*/
|
|
234
345
|
export function layoutText(text: string, options: TextLayoutOptions): TextLayout {
|
|
235
346
|
const { font, measurer, lineHeight } = options;
|
|
@@ -240,6 +351,10 @@ export function layoutText(text: string, options: TextLayoutOptions): TextLayout
|
|
|
240
351
|
const name = options.breaker ?? "greedy";
|
|
241
352
|
if (!Object.hasOwn(breakers, name)) throw new RangeError(`layoutText: breaker is "greedy", "total-fit" or "balanced", not ${String(name)}.`);
|
|
242
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.`);
|
|
243
358
|
let truncated = false;
|
|
244
359
|
|
|
245
360
|
let source = text;
|
|
@@ -253,8 +368,24 @@ export function layoutText(text: string, options: TextLayoutOptions): TextLayout
|
|
|
253
368
|
}
|
|
254
369
|
|
|
255
370
|
const words = wordsOf(source);
|
|
256
|
-
const
|
|
257
|
-
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);
|
|
258
389
|
const lineUnits = (line: string): number => {
|
|
259
390
|
const ws = wordsOf(line);
|
|
260
391
|
return ws.reduce((s, w) => s + width(w), 0) + space * Math.max(0, ws.length - 1);
|
|
@@ -262,14 +393,8 @@ export function layoutText(text: string, options: TextLayoutOptions): TextLayout
|
|
|
262
393
|
const widths = words.map(width);
|
|
263
394
|
const natural = widths.reduce((s, w) => s + w, 0) + space * Math.max(0, words.length - 1);
|
|
264
395
|
|
|
265
|
-
const maxWidth = options.maxWidth ?? (options.wrapWidth === undefined ? Infinity : options.wrapWidth + padding);
|
|
266
396
|
const fits = natural / TEXT_UNITS + padding <= maxWidth;
|
|
267
|
-
if (options.wrapWidth === undefined || fits)
|
|
268
|
-
const one = words.map((w) => w.text).join(" ");
|
|
269
|
-
const px = natural / TEXT_UNITS;
|
|
270
|
-
const box = Math.min(maxWidth, Math.max(options.minWidth ?? 0, px + padding));
|
|
271
|
-
return { lines: [one], widths: [px], lineCount: 1, width: box, height: lineHeight, truncated };
|
|
272
|
-
}
|
|
397
|
+
if (options.wrapWidth === undefined || fits) return oneLine(natural, bound !== undefined);
|
|
273
398
|
|
|
274
399
|
const limit = Math.round(options.wrapWidth * TEXT_UNITS);
|
|
275
400
|
// The items of the breaker: a box for each word, and glue of one space between two words.
|
|
@@ -279,7 +404,7 @@ export function layoutText(text: string, options: TextLayoutOptions): TextLayout
|
|
|
279
404
|
if (items.length > 0) items.push(FORCED);
|
|
280
405
|
let cur: { text: string; width: number } | undefined;
|
|
281
406
|
for (const g of graphemesOf(word.text)) {
|
|
282
|
-
const w =
|
|
407
|
+
const w = advanceOf(g, font, measurer, bound);
|
|
283
408
|
if (cur !== undefined && cur.width + w > limit) {
|
|
284
409
|
items.push(boxOf(cur), FORCED);
|
|
285
410
|
cur = undefined;
|
|
@@ -317,7 +442,7 @@ export function layoutText(text: string, options: TextLayoutOptions): TextLayout
|
|
|
317
442
|
truncated = true;
|
|
318
443
|
}
|
|
319
444
|
|
|
320
|
-
|
|
445
|
+
const layout: TextLayout = {
|
|
321
446
|
lines: lines.map((l) => l.text),
|
|
322
447
|
widths: lines.map((l) => l.units / TEXT_UNITS),
|
|
323
448
|
lineCount: lines.length,
|
|
@@ -326,6 +451,156 @@ export function layoutText(text: string, options: TextLayoutOptions): TextLayout
|
|
|
326
451
|
wrapWidth: options.wrapWidth,
|
|
327
452
|
truncated,
|
|
328
453
|
};
|
|
454
|
+
return bound === undefined ? layout : { ...layout, bounded: true };
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/** The counts of a `TextLayoutCache`. `calls` is the count of the `layoutText` calls, and `size` is the count of the entries. */
|
|
458
|
+
export interface TextLayoutCacheStats extends MeasurerStats {
|
|
459
|
+
readonly size: number;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/** The options of `createTextLayoutCache`. */
|
|
463
|
+
export interface TextLayoutCacheOptions {
|
|
464
|
+
/** The largest count of the entries. The default is 4096. With 0, the cache keeps no entry. */
|
|
465
|
+
readonly maxEntries?: number;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/** A cache of `layoutText` results. A caller asks for it with `createTextLayoutCache`. `layoutText` itself has no cache of results. */
|
|
469
|
+
export interface TextLayoutCache {
|
|
470
|
+
/**
|
|
471
|
+
* This function gives the result of `layoutText` for the text and the options.
|
|
472
|
+
* The result is deeply frozen. Equal arguments give the same object until the cache removes the entry.
|
|
473
|
+
*/
|
|
474
|
+
layout(text: string, options: TextLayoutOptions): TextLayout;
|
|
475
|
+
/** This function gives the counts since the start or since the last `reset`. */
|
|
476
|
+
stats(): TextLayoutCacheStats;
|
|
477
|
+
/** This function clears the entries and the counts. */
|
|
478
|
+
reset(): void;
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/** This function gives the key text of a number. It keeps -0, because `layoutText` can give -0 back in a result. */
|
|
482
|
+
function numberKey(value: number | undefined): string {
|
|
483
|
+
return Object.is(value, -0) ? "-0" : String(value);
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/**
|
|
487
|
+
* This function gives the key of a set of options, without the text and the measurer. Two different sets do not give one key.
|
|
488
|
+
* A number has no comma. The two lengths mark the end of the font and of the ellipsis.
|
|
489
|
+
*/
|
|
490
|
+
function optionsKey(o: TextLayoutOptions): string {
|
|
491
|
+
const numbers = `${numberKey(o.lineHeight)},${numberKey(o.wrapWidth)},${numberKey(o.maxLines)},${numberKey(o.maxChars)},${numberKey(o.padding)},${numberKey(o.minWidth)},${numberKey(o.maxWidth)}`;
|
|
492
|
+
return `${numbers},${(o.wordBreak ?? "keep") === "keep"},${o.breaker},${o.sizing ?? "exact"},${o.font.length},${o.ellipsis?.length},${o.font}${o.ellipsis ?? ""}`;
|
|
493
|
+
}
|
|
494
|
+
|
|
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. */
|
|
496
|
+
function sameOptions(a: TextLayoutOptions, b: TextLayoutOptions): boolean {
|
|
497
|
+
return (
|
|
498
|
+
a.font === b.font &&
|
|
499
|
+
a.measurer === b.measurer &&
|
|
500
|
+
Object.is(a.lineHeight, b.lineHeight) &&
|
|
501
|
+
Object.is(a.wrapWidth, b.wrapWidth) &&
|
|
502
|
+
Object.is(a.maxLines, b.maxLines) &&
|
|
503
|
+
Object.is(a.maxChars, b.maxChars) &&
|
|
504
|
+
Object.is(a.padding, b.padding) &&
|
|
505
|
+
Object.is(a.minWidth, b.minWidth) &&
|
|
506
|
+
Object.is(a.maxWidth, b.maxWidth) &&
|
|
507
|
+
a.ellipsis === b.ellipsis &&
|
|
508
|
+
a.wordBreak === b.wordBreak &&
|
|
509
|
+
a.breaker === b.breaker &&
|
|
510
|
+
a.sizing === b.sizing &&
|
|
511
|
+
a.charset === b.charset
|
|
512
|
+
);
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/** The set of options of the last call of a cache, with its layouts by text. */
|
|
516
|
+
interface CurrentOptions {
|
|
517
|
+
/** A copy of the options, so a later change of the object of the caller does not touch it. */
|
|
518
|
+
readonly options: TextLayoutOptions;
|
|
519
|
+
readonly generation: number | undefined;
|
|
520
|
+
readonly key: string;
|
|
521
|
+
readonly layouts: Map<string, TextLayout>;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/**
|
|
525
|
+
* This function gives a bounded cache of `layoutText` results, keyed by the text, the options, the measurer and the character set.
|
|
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.
|
|
527
|
+
* The key holds the raw font string, because a host can give two spellings of a font two different advances.
|
|
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.
|
|
529
|
+
*/
|
|
530
|
+
export function createTextLayoutCache(options: TextLayoutCacheOptions = {}): TextLayoutCache {
|
|
531
|
+
const max = options.maxEntries ?? 4096;
|
|
532
|
+
if (!(Number.isInteger(max) && max >= 0)) throw new RangeError(`createTextLayoutCache: maxEntries is an integer of 0 or more, not ${max}.`);
|
|
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.
|
|
534
|
+
const groups = new Map<string, Map<string, TextLayout>>();
|
|
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>();
|
|
537
|
+
let nextId = 0;
|
|
538
|
+
let current: CurrentOptions | undefined;
|
|
539
|
+
let size = 0;
|
|
540
|
+
let requests = 0;
|
|
541
|
+
let hits = 0;
|
|
542
|
+
let calls = 0;
|
|
543
|
+
const idOf = (item: object): number => {
|
|
544
|
+
let id = ids.get(item);
|
|
545
|
+
if (id === undefined) {
|
|
546
|
+
id = nextId++;
|
|
547
|
+
ids.set(item, id);
|
|
548
|
+
}
|
|
549
|
+
return id;
|
|
550
|
+
};
|
|
551
|
+
/** This function finds the layouts of a set of options, and it makes that set the most recently used. */
|
|
552
|
+
const open = (layoutOptions: TextLayoutOptions, generation: number | undefined): CurrentOptions => {
|
|
553
|
+
const charset = layoutOptions.charset === undefined ? "" : idOf(layoutOptions.charset);
|
|
554
|
+
const key = `${idOf(layoutOptions.measurer)},${generation},${charset},${optionsKey(layoutOptions)}`;
|
|
555
|
+
const layouts = groups.get(key) ?? new Map<string, TextLayout>();
|
|
556
|
+
if (groups.delete(key)) groups.set(key, layouts);
|
|
557
|
+
return { options: { ...layoutOptions }, generation, key, layouts };
|
|
558
|
+
};
|
|
559
|
+
/** This function removes one entry. */
|
|
560
|
+
const evict = (): void => {
|
|
561
|
+
const [key, layouts] = groups.entries().next().value!;
|
|
562
|
+
layouts.delete(layouts.keys().next().value!);
|
|
563
|
+
size--;
|
|
564
|
+
if (layouts.size === 0) groups.delete(key);
|
|
565
|
+
};
|
|
566
|
+
return {
|
|
567
|
+
layout(text, layoutOptions) {
|
|
568
|
+
requests++;
|
|
569
|
+
const generation = layoutOptions.measurer.generation?.();
|
|
570
|
+
if (current === undefined || generation !== current.generation || !sameOptions(current.options, layoutOptions)) current = open(layoutOptions, generation);
|
|
571
|
+
const { key, layouts } = current;
|
|
572
|
+
const known = layouts.get(text);
|
|
573
|
+
if (known !== undefined) {
|
|
574
|
+
hits++;
|
|
575
|
+
// This moves the text to the end of the order.
|
|
576
|
+
layouts.delete(text);
|
|
577
|
+
layouts.set(text, known);
|
|
578
|
+
return known;
|
|
579
|
+
}
|
|
580
|
+
calls++;
|
|
581
|
+
const layout = layoutText(text, layoutOptions);
|
|
582
|
+
// The callers share this object, so it is frozen also when the cache does not keep it.
|
|
583
|
+
Object.freeze(layout.lines);
|
|
584
|
+
Object.freeze(layout.widths);
|
|
585
|
+
Object.freeze(layout);
|
|
586
|
+
if (max > 0) {
|
|
587
|
+
if (size >= max) evict();
|
|
588
|
+
if (layouts.size === 0) groups.set(key, layouts);
|
|
589
|
+
layouts.set(text, layout);
|
|
590
|
+
size++;
|
|
591
|
+
}
|
|
592
|
+
return layout;
|
|
593
|
+
},
|
|
594
|
+
stats: () => ({ requests, hits, calls, size }),
|
|
595
|
+
reset() {
|
|
596
|
+
groups.clear();
|
|
597
|
+
current = undefined;
|
|
598
|
+
size = 0;
|
|
599
|
+
requests = 0;
|
|
600
|
+
hits = 0;
|
|
601
|
+
calls = 0;
|
|
602
|
+
},
|
|
603
|
+
};
|
|
329
604
|
}
|
|
330
605
|
|
|
331
606
|
/** The id of a text measure. `docs/TEXT.md` gives the definitions. */
|