@mark1russell7/layout-contract 0.2.18 → 0.2.20

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.
@@ -0,0 +1,104 @@
1
+ import { a as MeasureSpec } from "./measures-CQAuu3T5.js";
2
+ /**
3
+ * The advance function of a host: the width of a run of text in a font, in pixels.
4
+ * A browser host gives `canvasAdvance(context)`. A test or a server host gives a function of a font file.
5
+ */
6
+ export type AdvanceFn = (text: string, font: string) => number;
7
+ /** 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. */
8
+ export declare const TEXT_UNITS = 64;
9
+ /** The counts of a measurer: the requests, the cache hits and the calls of the advance function. */
10
+ export interface MeasurerStats {
11
+ readonly requests: number;
12
+ readonly hits: number;
13
+ readonly calls: number;
14
+ }
15
+ /** A measurer: the advance of a segment in a font, in whole units of 1/`TEXT_UNITS` pixel, with a cache. */
16
+ export interface TextMeasurer {
17
+ /** This function gives the advance of the segment in the font, in units. */
18
+ advance(segment: string, font: string): number;
19
+ /** This function gives the counts since the start or since the last `reset`. */
20
+ stats(): MeasurerStats;
21
+ /** This function clears the cache and the counts. */
22
+ reset(): void;
23
+ }
24
+ /** The options of `createMeasurer`. */
25
+ export interface MeasurerOptions {
26
+ /** The count of the cache entries. The default is 10000. With 0, the measurer has no cache. */
27
+ readonly maxEntries?: number;
28
+ }
29
+ /** This function gives the key of a font: the font string with its white space collapsed and trimmed. */
30
+ export declare function fontKey(font: string): string;
31
+ /**
32
+ * This function gives a measurer with a cache keyed by the font and the segment.
33
+ * The cache removes its oldest entry when it is full. The advance function rounds each width to whole units.
34
+ */
35
+ export declare function createMeasurer(measure: AdvanceFn, options?: MeasurerOptions): TextMeasurer;
36
+ /** The part of a canvas context that `canvasAdvance` uses. */
37
+ export interface CanvasTextContext {
38
+ font: string;
39
+ measureText(text: string): {
40
+ readonly width: number;
41
+ };
42
+ }
43
+ /** 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. */
44
+ export declare function canvasAdvance(context: CanvasTextContext): AdvanceFn;
45
+ /** This function gives the grapheme clusters of a text. Without `Intl.Segmenter`, it gives the code points. */
46
+ export declare function graphemesOf(text: string): string[];
47
+ /** The options of `layoutText`. All lengths are in pixels. */
48
+ export interface TextLayoutOptions {
49
+ readonly font: string;
50
+ readonly measurer: TextMeasurer;
51
+ /** The line height. A finite number above 0. */
52
+ readonly lineHeight: number;
53
+ /** The width of the lines of a text that does not fit on one line. Without it, the text stays on one line. */
54
+ readonly wrapWidth?: number;
55
+ /** The count of the lines. The last line that stays gets the ellipsis. The default is no limit. */
56
+ readonly maxLines?: number;
57
+ /** The count of the grapheme clusters. A longer text keeps `maxChars` clusters with the ellipsis at the end. The default is no limit. */
58
+ readonly maxChars?: number;
59
+ /** The text at the end of a cut text. The default is "…". */
60
+ readonly ellipsis?: string;
61
+ /** The space that the box adds to the width of the text. The default is 0. */
62
+ readonly padding?: number;
63
+ /** The smallest width of a box with one line. The default is 0. */
64
+ readonly minWidth?: number;
65
+ /** 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`. */
66
+ readonly maxWidth?: number;
67
+ /**
68
+ * The break of a word that is wider than a line. `keep` (the default) keeps the word whole, and the line overflows.
69
+ * `anywhere` breaks it between two grapheme clusters, as the CSS `overflow-wrap: anywhere`.
70
+ */
71
+ readonly wordBreak?: "keep" | "anywhere";
72
+ }
73
+ /** The layout of a text: its lines and its box. */
74
+ export interface TextLayout {
75
+ readonly lines: readonly string[];
76
+ /** The width of each line, in pixels. Each width is a whole number of units of 1/`TEXT_UNITS` pixel. */
77
+ readonly widths: readonly number[];
78
+ readonly lineCount: number;
79
+ /** The width of the box: the text and the padding. */
80
+ readonly width: number;
81
+ readonly height: number;
82
+ /** The width of the lines, or `undefined` for a text on one line. */
83
+ readonly wrapWidth?: number;
84
+ /** `true` when `maxChars` or `maxLines` cut the text. */
85
+ readonly truncated: boolean;
86
+ }
87
+ /**
88
+ * 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`.
89
+ *
90
+ * 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.
91
+ * 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.
92
+ */
93
+ export declare function layoutText(text: string, options: TextLayoutOptions): TextLayout;
94
+ /** The id of a text measure. `docs/TEXT.md` gives the definitions. */
95
+ export type TextMeasureId = "text.lines" | "text.raggedness" | "text.overflow" | "text.cacheHit" | "text.ms";
96
+ /** The specs of the text measures. */
97
+ export declare const TEXT_MEASURES: readonly MeasureSpec<TextMeasureId>[];
98
+ /**
99
+ * 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.
100
+ * `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.
101
+ * With `stats`, the measures also hold `text.cacheHit`: the hits divided by the requests.
102
+ */
103
+ export declare function textMeasures(layout: TextLayout, stats?: MeasurerStats): Partial<Record<TextMeasureId, number>>;
104
+ //# sourceMappingURL=text.d.ts.map
@@ -0,0 +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;;wBA2C3C,YAAY;;iBAMX;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 ADDED
@@ -0,0 +1,265 @@
1
+ // src/text.ts
2
+ /** 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. */
3
+ const TEXT_UNITS = 64;
4
+ /** This function gives the key of a font: the font string with its white space collapsed and trimmed. */
5
+ function fontKey(font) {
6
+ return font.trim().replace(/\s+/g, " ");
7
+ }
8
+ /**
9
+ * This function gives a measurer with a cache keyed by the font and the segment.
10
+ * The cache removes its oldest entry when it is full. The advance function rounds each width to whole units.
11
+ */
12
+ function createMeasurer(measure, options = {}) {
13
+ const max = options.maxEntries ?? 1e4;
14
+ if (!(Number.isInteger(max) && max >= 0)) throw new RangeError(`createMeasurer: maxEntries is an integer of 0 or more, not ${max}.`);
15
+ const cache = /* @__PURE__ */ new Map();
16
+ let requests = 0;
17
+ let hits = 0;
18
+ let calls = 0;
19
+ return {
20
+ advance(segment, font) {
21
+ requests++;
22
+ const key = `${fontKey(font)}\u0000${segment}`;
23
+ const known = cache.get(key);
24
+ if (known !== void 0) {
25
+ hits++;
26
+ return known;
27
+ }
28
+ calls++;
29
+ const px = measure(segment, font);
30
+ 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.`);
31
+ const units = Math.round(px * 64);
32
+ if (max > 0) {
33
+ if (cache.size >= max) cache.delete(cache.keys().next().value);
34
+ cache.set(key, units);
35
+ }
36
+ return units;
37
+ },
38
+ stats: () => ({
39
+ requests,
40
+ hits,
41
+ calls
42
+ }),
43
+ reset() {
44
+ cache.clear();
45
+ requests = 0;
46
+ hits = 0;
47
+ calls = 0;
48
+ }
49
+ };
50
+ }
51
+ /** 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. */
52
+ function canvasAdvance(context) {
53
+ let current;
54
+ return (text, font) => {
55
+ if (font !== current) {
56
+ context.font = font;
57
+ current = font;
58
+ }
59
+ return context.measureText(text).width;
60
+ };
61
+ }
62
+ const SPACE = /^\s+$/u;
63
+ /** 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
+ function wordsOf(text) {
65
+ const words = [];
66
+ let parts = [];
67
+ const flush = () => {
68
+ if (parts.length > 0) words.push({
69
+ text: parts.join(""),
70
+ parts
71
+ });
72
+ parts = [];
73
+ };
74
+ if (typeof Intl !== "undefined" && typeof Intl.Segmenter === "function") for (const s of new Intl.Segmenter(void 0, { granularity: "word" }).segment(text)) if (SPACE.test(s.segment)) flush();
75
+ else parts.push(s.segment);
76
+ else for (const s of text.split(/(\s+)/u)) if (s === "" || SPACE.test(s)) flush();
77
+ else parts.push(s);
78
+ flush();
79
+ return words;
80
+ }
81
+ /** This function gives the grapheme clusters of a text. Without `Intl.Segmenter`, it gives the code points. */
82
+ function graphemesOf(text) {
83
+ if (typeof Intl !== "undefined" && typeof Intl.Segmenter === "function") return Array.from(new Intl.Segmenter(void 0, { granularity: "grapheme" }).segment(text), (s) => s.segment);
84
+ return Array.from(text);
85
+ }
86
+ /**
87
+ * 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`.
88
+ *
89
+ * 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.
90
+ * 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.
91
+ */
92
+ function layoutText(text, options) {
93
+ const { font, measurer, lineHeight } = options;
94
+ if (!(Number.isFinite(lineHeight) && lineHeight > 0)) throw new RangeError(`layoutText: lineHeight is a finite number above 0, not ${lineHeight}.`);
95
+ const ellipsis = options.ellipsis ?? "…";
96
+ const padding = options.padding ?? 0;
97
+ const keep = (options.wordBreak ?? "keep") === "keep";
98
+ let truncated = false;
99
+ let source = text;
100
+ if (options.maxChars !== void 0) {
101
+ const clusters = graphemesOf(source);
102
+ if (clusters.length > options.maxChars) {
103
+ const room = Math.max(0, options.maxChars - graphemesOf(ellipsis).length);
104
+ source = clusters.slice(0, room).join("") + ellipsis;
105
+ truncated = true;
106
+ }
107
+ }
108
+ const words = wordsOf(source);
109
+ const space = measurer.advance(" ", font);
110
+ const width = (w) => w.parts.reduce((s, p) => s + measurer.advance(p, font), 0);
111
+ const lineUnits = (line) => {
112
+ const ws = wordsOf(line);
113
+ return ws.reduce((s, w) => s + width(w), 0) + space * Math.max(0, ws.length - 1);
114
+ };
115
+ const widths = words.map(width);
116
+ const natural = widths.reduce((s, w) => s + w, 0) + space * Math.max(0, words.length - 1);
117
+ const maxWidth = options.maxWidth ?? (options.wrapWidth === void 0 ? Infinity : options.wrapWidth + padding);
118
+ const fits = natural / 64 + padding <= maxWidth;
119
+ if (options.wrapWidth === void 0 || fits) {
120
+ const one = words.map((w) => w.text).join(" ");
121
+ const px = natural / 64;
122
+ const box = Math.min(maxWidth, Math.max(options.minWidth ?? 0, px + padding));
123
+ return {
124
+ lines: [one],
125
+ widths: [px],
126
+ lineCount: 1,
127
+ width: box,
128
+ height: lineHeight,
129
+ truncated
130
+ };
131
+ }
132
+ const limit = Math.round(options.wrapWidth * 64);
133
+ const lines = [];
134
+ let cur;
135
+ const push = () => {
136
+ if (cur !== void 0) lines.push(cur);
137
+ cur = void 0;
138
+ };
139
+ /** This function puts a word that is wider than a line on new lines, with a break between grapheme clusters. */
140
+ const split = (word) => {
141
+ for (const g of graphemesOf(word.text)) {
142
+ const w = measurer.advance(g, font);
143
+ if (cur !== void 0 && cur.units + w > limit) push();
144
+ if (cur === void 0) cur = {
145
+ text: g,
146
+ units: w
147
+ };
148
+ else {
149
+ cur.text += g;
150
+ cur.units += w;
151
+ }
152
+ }
153
+ };
154
+ words.forEach((word, i) => {
155
+ const w = widths[i];
156
+ if (cur !== void 0 && cur.units + space + w <= limit) {
157
+ cur.text += ` ${word.text}`;
158
+ cur.units += space + w;
159
+ return;
160
+ }
161
+ push();
162
+ if (w > limit && !keep) split(word);
163
+ else cur = {
164
+ text: word.text,
165
+ units: w
166
+ };
167
+ });
168
+ push();
169
+ if (lines.length === 0) lines.push({
170
+ text: "",
171
+ units: 0
172
+ });
173
+ const maxLines = options.maxLines ?? Infinity;
174
+ if (lines.length > maxLines) {
175
+ lines.length = Math.max(1, maxLines);
176
+ const last = lines[lines.length - 1];
177
+ const tail = measurer.advance(ellipsis, font);
178
+ const clusters = graphemesOf(last.text);
179
+ while (clusters.length > 0 && lineUnits(clusters.join("")) + tail > limit) clusters.pop();
180
+ const kept = clusters.join("").replace(/\s+$/u, "");
181
+ last.text = kept + ellipsis;
182
+ last.units = lineUnits(kept) + tail;
183
+ truncated = true;
184
+ }
185
+ return {
186
+ lines: lines.map((l) => l.text),
187
+ widths: lines.map((l) => l.units / 64),
188
+ lineCount: lines.length,
189
+ width: options.wrapWidth + padding,
190
+ height: lines.length * lineHeight,
191
+ wrapWidth: options.wrapWidth,
192
+ truncated
193
+ };
194
+ }
195
+ /** The specs of the text measures. */
196
+ const TEXT_MEASURES = Object.freeze([
197
+ {
198
+ id: "text.lines",
199
+ unit: "count",
200
+ direction: "lower",
201
+ min: 1,
202
+ max: Infinity,
203
+ minEffect: 0,
204
+ family: "text"
205
+ },
206
+ {
207
+ id: "text.raggedness",
208
+ unit: "0 to 1",
209
+ direction: "lower",
210
+ min: 0,
211
+ max: 1,
212
+ minEffect: .005,
213
+ family: "text"
214
+ },
215
+ {
216
+ id: "text.overflow",
217
+ unit: "share of the wrap width",
218
+ direction: "lower",
219
+ min: 0,
220
+ max: Infinity,
221
+ floor: 0,
222
+ tol: 0,
223
+ minEffect: 0,
224
+ family: "text",
225
+ role: "guard"
226
+ },
227
+ {
228
+ id: "text.cacheHit",
229
+ unit: "0 to 1",
230
+ direction: "higher",
231
+ min: 0,
232
+ max: 1,
233
+ family: "text",
234
+ role: "diagnostic"
235
+ },
236
+ {
237
+ id: "text.ms",
238
+ unit: "milliseconds",
239
+ direction: "lower",
240
+ min: 0,
241
+ max: Infinity,
242
+ family: "text",
243
+ role: "time"
244
+ }
245
+ ]);
246
+ /**
247
+ * 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.
248
+ * `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.
249
+ * With `stats`, the measures also hold `text.cacheHit`: the hits divided by the requests.
250
+ */
251
+ function textMeasures(layout, stats) {
252
+ const w = layout.wrapWidth;
253
+ const body = layout.widths.slice(0, -1);
254
+ const raggedness = w === void 0 || body.length === 0 ? 0 : body.reduce((s, x) => s + (Math.max(0, w - x) / w) ** 2, 0) / body.length;
255
+ const overflow = w === void 0 ? 0 : Math.max(0, ...layout.widths.map((x) => (x - w) / w));
256
+ return {
257
+ "text.lines": layout.lineCount,
258
+ "text.raggedness": raggedness,
259
+ "text.overflow": overflow,
260
+ ...stats === void 0 ? {} : { "text.cacheHit": stats.requests === 0 ? 0 : stats.hits / stats.requests }
261
+ };
262
+ }
263
+ export { TEXT_MEASURES, TEXT_UNITS, canvasAdvance, createMeasurer, fontKey, graphemesOf, layoutText, textMeasures };
264
+
265
+ //# sourceMappingURL=text.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"text.js","names":[],"sources":["../src/text.ts"],"sourcesContent":["import type { MeasureSpec } from \"./measures.ts\";\n\n/**\n * The advance function of a host: the width of a run of text in a font, in pixels.\n * A browser host gives `canvasAdvance(context)`. A test or a server host gives a function of a font file.\n */\nexport type AdvanceFn = (text: string, font: string) => number;\n\n/** The count of the units in one pixel. Each advance is a whole number of units, so each sum is exact and each port gets the same pixels. */\nexport const TEXT_UNITS = 64;\n\n/** The counts of a measurer: the requests, the cache hits and the calls of the advance function. */\nexport interface MeasurerStats {\n readonly requests: number;\n readonly hits: number;\n readonly calls: number;\n}\n\n/** A measurer: the advance of a segment in a font, in whole units of 1/`TEXT_UNITS` pixel, with a cache. */\nexport interface TextMeasurer {\n /** This function gives the advance of the segment in the font, in units. */\n advance(segment: string, font: string): number;\n /** This function gives the counts since the start or since the last `reset`. */\n stats(): MeasurerStats;\n /** This function clears the cache and the counts. */\n reset(): void;\n}\n\n/** The options of `createMeasurer`. */\nexport interface MeasurerOptions {\n /** The count of the cache entries. The default is 10000. With 0, the measurer has no cache. */\n readonly maxEntries?: number;\n}\n\n/** This function gives the key of a font: the font string with its white space collapsed and trimmed. */\nexport function fontKey(font: string): string {\n return font.trim().replace(/\\s+/g, \" \");\n}\n\n/**\n * This function gives a measurer with a cache keyed by the font and the segment.\n * The cache removes its oldest entry when it is full. The advance function rounds each width to whole units.\n */\nexport function createMeasurer(measure: AdvanceFn, options: MeasurerOptions = {}): TextMeasurer {\n const max = options.maxEntries ?? 10000;\n if (!(Number.isInteger(max) && max >= 0)) throw new RangeError(`createMeasurer: maxEntries is an integer of 0 or more, not ${max}.`);\n const cache = new Map<string, number>();\n let requests = 0;\n let hits = 0;\n let calls = 0;\n return {\n advance(segment, font) {\n requests++;\n const key = `${fontKey(font)}\\u0000${segment}`;\n const known = cache.get(key);\n if (known !== undefined) {\n hits++;\n return known;\n }\n calls++;\n const px = measure(segment, font);\n if (!Number.isFinite(px) || px < 0) throw new RangeError(`The advance of \"${segment}\" in \"${font}\" is ${px}, not a finite number of 0 or more.`);\n const units = Math.round(px * TEXT_UNITS);\n if (max > 0) {\n if (cache.size >= max) cache.delete(cache.keys().next().value!);\n cache.set(key, units);\n }\n return units;\n },\n stats: () => ({ requests, hits, calls }),\n reset() {\n cache.clear();\n requests = 0;\n hits = 0;\n calls = 0;\n },\n };\n}\n\n/** The part of a canvas context that `canvasAdvance` uses. */\nexport interface CanvasTextContext {\n font: string;\n measureText(text: string): { readonly width: number };\n}\n\n/** This function gives the advance function of a canvas context. It sets `font` only when the font changes, because a browser parses each new font string. */\nexport function canvasAdvance(context: CanvasTextContext): AdvanceFn {\n let current: string | undefined;\n return (text, font) => {\n if (font !== current) {\n context.font = font;\n current = font;\n }\n return context.measureText(text).width;\n };\n}\n\n/** A word of a text: its segments, which the measurer measures and caches one by one. */\ninterface Word {\n readonly text: string;\n readonly parts: readonly string[];\n}\n\nconst SPACE = /^\\s+$/u;\n\n/** This function splits the text into words at white space. Each word holds its word segments (`Intl.Segmenter`), so words that share segments share the cache. */\nfunction wordsOf(text: string): Word[] {\n const words: Word[] = [];\n let parts: string[] = [];\n const flush = (): void => {\n if (parts.length > 0) words.push({ text: parts.join(\"\"), parts });\n parts = [];\n };\n if (typeof Intl !== \"undefined\" && typeof Intl.Segmenter === \"function\") {\n for (const s of new Intl.Segmenter(undefined, { granularity: \"word\" }).segment(text)) {\n if (SPACE.test(s.segment)) flush();\n else parts.push(s.segment);\n }\n } else {\n for (const s of text.split(/(\\s+)/u)) {\n if (s === \"\" || SPACE.test(s)) flush();\n else parts.push(s);\n }\n }\n flush();\n return words;\n}\n\n/** This function gives the grapheme clusters of a text. Without `Intl.Segmenter`, it gives the code points. */\nexport function graphemesOf(text: string): string[] {\n if (typeof Intl !== \"undefined\" && typeof Intl.Segmenter === \"function\") return Array.from(new Intl.Segmenter(undefined, { granularity: \"grapheme\" }).segment(text), (s) => s.segment);\n return Array.from(text);\n}\n\n/** The options of `layoutText`. All lengths are in pixels. */\nexport interface TextLayoutOptions {\n readonly font: string;\n readonly measurer: TextMeasurer;\n /** The line height. A finite number above 0. */\n readonly lineHeight: number;\n /** The width of the lines of a text that does not fit on one line. Without it, the text stays on one line. */\n readonly wrapWidth?: number;\n /** The count of the lines. The last line that stays gets the ellipsis. The default is no limit. */\n readonly maxLines?: number;\n /** The count of the grapheme clusters. A longer text keeps `maxChars` clusters with the ellipsis at the end. The default is no limit. */\n readonly maxChars?: number;\n /** The text at the end of a cut text. The default is \"…\". */\n readonly ellipsis?: string;\n /** The space that the box adds to the width of the text. The default is 0. */\n readonly padding?: number;\n /** The smallest width of a box with one line. The default is 0. */\n readonly minWidth?: number;\n /** The largest width of a box with one line. A text that does not fit wraps at `wrapWidth`. The default is `wrapWidth` plus the padding, or no limit without `wrapWidth`. */\n readonly maxWidth?: number;\n /**\n * The break of a word that is wider than a line. `keep` (the default) keeps the word whole, and the line overflows.\n * `anywhere` breaks it between two grapheme clusters, as the CSS `overflow-wrap: anywhere`.\n */\n readonly wordBreak?: \"keep\" | \"anywhere\";\n}\n\n/** The layout of a text: its lines and its box. */\nexport interface TextLayout {\n readonly lines: readonly string[];\n /** The width of each line, in pixels. Each width is a whole number of units of 1/`TEXT_UNITS` pixel. */\n readonly widths: readonly number[];\n readonly lineCount: number;\n /** The width of the box: the text and the padding. */\n readonly width: number;\n readonly height: number;\n /** The width of the lines, or `undefined` for a text on one line. */\n readonly wrapWidth?: number;\n /** `true` when `maxChars` or `maxLines` cut the text. */\n readonly truncated: boolean;\n}\n\n/** A line of a layout, with its width in units. */\ninterface Line {\n text: string;\n units: number;\n}\n\n/**\n * This function lays out a text. It cuts the text to `maxChars`. It keeps the text on one line when it fits in `maxWidth`. Else it breaks the text into lines of `wrapWidth`.\n *\n * The breaker is greedy, as a browser with `white-space: normal`. It collapses each run of white space to one space, and a line does not count its last space.\n * The width of a word is the sum of the advances of its segments. `docs/TEXT.md` gives the rules and the error of this sum.\n */\nexport function layoutText(text: string, options: TextLayoutOptions): TextLayout {\n const { font, measurer, lineHeight } = options;\n if (!(Number.isFinite(lineHeight) && lineHeight > 0)) throw new RangeError(`layoutText: lineHeight is a finite number above 0, not ${lineHeight}.`);\n const ellipsis = options.ellipsis ?? \"…\";\n const padding = options.padding ?? 0;\n const keep = (options.wordBreak ?? \"keep\") === \"keep\";\n let truncated = false;\n\n let source = text;\n if (options.maxChars !== undefined) {\n const clusters = graphemesOf(source);\n if (clusters.length > options.maxChars) {\n const room = Math.max(0, options.maxChars - graphemesOf(ellipsis).length);\n source = clusters.slice(0, room).join(\"\") + ellipsis;\n truncated = true;\n }\n }\n\n const words = wordsOf(source);\n const space = measurer.advance(\" \", font);\n const width = (w: Word): number => w.parts.reduce((s, p) => s + measurer.advance(p, font), 0);\n const lineUnits = (line: string): number => {\n const ws = wordsOf(line);\n return ws.reduce((s, w) => s + width(w), 0) + space * Math.max(0, ws.length - 1);\n };\n const widths = words.map(width);\n const natural = widths.reduce((s, w) => s + w, 0) + space * Math.max(0, words.length - 1);\n\n const maxWidth = options.maxWidth ?? (options.wrapWidth === undefined ? Infinity : options.wrapWidth + padding);\n const fits = natural / TEXT_UNITS + padding <= maxWidth;\n if (options.wrapWidth === undefined || fits) {\n const one = words.map((w) => w.text).join(\" \");\n const px = natural / TEXT_UNITS;\n const box = Math.min(maxWidth, Math.max(options.minWidth ?? 0, px + padding));\n return { lines: [one], widths: [px], lineCount: 1, width: box, height: lineHeight, truncated };\n }\n\n const limit = Math.round(options.wrapWidth * TEXT_UNITS);\n const lines: Line[] = [];\n let cur: Line | undefined;\n const push = (): void => {\n if (cur !== undefined) lines.push(cur);\n cur = undefined;\n };\n /** This function puts a word that is wider than a line on new lines, with a break between grapheme clusters. */\n const split = (word: Word): void => {\n for (const g of graphemesOf(word.text)) {\n const w = measurer.advance(g, font);\n if (cur !== undefined && cur.units + w > limit) push();\n if (cur === undefined) cur = { text: g, units: w };\n else {\n cur.text += g;\n cur.units += w;\n }\n }\n };\n words.forEach((word, i) => {\n const w = widths[i]!;\n if (cur !== undefined && cur.units + space + w <= limit) {\n cur.text += ` ${word.text}`;\n cur.units += space + w;\n return;\n }\n push();\n if (w > limit && !keep) split(word);\n else cur = { text: word.text, units: w };\n });\n push();\n if (lines.length === 0) lines.push({ text: \"\", units: 0 });\n\n const maxLines = options.maxLines ?? Infinity;\n if (lines.length > maxLines) {\n lines.length = Math.max(1, maxLines);\n const last = lines[lines.length - 1]!;\n const tail = measurer.advance(ellipsis, font);\n const clusters = graphemesOf(last.text);\n while (clusters.length > 0 && lineUnits(clusters.join(\"\")) + tail > limit) clusters.pop();\n const kept = clusters.join(\"\").replace(/\\s+$/u, \"\");\n last.text = kept + ellipsis;\n last.units = lineUnits(kept) + tail;\n truncated = true;\n }\n\n return {\n lines: lines.map((l) => l.text),\n widths: lines.map((l) => l.units / TEXT_UNITS),\n lineCount: lines.length,\n width: options.wrapWidth + padding,\n height: lines.length * lineHeight,\n wrapWidth: options.wrapWidth,\n truncated,\n };\n}\n\n/** The id of a text measure. `docs/TEXT.md` gives the definitions. */\nexport type TextMeasureId = \"text.lines\" | \"text.raggedness\" | \"text.overflow\" | \"text.cacheHit\" | \"text.ms\";\n\n/** The specs of the text measures. */\nexport const TEXT_MEASURES: readonly MeasureSpec<TextMeasureId>[] = Object.freeze([\n { id: \"text.lines\", unit: \"count\", direction: \"lower\", min: 1, max: Infinity, minEffect: 0, family: \"text\" },\n { id: \"text.raggedness\", unit: \"0 to 1\", direction: \"lower\", min: 0, max: 1, minEffect: 0.005, family: \"text\" },\n { id: \"text.overflow\", unit: \"share of the wrap width\", direction: \"lower\", min: 0, max: Infinity, floor: 0, tol: 0, minEffect: 0, family: \"text\", role: \"guard\" },\n { id: \"text.cacheHit\", unit: \"0 to 1\", direction: \"higher\", min: 0, max: 1, family: \"text\", role: \"diagnostic\" },\n { id: \"text.ms\", unit: \"milliseconds\", direction: \"lower\", min: 0, max: Infinity, family: \"text\", role: \"time\" },\n] as const);\n\n/**\n * This function gives the measures of a layout. `text.raggedness` is the mean of `((wrapWidth - width) / wrapWidth)^2` over the lines before the last line.\n * `text.overflow` is the largest excess of a line over `wrapWidth`, as a share of `wrapWidth`. A text on one line gives 0 for the two values.\n * With `stats`, the measures also hold `text.cacheHit`: the hits divided by the requests.\n */\nexport function textMeasures(layout: TextLayout, stats?: MeasurerStats): Partial<Record<TextMeasureId, number>> {\n const w = layout.wrapWidth;\n const body = layout.widths.slice(0, -1);\n const raggedness = w === undefined || body.length === 0 ? 0 : body.reduce((s, x) => s + (Math.max(0, w - x) / w) ** 2, 0) / body.length;\n const overflow = w === undefined ? 0 : Math.max(0, ...layout.widths.map((x) => (x - w) / w));\n return {\n \"text.lines\": layout.lineCount,\n \"text.raggedness\": raggedness,\n \"text.overflow\": overflow,\n ...(stats === undefined ? {} : { \"text.cacheHit\": stats.requests === 0 ? 0 : stats.hits / stats.requests }),\n };\n}\n"],"mappings":";;AASA,MAAa,aAAa;;AA0B1B,SAAgB,QAAQ,MAAsB;CAC5C,OAAO,KAAK,KAAK,CAAC,CAAC,QAAQ,QAAQ,GAAG;AACxC;;;;;AAMA,SAAgB,eAAe,SAAoB,UAA2B,CAAC,GAAiB;CAC9F,MAAM,MAAM,QAAQ,cAAc;CAClC,IAAI,EAAE,OAAO,UAAU,GAAG,KAAK,OAAO,IAAI,MAAM,IAAI,WAAW,8DAA8D,IAAI,EAAE;CACnI,MAAM,wBAAQ,IAAI,IAAoB;CACtC,IAAI,WAAW;CACf,IAAI,OAAO;CACX,IAAI,QAAQ;CACZ,OAAO;EACL,QAAQ,SAAS,MAAM;GACrB;GACA,MAAM,MAAM,GAAG,QAAQ,IAAI,EAAE,QAAQ;GACrC,MAAM,QAAQ,MAAM,IAAI,GAAG;GAC3B,IAAI,UAAU,KAAA,GAAW;IACvB;IACA,OAAO;GACT;GACA;GACA,MAAM,KAAK,QAAQ,SAAS,IAAI;GAChC,IAAI,CAAC,OAAO,SAAS,EAAE,KAAK,KAAK,GAAG,MAAM,IAAI,WAAW,mBAAmB,QAAQ,QAAQ,KAAK,OAAO,GAAG,oCAAoC;GAC/I,MAAM,QAAQ,KAAK,MAAM,KAAA,EAAe;GACxC,IAAI,MAAM,GAAG;IACX,IAAI,MAAM,QAAQ,KAAK,MAAM,OAAO,MAAM,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,KAAM;IAC9D,MAAM,IAAI,KAAK,KAAK;GACtB;GACA,OAAO;EACT;EACA,cAAc;GAAE;GAAU;GAAM;EAAM;EACtC,QAAQ;GACN,MAAM,MAAM;GACZ,WAAW;GACX,OAAO;GACP,QAAQ;EACV;CACF;AACF;;AASA,SAAgB,cAAc,SAAuC;CACnE,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AAG,CAAC,IAAI,KAAK;CACjI,MAAM,WAAW,MAAM,KAAA,IAAY,IAAI,KAAK,IAAI,GAAG,GAAG,OAAO,OAAO,KAAK,OAAO,IAAI,KAAK,CAAC,CAAC;CAC3F,OAAO;EACL,cAAc,OAAO;EACrB,mBAAmB;EACnB,iBAAiB;EACjB,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,iBAAiB,MAAM,aAAa,IAAI,IAAI,MAAM,OAAO,MAAM,SAAS;CAC3G;AACF"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/layout-contract",
4
- "version": "0.2.18",
4
+ "version": "0.2.20",
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",
@@ -31,6 +31,10 @@
31
31
  "types": "./build/index.d.ts",
32
32
  "default": "./build/index.js"
33
33
  },
34
+ "./text": {
35
+ "types": "./build/text.d.ts",
36
+ "default": "./build/text.js"
37
+ },
34
38
  "./package.json": "./package.json"
35
39
  },
36
40
  "files": [
package/src/balance.ts ADDED
@@ -0,0 +1,233 @@
1
+ import { SIDES, type Rect, type Side } from "./geometry.ts";
2
+ import type { MeasureSpec } from "./measures.ts";
3
+ import { SHAPE_KIND_IDS, type ShapeKind } from "./shapes.ts";
4
+
5
+ /** A placed box: its id and its bounding box. */
6
+ export interface PlacedBox extends Rect {
7
+ readonly id: string;
8
+ }
9
+
10
+ /** The balance of one layout. `docs/BALANCE.md` gives the definitions. */
11
+ export interface Balance {
12
+ /** The standard deviation of the nearest-neighbour gaps divided by their mean. */
13
+ readonly gapCv: number;
14
+ /** The distance from the centroid of the free area to the center of the container, as a share of the half-diagonal. */
15
+ readonly centroidOffset: number;
16
+ /** The empty share of the strip at each side of the container. */
17
+ readonly side: Readonly<Record<Side, number>>;
18
+ /** The largest value of `side` minus the smallest value. */
19
+ readonly sideRange: number;
20
+ }
21
+
22
+ /** The depth of the strip of each side, as a share of the container. For `top` and `bottom`, it is a share of the height. For `left` and `right`, it is a share of the width. */
23
+ export const BALANCE_SIDE_DEPTH = 0.25;
24
+
25
+ /** A suffix of a balance or stability measure. A stage adds its prefix, for example `pack.balance.gapCv`. */
26
+ export type BalanceMeasureSuffix =
27
+ | "balance.gapCv"
28
+ | "balance.centroidOffset"
29
+ | "balance.side.top"
30
+ | "balance.side.right"
31
+ | "balance.side.bottom"
32
+ | "balance.side.left"
33
+ | "balance.sideRange"
34
+ | "stability.procrustes"
35
+ | "stability.seed";
36
+
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([
39
+ "balance.gapCv",
40
+ "balance.centroidOffset",
41
+ "balance.side.top",
42
+ "balance.side.right",
43
+ "balance.side.bottom",
44
+ "balance.side.left",
45
+ "balance.sideRange",
46
+ "stability.procrustes",
47
+ "stability.seed",
48
+ ] as const);
49
+
50
+ /** This function gives the area of the overlap of two rectangles. */
51
+ function overlapArea(a: Rect, b: Rect): number {
52
+ const w = Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x);
53
+ const h = Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y);
54
+ return w > 0 && h > 0 ? w * h : 0;
55
+ }
56
+
57
+ /** This function gives the distance between two rectangles. Two rectangles that touch or overlap give 0. */
58
+ function rectDistance(a: Rect, b: Rect): number {
59
+ const dx = Math.max(0, b.x - (a.x + a.w), a.x - (b.x + b.w));
60
+ const dy = Math.max(0, b.y - (a.y + a.h), a.y - (b.y + b.h));
61
+ return Math.hypot(dx, dy);
62
+ }
63
+
64
+ /**
65
+ * This function gives the gap of each box to its nearest other box, in the order of `boxes`.
66
+ * Each box scans the boxes sorted by `x` in the two directions. A scan stops when the distance on `x` alone is above the best gap of the box.
67
+ * To the left, the distance on `x` is at least `a.x - b.x - maxW`, with `maxW` the largest width. With fewer than 2 boxes, a gap is `Infinity`.
68
+ */
69
+ export function nearestGaps(boxes: readonly Rect[]): number[] {
70
+ const order = boxes.map((_, i) => i).sort((i, j) => boxes[i]!.x - boxes[j]!.x || i - j);
71
+ const maxW = boxes.reduce((m, b) => Math.max(m, b.w), 0);
72
+ const gaps = new Array<number>(boxes.length).fill(Infinity);
73
+ for (let k = 0; k < order.length; k++) {
74
+ const a = boxes[order[k]!]!;
75
+ let best = Infinity;
76
+ for (let m = k + 1; m < order.length; m++) {
77
+ const b = boxes[order[m]!]!;
78
+ if (b.x - (a.x + a.w) > best) break;
79
+ best = Math.min(best, rectDistance(a, b));
80
+ }
81
+ for (let m = k - 1; m >= 0; m--) {
82
+ const b = boxes[order[m]!]!;
83
+ if (a.x - b.x - maxW > best) break;
84
+ best = Math.min(best, rectDistance(a, b));
85
+ }
86
+ gaps[order[k]!] = best;
87
+ }
88
+ return gaps;
89
+ }
90
+
91
+ /**
92
+ * This function gives the balance of the placed boxes in the container: the evenness of the gaps and the place of the free space.
93
+ * The boxes do not overlap, as in the output of a packer. The area of a box outside the container does not count.
94
+ * `docs/BALANCE.md` gives the definitions and the reasons.
95
+ */
96
+ export function balanceOf(boxes: readonly Rect[], container: Rect): Balance {
97
+ const gaps = boxes.length < 2 ? [] : nearestGaps(boxes);
98
+ const mean = gaps.length === 0 ? 0 : gaps.reduce((s, g) => s + g, 0) / gaps.length;
99
+ const sd = gaps.length === 0 ? 0 : Math.sqrt(gaps.reduce((s, g) => s + (g - mean) ** 2, 0) / gaps.length);
100
+ const gapCv = mean > 0 ? sd / mean : 0;
101
+
102
+ const area = container.w * container.h;
103
+ const cx = container.x + container.w / 2;
104
+ const cy = container.y + container.h / 2;
105
+ let used = 0;
106
+ let mx = 0;
107
+ let my = 0;
108
+ for (const b of boxes) {
109
+ const x0 = Math.max(b.x, container.x);
110
+ const y0 = Math.max(b.y, container.y);
111
+ const x1 = Math.min(b.x + b.w, container.x + container.w);
112
+ const y1 = Math.min(b.y + b.h, container.y + container.h);
113
+ if (x1 <= x0 || y1 <= y0) continue;
114
+ const a = (x1 - x0) * (y1 - y0);
115
+ used += a;
116
+ mx += a * (x0 + x1) / 2;
117
+ my += a * (y0 + y1) / 2;
118
+ }
119
+ const free = area - used;
120
+ const half = Math.hypot(container.w, container.h) / 2;
121
+ let centroidOffset = 0;
122
+ if (free > 0 && half > 0) {
123
+ const fx = (area * cx - mx) / free;
124
+ const fy = (area * cy - my) / free;
125
+ centroidOffset = Math.min(1, Math.hypot(fx - cx, fy - cy) / half);
126
+ }
127
+
128
+ const dh = container.h * BALANCE_SIDE_DEPTH;
129
+ const dw = container.w * BALANCE_SIDE_DEPTH;
130
+ const strips: Record<Side, Rect> = {
131
+ top: { x: container.x, y: container.y, w: container.w, h: dh },
132
+ right: { x: container.x + container.w - dw, y: container.y, w: dw, h: container.h },
133
+ bottom: { x: container.x, y: container.y + container.h - dh, w: container.w, h: dh },
134
+ left: { x: container.x, y: container.y, w: dw, h: container.h },
135
+ };
136
+ const side = {} as Record<Side, number>;
137
+ for (const s of SIDES) {
138
+ const strip = strips[s];
139
+ const stripArea = strip.w * strip.h;
140
+ const filled = boxes.reduce((sum, b) => sum + overlapArea(b, strip), 0);
141
+ side[s] = stripArea > 0 ? Math.min(1, Math.max(0, 1 - filled / stripArea)) : 0;
142
+ }
143
+ const values = SIDES.map((s) => side[s]);
144
+ return { gapCv, centroidOffset, side, sideRange: Math.max(...values) - Math.min(...values) };
145
+ }
146
+
147
+ /** The options of `procrustesOf`. */
148
+ export interface ProcrustesOptions {
149
+ /** The unit of the result: the width `W` of the base, as in `joint.stability.mean`. A finite number above 0. */
150
+ readonly unit: number;
151
+ /** With `true` (the default), the alignment also rotates. With `false`, it only moves. */
152
+ readonly rotate?: boolean;
153
+ }
154
+
155
+ /**
156
+ * This function gives the root mean square move of the box centers from `base` to `next`, after the best alignment, in units of `unit`.
157
+ * The alignment is the orthogonal Procrustes fit: one move and, by default, one rotation. Only the ids in the two lists count.
158
+ * Fewer than 2 shared ids give 0, because the alignment then removes each move.
159
+ */
160
+ export function procrustesOf(base: readonly PlacedBox[], next: readonly PlacedBox[], options: ProcrustesOptions): number {
161
+ if (!(Number.isFinite(options.unit) && options.unit > 0)) throw new RangeError(`procrustesOf: the unit is a finite number above 0, not ${options.unit}.`);
162
+ const after = new Map(next.map((b) => [b.id, b]));
163
+ const a: [number, number][] = [];
164
+ const b: [number, number][] = [];
165
+ for (const p of base) {
166
+ const q = after.get(p.id);
167
+ if (q === undefined) continue;
168
+ a.push([p.x + p.w / 2, p.y + p.h / 2]);
169
+ b.push([q.x + q.w / 2, q.y + q.h / 2]);
170
+ }
171
+ const n = a.length;
172
+ if (n < 2) return 0;
173
+ const mean = (list: [number, number][]): [number, number] => [list.reduce((s, p) => s + p[0], 0) / n, list.reduce((s, p) => s + p[1], 0) / n];
174
+ const [ax, ay] = mean(a);
175
+ const [bx, by] = mean(b);
176
+ let dot = 0;
177
+ let cross = 0;
178
+ for (let i = 0; i < n; i++) {
179
+ const [px, py] = [a[i]![0] - ax, a[i]![1] - ay];
180
+ const [qx, qy] = [b[i]![0] - bx, b[i]![1] - by];
181
+ dot += px * qx + py * qy;
182
+ cross += px * qy - py * qx;
183
+ }
184
+ const theta = options.rotate === false || (dot === 0 && cross === 0) ? 0 : Math.atan2(cross, dot);
185
+ const cos = Math.cos(theta);
186
+ const sin = Math.sin(theta);
187
+ let sum = 0;
188
+ for (let i = 0; i < n; i++) {
189
+ const [px, py] = [a[i]![0] - ax, a[i]![1] - ay];
190
+ const [qx, qy] = [b[i]![0] - bx, b[i]![1] - by];
191
+ sum += (cos * px - sin * py - qx) ** 2 + (sin * px + cos * py - qy) ** 2;
192
+ }
193
+ return Math.sqrt(sum / n) / options.unit;
194
+ }
195
+
196
+ /**
197
+ * This function gives the value of `stability.procrustes`: the move of `procrustesOf` divided by the change share.
198
+ * The change share is `changed / count`, and it is at least `1 / count`. Thus a change of one box divides by the smallest share.
199
+ */
200
+ export function perChange(move: number, changed: number, count: number): number {
201
+ if (!(Number.isInteger(count) && count >= 1)) throw new RangeError(`perChange: the count is an integer of 1 or more, not ${count}.`);
202
+ const share = Math.max(1, Math.min(count, changed)) / count;
203
+ return move / share;
204
+ }
205
+
206
+ /** This function gives the balance values as measures, with the prefix of the stage, for example `pack.balance.gapCv`. */
207
+ export function balanceMeasures<S extends string>(stage: S, balance: Balance): Record<`${S}.${BalanceMeasureSuffix}`, number> {
208
+ const m: Record<string, number> = {
209
+ [`${stage}.balance.gapCv`]: balance.gapCv,
210
+ [`${stage}.balance.centroidOffset`]: balance.centroidOffset,
211
+ [`${stage}.balance.sideRange`]: balance.sideRange,
212
+ };
213
+ for (const s of SIDES) m[`${stage}.balance.side.${s}`] = balance.side[s];
214
+ return m as Record<`${S}.${BalanceMeasureSuffix}`, number>;
215
+ }
216
+
217
+ /**
218
+ * This function gives the specs of the balance and stability measures, with the prefix of the stage.
219
+ * The balance measures read the area of each box, so they support only `rect`. The stability measures read only the centers.
220
+ */
221
+ export function balanceMeasureSpecs<S extends string>(stage: S): readonly MeasureSpec<`${S}.${BalanceMeasureSuffix}`>[] {
222
+ const id = (suffix: BalanceMeasureSuffix): `${S}.${BalanceMeasureSuffix}` => `${stage}.${suffix}`;
223
+ const rect: readonly ShapeKind[] = ["rect"];
224
+ const centers = SHAPE_KIND_IDS;
225
+ return Object.freeze([
226
+ { id: id("balance.gapCv"), unit: "ratio", direction: "lower", min: 0, max: Infinity, minEffect: 0.01, family: "balance", shapes: rect },
227
+ { id: id("balance.centroidOffset"), unit: "0 to 1", direction: "lower", min: 0, max: 1, minEffect: 0.01, family: "balance", shapes: rect },
228
+ ...SIDES.map((s) => ({ id: id(`balance.side.${s}`), unit: "0 to 1", direction: "lower" as const, min: 0, max: 1, family: "balance", role: "diagnostic" as const, shapes: rect })),
229
+ { id: id("balance.sideRange"), unit: "0 to 1", direction: "lower", min: 0, max: 1, minEffect: 0.02, family: "balance", shapes: rect },
230
+ { id: id("stability.procrustes"), unit: "W for each change share", direction: "lower", min: 0, max: Infinity, floor: 0, tol: 0.005, minEffect: 0.005, family: "stability", role: "change-guard", shapes: centers },
231
+ { id: id("stability.seed"), unit: "W", direction: "lower", min: 0, max: Infinity, floor: 0, tol: 0.005, minEffect: 0.005, family: "stability", shapes: centers },
232
+ ]);
233
+ }