@ftrdotdev/pi-tui 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/CHANGELOG.md +225 -0
  2. package/README.md +5 -0
  3. package/package.json +18 -15
  4. package/src/activity-service.test.ts +97 -0
  5. package/src/activity.test.ts +1 -1
  6. package/src/activity.ts +38 -0
  7. package/src/chrome/budget.test.ts +345 -0
  8. package/src/chrome/budget.ts +220 -0
  9. package/src/chrome/declarations.ts +303 -0
  10. package/src/chrome/facts.test.ts +165 -0
  11. package/src/chrome/facts.ts +267 -0
  12. package/src/chrome/frame.ts +45 -0
  13. package/src/chrome/laws.test.ts +231 -0
  14. package/src/chrome/port.test.ts +164 -0
  15. package/src/chrome/port.ts +67 -0
  16. package/src/chrome/service-provider.test.ts +383 -0
  17. package/src/chrome/service-provider.ts +55 -0
  18. package/src/commands/git-execution.test.ts +5 -2
  19. package/src/commands/git-execution.ts +27 -15
  20. package/src/commands/git-status.test.ts +47 -15
  21. package/src/commands/git-status.ts +83 -31
  22. package/src/components/bordered-box.test.ts +12 -15
  23. package/src/components/bordered-box.ts +11 -7
  24. package/src/components/define-component.ts +1 -1
  25. package/src/components/index.ts +7 -0
  26. package/src/components/row-list.test.ts +310 -0
  27. package/src/components/row-list.ts +272 -0
  28. package/src/config.test.ts +118 -3
  29. package/src/config.ts +50 -42
  30. package/src/frame/box-frame.test.ts +53 -7
  31. package/src/harness-policy.test.ts +47 -0
  32. package/src/icons.test.ts +19 -0
  33. package/src/icons.ts +50 -31
  34. package/src/index.test.ts +135 -0
  35. package/src/index.ts +118 -119
  36. package/src/layers.test.ts +94 -0
  37. package/src/layers.ts +92 -0
  38. package/src/runtime-service.test.ts +218 -0
  39. package/src/runtime-service.ts +103 -0
  40. package/src/runtime.test.ts +165 -66
  41. package/src/runtime.ts +127 -93
  42. package/src/session-lifecycle-service.test.ts +95 -0
  43. package/src/session-lifecycle.test.ts +77 -0
  44. package/src/session-lifecycle.ts +21 -0
  45. package/src/state.test.ts +132 -3
  46. package/src/state.ts +43 -13
  47. package/src/telemetry-service.test.ts +250 -0
  48. package/src/telemetry.test.ts +322 -0
  49. package/src/telemetry.ts +130 -23
  50. package/src/ui/editor-tint.test.ts +58 -45
  51. package/src/ui/editor-tint.ts +1 -1
  52. package/src/ui/editor.ts +117 -53
  53. package/src/ui/footer.test.ts +349 -120
  54. package/src/ui/footer.ts +147 -124
  55. package/src/ui/header.test.ts +203 -223
  56. package/src/ui/header.ts +32 -96
  57. package/src/ui/preview.test.ts +73 -70
  58. package/src/ui/preview.ts +48 -33
  59. package/src/ui/render-helpers.test.ts +82 -13
  60. package/src/ui/render-helpers.ts +110 -122
  61. package/src/ui/settings-command.test.ts +70 -11
  62. package/src/ui/settings-command.ts +30 -45
  63. package/src/ui/theme-color.test.ts +4 -3
  64. package/src/usage-totals-service.test.ts +230 -0
  65. package/src/usage-totals-service.ts +59 -0
  66. package/src/utils.test.ts +46 -50
  67. package/src/utils.ts +41 -239
  68. package/src/vim/editor-host.test.ts +201 -75
  69. package/src/vim/editor-state.ts +2 -2
  70. package/src/vim/mode-indicator.test.ts +6 -5
  71. package/src/vim/mode-indicator.ts +13 -9
  72. package/src/vim/selection-render.ts +8 -4
  73. package/src/vim/text-model.test.ts +52 -14
  74. package/src/vim/text-model.ts +1 -1
  75. package/src/vim/vim-router.test.ts +3 -0
  76. package/src/vim/vim-router.ts +1 -1
