@mark1russell7/layout-contract 0.3.2 → 0.3.3
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/index.d.ts.map +1 -1
- package/build/index.js +43 -38
- package/build/index.js.map +1 -1
- package/build/text.js +1 -1
- package/build/text.js.map +1 -1
- package/package.json +2 -1
- package/src/balance.ts +1 -1
- package/src/edges.ts +1 -1
- package/src/families.ts +32 -26
- package/src/measures.ts +1 -1
- package/src/rules.ts +1 -1
- package/src/shapes.ts +3 -3
- package/src/strategy-space.ts +2 -2
- package/src/text.ts +3 -3
- package/src/tolerance.ts +1 -1
package/build/text.js
CHANGED
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 = 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 * 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>[] = 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,eA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Ac,MAAM;EAAS,WAAW;EAAS,KAAK;EAAG,KAAK;EAAU,WAAW;EAAG,QAAQ;CAAO;CAC3G;EAAE,IAAI;EAAmB,MAAM;EAAU,WAAW;EAAS,KAAK;EAAG,KAAK;EAAG,WAAW;EAAO,QAAQ;CAAO;CAC9G;EAAE,IAAI;EAAiB,MAAM;EAA2B,WAAW;EAAS,KAAK;EAAG,KAAK;EAAU,OAAO;EAAG,KAAK;EAAG,WAAW;EAAG,QAAQ;EAAQ,MAAM;CAAQ;CACjK;EAAE,IAAI;EAAiB,MAAM;EAAU,WAAW;EAAU,KAAK;EAAG,KAAK;EAAG,QAAQ;EAAQ,MAAM;CAAa;CAC/G;EAAE,IAAI;EAAW,MAAM;EAAgB,WAAW;EAAS,KAAK;EAAG,KAAK;EAAU,QAAQ;EAAQ,MAAM;CAAO;AACjH,CAAU;;;;;;AAOV,SAAgB,aAAa,QAAoB,OAA+D;CAC9G,MAAM,IAAI,OAAO;CACjB,MAAM,OAAO,OAAO,OAAO,MAAM,GAAG,EAAE;CACtC,MAAM,aAAa,MAAM,KAAA,KAAa,KAAK,WAAW,IAAI,IAAI,KAAK,QAAQ,GAAG,MAAM,KAAK,KAAK,IAAI,GAAG,IAAI,CAAC,IAAI,MAAM,GAAG,CAAC,IAAI,KAAK;CACjI,MAAM,WAAW,MAAM,KAAA,IAAY,IAAI,KAAK,IAAI,GAAG,GAAG,OAAO,OAAO,KAAK,OAAO,IAAI,KAAK,CAAC,CAAC;CAC3F,OAAO;EACL,cAAc,OAAO;EACrB,mBAAmB;EACnB,iBAAiB;EACjB,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,iBAAiB,MAAM,aAAa,IAAI,IAAI,MAAM,OAAO,MAAM,SAAS;CAC3G;AACF"}
|
|
1
|
+
{"version":3,"file":"text.js","names":[],"sources":["../src/text.ts"],"sourcesContent":["import { breakers, linesOf, type Box, type Item, type Penalty } from \"@mark1russell7/typeset/breaking\";\nimport type { MeasureSpec } from \"./measures.ts\";\n\n/**\n * The advance function of a host: the width of a run of text in a font, in pixels.\n * A browser host gives `canvasAdvance(context)`. A test or a server host gives a function of a font file.\n */\nexport type AdvanceFn = (text: string, font: string) => number;\n\n/** The count of the units in one pixel. Each advance is a whole number of units, so each sum is exact and each port gets the same pixels. */\nexport const TEXT_UNITS = 64;\n\n/** The counts of a measurer: the requests, the cache hits and the calls of the advance function. */\nexport interface MeasurerStats {\n readonly requests: number;\n readonly hits: number;\n readonly calls: number;\n}\n\n/** A measurer: the advance of a segment in a font, in whole units of 1/`TEXT_UNITS` pixel, with a cache. */\nexport interface TextMeasurer {\n /** This function gives the advance of the segment in the font, in units. */\n advance(segment: string, font: string): number;\n /** This function gives the counts since the start or since the last `reset`. */\n stats(): MeasurerStats;\n /** This function clears the cache and the counts. */\n reset(): void;\n}\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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AAoB,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.3",
|
|
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",
|
|
@@ -51,6 +51,7 @@
|
|
|
51
51
|
"devDependencies": {
|
|
52
52
|
"@mark1russell7/cue": "^1.0.2",
|
|
53
53
|
"@types/node": "^26.6.4",
|
|
54
|
+
"esbuild": "^0.28.2",
|
|
54
55
|
"typescript": "^7.0.2",
|
|
55
56
|
"vitest": "^5.0.3",
|
|
56
57
|
"tsdown": "^0.23.1",
|
package/src/balance.ts
CHANGED
|
@@ -35,7 +35,7 @@ export type BalanceMeasureSuffix =
|
|
|
35
35
|
| "stability.seed";
|
|
36
36
|
|
|
37
37
|
/** The suffixes of the balance and stability measures, in the order of `docs/BALANCE.md`. */
|
|
38
|
-
export const BALANCE_MEASURE_SUFFIXES: readonly BalanceMeasureSuffix[] = Object.freeze([
|
|
38
|
+
export const BALANCE_MEASURE_SUFFIXES: readonly BalanceMeasureSuffix[] = /* @__PURE__ */ Object.freeze([
|
|
39
39
|
"balance.gapCv",
|
|
40
40
|
"balance.centroidOffset",
|
|
41
41
|
"balance.side.top",
|
package/src/edges.ts
CHANGED
|
@@ -21,7 +21,7 @@ export interface EdgeStepParams {
|
|
|
21
21
|
}
|
|
22
22
|
|
|
23
23
|
/** The mean count of the edges of each box for each value of `edgeDensity`. */
|
|
24
|
-
export const EDGE_DENSITY: Readonly<Record<EdgeStepParams["edgeDensity"], number>> = Object.freeze({ sparse: 0.5, medium: 1.5, dense: 4 });
|
|
24
|
+
export const EDGE_DENSITY: Readonly<Record<EdgeStepParams["edgeDensity"], number>> = /* @__PURE__ */ Object.freeze({ sparse: 0.5, medium: 1.5, dense: 4 });
|
|
25
25
|
|
|
26
26
|
/** The version of `edgeStep`. A change of its output gives a new version. */
|
|
27
27
|
export const EDGE_STEP_VERSION = 1;
|
package/src/families.ts
CHANGED
|
@@ -173,7 +173,7 @@ export interface FamilyRegistry<O = LayoutInput> {
|
|
|
173
173
|
}
|
|
174
174
|
|
|
175
175
|
/** The default key of a family in a manifest: the kind of the cell alone. It is the map form of `FamilyBy` with the entry `"*"`. */
|
|
176
|
-
export const DEFAULT_FAMILY_BY: FamilyBy = Object.freeze({ "*": Object.freeze([]) as readonly string[] });
|
|
176
|
+
export const DEFAULT_FAMILY_BY: FamilyBy = /* @__PURE__ */ Object.freeze({ "*": /* @__PURE__ */ Object.freeze([]) as readonly string[] });
|
|
177
177
|
|
|
178
178
|
/** This function gives an `enum` dimension. */
|
|
179
179
|
const choice = (name: string, values: readonly string[], value: string, meaning: string, engines: readonly string[]): CorpusDimension =>
|
|
@@ -199,6 +199,12 @@ const range = (
|
|
|
199
199
|
engines: Object.freeze([...engines]),
|
|
200
200
|
});
|
|
201
201
|
|
|
202
|
+
/**
|
|
203
|
+
* This function gives a dimension with the condition `when`, as a frozen object.
|
|
204
|
+
* A spread in the literal of `CORPUS_DIMENSIONS` is a side effect for a bundler, so the copy is in this function.
|
|
205
|
+
*/
|
|
206
|
+
const withWhen = (dimension: CorpusDimension, when: NonNullable<CorpusDimension["when"]>): CorpusDimension => Object.freeze({ ...dimension, when });
|
|
207
|
+
|
|
202
208
|
const P = "packing";
|
|
203
209
|
const H = "highways";
|
|
204
210
|
const J = "joint";
|
|
@@ -207,27 +213,27 @@ const J = "joint";
|
|
|
207
213
|
* The shared dimension table. A family takes a dimension of it with `sharedDimension`, or declares its own dimension.
|
|
208
214
|
* The coverage table of each dimension and each engine is in `docs/CORPUS.md`.
|
|
209
215
|
*/
|
|
210
|
-
export const CORPUS_DIMENSIONS: Readonly<Record<string, CorpusDimension>> = Object.freeze({
|
|
211
|
-
count: range("count", "int", { min: 0, max: 100_000, value: 100, scale: "log", levels: [1, 10, 100, 1000, 10_000] }, "The count of the items (n) of an input.", [P, H, J]),
|
|
212
|
-
sizes: choice("sizes", ["identical", "nearIdentical", "uniform", "heavyTail", "bimodal", "extremeAspect"], "uniform", "The distribution of the sizes of the items.", [P, J]),
|
|
213
|
-
aspect: range("aspect", "real", { min: 0.25, max: 4, value: 1, scale: "log" }, "The width over the height of a container with no fixed size.", [P]),
|
|
214
|
-
density: range("density", "real", { min: 0.05, max: 1, value: 0.4, scale: "linear" }, "The area of the items over the area of the frame of the container.", [P]),
|
|
215
|
-
obstacles: choice("obstacles", ["none", "center", "scattered", "wall", "corridors", "touching", "edge"], "none", "The layout of the fixed obstacles.", [P, J]),
|
|
216
|
-
containerSize: choice("containerSize", ["fixed", "freeHeight", "freeWidth", "freeAspect", "freeArea"], "fixed", "The sides of the container that the engine can change.", [P, J]),
|
|
217
|
-
containerShape: choice("containerShape", ["rect", "convex", "polygon", "circle", "ellipse", "holes"], "rect", "The kind of the shape of the container.", [P, J]),
|
|
218
|
-
shape: choice("shape", SHAPE_KIND_IDS, "rect", "The shape kind of each item: a `ShapeKind` of `shapes.ts`.", [P]),
|
|
219
|
-
order: choice("order", ["free", "soft"], "free", "The reading order of the items: no order, or a rank on each item.", [P]),
|
|
220
|
-
groups: choice("groups", ["none", "flat", "nested"], "none", "The groups of the items: no groups, one level, or groups in groups.", [H, J]),
|
|
221
|
-
edgeDensity: choice("edgeDensity", ["sparse", "medium", "dense"], "medium", "The mean count of the edges of each item: 0.5, 1.5 or 4.", [H, J]),
|
|
222
|
-
edgeShape: choice("edgeShape", ["random", "clustered", "hubChain", "hubs", "longRange", "tree", "bundled"], "random", "The topology of the edges.", [H, J]),
|
|
223
|
-
ports: choice("ports", ["free", "sides", "fixed"], "free", "The ports of the edges: free, a side for each end, or fixed ports.", [H, J]),
|
|
224
|
-
hubBy:
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
spacing: choice("spacing", ["stress", "gap", "margin", "both"], "both", "The split of the route clearance between the margins and the gap. `stress` has neither.", [J]),
|
|
229
|
-
margin: range("margin", "real", { min: 0, max: 32, value: 0 }, "The margin of each item, in units.", [P, J]),
|
|
230
|
-
gap: range("gap", "real", { min: 0, max: 32, value: 0 }, "The free space between two items, in units.", [P, J]),
|
|
216
|
+
export const CORPUS_DIMENSIONS: Readonly<Record<string, CorpusDimension>> = /* @__PURE__ */ Object.freeze({
|
|
217
|
+
count: /* @__PURE__ */ range("count", "int", { min: 0, max: 100_000, value: 100, scale: "log", levels: [1, 10, 100, 1000, 10_000] }, "The count of the items (n) of an input.", [P, H, J]),
|
|
218
|
+
sizes: /* @__PURE__ */ choice("sizes", ["identical", "nearIdentical", "uniform", "heavyTail", "bimodal", "extremeAspect"], "uniform", "The distribution of the sizes of the items.", [P, J]),
|
|
219
|
+
aspect: /* @__PURE__ */ range("aspect", "real", { min: 0.25, max: 4, value: 1, scale: "log" }, "The width over the height of a container with no fixed size.", [P]),
|
|
220
|
+
density: /* @__PURE__ */ range("density", "real", { min: 0.05, max: 1, value: 0.4, scale: "linear" }, "The area of the items over the area of the frame of the container.", [P]),
|
|
221
|
+
obstacles: /* @__PURE__ */ choice("obstacles", ["none", "center", "scattered", "wall", "corridors", "touching", "edge"], "none", "The layout of the fixed obstacles.", [P, J]),
|
|
222
|
+
containerSize: /* @__PURE__ */ choice("containerSize", ["fixed", "freeHeight", "freeWidth", "freeAspect", "freeArea"], "fixed", "The sides of the container that the engine can change.", [P, J]),
|
|
223
|
+
containerShape: /* @__PURE__ */ choice("containerShape", ["rect", "convex", "polygon", "circle", "ellipse", "holes"], "rect", "The kind of the shape of the container.", [P, J]),
|
|
224
|
+
shape: /* @__PURE__ */ choice("shape", SHAPE_KIND_IDS, "rect", "The shape kind of each item: a `ShapeKind` of `shapes.ts`.", [P]),
|
|
225
|
+
order: /* @__PURE__ */ choice("order", ["free", "soft"], "free", "The reading order of the items: no order, or a rank on each item.", [P]),
|
|
226
|
+
groups: /* @__PURE__ */ choice("groups", ["none", "flat", "nested"], "none", "The groups of the items: no groups, one level, or groups in groups.", [H, J]),
|
|
227
|
+
edgeDensity: /* @__PURE__ */ choice("edgeDensity", ["sparse", "medium", "dense"], "medium", "The mean count of the edges of each item: 0.5, 1.5 or 4.", [H, J]),
|
|
228
|
+
edgeShape: /* @__PURE__ */ choice("edgeShape", ["random", "clustered", "hubChain", "hubs", "longRange", "tree", "bundled"], "random", "The topology of the edges.", [H, J]),
|
|
229
|
+
ports: /* @__PURE__ */ choice("ports", ["free", "sides", "fixed"], "free", "The ports of the edges: free, a side for each end, or fixed ports.", [H, J]),
|
|
230
|
+
hubBy: /* @__PURE__ */ withWhen(
|
|
231
|
+
/* @__PURE__ */ choice("hubBy", ["area", "random"], "area", "The order of the hubs of the shapes hubs and tree: the largest item first, or random.", [J]),
|
|
232
|
+
/* @__PURE__ */ Object.freeze({ param: "edgeShape", in: /* @__PURE__ */ Object.freeze(["hubs", "tree"]) }),
|
|
233
|
+
),
|
|
234
|
+
spacing: /* @__PURE__ */ choice("spacing", ["stress", "gap", "margin", "both"], "both", "The split of the route clearance between the margins and the gap. `stress` has neither.", [J]),
|
|
235
|
+
margin: /* @__PURE__ */ range("margin", "real", { min: 0, max: 32, value: 0 }, "The margin of each item, in units.", [P, J]),
|
|
236
|
+
gap: /* @__PURE__ */ range("gap", "real", { min: 0, max: 32, value: 0 }, "The free space between two items, in units.", [P, J]),
|
|
231
237
|
});
|
|
232
238
|
|
|
233
239
|
/**
|
|
@@ -763,7 +769,7 @@ export function composeFamily(base: CorpusFamily<LayoutInput>, steps: readonly C
|
|
|
763
769
|
}
|
|
764
770
|
|
|
765
771
|
/** The dimensions of `EDGES_STEP`: the parameters of `edgeStep`, from the shared table. */
|
|
766
|
-
const EDGE_DIMENSIONS: readonly CorpusDimension[] = Object.freeze(["edgeDensity", "edgeShape", "groups", "ports", "hubBy"].map((n) => CORPUS_DIMENSIONS[n]!));
|
|
772
|
+
const EDGE_DIMENSIONS: readonly CorpusDimension[] = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ ["edgeDensity", "edgeShape", "groups", "ports", "hubBy"].map((n) => CORPUS_DIMENSIONS[n]!));
|
|
767
773
|
|
|
768
774
|
/** This function gives the parameters of `edgeStep` from the values of the dimensions. It throws a `RangeError` for a missing or a bad value. */
|
|
769
775
|
function edgeParams(d: DimensionValues): EdgeStepParams {
|
|
@@ -787,7 +793,7 @@ function edgeParams(d: DimensionValues): EdgeStepParams {
|
|
|
787
793
|
* The step `edges` of `edgeStep` (version 1), as a corpus step. Its family part is `e-<edgeDensity>.<edgeShape>.<groups>.<ports>`.
|
|
788
794
|
* The value `random` of `hubBy` adds the part `.hub-random`.
|
|
789
795
|
*/
|
|
790
|
-
export const EDGES_STEP: CorpusStep = Object.freeze({
|
|
796
|
+
export const EDGES_STEP: CorpusStep = /* @__PURE__ */ Object.freeze({
|
|
791
797
|
name: "edges",
|
|
792
798
|
version: 1,
|
|
793
799
|
owner: "layout-contract",
|
|
@@ -807,12 +813,12 @@ const XCHECK_SET = "xcheck-v1";
|
|
|
807
813
|
* It is the one copy of the generator of `docs/FORMAT.md` of `packing`. Its input is the input of `packing`, byte for byte.
|
|
808
814
|
* The steps `container`, `obstacles` and `boxes` each have a stream of `stepRandom`. Each value is a whole number, so the family is `exact`.
|
|
809
815
|
*/
|
|
810
|
-
export const RECT_SCATTERED: CorpusFamily<LayoutInput> = Object.freeze({
|
|
816
|
+
export const RECT_SCATTERED: CorpusFamily<LayoutInput> = /* @__PURE__ */ Object.freeze({
|
|
811
817
|
name: "rect-scattered",
|
|
812
818
|
version: 1,
|
|
813
819
|
owner: "layout-contract",
|
|
814
820
|
meaning: "Rectangle obstacles at random places in a fixed rectangle container, and boxes of random sizes.",
|
|
815
|
-
dimensions: Object.freeze([sharedDimension("count", { default: 40 })]),
|
|
821
|
+
dimensions: /* @__PURE__ */ Object.freeze([/* @__PURE__ */ sharedDimension("count", { default: 40 })]),
|
|
816
822
|
seeding: "stepRandom(seed, container) gives w and h. stepRandom(seed, obstacles) gives n, then ow, oh, x and y of each obstacle. stepRandom(seed, boxes) gives bw and bh of each box.",
|
|
817
823
|
crossEngine: "exact",
|
|
818
824
|
generate(seed: number, dims: DimensionValues, context: GenerateContext): LayoutInput {
|
package/src/measures.ts
CHANGED
|
@@ -60,7 +60,7 @@ const AREA: readonly ShapeKind[] = ["rect"];
|
|
|
60
60
|
* The specs of the joint measures, in the order of `docs/JOINT-MEASURES.md`.
|
|
61
61
|
* `joint.fill` and `joint.straight.length` read the area of each box, so they support only `rect`. `docs/SHAPES.md` tells the reasons.
|
|
62
62
|
*/
|
|
63
|
-
export const JOINT_MEASURES: readonly MeasureSpec<JointMeasureId>[] = Object.freeze([
|
|
63
|
+
export const JOINT_MEASURES: readonly MeasureSpec<JointMeasureId>[] = /* @__PURE__ */ Object.freeze([
|
|
64
64
|
{ id: "joint.fill", minEffect: 0.001, unit: "0 to 1", direction: "higher", min: 0, max: 1, floor: 1, role: "guard", shapes: AREA },
|
|
65
65
|
{ id: "joint.aspectError", minEffect: 0.01, unit: "natural log", direction: "lower", min: 0, max: Infinity, floor: 0, tol: 0.01, role: "guard", shapes: BOUNDS_ONLY },
|
|
66
66
|
{ id: "joint.spill", minEffect: 0.001, unit: "0 to 1", direction: "lower", min: 0, max: 1, floor: 0, tol: 0.001, role: "guard", shapes: BOUNDS_ONLY },
|
package/src/rules.ts
CHANGED
|
@@ -135,7 +135,7 @@ export interface PackHard {
|
|
|
135
135
|
* For the other kinds, the count is safe: a shape is inside its bounding box, so the count is an upper bound. A count of 0 tells that the rule has no break.
|
|
136
136
|
* `locked-kept` and `complete` read only the positions and the ids, so they support each kind.
|
|
137
137
|
*/
|
|
138
|
-
export const PACK_HARD_RULES: readonly ShapeSupport<keyof PackHard>[] = Object.freeze([
|
|
138
|
+
export const PACK_HARD_RULES: readonly ShapeSupport<keyof PackHard>[] = /* @__PURE__ */ Object.freeze([
|
|
139
139
|
{ id: "no-overlap", shapes: ["rect"], safe: ["polygon", "circle", "free"] },
|
|
140
140
|
{ id: "in-container", shapes: ["rect"], safe: ["polygon", "circle", "free"] },
|
|
141
141
|
{ id: "locked-kept", shapes: SHAPE_KIND_IDS },
|
package/src/shapes.ts
CHANGED
|
@@ -35,7 +35,7 @@ export interface ShapeKindSpec {
|
|
|
35
35
|
* The declared shape kinds, in their order. Only `rect` has all of its geometry.
|
|
36
36
|
* `polygon` and `circle` have their bounding box and their exact area. `free` has its bounding box only.
|
|
37
37
|
*/
|
|
38
|
-
export const SHAPE_KINDS: readonly ShapeKindSpec[] = Object.freeze([
|
|
38
|
+
export const SHAPE_KINDS: readonly ShapeKindSpec[] = /* @__PURE__ */ Object.freeze([
|
|
39
39
|
{ id: "rect", fields: ["w", "h"], regions: ["rect"], geometry: { bounds: true, area: true, contains: true, overlap: true } },
|
|
40
40
|
{ id: "polygon", fields: ["points", "holes?"], regions: ["polygon"], geometry: { bounds: true, area: true, contains: false, overlap: false } },
|
|
41
41
|
{ id: "circle", fields: ["cx", "cy", "r"], regions: ["circle"], geometry: { bounds: true, area: true, contains: false, overlap: false } },
|
|
@@ -43,10 +43,10 @@ export const SHAPE_KINDS: readonly ShapeKindSpec[] = Object.freeze([
|
|
|
43
43
|
] as const);
|
|
44
44
|
|
|
45
45
|
/** The ids of `SHAPE_KINDS`, in their order. */
|
|
46
|
-
export const SHAPE_KIND_IDS: readonly ShapeKind[] = Object.freeze(SHAPE_KINDS.map((k) => k.id));
|
|
46
|
+
export const SHAPE_KIND_IDS: readonly ShapeKind[] = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ SHAPE_KINDS.map((k) => k.id));
|
|
47
47
|
|
|
48
48
|
/** The shape kinds of a measure or a rule without `shapes`. The contract measured only rectangles before L46. */
|
|
49
|
-
export const DEFAULT_SHAPES: readonly ShapeKind[] = Object.freeze(["rect"] as const);
|
|
49
|
+
export const DEFAULT_SHAPES: readonly ShapeKind[] = /* @__PURE__ */ Object.freeze(["rect"] as const);
|
|
50
50
|
|
|
51
51
|
/** A measure or a rule, with the shape kinds that it supports. Without `shapes`, it supports `DEFAULT_SHAPES`. */
|
|
52
52
|
export interface ShapeSupport<Id extends string = string> {
|
package/src/strategy-space.ts
CHANGED
|
@@ -345,7 +345,7 @@ const supportsShapes = (o: StageOption, shapes: readonly ShapeKind[] | undefined
|
|
|
345
345
|
shapes === undefined || o.supports?.shape === undefined || shapes.every((k) => o.supports!.shape!.includes(k));
|
|
346
346
|
|
|
347
347
|
/** The shape kinds that the members of an option with `view: "bounds"` see: a bounding box is a `rect`. */
|
|
348
|
-
const BOUNDS_VIEW: readonly ShapeKind[] = Object.freeze(["rect"] as const);
|
|
348
|
+
const BOUNDS_VIEW: readonly ShapeKind[] = /* @__PURE__ */ Object.freeze(["rect"] as const);
|
|
349
349
|
|
|
350
350
|
/**
|
|
351
351
|
* This function gives the shape kinds of the members of a meta option. With `view: "bounds"`, a list with a kind becomes `BOUNDS_VIEW`.
|
|
@@ -811,7 +811,7 @@ function restrict(space: StrategySpace, shapes: readonly ShapeKind[] | undefined
|
|
|
811
811
|
}
|
|
812
812
|
|
|
813
813
|
/** The space of the members of a meta option of a restricted space, when it is not the part of the option. Only `view: "bounds"` makes such a space. */
|
|
814
|
-
const memberSpaces = new WeakMap<StageOption, StrategySpace>();
|
|
814
|
+
const memberSpaces = /* @__PURE__ */ new WeakMap<StageOption, StrategySpace>();
|
|
815
815
|
|
|
816
816
|
/**
|
|
817
817
|
* This function tells if an option of a restricted space has a member list. A base option and a meta option with a `pool` have one.
|
package/src/text.ts
CHANGED
|
@@ -105,7 +105,7 @@ interface Word {
|
|
|
105
105
|
const SPACE = /^\s+$/u;
|
|
106
106
|
|
|
107
107
|
/** The segmenters of the module. A new `Intl.Segmenter` loads the data of the locale, so the module makes each granularity only once. */
|
|
108
|
-
const segmenters = new Map<"word" | "grapheme", Intl.Segmenter | null>();
|
|
108
|
+
const segmenters = /* @__PURE__ */ new Map<"word" | "grapheme", Intl.Segmenter | null>();
|
|
109
109
|
|
|
110
110
|
/** This function gives the segmenter of a granularity, or `null` without `Intl.Segmenter`. */
|
|
111
111
|
function segmenterOf(granularity: "word" | "grapheme"): Intl.Segmenter | null {
|
|
@@ -119,7 +119,7 @@ function segmenterOf(granularity: "word" | "grapheme"): Intl.Segmenter | null {
|
|
|
119
119
|
|
|
120
120
|
/** The largest count of texts in the memo of `wordsOf`. A page often asks for the same labels many times. */
|
|
121
121
|
const WORDS_MEMO = 4096;
|
|
122
|
-
const wordsMemo = new Map<string, readonly Word[]>();
|
|
122
|
+
const wordsMemo = /* @__PURE__ */ new Map<string, readonly Word[]>();
|
|
123
123
|
|
|
124
124
|
/** 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. */
|
|
125
125
|
function wordsOf(text: string): readonly Word[] {
|
|
@@ -332,7 +332,7 @@ export function layoutText(text: string, options: TextLayoutOptions): TextLayout
|
|
|
332
332
|
export type TextMeasureId = "text.lines" | "text.raggedness" | "text.overflow" | "text.cacheHit" | "text.ms";
|
|
333
333
|
|
|
334
334
|
/** The specs of the text measures. */
|
|
335
|
-
export const TEXT_MEASURES: readonly MeasureSpec<TextMeasureId>[] = Object.freeze([
|
|
335
|
+
export const TEXT_MEASURES: readonly MeasureSpec<TextMeasureId>[] = /* @__PURE__ */ Object.freeze([
|
|
336
336
|
{ id: "text.lines", unit: "count", direction: "lower", min: 1, max: Infinity, minEffect: 0, family: "text" },
|
|
337
337
|
{ id: "text.raggedness", unit: "0 to 1", direction: "lower", min: 0, max: 1, minEffect: 0.005, family: "text" },
|
|
338
338
|
{ 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" },
|
package/src/tolerance.ts
CHANGED
|
@@ -28,4 +28,4 @@ export interface Tolerance {
|
|
|
28
28
|
* The default tolerance of each rule. The packer is exact, so `overlap` is one unit of the rounding.
|
|
29
29
|
* Routes are sampled curves that follow the margin line, so `through` is larger.
|
|
30
30
|
*/
|
|
31
|
-
export const DEFAULT_TOLERANCE: Tolerance = Object.freeze({ overlap: 0.001, through: 0.5 });
|
|
31
|
+
export const DEFAULT_TOLERANCE: Tolerance = /* @__PURE__ */ Object.freeze({ overlap: 0.001, through: 0.5 });
|