@mark1russell7/layout-contract 0.3.4 → 0.3.5
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 +30 -0
- package/build/text.d.ts.map +1 -1
- package/build/text.js +106 -2
- package/build/text.js.map +1 -1
- package/package.json +1 -1
- package/src/text.ts +151 -0
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`, `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 {
|
|
@@ -97,6 +99,34 @@ export interface TextLayout {
|
|
|
97
99
|
* 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.
|
|
98
100
|
*/
|
|
99
101
|
export declare function layoutText(text: string, options: TextLayoutOptions): TextLayout;
|
|
102
|
+
/** The counts of a `TextLayoutCache`. `calls` is the count of the `layoutText` calls, and `size` is the count of the entries. */
|
|
103
|
+
export interface TextLayoutCacheStats extends MeasurerStats {
|
|
104
|
+
readonly size: number;
|
|
105
|
+
}
|
|
106
|
+
/** The options of `createTextLayoutCache`. */
|
|
107
|
+
export interface TextLayoutCacheOptions {
|
|
108
|
+
/** The largest count of the entries. The default is 4096. With 0, the cache keeps no entry. */
|
|
109
|
+
readonly maxEntries?: number;
|
|
110
|
+
}
|
|
111
|
+
/** A cache of `layoutText` results. A caller asks for it with `createTextLayoutCache`. `layoutText` itself has no cache of results. */
|
|
112
|
+
export interface TextLayoutCache {
|
|
113
|
+
/**
|
|
114
|
+
* This function gives the result of `layoutText` for the text and the options.
|
|
115
|
+
* The result is deeply frozen. Equal arguments give the same object until the cache removes the entry.
|
|
116
|
+
*/
|
|
117
|
+
layout(text: string, options: TextLayoutOptions): TextLayout;
|
|
118
|
+
/** This function gives the counts since the start or since the last `reset`. */
|
|
119
|
+
stats(): TextLayoutCacheStats;
|
|
120
|
+
/** This function clears the entries and the counts. */
|
|
121
|
+
reset(): void;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* This function gives a bounded cache of `layoutText` results, keyed by the text, the options and the measurer.
|
|
125
|
+
* A full cache removes one entry. It takes the set of options that a caller used least recently, and in it the text that a caller used least recently.
|
|
126
|
+
* The key holds the raw font string, because a host can give two spellings of a font two different advances.
|
|
127
|
+
* 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.
|
|
128
|
+
*/
|
|
129
|
+
export declare function createTextLayoutCache(options?: TextLayoutCacheOptions): TextLayoutCache;
|
|
100
130
|
/** The id of a text measure. `docs/TEXT.md` gives the definitions. */
|
|
101
131
|
export type TextMeasureId = "text.lines" | "text.raggedness" | "text.overflow" | "text.cacheHit" | "text.ms";
|
|
102
132
|
/** 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;;iBAOX;WACN;WACA,UAAU;;WAEV;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;;;;WAKA;;;;;WAKA;;;iBAIM;WACN;;WAEA;WACA;;WAEA;WACA;;WAEA;;WAEA;;;;;;;;;wBAwBK,WAAW,cAAc,SAAS,oBAAoB;;iBAkGrD,6BAA6B;WACnC;;;iBAIM;;WAEN;;;iBAIM;;;;;EAKf,OAAO,cAAc,SAAS,oBAAoB;;EAElD,SAAS;;EAET;;;;;;;;wBAkDc,sBAAsB,UAAS,yBAA8B;;YA4EjE;;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. */
|
|
@@ -245,6 +248,107 @@ function layoutText(text, options) {
|
|
|
245
248
|
truncated
|
|
246
249
|
};
|
|
247
250
|
}
|
|
251
|
+
/** This function gives the key text of a number. It keeps -0, because `layoutText` can give -0 back in a result. */
|
|
252
|
+
function numberKey(value) {
|
|
253
|
+
return Object.is(value, -0) ? "-0" : String(value);
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* This function gives the key of a set of options, without the text and the measurer. Two different sets do not give one key.
|
|
257
|
+
* A number has no comma. The two lengths mark the end of the font and of the ellipsis.
|
|
258
|
+
*/
|
|
259
|
+
function optionsKey(o) {
|
|
260
|
+
return `${`${numberKey(o.lineHeight)},${numberKey(o.wrapWidth)},${numberKey(o.maxLines)},${numberKey(o.maxChars)},${numberKey(o.padding)},${numberKey(o.minWidth)},${numberKey(o.maxWidth)}`},${(o.wordBreak ?? "keep") === "keep"},${o.breaker},${o.font.length},${o.ellipsis?.length},${o.font}${o.ellipsis ?? ""}`;
|
|
261
|
+
}
|
|
262
|
+
/** This function tells if two sets of options are the same. It uses `Object.is`, so 0 and -0 are different. It makes no string, so it is cheap on each hit. */
|
|
263
|
+
function sameOptions(a, b) {
|
|
264
|
+
return a.font === b.font && a.measurer === b.measurer && Object.is(a.lineHeight, b.lineHeight) && Object.is(a.wrapWidth, b.wrapWidth) && Object.is(a.maxLines, b.maxLines) && Object.is(a.maxChars, b.maxChars) && Object.is(a.padding, b.padding) && Object.is(a.minWidth, b.minWidth) && Object.is(a.maxWidth, b.maxWidth) && a.ellipsis === b.ellipsis && a.wordBreak === b.wordBreak && a.breaker === b.breaker;
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* This function gives a bounded cache of `layoutText` results, keyed by the text, the options and the measurer.
|
|
268
|
+
* A full cache removes one entry. It takes the set of options that a caller used least recently, and in it the text that a caller used least recently.
|
|
269
|
+
* The key holds the raw font string, because a host can give two spellings of a font two different advances.
|
|
270
|
+
* 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.
|
|
271
|
+
*/
|
|
272
|
+
function createTextLayoutCache(options = {}) {
|
|
273
|
+
const max = options.maxEntries ?? 4096;
|
|
274
|
+
if (!(Number.isInteger(max) && max >= 0)) throw new RangeError(`createTextLayoutCache: maxEntries is an integer of 0 or more, not ${max}.`);
|
|
275
|
+
const groups = /* @__PURE__ */ new Map();
|
|
276
|
+
const ids = /* @__PURE__ */ new WeakMap();
|
|
277
|
+
let nextId = 0;
|
|
278
|
+
let current;
|
|
279
|
+
let size = 0;
|
|
280
|
+
let requests = 0;
|
|
281
|
+
let hits = 0;
|
|
282
|
+
let calls = 0;
|
|
283
|
+
const idOf = (measurer) => {
|
|
284
|
+
let id = ids.get(measurer);
|
|
285
|
+
if (id === void 0) {
|
|
286
|
+
id = nextId++;
|
|
287
|
+
ids.set(measurer, id);
|
|
288
|
+
}
|
|
289
|
+
return id;
|
|
290
|
+
};
|
|
291
|
+
/** This function finds the layouts of a set of options, and it makes that set the most recently used. */
|
|
292
|
+
const open = (layoutOptions, generation) => {
|
|
293
|
+
const key = `${idOf(layoutOptions.measurer)},${generation},${optionsKey(layoutOptions)}`;
|
|
294
|
+
const layouts = groups.get(key) ?? /* @__PURE__ */ new Map();
|
|
295
|
+
if (groups.delete(key)) groups.set(key, layouts);
|
|
296
|
+
return {
|
|
297
|
+
options: { ...layoutOptions },
|
|
298
|
+
generation,
|
|
299
|
+
key,
|
|
300
|
+
layouts
|
|
301
|
+
};
|
|
302
|
+
};
|
|
303
|
+
/** This function removes one entry. */
|
|
304
|
+
const evict = () => {
|
|
305
|
+
const [key, layouts] = groups.entries().next().value;
|
|
306
|
+
layouts.delete(layouts.keys().next().value);
|
|
307
|
+
size--;
|
|
308
|
+
if (layouts.size === 0) groups.delete(key);
|
|
309
|
+
};
|
|
310
|
+
return {
|
|
311
|
+
layout(text, layoutOptions) {
|
|
312
|
+
requests++;
|
|
313
|
+
const generation = layoutOptions.measurer.generation?.();
|
|
314
|
+
if (current === void 0 || generation !== current.generation || !sameOptions(current.options, layoutOptions)) current = open(layoutOptions, generation);
|
|
315
|
+
const { key, layouts } = current;
|
|
316
|
+
const known = layouts.get(text);
|
|
317
|
+
if (known !== void 0) {
|
|
318
|
+
hits++;
|
|
319
|
+
layouts.delete(text);
|
|
320
|
+
layouts.set(text, known);
|
|
321
|
+
return known;
|
|
322
|
+
}
|
|
323
|
+
calls++;
|
|
324
|
+
const layout = layoutText(text, layoutOptions);
|
|
325
|
+
Object.freeze(layout.lines);
|
|
326
|
+
Object.freeze(layout.widths);
|
|
327
|
+
Object.freeze(layout);
|
|
328
|
+
if (max > 0) {
|
|
329
|
+
if (size >= max) evict();
|
|
330
|
+
if (layouts.size === 0) groups.set(key, layouts);
|
|
331
|
+
layouts.set(text, layout);
|
|
332
|
+
size++;
|
|
333
|
+
}
|
|
334
|
+
return layout;
|
|
335
|
+
},
|
|
336
|
+
stats: () => ({
|
|
337
|
+
requests,
|
|
338
|
+
hits,
|
|
339
|
+
calls,
|
|
340
|
+
size
|
|
341
|
+
}),
|
|
342
|
+
reset() {
|
|
343
|
+
groups.clear();
|
|
344
|
+
current = void 0;
|
|
345
|
+
size = 0;
|
|
346
|
+
requests = 0;
|
|
347
|
+
hits = 0;
|
|
348
|
+
calls = 0;
|
|
349
|
+
}
|
|
350
|
+
};
|
|
351
|
+
}
|
|
248
352
|
/** The specs of the text measures. */
|
|
249
353
|
const TEXT_MEASURES = /* @__PURE__ */ Object.freeze([
|
|
250
354
|
{
|
|
@@ -313,6 +417,6 @@ function textMeasures(layout, stats) {
|
|
|
313
417
|
...stats === void 0 ? {} : { "text.cacheHit": stats.requests === 0 ? 0 : stats.hits / stats.requests }
|
|
314
418
|
};
|
|
315
419
|
}
|
|
316
|
-
export { TEXT_MEASURES, TEXT_UNITS, canvasAdvance, createMeasurer, fontKey, graphemesOf, layoutText, textMeasures };
|
|
420
|
+
export { TEXT_MEASURES, TEXT_UNITS, canvasAdvance, createMeasurer, createTextLayoutCache, fontKey, graphemesOf, layoutText, textMeasures };
|
|
317
421
|
|
|
318
422
|
//# 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,IAAI,EAAE;CACnI,MAAM,wBAAQ,IAAI,IAAoB;CACtC,IAAI,WAAW;CACf,IAAI,OAAO;CACX,IAAI,QAAQ;CACZ,OAAO;EACL,QAAQ,SAAS,MAAM;GACrB;GACA,MAAM,MAAM,GAAG,QAAQ,IAAI,EAAE,QAAQ;GACrC,MAAM,QAAQ,MAAM,IAAI,GAAG;GAC3B,IAAI,UAAU,KAAA,GAAW;IACvB;IACA,OAAO;GACT;GACA;GACA,MAAM,KAAK,QAAQ,SAAS,IAAI;GAChC,IAAI,CAAC,OAAO,SAAS,EAAE,KAAK,KAAK,GAAG,MAAM,IAAI,WAAW,mBAAmB,QAAQ,QAAQ,KAAK,OAAO,GAAG,oCAAoC;GAC/I,MAAM,QAAQ,KAAK,MAAM,KAAA,EAAe;GACxC,IAAI,MAAM,GAAG;IACX,IAAI,MAAM,QAAQ,KAAK,MAAM,OAAO,MAAM,KAAK,CAAC,CAAC,KAAK,CAA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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 options of `layoutText`. All lengths are in pixels. */\nexport interface TextLayoutOptions {\n readonly font: string;\n readonly measurer: TextMeasurer;\n /** The line height. A finite number above 0. */\n readonly lineHeight: number;\n /** The width of the lines of a text that does not fit on one line. Without it, the text stays on one line. */\n readonly wrapWidth?: number;\n /** The count of the lines. The last line that stays gets the ellipsis. The default is no limit. */\n readonly maxLines?: number;\n /** The count of the grapheme clusters. A longer text keeps `maxChars` clusters with the ellipsis at the end. The default is no limit. */\n readonly maxChars?: number;\n /** The text at the end of a cut text. The default is \"…\". */\n readonly ellipsis?: string;\n /** The space that the box adds to the width of the text. The default is 0. */\n readonly padding?: number;\n /** The smallest width of a box with one line. The default is 0. */\n readonly minWidth?: number;\n /** The largest width of a box with one line. A text that does not fit wraps at `wrapWidth`. The default is `wrapWidth` plus the padding, or no limit without `wrapWidth`. */\n readonly maxWidth?: number;\n /**\n * The break of a word that is wider than a line. `keep` (the default) keeps the word whole, and the line overflows.\n * `anywhere` breaks it between two grapheme clusters, as the CSS `overflow-wrap: anywhere`.\n */\n readonly wordBreak?: \"keep\" | \"anywhere\";\n /**\n * The line breaker of `@mark1russell7/typeset`. `greedy` (the default) fills each line, as a browser. `total-fit` (Knuth and Plass)\n * makes the lines more equal. `balanced` keeps the greedy line count with the least width.\n */\n readonly breaker?: \"greedy\" | \"total-fit\" | \"balanced\";\n}\n\n/** The layout of a text: its lines and its box. */\nexport interface TextLayout {\n readonly lines: readonly string[];\n /** The width of each line, in pixels. Each width is a whole number of units of 1/`TEXT_UNITS` pixel. */\n readonly widths: readonly number[];\n readonly lineCount: number;\n /** The width of the box: the text and the padding. */\n readonly width: number;\n readonly height: number;\n /** The width of the lines, or `undefined` for a text on one line. */\n readonly wrapWidth?: number;\n /** `true` when `maxChars` or `maxLines` cut the text. */\n readonly truncated: boolean;\n}\n\n/** A forced break: a penalty with no text, no width and the cost `-Infinity`. */\nconst FORCED: Penalty = { type: \"penalty\", text: \"\", width: 0, cost: -Infinity, flagged: false };\n\n/** This function gives the box of a part of a word. */\nfunction boxOf(part: { readonly text: string; readonly width: number }): Box {\n return { type: \"box\", text: part.text, width: part.width };\n}\n\n/** A line of a layout, with its width in units. */\ninterface Line {\n text: string;\n units: number;\n}\n\n/**\n * This function lays out a text. It cuts the text to `maxChars`. It keeps the text on one line when it fits in `maxWidth`. Else it breaks the text into lines of `wrapWidth`.\n *\n * The breaker comes from `@mark1russell7/typeset`. The default is greedy, as a browser with `white-space: normal`.\n * It collapses each run of white space to one space, and a line does not count its last space.\n * The width of a word is the sum of the advances of its segments. `docs/TEXT.md` gives the rules and the error of this sum.\n */\nexport function layoutText(text: string, options: TextLayoutOptions): TextLayout {\n const { font, measurer, lineHeight } = options;\n if (!(Number.isFinite(lineHeight) && lineHeight > 0)) throw new RangeError(`layoutText: lineHeight is a finite number above 0, not ${lineHeight}.`);\n const ellipsis = options.ellipsis ?? \"…\";\n const padding = options.padding ?? 0;\n const keep = (options.wordBreak ?? \"keep\") === \"keep\";\n const name = options.breaker ?? \"greedy\";\n if (!Object.hasOwn(breakers, name)) throw new RangeError(`layoutText: breaker is \"greedy\", \"total-fit\" or \"balanced\", not ${String(name)}.`);\n const breaker = breakers[name];\n let truncated = false;\n\n let source = text;\n if (options.maxChars !== undefined) {\n const clusters = graphemesOf(source);\n if (clusters.length > options.maxChars) {\n const room = Math.max(0, options.maxChars - graphemesOf(ellipsis).length);\n source = clusters.slice(0, room).join(\"\") + ellipsis;\n truncated = true;\n }\n }\n\n const words = wordsOf(source);\n const space = measurer.advance(\" \", font);\n const width = (w: Word): number => w.parts.reduce((s, p) => s + measurer.advance(p, font), 0);\n const lineUnits = (line: string): number => {\n const ws = wordsOf(line);\n return ws.reduce((s, w) => s + width(w), 0) + space * Math.max(0, ws.length - 1);\n };\n const widths = words.map(width);\n const natural = widths.reduce((s, w) => s + w, 0) + space * Math.max(0, words.length - 1);\n\n const maxWidth = options.maxWidth ?? (options.wrapWidth === undefined ? Infinity : options.wrapWidth + padding);\n const fits = natural / TEXT_UNITS + padding <= maxWidth;\n if (options.wrapWidth === undefined || fits) {\n const one = words.map((w) => w.text).join(\" \");\n const px = natural / TEXT_UNITS;\n const box = Math.min(maxWidth, Math.max(options.minWidth ?? 0, px + padding));\n return { lines: [one], widths: [px], lineCount: 1, width: box, height: lineHeight, truncated };\n }\n\n const limit = Math.round(options.wrapWidth * TEXT_UNITS);\n // The items of the breaker: a box for each word, and glue of one space between two words.\n const items: Item[] = [];\n /** This function puts a word that is wider than a line on new lines, with a break between grapheme clusters. Each forced penalty ends a line. */\n const split = (word: Word): void => {\n if (items.length > 0) items.push(FORCED);\n let cur: { text: string; width: number } | undefined;\n for (const g of graphemesOf(word.text)) {\n const w = measurer.advance(g, font);\n if (cur !== undefined && cur.width + w > limit) {\n items.push(boxOf(cur), FORCED);\n cur = undefined;\n }\n if (cur === undefined) cur = { text: g, width: w };\n else {\n cur.text += g;\n cur.width += w;\n }\n }\n if (cur !== undefined) items.push(boxOf(cur));\n };\n words.forEach((word, i) => {\n const w = widths[i]!;\n if (w > limit && !keep) split(word);\n else {\n if (items.length > 0) items.push({ type: \"glue\", text: \" \", width: space });\n items.push({ type: \"box\", text: word.text, width: w });\n }\n });\n const paragraph = { items };\n const lines: Line[] = linesOf(paragraph, breaker.breaks(paragraph, limit)).map((l) => ({ text: l.text, units: l.width }));\n if (lines.length === 0) lines.push({ text: \"\", units: 0 });\n\n const maxLines = options.maxLines ?? Infinity;\n if (lines.length > maxLines) {\n lines.length = Math.max(1, maxLines);\n const last = lines[lines.length - 1]!;\n const tail = measurer.advance(ellipsis, font);\n const clusters = graphemesOf(last.text);\n while (clusters.length > 0 && lineUnits(clusters.join(\"\")) + tail > limit) clusters.pop();\n const kept = clusters.join(\"\").replace(/\\s+$/u, \"\");\n last.text = kept + ellipsis;\n last.units = lineUnits(kept) + tail;\n truncated = true;\n }\n\n return {\n lines: lines.map((l) => l.text),\n widths: lines.map((l) => l.units / TEXT_UNITS),\n lineCount: lines.length,\n width: options.wrapWidth + padding,\n height: lines.length * lineHeight,\n wrapWidth: options.wrapWidth,\n truncated,\n };\n}\n\n/** The counts of a `TextLayoutCache`. `calls` is the count of the `layoutText` calls, and `size` is the count of the entries. */\nexport interface TextLayoutCacheStats extends MeasurerStats {\n readonly size: number;\n}\n\n/** The options of `createTextLayoutCache`. */\nexport interface TextLayoutCacheOptions {\n /** The largest count of the entries. The default is 4096. With 0, the cache keeps no entry. */\n readonly maxEntries?: number;\n}\n\n/** A cache of `layoutText` results. A caller asks for it with `createTextLayoutCache`. `layoutText` itself has no cache of results. */\nexport interface TextLayoutCache {\n /**\n * This function gives the result of `layoutText` for the text and the options.\n * The result is deeply frozen. Equal arguments give the same object until the cache removes the entry.\n */\n layout(text: string, options: TextLayoutOptions): TextLayout;\n /** This function gives the counts since the start or since the last `reset`. */\n stats(): TextLayoutCacheStats;\n /** This function clears the entries and the counts. */\n reset(): void;\n}\n\n/** This function gives the key text of a number. It keeps -0, because `layoutText` can give -0 back in a result. */\nfunction numberKey(value: number | undefined): string {\n return Object.is(value, -0) ? \"-0\" : String(value);\n}\n\n/**\n * This function gives the key of a set of options, without the text and the measurer. Two different sets do not give one key.\n * A number has no comma. The two lengths mark the end of the font and of the ellipsis.\n */\nfunction optionsKey(o: TextLayoutOptions): string {\n const numbers = `${numberKey(o.lineHeight)},${numberKey(o.wrapWidth)},${numberKey(o.maxLines)},${numberKey(o.maxChars)},${numberKey(o.padding)},${numberKey(o.minWidth)},${numberKey(o.maxWidth)}`;\n return `${numbers},${(o.wordBreak ?? \"keep\") === \"keep\"},${o.breaker},${o.font.length},${o.ellipsis?.length},${o.font}${o.ellipsis ?? \"\"}`;\n}\n\n/** This function tells if two sets of options are the same. It uses `Object.is`, so 0 and -0 are different. It makes no string, so it is cheap on each hit. */\nfunction sameOptions(a: TextLayoutOptions, b: TextLayoutOptions): boolean {\n return (\n a.font === b.font &&\n a.measurer === b.measurer &&\n Object.is(a.lineHeight, b.lineHeight) &&\n Object.is(a.wrapWidth, b.wrapWidth) &&\n Object.is(a.maxLines, b.maxLines) &&\n Object.is(a.maxChars, b.maxChars) &&\n Object.is(a.padding, b.padding) &&\n Object.is(a.minWidth, b.minWidth) &&\n Object.is(a.maxWidth, b.maxWidth) &&\n a.ellipsis === b.ellipsis &&\n a.wordBreak === b.wordBreak &&\n a.breaker === b.breaker\n );\n}\n\n/** The set of options of the last call of a cache, with its layouts by text. */\ninterface CurrentOptions {\n /** A copy of the options, so a later change of the object of the caller does not touch it. */\n readonly options: TextLayoutOptions;\n readonly generation: number | undefined;\n readonly key: string;\n readonly layouts: Map<string, TextLayout>;\n}\n\n/**\n * This function gives a bounded cache of `layoutText` results, keyed by the text, the options and the measurer.\n * A full cache removes one entry. It takes the set of options that a caller used least recently, and in it the text that a caller used least recently.\n * The key holds the raw font string, because a host can give two spellings of a font two different advances.\n * A measurer with `generation` starts a new set of keys after each `reset`. For a different measurer, start `reset` of the cache after a change of the advances.\n */\nexport function createTextLayoutCache(options: TextLayoutCacheOptions = {}): TextLayoutCache {\n const max = options.maxEntries ?? 4096;\n if (!(Number.isInteger(max) && max >= 0)) throw new RangeError(`createTextLayoutCache: maxEntries is an integer of 0 or more, not ${max}.`);\n // Each Map keeps the order of insertion, so its first key is the least recently used. A set of options is here only while it has an entry.\n const groups = new Map<string, Map<string, TextLayout>>();\n // A measurer is an object. It gets a number here, so a key does not keep the measurer alive.\n const ids = new WeakMap<TextMeasurer, number>();\n let nextId = 0;\n let current: CurrentOptions | undefined;\n let size = 0;\n let requests = 0;\n let hits = 0;\n let calls = 0;\n const idOf = (measurer: TextMeasurer): number => {\n let id = ids.get(measurer);\n if (id === undefined) {\n id = nextId++;\n ids.set(measurer, id);\n }\n return id;\n };\n /** This function finds the layouts of a set of options, and it makes that set the most recently used. */\n const open = (layoutOptions: TextLayoutOptions, generation: number | undefined): CurrentOptions => {\n const key = `${idOf(layoutOptions.measurer)},${generation},${optionsKey(layoutOptions)}`;\n const layouts = groups.get(key) ?? new Map<string, TextLayout>();\n if (groups.delete(key)) groups.set(key, layouts);\n return { options: { ...layoutOptions }, generation, key, layouts };\n };\n /** This function removes one entry. */\n const evict = (): void => {\n const [key, layouts] = groups.entries().next().value!;\n layouts.delete(layouts.keys().next().value!);\n size--;\n if (layouts.size === 0) groups.delete(key);\n };\n return {\n layout(text, layoutOptions) {\n requests++;\n const generation = layoutOptions.measurer.generation?.();\n if (current === undefined || generation !== current.generation || !sameOptions(current.options, layoutOptions)) current = open(layoutOptions, generation);\n const { key, layouts } = current;\n const known = layouts.get(text);\n if (known !== undefined) {\n hits++;\n // This moves the text to the end of the order.\n layouts.delete(text);\n layouts.set(text, known);\n return known;\n }\n calls++;\n const layout = layoutText(text, layoutOptions);\n // The callers share this object, so it is frozen also when the cache does not keep it.\n Object.freeze(layout.lines);\n Object.freeze(layout.widths);\n Object.freeze(layout);\n if (max > 0) {\n if (size >= max) evict();\n if (layouts.size === 0) groups.set(key, layouts);\n layouts.set(text, layout);\n size++;\n }\n return layout;\n },\n stats: () => ({ requests, hits, calls, size }),\n reset() {\n groups.clear();\n current = undefined;\n size = 0;\n requests = 0;\n hits = 0;\n calls = 0;\n },\n };\n}\n\n/** The id of a text measure. `docs/TEXT.md` gives the definitions. */\nexport type TextMeasureId = \"text.lines\" | \"text.raggedness\" | \"text.overflow\" | \"text.cacheHit\" | \"text.ms\";\n\n/** The specs of the text measures. */\nexport const TEXT_MEASURES: readonly MeasureSpec<TextMeasureId>[] = /* @__PURE__ */ Object.freeze([\n { id: \"text.lines\", unit: \"count\", direction: \"lower\", min: 1, max: Infinity, minEffect: 0, family: \"text\" },\n { id: \"text.raggedness\", unit: \"0 to 1\", direction: \"lower\", min: 0, max: 1, minEffect: 0.005, family: \"text\" },\n { id: \"text.overflow\", unit: \"share of the wrap width\", direction: \"lower\", min: 0, max: Infinity, floor: 0, tol: 0, minEffect: 0, family: \"text\", role: \"guard\" },\n { id: \"text.cacheHit\", unit: \"0 to 1\", direction: \"higher\", min: 0, max: 1, family: \"text\", role: \"diagnostic\" },\n { id: \"text.ms\", unit: \"milliseconds\", direction: \"lower\", min: 0, max: Infinity, family: \"text\", role: \"time\" },\n] as const);\n\n/**\n * This function gives the measures of a layout. `text.raggedness` is the mean of `((wrapWidth - width) / wrapWidth)^2` over the lines before the last line.\n * `text.overflow` is the largest excess of a line over `wrapWidth`, as a share of `wrapWidth`. A text on one line gives 0 for the two values.\n * With `stats`, the measures also hold `text.cacheHit`: the hits divided by the requests.\n */\nexport function textMeasures(layout: TextLayout, stats?: MeasurerStats): Partial<Record<TextMeasureId, number>> {\n const w = layout.wrapWidth;\n const body = layout.widths.slice(0, -1);\n const raggedness = w === undefined || body.length === 0 ? 0 : body.reduce((s, x) => s + (Math.max(0, w - x) / w) ** 2, 0) / body.length;\n const overflow = w === undefined ? 0 : Math.max(0, ...layout.widths.map((x) => (x - w) / w));\n return {\n \"text.lines\": layout.lineCount,\n \"text.raggedness\": raggedness,\n \"text.overflow\": overflow,\n ...(stats === undefined ? {} : { \"text.cacheHit\": stats.requests === 0 ? 0 : stats.hits / stats.requests }),\n };\n}\n"],"mappings":";;;AAUA,MAAa,aAAa;;AA4B1B,SAAgB,QAAQ,MAAsB;CAC5C,OAAO,KAAK,KAAK,CAAC,CAAC,QAAQ,QAAQ,GAAG;AACxC;;;;;AAMA,SAAgB,eAAe,SAAoB,UAA2B,CAAC,GAAiB;CAC9F,MAAM,MAAM,QAAQ,cAAc;CAClC,IAAI,EAAE,OAAO,UAAU,GAAG,KAAK,OAAO,IAAI,MAAM,IAAI,WAAW,8DAA8D,IAAI,EAAE;CACnI,MAAM,wBAAQ,IAAI,IAAoB;CACtC,IAAI,WAAW;CACf,IAAI,OAAO;CACX,IAAI,QAAQ;CACZ,IAAI,aAAa;CACjB,OAAO;EACL,QAAQ,SAAS,MAAM;GACrB;GACA,MAAM,MAAM,GAAG,QAAQ,IAAI,EAAE,QAAQ;GACrC,MAAM,QAAQ,MAAM,IAAI,GAAG;GAC3B,IAAI,UAAU,KAAA,GAAW;IACvB;IACA,OAAO;GACT;GACA;GACA,MAAM,KAAK,QAAQ,SAAS,IAAI;GAChC,IAAI,CAAC,OAAO,SAAS,EAAE,KAAK,KAAK,GAAG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AAO,QAAQ;CAAO;CAC9G;EAAE,IAAI;EAAiB,MAAM;EAA2B,WAAW;EAAS,KAAK;EAAG,KAAK;EAAU,OAAO;EAAG,KAAK;EAAG,WAAW;EAAG,QAAQ;EAAQ,MAAM;CAAQ;CACjK;EAAE,IAAI;EAAiB,MAAM;EAAU,WAAW;EAAU,KAAK;EAAG,KAAK;EAAG,QAAQ;EAAQ,MAAM;CAAa;CAC/G;EAAE,IAAI;EAAW,MAAM;EAAgB,WAAW;EAAS,KAAK;EAAG,KAAK;EAAU,QAAQ;EAAQ,MAAM;CAAO;AACjH,CAAU;;;;;;AAOV,SAAgB,aAAa,QAAoB,OAA+D;CAC9G,MAAM,IAAI,OAAO;CACjB,MAAM,OAAO,OAAO,OAAO,MAAM,GAAG,EAAE;CACtC,MAAM,aAAa,MAAM,KAAA,KAAa,KAAK,WAAW,IAAI,IAAI,KAAK,QAAQ,GAAG,MAAM,KAAK,KAAK,IAAI,GAAG,IAAI,CAAC,IAAI,MAAM,GAAG,CAAC,IAAI,KAAK;CACjI,MAAM,WAAW,MAAM,KAAA,IAAY,IAAI,KAAK,IAAI,GAAG,GAAG,OAAO,OAAO,KAAK,OAAO,IAAI,KAAK,CAAC,CAAC;CAC3F,OAAO;EACL,cAAc,OAAO;EACrB,mBAAmB;EACnB,iBAAiB;EACjB,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,iBAAiB,MAAM,aAAa,IAAI,IAAI,MAAM,OAAO,MAAM,SAAS;CAC3G;AACF"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package",
|
|
3
3
|
"name": "@mark1russell7/layout-contract",
|
|
4
|
-
"version": "0.3.
|
|
4
|
+
"version": "0.3.5",
|
|
5
5
|
"description": "The shared contract of the packing and highways layout engines: the input and record formats, the turn rule, margins, tolerances and hard rules.",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"layout",
|
package/src/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
|
|
|
@@ -328,6 +333,152 @@ export function layoutText(text: string, options: TextLayoutOptions): TextLayout
|
|
|
328
333
|
};
|
|
329
334
|
}
|
|
330
335
|
|
|
336
|
+
/** The counts of a `TextLayoutCache`. `calls` is the count of the `layoutText` calls, and `size` is the count of the entries. */
|
|
337
|
+
export interface TextLayoutCacheStats extends MeasurerStats {
|
|
338
|
+
readonly size: number;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** The options of `createTextLayoutCache`. */
|
|
342
|
+
export interface TextLayoutCacheOptions {
|
|
343
|
+
/** The largest count of the entries. The default is 4096. With 0, the cache keeps no entry. */
|
|
344
|
+
readonly maxEntries?: number;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/** A cache of `layoutText` results. A caller asks for it with `createTextLayoutCache`. `layoutText` itself has no cache of results. */
|
|
348
|
+
export interface TextLayoutCache {
|
|
349
|
+
/**
|
|
350
|
+
* This function gives the result of `layoutText` for the text and the options.
|
|
351
|
+
* The result is deeply frozen. Equal arguments give the same object until the cache removes the entry.
|
|
352
|
+
*/
|
|
353
|
+
layout(text: string, options: TextLayoutOptions): TextLayout;
|
|
354
|
+
/** This function gives the counts since the start or since the last `reset`. */
|
|
355
|
+
stats(): TextLayoutCacheStats;
|
|
356
|
+
/** This function clears the entries and the counts. */
|
|
357
|
+
reset(): void;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/** This function gives the key text of a number. It keeps -0, because `layoutText` can give -0 back in a result. */
|
|
361
|
+
function numberKey(value: number | undefined): string {
|
|
362
|
+
return Object.is(value, -0) ? "-0" : String(value);
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* This function gives the key of a set of options, without the text and the measurer. Two different sets do not give one key.
|
|
367
|
+
* A number has no comma. The two lengths mark the end of the font and of the ellipsis.
|
|
368
|
+
*/
|
|
369
|
+
function optionsKey(o: TextLayoutOptions): string {
|
|
370
|
+
const numbers = `${numberKey(o.lineHeight)},${numberKey(o.wrapWidth)},${numberKey(o.maxLines)},${numberKey(o.maxChars)},${numberKey(o.padding)},${numberKey(o.minWidth)},${numberKey(o.maxWidth)}`;
|
|
371
|
+
return `${numbers},${(o.wordBreak ?? "keep") === "keep"},${o.breaker},${o.font.length},${o.ellipsis?.length},${o.font}${o.ellipsis ?? ""}`;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** 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. */
|
|
375
|
+
function sameOptions(a: TextLayoutOptions, b: TextLayoutOptions): boolean {
|
|
376
|
+
return (
|
|
377
|
+
a.font === b.font &&
|
|
378
|
+
a.measurer === b.measurer &&
|
|
379
|
+
Object.is(a.lineHeight, b.lineHeight) &&
|
|
380
|
+
Object.is(a.wrapWidth, b.wrapWidth) &&
|
|
381
|
+
Object.is(a.maxLines, b.maxLines) &&
|
|
382
|
+
Object.is(a.maxChars, b.maxChars) &&
|
|
383
|
+
Object.is(a.padding, b.padding) &&
|
|
384
|
+
Object.is(a.minWidth, b.minWidth) &&
|
|
385
|
+
Object.is(a.maxWidth, b.maxWidth) &&
|
|
386
|
+
a.ellipsis === b.ellipsis &&
|
|
387
|
+
a.wordBreak === b.wordBreak &&
|
|
388
|
+
a.breaker === b.breaker
|
|
389
|
+
);
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** The set of options of the last call of a cache, with its layouts by text. */
|
|
393
|
+
interface CurrentOptions {
|
|
394
|
+
/** A copy of the options, so a later change of the object of the caller does not touch it. */
|
|
395
|
+
readonly options: TextLayoutOptions;
|
|
396
|
+
readonly generation: number | undefined;
|
|
397
|
+
readonly key: string;
|
|
398
|
+
readonly layouts: Map<string, TextLayout>;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* This function gives a bounded cache of `layoutText` results, keyed by the text, the options and the measurer.
|
|
403
|
+
* A full cache removes one entry. It takes the set of options that a caller used least recently, and in it the text that a caller used least recently.
|
|
404
|
+
* The key holds the raw font string, because a host can give two spellings of a font two different advances.
|
|
405
|
+
* 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.
|
|
406
|
+
*/
|
|
407
|
+
export function createTextLayoutCache(options: TextLayoutCacheOptions = {}): TextLayoutCache {
|
|
408
|
+
const max = options.maxEntries ?? 4096;
|
|
409
|
+
if (!(Number.isInteger(max) && max >= 0)) throw new RangeError(`createTextLayoutCache: maxEntries is an integer of 0 or more, not ${max}.`);
|
|
410
|
+
// Each Map keeps the order of insertion, so its first key is the least recently used. A set of options is here only while it has an entry.
|
|
411
|
+
const groups = new Map<string, Map<string, TextLayout>>();
|
|
412
|
+
// A measurer is an object. It gets a number here, so a key does not keep the measurer alive.
|
|
413
|
+
const ids = new WeakMap<TextMeasurer, number>();
|
|
414
|
+
let nextId = 0;
|
|
415
|
+
let current: CurrentOptions | undefined;
|
|
416
|
+
let size = 0;
|
|
417
|
+
let requests = 0;
|
|
418
|
+
let hits = 0;
|
|
419
|
+
let calls = 0;
|
|
420
|
+
const idOf = (measurer: TextMeasurer): number => {
|
|
421
|
+
let id = ids.get(measurer);
|
|
422
|
+
if (id === undefined) {
|
|
423
|
+
id = nextId++;
|
|
424
|
+
ids.set(measurer, id);
|
|
425
|
+
}
|
|
426
|
+
return id;
|
|
427
|
+
};
|
|
428
|
+
/** This function finds the layouts of a set of options, and it makes that set the most recently used. */
|
|
429
|
+
const open = (layoutOptions: TextLayoutOptions, generation: number | undefined): CurrentOptions => {
|
|
430
|
+
const key = `${idOf(layoutOptions.measurer)},${generation},${optionsKey(layoutOptions)}`;
|
|
431
|
+
const layouts = groups.get(key) ?? new Map<string, TextLayout>();
|
|
432
|
+
if (groups.delete(key)) groups.set(key, layouts);
|
|
433
|
+
return { options: { ...layoutOptions }, generation, key, layouts };
|
|
434
|
+
};
|
|
435
|
+
/** This function removes one entry. */
|
|
436
|
+
const evict = (): void => {
|
|
437
|
+
const [key, layouts] = groups.entries().next().value!;
|
|
438
|
+
layouts.delete(layouts.keys().next().value!);
|
|
439
|
+
size--;
|
|
440
|
+
if (layouts.size === 0) groups.delete(key);
|
|
441
|
+
};
|
|
442
|
+
return {
|
|
443
|
+
layout(text, layoutOptions) {
|
|
444
|
+
requests++;
|
|
445
|
+
const generation = layoutOptions.measurer.generation?.();
|
|
446
|
+
if (current === undefined || generation !== current.generation || !sameOptions(current.options, layoutOptions)) current = open(layoutOptions, generation);
|
|
447
|
+
const { key, layouts } = current;
|
|
448
|
+
const known = layouts.get(text);
|
|
449
|
+
if (known !== undefined) {
|
|
450
|
+
hits++;
|
|
451
|
+
// This moves the text to the end of the order.
|
|
452
|
+
layouts.delete(text);
|
|
453
|
+
layouts.set(text, known);
|
|
454
|
+
return known;
|
|
455
|
+
}
|
|
456
|
+
calls++;
|
|
457
|
+
const layout = layoutText(text, layoutOptions);
|
|
458
|
+
// The callers share this object, so it is frozen also when the cache does not keep it.
|
|
459
|
+
Object.freeze(layout.lines);
|
|
460
|
+
Object.freeze(layout.widths);
|
|
461
|
+
Object.freeze(layout);
|
|
462
|
+
if (max > 0) {
|
|
463
|
+
if (size >= max) evict();
|
|
464
|
+
if (layouts.size === 0) groups.set(key, layouts);
|
|
465
|
+
layouts.set(text, layout);
|
|
466
|
+
size++;
|
|
467
|
+
}
|
|
468
|
+
return layout;
|
|
469
|
+
},
|
|
470
|
+
stats: () => ({ requests, hits, calls, size }),
|
|
471
|
+
reset() {
|
|
472
|
+
groups.clear();
|
|
473
|
+
current = undefined;
|
|
474
|
+
size = 0;
|
|
475
|
+
requests = 0;
|
|
476
|
+
hits = 0;
|
|
477
|
+
calls = 0;
|
|
478
|
+
},
|
|
479
|
+
};
|
|
480
|
+
}
|
|
481
|
+
|
|
331
482
|
/** The id of a text measure. `docs/TEXT.md` gives the definitions. */
|
|
332
483
|
export type TextMeasureId = "text.lines" | "text.raggedness" | "text.overflow" | "text.cacheHit" | "text.ms";
|
|
333
484
|
|