@mark1russell7/layout-contract 0.2.20 → 0.2.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/text.d.ts.map +1 -1
- package/build/text.js +27 -2
- package/build/text.js.map +1 -1
- package/package.json +1 -1
- package/src/text.ts +34 -4
package/build/text.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"text.d.ts","names":[],"sources":["../src/text.ts"],"mappings":";;;;;YAMY,aAAa,cAAc;;qBAG1B;;iBAGI;WACN;WACA;WACA;;;iBAIM;;EAEf,QAAQ,iBAAiB;;EAEzB,SAAS;;EAET;;;iBAIe;;WAEN;;;wBAIK,QAAQ;;;;;wBAQR,eAAe,SAAS,WAAW,UAAS,kBAAuB;;iBAqClE;EACf;EACA,YAAY;aAA0B;;;;wBAIxB,cAAc,SAAS,oBAAoB;;
|
|
1
|
+
{"version":3,"file":"text.d.ts","names":[],"sources":["../src/text.ts"],"mappings":";;;;;YAMY,aAAa,cAAc;;qBAG1B;;iBAGI;WACN;WACA;WACA;;;iBAIM;;EAEf,QAAQ,iBAAiB;;EAEzB,SAAS;;EAET;;;iBAIe;;WAEN;;;wBAIK,QAAQ;;;;;wBAQR,eAAe,SAAS,WAAW,UAAS,kBAAuB;;iBAqClE;EACf;EACA,YAAY;aAA0B;;;;wBAIxB,cAAc,SAAS,oBAAoB;;wBAwE3C,YAAY;;iBAOX;WACN;WACA,UAAU;;WAEV;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;;;;WAKA;;;iBAIM;WACN;;WAEA;WACA;;WAEA;WACA;;WAEA;;WAEA;;;;;;;;wBAeK,WAAW,cAAc,SAAS,oBAAoB;;YA+F1D;;qBAGC,wBAAwB,YAAY;;;;;;wBAajC,aAAa,QAAQ,YAAY,QAAQ,gBAAgB,QAAQ,OAAO"}
|
package/build/text.js
CHANGED
|
@@ -60,8 +60,31 @@ function canvasAdvance(context) {
|
|
|
60
60
|
};
|
|
61
61
|
}
|
|
62
62
|
const SPACE = /^\s+$/u;
|
|
63
|
+
/** The segmenters of the module. A new `Intl.Segmenter` loads the data of the locale, so the module makes each granularity only once. */
|
|
64
|
+
const segmenters = /* @__PURE__ */ new Map();
|
|
65
|
+
/** This function gives the segmenter of a granularity, or `null` without `Intl.Segmenter`. */
|
|
66
|
+
function segmenterOf(granularity) {
|
|
67
|
+
let s = segmenters.get(granularity);
|
|
68
|
+
if (s === void 0) {
|
|
69
|
+
s = typeof Intl !== "undefined" && typeof Intl.Segmenter === "function" ? new Intl.Segmenter(void 0, { granularity }) : null;
|
|
70
|
+
segmenters.set(granularity, s);
|
|
71
|
+
}
|
|
72
|
+
return s;
|
|
73
|
+
}
|
|
74
|
+
/** The largest count of texts in the memo of `wordsOf`. A page often asks for the same labels many times. */
|
|
75
|
+
const WORDS_MEMO = 4096;
|
|
76
|
+
const wordsMemo = /* @__PURE__ */ new Map();
|
|
63
77
|
/** 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. */
|
|
64
78
|
function wordsOf(text) {
|
|
79
|
+
const known = wordsMemo.get(text);
|
|
80
|
+
if (known !== void 0) return known;
|
|
81
|
+
const words = splitWords(text);
|
|
82
|
+
if (wordsMemo.size >= WORDS_MEMO) wordsMemo.delete(wordsMemo.keys().next().value);
|
|
83
|
+
wordsMemo.set(text, words);
|
|
84
|
+
return words;
|
|
85
|
+
}
|
|
86
|
+
/** This function gives the words of `wordsOf` with no memo. */
|
|
87
|
+
function splitWords(text) {
|
|
65
88
|
const words = [];
|
|
66
89
|
let parts = [];
|
|
67
90
|
const flush = () => {
|
|
@@ -71,7 +94,8 @@ function wordsOf(text) {
|
|
|
71
94
|
});
|
|
72
95
|
parts = [];
|
|
73
96
|
};
|
|
74
|
-
|
|
97
|
+
const segmenter = segmenterOf("word");
|
|
98
|
+
if (segmenter !== null) for (const s of segmenter.segment(text)) if (SPACE.test(s.segment)) flush();
|
|
75
99
|
else parts.push(s.segment);
|
|
76
100
|
else for (const s of text.split(/(\s+)/u)) if (s === "" || SPACE.test(s)) flush();
|
|
77
101
|
else parts.push(s);
|
|
@@ -80,7 +104,8 @@ function wordsOf(text) {
|
|
|
80
104
|
}
|
|
81
105
|
/** This function gives the grapheme clusters of a text. Without `Intl.Segmenter`, it gives the code points. */
|
|
82
106
|
function graphemesOf(text) {
|
|
83
|
-
|
|
107
|
+
const segmenter = segmenterOf("grapheme");
|
|
108
|
+
if (segmenter !== null) return Array.from(segmenter.segment(text), (s) => s.segment);
|
|
84
109
|
return Array.from(text);
|
|
85
110
|
}
|
|
86
111
|
/**
|
package/build/text.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"text.js","names":[],"sources":["../src/text.ts"],"sourcesContent":["import 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/** 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): 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 if (typeof Intl !== \"undefined\" && typeof Intl.Segmenter === \"function\") {\n for (const s of new Intl.Segmenter(undefined, { granularity: \"word\" }).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 if (typeof Intl !== \"undefined\" && typeof Intl.Segmenter === \"function\") return Array.from(new Intl.Segmenter(undefined, { granularity: \"grapheme\" }).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\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 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 is greedy, as a browser with `white-space: normal`. It collapses each run of white space to one space, and a line does not count its last space.\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 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 const lines: Line[] = [];\n let cur: Line | undefined;\n const push = (): void => {\n if (cur !== undefined) lines.push(cur);\n cur = undefined;\n };\n /** This function puts a word that is wider than a line on new lines, with a break between grapheme clusters. */\n const split = (word: Word): void => {\n for (const g of graphemesOf(word.text)) {\n const w = measurer.advance(g, font);\n if (cur !== undefined && cur.units + w > limit) push();\n if (cur === undefined) cur = { text: g, units: w };\n else {\n cur.text += g;\n cur.units += w;\n }\n }\n };\n words.forEach((word, i) => {\n const w = widths[i]!;\n if (cur !== undefined && cur.units + space + w <= limit) {\n cur.text += ` ${word.text}`;\n cur.units += space + w;\n return;\n }\n push();\n if (w > limit && !keep) split(word);\n else cur = { text: word.text, units: w };\n });\n push();\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>[] = 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":";;AASA,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,GAA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ureSpec } 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 = 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 = 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\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 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 is greedy, as a browser with `white-space: normal`. It collapses each run of white space to one space, and a line does not count its last space.\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 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 const lines: Line[] = [];\n let cur: Line | undefined;\n const push = (): void => {\n if (cur !== undefined) lines.push(cur);\n cur = undefined;\n };\n /** This function puts a word that is wider than a line on new lines, with a break between grapheme clusters. */\n const split = (word: Word): void => {\n for (const g of graphemesOf(word.text)) {\n const w = measurer.advance(g, font);\n if (cur !== undefined && cur.units + w > limit) push();\n if (cur === undefined) cur = { text: g, units: w };\n else {\n cur.text += g;\n cur.units += w;\n }\n }\n };\n words.forEach((word, i) => {\n const w = widths[i]!;\n if (cur !== undefined && cur.units + space + w <= limit) {\n cur.text += ` ${word.text}`;\n cur.units += space + w;\n return;\n }\n push();\n if (w > limit && !keep) split(word);\n else cur = { text: word.text, units: w };\n });\n push();\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>[] = 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":";;AASA,MAAa,aAAa;;AA0B1B,SAAgB,QAAQ,MAAsB;CAC5C,OAAO,KAAK,KAAK,CAAC,CAAC,QAAQ,QAAQ,GAAG;AACxC;;;;;AAMA,SAAgB,eAAe,SAAoB,U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,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.2.
|
|
4
|
+
"version": "0.2.21",
|
|
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
|
@@ -103,16 +103,45 @@ interface Word {
|
|
|
103
103
|
|
|
104
104
|
const SPACE = /^\s+$/u;
|
|
105
105
|
|
|
106
|
+
/** The segmenters of the module. A new `Intl.Segmenter` loads the data of the locale, so the module makes each granularity only once. */
|
|
107
|
+
const segmenters = new Map<"word" | "grapheme", Intl.Segmenter | null>();
|
|
108
|
+
|
|
109
|
+
/** This function gives the segmenter of a granularity, or `null` without `Intl.Segmenter`. */
|
|
110
|
+
function segmenterOf(granularity: "word" | "grapheme"): Intl.Segmenter | null {
|
|
111
|
+
let s = segmenters.get(granularity);
|
|
112
|
+
if (s === undefined) {
|
|
113
|
+
s = typeof Intl !== "undefined" && typeof Intl.Segmenter === "function" ? new Intl.Segmenter(undefined, { granularity }) : null;
|
|
114
|
+
segmenters.set(granularity, s);
|
|
115
|
+
}
|
|
116
|
+
return s;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** The largest count of texts in the memo of `wordsOf`. A page often asks for the same labels many times. */
|
|
120
|
+
const WORDS_MEMO = 4096;
|
|
121
|
+
const wordsMemo = new Map<string, readonly Word[]>();
|
|
122
|
+
|
|
106
123
|
/** This function splits the text into words at white space. Each word holds its word segments (`Intl.Segmenter`), so words that share segments share the cache. */
|
|
107
|
-
function wordsOf(text: string): Word[] {
|
|
124
|
+
function wordsOf(text: string): readonly Word[] {
|
|
125
|
+
const known = wordsMemo.get(text);
|
|
126
|
+
if (known !== undefined) return known;
|
|
127
|
+
const words = splitWords(text);
|
|
128
|
+
// The memo forgets its oldest text when it is full.
|
|
129
|
+
if (wordsMemo.size >= WORDS_MEMO) wordsMemo.delete(wordsMemo.keys().next().value!);
|
|
130
|
+
wordsMemo.set(text, words);
|
|
131
|
+
return words;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** This function gives the words of `wordsOf` with no memo. */
|
|
135
|
+
function splitWords(text: string): Word[] {
|
|
108
136
|
const words: Word[] = [];
|
|
109
137
|
let parts: string[] = [];
|
|
110
138
|
const flush = (): void => {
|
|
111
139
|
if (parts.length > 0) words.push({ text: parts.join(""), parts });
|
|
112
140
|
parts = [];
|
|
113
141
|
};
|
|
114
|
-
|
|
115
|
-
|
|
142
|
+
const segmenter = segmenterOf("word");
|
|
143
|
+
if (segmenter !== null) {
|
|
144
|
+
for (const s of segmenter.segment(text)) {
|
|
116
145
|
if (SPACE.test(s.segment)) flush();
|
|
117
146
|
else parts.push(s.segment);
|
|
118
147
|
}
|
|
@@ -128,7 +157,8 @@ function wordsOf(text: string): Word[] {
|
|
|
128
157
|
|
|
129
158
|
/** This function gives the grapheme clusters of a text. Without `Intl.Segmenter`, it gives the code points. */
|
|
130
159
|
export function graphemesOf(text: string): string[] {
|
|
131
|
-
|
|
160
|
+
const segmenter = segmenterOf("grapheme");
|
|
161
|
+
if (segmenter !== null) return Array.from(segmenter.segment(text), (s) => s.segment);
|
|
132
162
|
return Array.from(text);
|
|
133
163
|
}
|
|
134
164
|
|