@mark1russell7/layout-contract 0.2.20 → 0.3.0
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 +8 -1
- package/build/index.d.ts +21 -2
- package/build/index.d.ts.map +1 -1
- package/build/index.js +146 -14
- package/build/index.js.map +1 -1
- 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/hash.ts +7 -6
- package/src/record.ts +82 -3
- package/src/text.ts +34 -4
- package/src/utf8.ts +48 -9
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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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 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 = 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"],"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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.
|
|
4
|
+
"version": "0.3.0",
|
|
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/hash.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { canonicalInput, type LayoutInput } from "./input.ts";
|
|
2
2
|
import { RECORD_EPS } from "./tolerance.ts";
|
|
3
|
-
import {
|
|
3
|
+
import { utf8Write } from "./utf8.ts";
|
|
4
4
|
|
|
5
5
|
/** The round constants of SHA-256. */
|
|
6
6
|
const K: readonly number[] = [
|
|
@@ -16,12 +16,13 @@ const K: readonly number[] = [
|
|
|
16
16
|
* It uses no API of Node or of the browser.
|
|
17
17
|
*/
|
|
18
18
|
export function sha256Hex(text: string): string {
|
|
19
|
-
|
|
20
|
-
const
|
|
21
|
-
const
|
|
19
|
+
// The bytes go straight into the padded buffer, so the digest makes one array, not a list of the bytes and a copy.
|
|
20
|
+
const length = utf8Write(text);
|
|
21
|
+
const bits = length * 8;
|
|
22
|
+
const total = Math.ceil((length + 9) / 64) * 64;
|
|
22
23
|
const data = new Uint8Array(total);
|
|
23
|
-
data
|
|
24
|
-
data[
|
|
24
|
+
utf8Write(text, data);
|
|
25
|
+
data[length] = 0x80;
|
|
25
26
|
const view = new DataView(data.buffer);
|
|
26
27
|
view.setUint32(total - 8, Math.floor(bits / 0x100000000));
|
|
27
28
|
view.setUint32(total - 4, bits >>> 0);
|
package/src/record.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { Tolerance } from "./tolerance.ts";
|
|
2
2
|
import type { LayoutInput } from "./input.ts";
|
|
3
|
-
import { shapeKindsOf, type ShapeKind } from "./shapes.ts";
|
|
3
|
+
import { isShapeKind, shapeKindsOf, type ShapeKind } from "./shapes.ts";
|
|
4
4
|
|
|
5
5
|
/** The stage of a record: the packer, the router, or both together. */
|
|
6
6
|
export type Stage = "pack" | "route" | "joint";
|
|
@@ -30,8 +30,11 @@ export interface LayoutRecord {
|
|
|
30
30
|
readonly hard: Readonly<Record<string, number>>;
|
|
31
31
|
/** The tolerance of each hard rule of the run. */
|
|
32
32
|
readonly tolerance?: Readonly<Partial<Tolerance>>;
|
|
33
|
-
/**
|
|
34
|
-
|
|
33
|
+
/**
|
|
34
|
+
* The value is `true` when two runs with the same seed give the same positions.
|
|
35
|
+
* A skipped record has `null`, because no run made a claim. Each other record has a boolean.
|
|
36
|
+
*/
|
|
37
|
+
readonly deterministic: boolean | null;
|
|
35
38
|
/** The id of the prediction that was written before the run. */
|
|
36
39
|
readonly prediction?: string;
|
|
37
40
|
/** The median of `msRuns`, or the time of the one run. */
|
|
@@ -67,6 +70,10 @@ export interface RunEnv {
|
|
|
67
70
|
readonly cpu: string;
|
|
68
71
|
/** The count of the logical processors. */
|
|
69
72
|
readonly cpus: number;
|
|
73
|
+
/** The mode of the timing, for example `process` or `fresh` of `paired-time/1`. Each timing record names its mode. */
|
|
74
|
+
readonly mode?: string;
|
|
75
|
+
/** The context of the run, for example `ci` or `local`, with the Node flags. */
|
|
76
|
+
readonly context?: string;
|
|
70
77
|
}
|
|
71
78
|
|
|
72
79
|
/** The facts of a run that the input does not give. */
|
|
@@ -90,3 +97,75 @@ export function toLayoutRecord(input: LayoutInput, run: RunFacts): LayoutRecord
|
|
|
90
97
|
...(onlyRect ? {} : { shapes }),
|
|
91
98
|
};
|
|
92
99
|
}
|
|
100
|
+
|
|
101
|
+
type Fields = Readonly<Record<string, unknown>>;
|
|
102
|
+
|
|
103
|
+
const isFields = (v: unknown): v is Fields => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
104
|
+
|
|
105
|
+
const STAGES: readonly string[] = ["pack", "route", "joint"];
|
|
106
|
+
const RECORD_STRINGS = ["step", "strategy", "corpus", "input", "inputHash", "set"] as const;
|
|
107
|
+
const RECORD_NUMBERS = ["seed", "nodes", "edges", "ms"] as const;
|
|
108
|
+
const RECORD_OPTIONAL_STRINGS = ["prediction", "outputHash", "skipped", "commit"] as const;
|
|
109
|
+
const ENV_STRINGS = ["node", "os", "arch", "runner", "cpu"] as const;
|
|
110
|
+
const ENV_OPTIONAL_STRINGS = ["mode", "context"] as const;
|
|
111
|
+
|
|
112
|
+
/** This function adds a problem for each value of a map that is not a number. */
|
|
113
|
+
function numberMap(out: string[], v: unknown, name: string): void {
|
|
114
|
+
if (!isFields(v)) {
|
|
115
|
+
out.push(`${name} is not an object`);
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
for (const [key, n] of Object.entries(v)) if (typeof n !== "number") out.push(`${name}.${key} is not a number`);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** This function gives the problems of the field `env` of a record. */
|
|
122
|
+
function envProblems(env: unknown): string[] {
|
|
123
|
+
if (!isFields(env)) return ["env is not an object"];
|
|
124
|
+
const out: string[] = [];
|
|
125
|
+
for (const key of ENV_STRINGS) if (typeof env[key] !== "string") out.push(`env.${key} is not a string`);
|
|
126
|
+
if (typeof env["cpus"] !== "number") out.push("env.cpus is not a number");
|
|
127
|
+
for (const key of ENV_OPTIONAL_STRINGS) if (env[key] !== undefined && typeof env[key] !== "string") out.push(`env.${key} is not a string`);
|
|
128
|
+
return out;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* This function gives the problems of one `layout-record/1` value. An empty list means a good record.
|
|
133
|
+
* A record that has `skipped` has `deterministic: null`. An old skipped record with a boolean is also correct.
|
|
134
|
+
* A record without `skipped` has a boolean. The check accepts fields that the format does not know.
|
|
135
|
+
*/
|
|
136
|
+
export function checkLayoutRecord(value: unknown): string[] {
|
|
137
|
+
if (!isFields(value)) return ["the record is not an object"];
|
|
138
|
+
const out: string[] = [];
|
|
139
|
+
const v = value;
|
|
140
|
+
if (v["schema"] !== "layout-record/1") out.push("schema is not layout-record/1");
|
|
141
|
+
if (typeof v["stage"] !== "string" || !STAGES.includes(v["stage"])) out.push("stage is not pack, route or joint");
|
|
142
|
+
for (const key of RECORD_STRINGS) if (typeof v[key] !== "string") out.push(`${key} is not a string`);
|
|
143
|
+
for (const key of RECORD_NUMBERS) if (typeof v[key] !== "number") out.push(`${key} is not a number`);
|
|
144
|
+
for (const key of RECORD_OPTIONAL_STRINGS) if (v[key] !== undefined && typeof v[key] !== "string") out.push(`${key} is not a string`);
|
|
145
|
+
if (!isFields(v["options"])) out.push("options is not an object");
|
|
146
|
+
numberMap(out, v["measures"], "measures");
|
|
147
|
+
numberMap(out, v["hard"], "hard");
|
|
148
|
+
if (v["tolerance"] !== undefined) numberMap(out, v["tolerance"], "tolerance");
|
|
149
|
+
const shapes = v["shapes"];
|
|
150
|
+
if (shapes !== undefined && (!Array.isArray(shapes) || !shapes.every(isShapeKind))) out.push("shapes is not a list of shape kinds");
|
|
151
|
+
const msRuns = v["msRuns"];
|
|
152
|
+
if (msRuns !== undefined && (!Array.isArray(msRuns) || !msRuns.every((n) => typeof n === "number"))) out.push("msRuns is not a list of numbers");
|
|
153
|
+
if (v["env"] !== undefined) out.push(...envProblems(v["env"]));
|
|
154
|
+
const deterministic = v["deterministic"];
|
|
155
|
+
if (v["skipped"] === undefined) {
|
|
156
|
+
if (typeof deterministic !== "boolean") out.push("deterministic is not a boolean, and the record has no skipped");
|
|
157
|
+
} else if (deterministic !== null && typeof deterministic !== "boolean") out.push("deterministic of a skipped record is not null or a boolean");
|
|
158
|
+
return out;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* This function reads one `layout-record/1` value, for example one parsed line of a JSON Lines file.
|
|
163
|
+
* It throws a `TypeError` with the problems of `checkLayoutRecord`.
|
|
164
|
+
* An old skipped record has a boolean `deterministic`. The result has `null` in its place, because no run made that claim.
|
|
165
|
+
*/
|
|
166
|
+
export function parseLayoutRecord(value: unknown): LayoutRecord {
|
|
167
|
+
const problems = checkLayoutRecord(value);
|
|
168
|
+
if (problems.length > 0) throw new TypeError(`The record is not a layout-record/1: ${problems.join(", ")}.`);
|
|
169
|
+
const record = value as LayoutRecord;
|
|
170
|
+
return record.skipped !== undefined && record.deterministic !== null ? { ...record, deterministic: null } : record;
|
|
171
|
+
}
|
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
|
|
package/src/utf8.ts
CHANGED
|
@@ -1,12 +1,51 @@
|
|
|
1
|
-
/**
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
1
|
+
/**
|
|
2
|
+
* This function writes the UTF-8 bytes of a string into `out`, from the index `at`, and gives the index after the last byte.
|
|
3
|
+
* With no `out`, it writes nothing and gives the count of the bytes. A lone surrogate gives the 3 bytes of its code.
|
|
4
|
+
* It reads the UTF-16 code units, so it makes no string for each character (L81: `sha256Hex` allocated 2 GB in one pair).
|
|
5
|
+
*/
|
|
6
|
+
export function utf8Write(text: string, out?: Uint8Array, at = 0): number {
|
|
7
|
+
let n = at;
|
|
8
|
+
for (let i = 0; i < text.length; i++) {
|
|
9
|
+
let c = text.charCodeAt(i);
|
|
10
|
+
if (c >= 0xd800 && c < 0xdc00 && i + 1 < text.length) {
|
|
11
|
+
const low = text.charCodeAt(i + 1);
|
|
12
|
+
if (low >= 0xdc00 && low < 0xe000) {
|
|
13
|
+
c = 0x10000 + ((c - 0xd800) << 10) + (low - 0xdc00);
|
|
14
|
+
i++;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
if (c < 0x80) {
|
|
18
|
+
if (out !== undefined) out[n] = c;
|
|
19
|
+
n += 1;
|
|
20
|
+
} else if (c < 0x800) {
|
|
21
|
+
if (out !== undefined) {
|
|
22
|
+
out[n] = 0xc0 | (c >> 6);
|
|
23
|
+
out[n + 1] = 0x80 | (c & 63);
|
|
24
|
+
}
|
|
25
|
+
n += 2;
|
|
26
|
+
} else if (c < 0x10000) {
|
|
27
|
+
if (out !== undefined) {
|
|
28
|
+
out[n] = 0xe0 | (c >> 12);
|
|
29
|
+
out[n + 1] = 0x80 | ((c >> 6) & 63);
|
|
30
|
+
out[n + 2] = 0x80 | (c & 63);
|
|
31
|
+
}
|
|
32
|
+
n += 3;
|
|
33
|
+
} else {
|
|
34
|
+
if (out !== undefined) {
|
|
35
|
+
out[n] = 0xf0 | (c >> 18);
|
|
36
|
+
out[n + 1] = 0x80 | ((c >> 12) & 63);
|
|
37
|
+
out[n + 2] = 0x80 | ((c >> 6) & 63);
|
|
38
|
+
out[n + 3] = 0x80 | (c & 63);
|
|
39
|
+
}
|
|
40
|
+
n += 4;
|
|
41
|
+
}
|
|
10
42
|
}
|
|
43
|
+
return n;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** This function gives the UTF-8 bytes of a string. The package has no runtime dependencies, thus it does not use `TextEncoder`. */
|
|
47
|
+
export function utf8(text: string): Uint8Array {
|
|
48
|
+
const bytes = new Uint8Array(utf8Write(text));
|
|
49
|
+
utf8Write(text, bytes);
|
|
11
50
|
return bytes;
|
|
12
51
|
}
|