@@ -0,0 +1,345 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import { PROPERTY_RUNS } from "@ftrdotdev/pi-test-kit";
3
+ import { Arbitrary, Schema } from "effect";
4
+ import { segmentPlanArbitrary } from "../../test-support/generators.ts";
5
+ import { composeLine, fitSurface, type Decision } from "./budget.ts";
6
+ import type { SegmentDeclaration, Degradation } from "./declarations.ts";
7
+
8
+ // The engine knows nothing of pi, themes or `visibleWidth`: the test measures
9
+ // by code points, which is the same unit the ASCII fixtures use.
10
+ const measure = (text: string): number => Array.from(text).length;
11
+ const width = (text: string): number => measure(text);
12
+
13
+ /** The test's code-point truncator; production injects pi's `truncateToWidth`. */
14
+ const truncate = (text: string, maxWidth: number, ellipsis: string): string => {
15
+ if (maxWidth <= 0) return "";
16
+ if (measure(text) <= maxWidth) return text;
17
+ const ellipsisWidth = measure(ellipsis);
18
+ if (ellipsisWidth >= maxWidth) {
19
+ let clipped = "";
20
+ for (const char of ellipsis) {
21
+ if (measure(clipped + char) > maxWidth) break;
22
+ clipped += char;
23
+ }
24
+ return clipped;
25
+ }
26
+ let prefix = "";
27
+ for (const char of text) {
28
+ if (measure(prefix + char) + ellipsisWidth > maxWidth) break;
29
+ prefix += char;
30
+ }
31
+ return prefix + ellipsis;
32
+ };
33
+ const fitOptions = { measure, truncate } as const;
34
+
35
+ const declaration = (
36
+ id: string,
37
+ overrides: Partial<SegmentDeclaration> = {},
38
+ ): SegmentDeclaration => ({
39
+ id,
40
+ fact: "cwd",
41
+ line: 1,
42
+ priority: 1,
43
+ minWidth: 1,
44
+ degradation: "truncate" as Degradation,
45
+ align: "left",
46
+ separator: " ",
47
+ ...overrides,
48
+ });
49
+
50
+ const resolve = (entries: Record<string, string>) =>
51
+ Object.entries(entries).map(([id, text]) => ({ id, text }));
52
+
53
+ it("keeps everything when the width is sufficient", () => {
54
+ // Arrange: two left segments that together need exactly 9 columns.
55
+ const declarations = [
56
+ declaration("first", { priority: 2, minWidth: 4 }),
57
+ declaration("second", { priority: 1, minWidth: 4 }),
58
+ ];
59
+ const resolved = resolve({ first: "abcd", second: "wxyz" });
60
+
61
+ // Act: fit at the exact width (4 + space + 4).
62
+ const decisions = fitSurface(declarations, resolved, 9, { ...fitOptions });
63
+
64
+ // Assert: both kept, in declaration order, composed at exactly 9.
65
+ assert.deepStrictEqual(
66
+ decisions.map((entry) => [entry.id, entry.action]),
67
+ [
68
+ ["first", "keep"],
69
+ ["second", "keep"],
70
+ ],
71
+ );
72
+ assert.strictEqual(width(composeLine(decisions, 9)), 9);
73
+ });
74
+
75
+ it("drops the lowest priority first", () => {
76
+ // Arrange: the same two segments.
77
+ const declarations = [
78
+ declaration("first", { priority: 2, minWidth: 4 }),
79
+ declaration("second", { priority: 1, minWidth: 4 }),
80
+ ];
81
+ const resolved = resolve({ first: "abcd", second: "wxyz" });
82
+
83
+ // Act: fit at one segment's width.
84
+ const decisions = fitSurface(declarations, resolved, 4, { ...fitOptions });
85
+
86
+ // Assert: the high priority survives; the low one drops for width.
87
+ assert.strictEqual(decisions[0]!.action, "keep");
88
+ assert.strictEqual(decisions[1]!.action, "drop");
89
+ assert.strictEqual(decisions[1]!.text, "");
90
+ assert.strictEqual(decisions[1]!.reason, "width");
91
+ });
92
+
93
+ it("truncates a truncate segment to its grant and never below minWidth", () => {
94
+ // Arrange: one long branch name with a floor of 6.
95
+ const declarations = [declaration("branch", { minWidth: 6 })];
96
+ const resolved = resolve({ branch: "a-long-branch-name" });
97
+
98
+ // Act: fit at 8.
99
+ const decisions = fitSurface(declarations, resolved, 8, { ...fitOptions });
100
+
101
+ // Assert: one truncation to exactly the grant, ending with the ellipsis.
102
+ assert.strictEqual(decisions.length, 1);
103
+ assert.strictEqual(decisions[0]!.action, "truncate");
104
+ assert.strictEqual(width(decisions[0]!.text), 8);
105
+ assert.ok(decisions[0]!.text.endsWith("..."));
106
+ });
107
+
108
+ it("a drop segment is never truncated; a truncate segment drops only below its floor", () => {
109
+ // Arrange: a truncatable high priority and a drop-only low priority.
110
+ const declarations = [
111
+ declaration("branch", { priority: 2, minWidth: 6, degradation: "truncate" }),
112
+ declaration("runtime", { priority: 1, minWidth: 4, degradation: "drop" }),
113
+ ];
114
+ const resolved = resolve({ branch: "0123456789", runtime: "abcdefghij" });
115
+
116
+ // Act/Assert: the drop-only segment drops; the truncatable one keeps ≥ 6.
117
+ const at8 = fitSurface(declarations, resolved, 8, { ...fitOptions });
118
+ assert.strictEqual(at8[1]!.action, "drop");
119
+ assert.notStrictEqual(at8[0]!.action, "drop");
120
+ assert.ok(at8[0]!.width >= 6);
121
+
122
+ // Act/Assert: at 5 the truncatable floor cannot be met, so it drops too.
123
+ const at5 = fitSurface(declarations, resolved, 5, { ...fitOptions });
124
+ assert.strictEqual(at5[0]!.action, "drop");
125
+ assert.strictEqual(at5[0]!.reason, "width");
126
+
127
+ // Act/Assert: a grant that clears the drop-only floor still cannot shrink it.
128
+ // Ten columns of drop-only text plus a four-column keep at 12 leaves a
129
+ // seven-column grant, which the old engine would truncate.
130
+ const dropThenKeep = [
131
+ declaration("runtime", { priority: 1, minWidth: 4, degradation: "drop" }),
132
+ declaration("branch", { priority: 2, minWidth: 4, degradation: "truncate" }),
133
+ ];
134
+ const at12 = fitSurface(
135
+ dropThenKeep,
136
+ resolve({ runtime: "abcdefghij", branch: "wxyz" }),
137
+ 12,
138
+ fitOptions,
139
+ );
140
+ assert.strictEqual(at12[0]!.action, "drop");
141
+ assert.strictEqual(at12[0]!.reason, "width");
142
+ assert.strictEqual(at12[1]!.action, "keep");
143
+ });
144
+
145
+ it("kept text never measures below its floor, whatever the degradation", () => {
146
+ // Arrange: two floors of 6 and three available columns.
147
+ for (const degradation of ["drop-then-truncate", "truncate"] as const) {
148
+ const declarations = [declaration("only", { minWidth: 6, degradation })];
149
+
150
+ // Act: fit far below the floor.
151
+ const decisions = fitSurface(
152
+ declarations,
153
+ resolve({ only: "01234567890123456789" }),
154
+ 3,
155
+ fitOptions,
156
+ );
157
+
158
+ // Assert: a drop, never a 3-column truncation and never an overflow.
159
+ assert.strictEqual(decisions[0]!.action, "drop");
160
+ assert.strictEqual(decisions[0]!.reason, "width");
161
+ }
162
+ });
163
+
164
+ it("a declaration with no resolved text yields a drop with its reason", () => {
165
+ // Arrange: only the second declaration resolves.
166
+ const declarations = [declaration("missing"), declaration("present", { priority: 2 })];
167
+
168
+ // Act: fit wide.
169
+ const decisions = fitSurface(declarations, resolve({ present: "ok" }), 80, { ...fitOptions });
170
+
171
+ // Assert: one decision per declaration, the first unavailable.
172
+ assert.strictEqual(decisions.length, 2);
173
+ assert.strictEqual(decisions[0]!.action, "drop");
174
+ assert.strictEqual(decisions[0]!.text, "");
175
+ assert.strictEqual(decisions[0]!.reason, "unavailable");
176
+ assert.strictEqual(decisions[1]!.action, "keep");
177
+ });
178
+
179
+ it("keeps the right-aligned group on the right and counts its separator once", () => {
180
+ // Arrange: one left segment and two right segments with a right-group separator.
181
+ const declarations = [
182
+ declaration("left", { priority: 9, minWidth: 4 }),
183
+ declaration("rightA", { priority: 5, minWidth: 2, align: "right" }),
184
+ declaration("rightB", { priority: 4, minWidth: 2, align: "right" }),
185
+ ];
186
+ const resolved = resolve({ left: "abcd", rightA: "xx", rightB: "yy" });
187
+
188
+ // Act: fit at exactly 4 + 1 + (2 + 1 + 2).
189
+ const decisions = fitSurface(declarations, resolved, 10, { ...fitOptions });
190
+
191
+ // Assert: every decision carries its declaration separator; exact fit.
192
+ assert.deepStrictEqual(
193
+ decisions.map((entry) => entry.separator),
194
+ [" ", " ", " "],
195
+ );
196
+ assert.deepStrictEqual(
197
+ decisions.map((entry) => entry.action),
198
+ ["keep", "keep", "keep"],
199
+ );
200
+ const composed = composeLine(decisions, 10);
201
+ assert.strictEqual(width(composed), 10);
202
+ assert.ok(composed.startsWith("abcd"));
203
+ assert.ok(composed.endsWith("xx yy"));
204
+
205
+ // Act/Assert: one column less drops the lowest-priority right segment and
206
+ // the composed line still fits (padded between the groups).
207
+ const narrower = fitSurface(declarations, resolved, 9, { ...fitOptions });
208
+ assert.strictEqual(narrower[2]!.action, "drop");
209
+ assert.ok(width(composeLine(narrower, 9)) <= 9);
210
+ });
211
+
212
+ it("measures a wide separator in columns when composing", () => {
213
+ // Arrange: two right-aligned fields joined by a two-column separator.
214
+ const wideMeasure = (text: string): number =>
215
+ Array.from(text).reduce((total, char) => total + (char === "界" ? 2 : 1), 0);
216
+ const declarations = [
217
+ declaration("a", { priority: 2, minWidth: 2, align: "right", separator: "界" }),
218
+ declaration("b", { priority: 1, minWidth: 2, align: "right", separator: "界" }),
219
+ ];
220
+
221
+ // Act: fit at exactly 2 + 2 + 2 columns.
222
+ const decisions = fitSurface(declarations, resolve({ a: "aa", b: "bb" }), 6, {
223
+ measure: wideMeasure,
224
+ truncate,
225
+ });
226
+
227
+ // Assert: composition pads by the measured separator width, not code points.
228
+ assert.strictEqual(wideMeasure(composeLine(decisions, 6)), 6);
229
+ });
230
+
231
+ /** A width in the property's sweep, including zero and negative. */
232
+ const widthArbitrary = Arbitrary.schema(
233
+ Schema.Int.check(Schema.isBetween({ minimum: -20, maximum: 200 })),
234
+ );
235
+
236
+ /** An optional per-line cap: 0 encodes "no cap". */
237
+ const maxPerLineArbitrary = Arbitrary.map(
238
+ Arbitrary.schema(Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 2 }))),
239
+ (value) => (value === 0 ? undefined : value),
240
+ );
241
+
242
+ /** The generated plan plus the width it must fit. */
243
+ const fitCaseArbitrary = Arbitrary.all({
244
+ plan: segmentPlanArbitrary,
245
+ available: widthArbitrary,
246
+ maxPerLine: maxPerLineArbitrary,
247
+ });
248
+
249
+ it.prop(
250
+ "is total and deterministic at every width",
251
+ { fit: fitCaseArbitrary },
252
+ ({ fit }) => {
253
+ // Arrange: generated declarations with unique ids and a resolved text each.
254
+ const declarations = fit.plan.map((row, index) =>
255
+ declaration(`s${index}`, {
256
+ priority: row.priority,
257
+ minWidth: row.minWidth,
258
+ degradation: row.degradation,
259
+ align: row.align,
260
+ line: row.line,
261
+ separator: row.separator,
262
+ }),
263
+ );
264
+ const resolved = fit.plan.map((row, index) => ({ id: `s${index}`, text: row.text }));
265
+ const options = {
266
+ ...fitOptions,
267
+ ...(fit.maxPerLine === undefined ? {} : { maxPerLine: fit.maxPerLine }),
268
+ };
269
+
270
+ // Act: fit twice.
271
+ const first = fitSurface(declarations, resolved, fit.available, options);
272
+ const second = fitSurface(declarations, resolved, fit.available, options);
273
+
274
+ // Assert: determinism and totality.
275
+ assert.deepStrictEqual(first, second);
276
+ assert.strictEqual(first.length, declarations.length);
277
+ assert.deepStrictEqual(
278
+ first.map((entry) => entry.id),
279
+ declarations.map((entry) => entry.id),
280
+ );
281
+
282
+ // Assert: floors hold, and nothing exceeds the available width.
283
+ const priorityById = new Map(declarations.map((entry) => [entry.id, entry.priority]));
284
+ const minWidthById = new Map(declarations.map((entry) => [entry.id, entry.minWidth]));
285
+ for (const entry of first) {
286
+ if (entry.action === "drop") continue;
287
+ assert.ok(
288
+ entry.width >= minWidthById.get(entry.id)!,
289
+ `${entry.id}: kept ${entry.width} below its floor`,
290
+ );
291
+ }
292
+ // Assert: each declared line composes within the available width.
293
+ const byLine = new Map<number, Decision[]>();
294
+ for (const entry of first) {
295
+ byLine.set(entry.line, [...(byLine.get(entry.line) ?? []), entry]);
296
+ }
297
+ for (const lineDecisions of byLine.values()) {
298
+ assert.ok(
299
+ width(composeLine(lineDecisions, Math.max(0, fit.available))) <= Math.max(0, fit.available),
300
+ );
301
+ }
302
+
303
+ // Assert: the narrow cap holds per line, when set.
304
+ if (fit.maxPerLine !== undefined) {
305
+ const keptPerLine = new Map<number, number>();
306
+ for (const entry of first) {
307
+ if (entry.action === "drop") continue;
308
+ keptPerLine.set(entry.line, (keptPerLine.get(entry.line) ?? 0) + 1);
309
+ }
310
+ for (const kept of keptPerLine.values()) assert.ok(kept <= fit.maxPerLine);
311
+ }
312
+
313
+ // Assert: priority monotonicity within a line — nothing keeps below a
314
+ // width drop. Fitting is per line, so the total order is per line too.
315
+ for (const lineDecisions of byLine.values()) {
316
+ const keptOnLine = lineDecisions
317
+ .filter((entry) => entry.action === "keep")
318
+ .map((entry) => priorityById.get(entry.id)!);
319
+ for (const entry of lineDecisions) {
320
+ if (entry.action !== "drop" || entry.reason !== "width") continue;
321
+ const dropped = priorityById.get(entry.id)!;
322
+ for (const kept of keptOnLine) {
323
+ assert.ok(kept >= dropped, `${entry.id}: a lower priority survived on its line`);
324
+ }
325
+ }
326
+ }
327
+
328
+ // Assert: a non-positive width drops every resolvable decision.
329
+ if (fit.available <= 0) {
330
+ for (const entry of first) {
331
+ if (entry.reason === "unavailable") continue;
332
+ assert.strictEqual(entry.action, "drop");
333
+ }
334
+ }
335
+
336
+ // Assert: decisions mirror their declarations' alignment and separator.
337
+ const declarationById = new Map(declarations.map((entry) => [entry.id, entry]));
338
+ for (const entry of first as readonly Decision[]) {
339
+ const source = declarationById.get(entry.id)!;
340
+ assert.strictEqual(entry.align, source.align);
341
+ assert.strictEqual(entry.separator, source.separator);
342
+ }
343
+ },
344
+ { arbitrary: { runs: PROPERTY_RUNS } },
345
+ );
@@ -0,0 +1,220 @@
1
+ // The budget engine: one total, deterministic function that fits a surface's
2
+ // declarations against a width. It measures text through a required injected
3
+ // measurer, so it knows nothing of pi, themes or `visibleWidth`.
4
+ import type { FactId } from "./facts.ts";
5
+ import type { SegmentDeclaration } from "./declarations.ts";
6
+
7
+ export type Action = "keep" | "truncate" | "drop";
8
+ export type DropReason = "width" | "unavailable";
9
+
10
+ export interface Decision {
11
+ readonly id: string;
12
+ readonly fact: FactId;
13
+ readonly line: number;
14
+ readonly action: Action;
15
+ /** "" for a drop. */
16
+ readonly text: string;
17
+ /** The measured width of `text`. */
18
+ readonly width: number;
19
+ readonly align: "left" | "right";
20
+ /** Precedes this decision when its group already has one. */
21
+ readonly separator: string;
22
+ /** The measured width of `separator`. */
23
+ readonly separatorWidth: number;
24
+ readonly reason?: DropReason;
25
+ }
26
+
27
+ export interface FitOptions {
28
+ /** Required: production passes `visibleWidth`, tests pass a code-point counter. */
29
+ readonly measure: (text: string) => number;
30
+ /** Required: production passes `truncateToWidth`; tests pass a code-point cutter. */
31
+ readonly truncate: (text: string, width: number, ellipsis: string) => string;
32
+ /** Defaults to "...". */
33
+ readonly ellipsis?: string;
34
+ /** Narrow law: when set, no line keeps more than this many fields. */
35
+ readonly maxPerLine?: number;
36
+ }
37
+
38
+ interface Live {
39
+ readonly declaration: SegmentDeclaration;
40
+ text: string;
41
+ width: number;
42
+ action: Action;
43
+ reason?: DropReason;
44
+ }
45
+
46
+ const ELLIPSIS = "...";
47
+
48
+ /** The measured width of a group's separators and texts, first one bare. */
49
+ function groupWidth(entries: readonly Live[], measure: (text: string) => number): number {
50
+ return entries.reduce(
51
+ (total, entry, index) =>
52
+ total + (index === 0 ? 0 : measure(entry.declaration.separator)) + entry.width,
53
+ 0,
54
+ );
55
+ }
56
+
57
+ /** The width `composeLine` would produce for the live entries on one line. */
58
+ function composedWidth(entries: readonly Live[], measure: (text: string) => number): number {
59
+ const left = entries.filter((entry) => entry.declaration.align === "left");
60
+ const right = entries.filter((entry) => entry.declaration.align === "right");
61
+ const groupJoin = left.length > 0 && right.length > 0 ? 1 : 0;
62
+ return groupWidth(left, measure) + groupWidth(right, measure) + groupJoin;
63
+ }
64
+
65
+ const lowestPriority = (entries: readonly Live[]): Live =>
66
+ entries.reduce((lowest, entry) =>
67
+ entry.declaration.priority < lowest.declaration.priority ? entry : lowest,
68
+ );
69
+
70
+ const toDecision = (entry: Live, measure: (text: string) => number): Decision => ({
71
+ id: entry.declaration.id,
72
+ fact: entry.declaration.fact,
73
+ line: entry.declaration.line,
74
+ action: entry.action,
75
+ text: entry.text,
76
+ width: entry.width,
77
+ align: entry.declaration.align,
78
+ separator: entry.declaration.separator,
79
+ separatorWidth: measure(entry.declaration.separator),
80
+ ...(entry.reason === undefined ? {} : { reason: entry.reason }),
81
+ });
82
+
83
+ export function fitSurface(
84
+ declarations: readonly SegmentDeclaration[],
85
+ resolved: readonly { readonly id: string; readonly text: string }[],
86
+ availableWidth: number,
87
+ options: FitOptions,
88
+ ): readonly Decision[] {
89
+ const measure = options.measure;
90
+ const ellipsis = options.ellipsis ?? ELLIPSIS;
91
+ const truncate = options.truncate;
92
+ const resolvedById = new Map(resolved.map((entry) => [entry.id, entry.text]));
93
+
94
+ // One decision per declaration, in declaration order. A resolved text that
95
+ // cannot reach the declaration's legible floor is unavailable: the engine
96
+ // drops a field rather than show it below its floor.
97
+ const entries: Live[] = declarations.map((declaration) => {
98
+ const text = resolvedById.get(declaration.id);
99
+ if (text === undefined || text === "") {
100
+ return {
101
+ declaration,
102
+ text: "",
103
+ width: 0,
104
+ action: "drop",
105
+ reason: "unavailable",
106
+ };
107
+ }
108
+ const textWidth = measure(text);
109
+ if (textWidth < declaration.minWidth) {
110
+ return { declaration, text: "", width: 0, action: "drop", reason: "unavailable" };
111
+ }
112
+ return { declaration, text, width: textWidth, action: "keep" };
113
+ });
114
+
115
+ if (availableWidth <= 0) {
116
+ for (const entry of entries) {
117
+ if (entry.reason === "unavailable") continue;
118
+ entry.action = "drop";
119
+ entry.text = "";
120
+ entry.width = 0;
121
+ entry.reason = "width";
122
+ }
123
+ return entries.map((entry) => toDecision(entry, measure));
124
+ }
125
+
126
+ const lines = [...new Set(declarations.map((declaration) => declaration.line))];
127
+ for (const line of lines) {
128
+ let live = entries.filter(
129
+ (entry) => entry.declaration.line === line && entry.action !== "drop",
130
+ );
131
+ while (live.length > 0) {
132
+ const total = composedWidth(live, measure);
133
+ if (total <= availableWidth) break;
134
+
135
+ // Yield the lowest priority first: a total order, so drops are monotone.
136
+ // Only a truncatable degradation may shrink; a drop-only field vanishes
137
+ // whole, even when its grant would clear the floor.
138
+ const target = lowestPriority(live);
139
+ const grant = availableWidth - (total - target.width);
140
+ if (
141
+ target.declaration.degradation !== "drop" &&
142
+ grant >= target.declaration.minWidth &&
143
+ grant < target.width
144
+ ) {
145
+ const truncated = truncate(target.text, grant, ellipsis);
146
+ const truncatedWidth = measure(truncated);
147
+ if (truncatedWidth >= target.declaration.minWidth && truncatedWidth < target.width) {
148
+ target.text = truncated;
149
+ target.width = truncatedWidth;
150
+ target.action = "truncate";
151
+ continue;
152
+ }
153
+ }
154
+ target.action = "drop";
155
+ target.text = "";
156
+ target.width = 0;
157
+ target.reason = "width";
158
+ live = live.filter((entry) => entry !== target);
159
+ }
160
+ }
161
+
162
+ // Narrow law: cap the kept fields per line, lowest priority yielding first.
163
+ if (options.maxPerLine !== undefined) {
164
+ for (const line of lines) {
165
+ let kept = entries.filter(
166
+ (entry) => entry.declaration.line === line && entry.action !== "drop",
167
+ );
168
+ while (kept.length > options.maxPerLine) {
169
+ const target = lowestPriority(kept);
170
+ target.action = "drop";
171
+ target.text = "";
172
+ target.width = 0;
173
+ target.reason = "width";
174
+ kept = kept.filter((entry) => entry !== target);
175
+ }
176
+ }
177
+ }
178
+
179
+ return entries.map((entry) => toDecision(entry, measure));
180
+ }
181
+
182
+ /** One aligned group: the first text bare, every later one after its separator. */
183
+ const joinGroup = (
184
+ entries: readonly Decision[],
185
+ paintSeparator: (separator: string) => string,
186
+ ): string =>
187
+ entries
188
+ .map((entry, index) =>
189
+ index === 0 ? entry.text : paintSeparator(entry.separator) + entry.text,
190
+ )
191
+ .join("");
192
+
193
+ /** One group's measured width, from each decision's measured text. */
194
+ const joinWidth = (entries: readonly Decision[]): number =>
195
+ entries.reduce(
196
+ (total, entry, index) => total + (index === 0 ? 0 : entry.separatorWidth) + entry.width,
197
+ 0,
198
+ );
199
+
200
+ /**
201
+ * Compose one line from fitted decisions: right-aligned decisions hug the end,
202
+ * the rest the start, with one space between the groups. Kept decisions already
203
+ * fit, so this pads only. `paintSeparator` styles the declaration separators
204
+ * (the default is identity); the group gap between left and right stays plain.
205
+ */
206
+ export function composeLine(
207
+ decisions: readonly Decision[],
208
+ width: number,
209
+ paintSeparator: (separator: string) => string = (separator) => separator,
210
+ ): string {
211
+ const kept = decisions.filter((entry) => entry.action !== "drop");
212
+ const left = kept.filter((entry) => entry.align === "left");
213
+ const right = kept.filter((entry) => entry.align === "right");
214
+ if (right.length === 0) return joinGroup(left, paintSeparator);
215
+ if (left.length === 0) {
216
+ return " ".repeat(Math.max(0, width - joinWidth(right))) + joinGroup(right, paintSeparator);
217
+ }
218
+ const pad = Math.max(1, width - joinWidth(left) - joinWidth(right));
219
+ return joinGroup(left, paintSeparator) + " ".repeat(pad) + joinGroup(right, paintSeparator);
220
+ }