ccleanup 1.0.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.
@@ -0,0 +1,922 @@
1
+ import { sessionKey } from "../core/scan.js";
2
+ import { messages } from "../i18n/messages.js";
3
+ import { DAY, formatAge, formatDuration, formatSize, GB, MB } from "../lib/format.js";
4
+ import { cut, fit, skip, width } from "../lib/text.js";
5
+ import { line, selectionStyle } from "./line.js";
6
+ import { logo, LOGO_WIDTH, wordmark } from "./logo.js";
7
+ import { confirmBox, DETAILS_ROWS, detailsBox, helpBox, overlay } from "./panels.js";
8
+ import { mix } from "./theme.js";
9
+ const SIZE_WIDTH = 9;
10
+ const AGE_WIDTH = 5;
11
+ const PREFIX_WIDTH = 4;
12
+ const SPARE = 1;
13
+ const STATS_WIDTH = 50;
14
+ const FULL_ROWS = 18;
15
+ const SCAN_FOLD_AT = 2000;
16
+ const SCAN_FOLD_MS = 400;
17
+ const FIREFLY_CELLS = 8;
18
+ const FIREFLY_TRAIL = 60;
19
+ const FIREFLY_TRAIL_MS = 500;
20
+ // Top speed of the firefly across, in braille dots per millisecond
21
+ const FIREFLY_SPEED = 0.02;
22
+ const EMBER_SPAWN_MS = 110;
23
+ const EMBER_LIFE_MS = 1300;
24
+ const BRAILLE = 0x2800;
25
+ // Braille dot bits, top to bottom, for the left and right columns
26
+ const BRAILLE_DOTS = [
27
+ [0x01, 0x08],
28
+ [0x02, 0x10],
29
+ [0x04, 0x20],
30
+ [0x40, 0x80],
31
+ ];
32
+ export const SCAN_SETTLE_MS = SCAN_FOLD_AT + SCAN_FOLD_MS;
33
+ export const MIN_COLS = 40;
34
+ export const MIN_ROWS = 8;
35
+ /**
36
+ * Color of a size: the bigger, the louder.
37
+ *
38
+ * @param bytes - Size of the session
39
+ * @returns Muted under 10 MB, plain under 100 MB, warning under 1 GB, error above
40
+ */
41
+ function sizeTone(bytes) {
42
+ if (bytes >= GB)
43
+ return "err";
44
+ if (bytes >= 100 * MB)
45
+ return "warn";
46
+ if (bytes < 10 * MB)
47
+ return "muted";
48
+ return "text";
49
+ }
50
+ /**
51
+ * Ease-in-out curve for the progress bar motion.
52
+ *
53
+ * @param t - Progress, clamped to 0..1
54
+ * @returns The eased progress, 0..1
55
+ */
56
+ function easeInOut(t) {
57
+ const x = Math.min(1, Math.max(0, t));
58
+ return x < 0.5 ? 2 * x * x : 1 - (-2 * x + 2) ** 2 / 2;
59
+ }
60
+ /**
61
+ * Two-tone progress bar.
62
+ *
63
+ * @param theme - Theme of the output: colors, depth and glyph set
64
+ * @param fraction - Filled part, clamped to 0..1
65
+ * @param cells - Width of the bar
66
+ * @param tone - Color of the filled part; the rest is a dim track
67
+ * @returns The bar segments
68
+ */
69
+ function bar(theme, fraction, cells, tone) {
70
+ const filled = Math.round(Math.min(1, Math.max(0, fraction)) * cells);
71
+ return [
72
+ [theme.glyphs.bar.repeat(filled), { fg: tone }],
73
+ [theme.glyphs.track.repeat(cells - filled), { fg: "muted", dim: true }],
74
+ ];
75
+ }
76
+ /**
77
+ * Color between two tokens.
78
+ *
79
+ * @param theme - Theme of the output: an exact mix from 256 colors up, the nearer token below
80
+ * @param from - Token at ratio 0
81
+ * @param to - Token at ratio 1
82
+ * @param ratio - Position between the two, 0 to 1
83
+ * @returns The style of that color
84
+ */
85
+ function tint(theme, from, to, ratio) {
86
+ if (theme.depth >= 8)
87
+ return { rgb: mix(theme.rgb(from), theme.rgb(to), ratio) };
88
+ return { fg: ratio < 0.5 ? from : to };
89
+ }
90
+ /**
91
+ * Progress bar of the scan: an accent to pink filled part crossed by a slow wave of light.
92
+ *
93
+ * @param theme - Theme of the output; below 256 colors the filled part takes the accent
94
+ * @param fraction - Filled part, clamped to 0..1
95
+ * @param cells - Width of the bar
96
+ * @param clock - Current time, which moves the wave
97
+ * @returns The bar segments
98
+ */
99
+ function shimmer(theme, fraction, cells, clock) {
100
+ if (theme.depth < 8)
101
+ return bar(theme, fraction, cells, "accent");
102
+ const filled = Math.round(Math.min(1, Math.max(0, fraction)) * cells);
103
+ const accent = theme.rgb("accent");
104
+ const pink = theme.rgb("pink");
105
+ const glow = theme.rgb("glow");
106
+ const segments = [];
107
+ for (let i = 0; i < filled; i++) {
108
+ const wave = (Math.sin(i / 2.5 - clock / 140) + 1) / 2;
109
+ const base = mix(accent, pink, i / Math.max(1, cells - 1));
110
+ segments.push([theme.glyphs.bar, { rgb: mix(base, glow, wave * 0.7) }]);
111
+ }
112
+ segments.push([theme.glyphs.track.repeat(cells - filled), { fg: "muted", dim: true }]);
113
+ return segments;
114
+ }
115
+ /**
116
+ * Firefly of the scan line: a light wandering over a few braille cells, its trail cooling
117
+ * from glow to ember, like the embers that rise under the list.
118
+ *
119
+ * Its path mixes two slow waves, across and up and down the four dot rows, and the trail
120
+ * is the same path a little earlier, so the frame depends only on the clock. Without
121
+ * Unicode it falls back to the ASCII spinner.
122
+ *
123
+ * @param theme - Theme of the output: colors, depth and glyph set
124
+ * @param clock - Current time
125
+ * @returns FIREFLY_CELLS cells
126
+ */
127
+ function firefly(theme, clock) {
128
+ if (!theme.unicode) {
129
+ return [
130
+ [spinner(theme, clock), { fg: "accent", bold: true }],
131
+ [" ".repeat(FIREFLY_CELLS - 1)],
132
+ ];
133
+ }
134
+ const span = FIREFLY_CELLS * 2 - 1;
135
+ const pace = (2 * FIREFLY_SPEED) / span;
136
+ const dots = Array(FIREFLY_CELLS).fill(0);
137
+ const heat = Array(FIREFLY_CELLS).fill(0);
138
+ for (let k = 0; k < FIREFLY_TRAIL; k++) {
139
+ const t = clock - (k * FIREFLY_TRAIL_MS) / FIREFLY_TRAIL;
140
+ const x = Math.round(((Math.sin(t * pace) + 1) / 2) * span);
141
+ const y = Math.min(3, Math.floor(((Math.sin(t / 430 + 1) + 1) / 2) * 4));
142
+ const cell = Math.floor(x / 2);
143
+ dots[cell] = dots[cell] | BRAILLE_DOTS[y][x % 2];
144
+ heat[cell] = Math.max(heat[cell], 1 - k / FIREFLY_TRAIL);
145
+ }
146
+ return dots.map((bits, i) => bits === 0
147
+ ? [" "]
148
+ : [String.fromCodePoint(BRAILLE + bits), tint(theme, "ember", "glow", heat[i])]);
149
+ }
150
+ /**
151
+ * Mixes the bits of an integer, for the placement of the embers.
152
+ *
153
+ * @param n - Integer to hash; only its low 32 bits count
154
+ * @returns An unsigned 32-bit hash
155
+ */
156
+ function hash(n) {
157
+ let h = Math.imul(n ^ 0x9e3779b9, 0x85ebca6b);
158
+ h ^= h >>> 13;
159
+ h = Math.imul(h, 0xc2b2ae35);
160
+ h ^= h >>> 16;
161
+ return h >>> 0;
162
+ }
163
+ /**
164
+ * Tells whether the embers show: during the scan, then while the last ones rise.
165
+ *
166
+ * @param state - Frame state, read only
167
+ * @returns False on terminals without color or Unicode
168
+ */
169
+ function embersActive(state) {
170
+ const { theme, scan, clock } = state;
171
+ if (!theme.enabled || !theme.unicode || theme.depth < 4)
172
+ return false;
173
+ return scan.endedAt === undefined || clock - scan.endedAt < EMBER_LIFE_MS;
174
+ }
175
+ /**
176
+ * Embers rising under the last row of the list, drawn with braille dots; the list grows
177
+ * as sessions are measured, so they follow the newest rows down.
178
+ *
179
+ * One ember is born every EMBER_SPAWN_MS at a column taken from the hash of its birth
180
+ * tick, then climbs the four dot rows and cools down: the frame depends only on the clock,
181
+ * so the view stays a pure function of its state.
182
+ *
183
+ * @param state - Frame state, read only
184
+ * @param cols - Terminal width in cells
185
+ * @returns The painted line, aligned with the data columns
186
+ */
187
+ function emberLine(state, cols) {
188
+ const { theme, clock, scan } = state;
189
+ const cells = cols - SPARE - PREFIX_WIDTH;
190
+ if (cells <= 0)
191
+ return "";
192
+ const dots = Array(cells).fill(0);
193
+ const heat = Array(cells).fill(0);
194
+ const first = Math.ceil(Math.max(clock - EMBER_LIFE_MS, scan.startedAt) / EMBER_SPAWN_MS);
195
+ const last = Math.floor(Math.min(clock, scan.endedAt ?? clock) / EMBER_SPAWN_MS);
196
+ for (let tick = first; tick <= last; tick++) {
197
+ const age = clock - tick * EMBER_SPAWN_MS;
198
+ if (age < 0 || age >= EMBER_LIFE_MS)
199
+ continue;
200
+ const h = hash(tick);
201
+ const cell = h % cells;
202
+ const height = 1 - age / EMBER_LIFE_MS;
203
+ const row = Math.min(3, Math.floor(height * 4));
204
+ dots[cell] = dots[cell] | BRAILLE_DOTS[row][(h >>> 16) & 1];
205
+ heat[cell] = Math.max(heat[cell], height);
206
+ }
207
+ const segments = [[" ".repeat(PREFIX_WIDTH)]];
208
+ dots.forEach((bits, i) => {
209
+ if (bits === 0)
210
+ segments.push([" "]);
211
+ else
212
+ segments.push([
213
+ String.fromCodePoint(BRAILLE + bits),
214
+ tint(theme, "ember", "glow", heat[i]),
215
+ ]);
216
+ });
217
+ return line(theme, segments, cols - SPARE);
218
+ }
219
+ /**
220
+ * Current frame of the spinner.
221
+ *
222
+ * @param theme - Theme of the output: colors, depth and glyph set
223
+ * @param clock - Current time; one frame every 80 ms
224
+ * @returns One glyph
225
+ */
226
+ function spinner(theme, clock) {
227
+ const frames = theme.glyphs.spinner;
228
+ return frames[Math.floor(clock / 80) % frames.length];
229
+ }
230
+ /**
231
+ * Width of the project column, fitted to the data.
232
+ *
233
+ * @param sessions - Sessions shown
234
+ * @param cols - Terminal width in cells
235
+ * @returns The longest project label, between 8 cells and a quarter of the width (24 at most)
236
+ */
237
+ function projectWidth(sessions, cols) {
238
+ const longest = sessions.reduce((max, session) => Math.max(max, width(session.project)), 0);
239
+ return Math.max(8, Math.min(24, longest, Math.floor(cols / 4)));
240
+ }
241
+ /**
242
+ * Width left for the title column.
243
+ *
244
+ * @param cols - Terminal width in cells
245
+ * @param project - Width of the project column
246
+ * @param prefix - Width of the cursor and mark columns, 0 for the plain table
247
+ * @returns At least 8 cells
248
+ */
249
+ function titleWidth(cols, project, prefix) {
250
+ return Math.max(8, cols - SPARE - prefix - SIZE_WIDTH - AGE_WIDTH - project - 3);
251
+ }
252
+ /**
253
+ * Column headers, the active sort highlighted with its direction, and the position of
254
+ * the cursor on the right.
255
+ *
256
+ * @param state - Frame state, read only
257
+ * @param cols - Terminal width in cells
258
+ * @param project - Width of the project column
259
+ * @returns The painted header line
260
+ */
261
+ function columnHeader(state, cols, project) {
262
+ const { theme, lang, sort, reversed, sessions, cursor } = state;
263
+ const columns = messages(lang).columns;
264
+ const direction = (mode) => (mode === "project") !== reversed ? theme.glyphs.sortUp : theme.glyphs.sortDown;
265
+ const label = (text, mode) => sort === mode ? `${text} ${direction(mode)}` : text;
266
+ const style = (mode) => sort === mode ? { fg: "accent", bold: true } : { fg: "muted" };
267
+ const position = sessions.length > 0 ? `${cursor + 1}/${sessions.length}` : "";
268
+ const title = titleWidth(cols, project, PREFIX_WIDTH) - width(position) - 1;
269
+ return line(theme, [
270
+ [" ".repeat(PREFIX_WIDTH)],
271
+ [fit(label(columns.size, "size"), SIZE_WIDTH, "right"), style("size")],
272
+ [" "],
273
+ [fit(label(columns.age, "age"), AGE_WIDTH, "right"), style("age")],
274
+ [" "],
275
+ [
276
+ fit(label(columns.project, "project"), project, "left", theme.glyphs.ellipsis),
277
+ style("project"),
278
+ ],
279
+ [" "],
280
+ [fit(columns.title, Math.max(0, title)), { fg: "muted" }],
281
+ [" "],
282
+ [position, { fg: "muted" }],
283
+ ], cols - SPARE);
284
+ }
285
+ /**
286
+ * Mark column of a row: the deletion state first, else a dot when marked, else nothing.
287
+ *
288
+ * @param theme - Theme of the output: colors, depth and glyph set
289
+ * @param session - Session of the row
290
+ * @param options - State of the row in the list
291
+ * @param clock - Current time, for the spinner
292
+ * @returns The mark segment, one cell wide
293
+ */
294
+ function markSegment(theme, session, options, clock) {
295
+ const { glyphs } = theme;
296
+ if (session.pending)
297
+ return [" "];
298
+ if (options.rowState === "deleting")
299
+ return [spinner(theme, clock), { fg: "warn", bold: true }];
300
+ if (options.rowState === "deleted")
301
+ return [glyphs.ok, { fg: "ok", bold: true }];
302
+ if (options.rowState === "error")
303
+ return [glyphs.err, { fg: "err", bold: true }];
304
+ if (options.marked)
305
+ return [glyphs.marked, { fg: "pink", bold: true }];
306
+ if (options.markable)
307
+ return [glyphs.unmarked, { fg: "muted", dim: true }];
308
+ return [" "];
309
+ }
310
+ /**
311
+ * Tag that flags a protected session: a colored word, or a soft pill when it must stand
312
+ * out a little more, both quiet enough not to pull the eye away from the sizes.
313
+ *
314
+ * @param theme - Theme of the output; the pill needs 256 colors, else it stays a word
315
+ * @param label - Text of the tag
316
+ * @param tone - Color of the word, and tint of the pill
317
+ * @param pill - Lay the word on a background lightly tinted with its color
318
+ * @returns The tag segment; between brackets when the output is not a terminal
319
+ */
320
+ function badgeSegment(theme, label, tone, pill = false) {
321
+ if (!theme.enabled)
322
+ return [`[${label}]`];
323
+ if (pill && theme.depth >= 8) {
324
+ const tint = mix(theme.rgb("paper"), theme.rgb(tone), theme.dark ? 0.22 : 0.16);
325
+ return [` ${label} `, { fg: tone, bgRgb: tint }];
326
+ }
327
+ return [label, { fg: tone, dim: theme.depth < 4 }];
328
+ }
329
+ /**
330
+ * Tag of a session, if it has one: an open session, never deleted, gets the pill; a
331
+ * recent one, protected only by default, the plain word.
332
+ *
333
+ * @param theme - Theme of the output
334
+ * @param lang - Language of the label
335
+ * @param session - Measured session
336
+ * @returns The open tag, else the recent tag, else undefined
337
+ */
338
+ function sessionBadge(theme, lang, session) {
339
+ if (session.open)
340
+ return badgeSegment(theme, messages(lang).open, "accent", true);
341
+ if (session.recent)
342
+ return badgeSegment(theme, messages(lang).recent, "ok");
343
+ return undefined;
344
+ }
345
+ /**
346
+ * Size, age, project and title of a measured session.
347
+ *
348
+ * @param context - Theme, language, scan time and age threshold
349
+ * @param session - Measured session
350
+ * @param room - Width left for the tag and the title
351
+ * @param project - Width of the project column
352
+ * @param options - State of the row in the list
353
+ * @returns The data segments of the row
354
+ */
355
+ function dataSegments(context, session, room, project, options) {
356
+ const { theme, lang, now, olderThan } = context;
357
+ const deleted = options.rowState === "deleted";
358
+ const gone = { fg: "muted", strike: true };
359
+ const age = now - session.mtime;
360
+ const ageTone = age < DAY ? "muted" : age >= olderThan ? "warn" : "text";
361
+ const badge = sessionBadge(theme, lang, session);
362
+ const tagWidth = badge ? width(badge[0]) + 1 : 0;
363
+ const titleTone = options.rowState === "error" ? "err" : badge ? "muted" : "text";
364
+ const segments = [
365
+ [
366
+ fit(formatSize(session.bytes, lang), SIZE_WIDTH, "right"),
367
+ deleted ? gone : { fg: sizeTone(session.bytes) },
368
+ ],
369
+ [" "],
370
+ [fit(formatAge(age, lang), AGE_WIDTH, "right"), deleted ? gone : { fg: ageTone }],
371
+ [" "],
372
+ [
373
+ fit(session.project, project, "left", theme.glyphs.ellipsis),
374
+ deleted ? gone : { fg: "text" },
375
+ ],
376
+ [" "],
377
+ ];
378
+ if (badge)
379
+ segments.push(deleted ? [badge[0], gone] : badge, [" "]);
380
+ segments.push([
381
+ cut(session.title || "-", Math.max(1, room - tagWidth), theme.glyphs.ellipsis),
382
+ deleted ? gone : { fg: titleTone, bold: options.marked },
383
+ ]);
384
+ return segments;
385
+ }
386
+ /**
387
+ * One session row, in the interactive list or in the plain table.
388
+ *
389
+ * @param context - Theme, language, scan time, age threshold and clock
390
+ * @param session - Session of the row; a pending one shows dots until it is measured
391
+ * @param cols - Terminal width in cells
392
+ * @param project - Width of the project column
393
+ * @param options - Cursor, mark and deletion state of the row
394
+ * @returns The painted row, a full-width bar when selected
395
+ */
396
+ function sessionRow(context, session, cols, project, options = {}) {
397
+ const { theme, clock } = context;
398
+ const prefix = options.prefix ? PREFIX_WIDTH : 0;
399
+ const segments = [];
400
+ if (options.prefix) {
401
+ segments.push([options.selected ? theme.glyphs.cursor : " ", { fg: "accent", bold: true }], [" "], markSegment(theme, session, options, clock), [" "]);
402
+ }
403
+ const room = titleWidth(cols, project, prefix);
404
+ segments.push(...dataSegments(context, session, room, project, options));
405
+ const base = options.selected ? selectionStyle(theme) : {};
406
+ return line(theme, segments, cols - SPARE, base, options.selected);
407
+ }
408
+ /**
409
+ * The four statistics shown right of the logo.
410
+ *
411
+ * @param state - Frame state, read only
412
+ * @returns One list of segments per line; a changed value flashes for a moment
413
+ */
414
+ function statLines(state) {
415
+ const { lang, stats, flashes, clock, olderThan } = state;
416
+ const m = messages(lang);
417
+ const size = (bytes) => formatSize(bytes, lang);
418
+ const labelWidth = Math.max(...Object.values(m.stats).map((label) => width(label))) + 2;
419
+ const countWidth = String(stats.sessions.count).length;
420
+ const flashing = (key) => (flashes.get(key) ?? 0) > clock;
421
+ const entry = (key, value, tone, extra = []) => {
422
+ const lit = flashing(key);
423
+ const segments = [
424
+ [fit(m.stats[key], labelWidth), { fg: "muted" }],
425
+ [
426
+ value,
427
+ {
428
+ fg: lit ? (key === "freed" ? "ok" : "warn") : tone,
429
+ bold: lit || key === "freed",
430
+ },
431
+ ],
432
+ ...extra,
433
+ ];
434
+ return segments;
435
+ };
436
+ const pair = (count, bytes) => `${String(count).padStart(countWidth)} ${size(bytes)}`;
437
+ const days = Math.round(olderThan / DAY);
438
+ return [
439
+ entry("sessions", pair(stats.sessions.count, stats.sessions.bytes), "text"),
440
+ entry("marked", pair(stats.marked.count, stats.marked.bytes), stats.marked.count > 0 ? "pink" : "muted"),
441
+ entry("releasable", pair(stats.releasable.count, stats.releasable.bytes), stats.releasable.count > 0 ? "warn" : "muted", [[` ${m.olderTag(days)}`, { fg: "muted", dim: true }]]),
442
+ entry("freed", size(stats.freed), stats.freed > 0 ? "ok" : "muted"),
443
+ ];
444
+ }
445
+ /**
446
+ * Large header: block logo with the version below, statistics on the right.
447
+ *
448
+ * @param state - Frame state, read only
449
+ * @param cols - Terminal width in cells
450
+ * @returns Four lines
451
+ */
452
+ function fullHeader(state, cols) {
453
+ const { theme, lang, version } = state;
454
+ const subtitle = `v${version} ${messages(lang).subtitle}`;
455
+ const left = [...logo(theme), theme.paint(subtitle, { fg: "muted" })];
456
+ const stats = statLines(state);
457
+ const gap = 6;
458
+ const leftWidth = Math.max(LOGO_WIDTH, width(subtitle));
459
+ const room = Math.max(0, cols - SPARE - leftWidth - gap - 1);
460
+ return left.map((text, i) => {
461
+ const pad = " ".repeat(Math.max(0, leftWidth - width(text)) + gap);
462
+ return ` ${text}${pad}${line(theme, stats[i] ?? [], room)}`;
463
+ });
464
+ }
465
+ /**
466
+ * Header for a terminal too narrow to put the statistics beside the logo: the logo, the
467
+ * version, then the statistics on one line.
468
+ *
469
+ * @param state - Frame state, read only
470
+ * @param cols - Terminal width in cells
471
+ * @returns Five lines
472
+ */
473
+ function stackedHeader(state, cols) {
474
+ const { theme, lang, version } = state;
475
+ const subtitle = theme.paint(`v${version} ${messages(lang).subtitle}`, { fg: "muted" });
476
+ return [
477
+ ...logo(theme).map((row) => ` ${row}`),
478
+ ` ${subtitle}`,
479
+ ...compactHeader(state, cols, false),
480
+ ];
481
+ }
482
+ /**
483
+ * One-line header for small terminals.
484
+ *
485
+ * @param state - Frame state, read only
486
+ * @param cols - Terminal width in cells
487
+ * @param named - Start with the name and the version; off under the logo, which shows them
488
+ * @returns One line: name, version, totals, marked and freed space
489
+ */
490
+ function compactHeader(state, cols, named = true) {
491
+ const { theme, lang, stats, version } = state;
492
+ const m = messages(lang);
493
+ const size = (bytes) => formatSize(bytes, lang);
494
+ const sep = [" / ", { fg: "muted", dim: true }];
495
+ const head = named ? `${wordmark(theme)} ${theme.paint(`v${version}`, { fg: "muted" })}` : "";
496
+ const rest = line(theme, [
497
+ named ? sep : [""],
498
+ [`${m.stats.sessions} ${stats.sessions.count}, ${size(stats.sessions.bytes)}`],
499
+ sep,
500
+ [
501
+ `${m.stats.marked} ${stats.marked.count}, ${size(stats.marked.bytes)}`,
502
+ { fg: stats.marked.count > 0 ? "pink" : "muted" },
503
+ ],
504
+ sep,
505
+ [
506
+ `${m.stats.freed} ${size(stats.freed)}`,
507
+ { fg: stats.freed > 0 ? "ok" : "muted", bold: stats.freed > 0 },
508
+ ],
509
+ ], Math.max(0, cols - SPARE - width(head) - 1));
510
+ return [` ${head}${rest}`];
511
+ }
512
+ /**
513
+ * Activity of a running deletion: spinner, counter, bar in bytes and elapsed time.
514
+ *
515
+ * @param state - Frame state with a deletion running
516
+ * @param cells - Width of the bar
517
+ * @returns The segments of the activity line
518
+ */
519
+ function deletionActivity(state, cells) {
520
+ const { theme, lang, clock } = state;
521
+ const deletion = state.deletion;
522
+ const elapsed = formatDuration(clock - deletion.startedAt, lang);
523
+ const amounts = `${formatSize(deletion.freed, lang)} / ${formatSize(deletion.bytes, lang)}`;
524
+ return [
525
+ [spinner(theme, clock), { fg: "warn", bold: true }],
526
+ [` ${messages(lang).deleting(deletion.done, deletion.total)} `, { fg: "text" }],
527
+ ...bar(theme, deletion.bytes > 0 ? deletion.freed / deletion.bytes : 1, cells, "warn"),
528
+ [` ${amounts}, ${elapsed}`, { fg: "muted" }],
529
+ ];
530
+ }
531
+ /**
532
+ * Activity of the scan: the firefly, counter and a shimmering bar that opens with an
533
+ * ease-in-out; once done, a check mark, then the bar folds toward its center after two
534
+ * seconds.
535
+ *
536
+ * @param state - Frame state, read only
537
+ * @param cells - Width of the bar
538
+ * @returns The segments of the activity line
539
+ */
540
+ function scanActivity(state, cells) {
541
+ const { theme, lang, clock, scan } = state;
542
+ const m = messages(lang);
543
+ if (scan.endedAt === undefined) {
544
+ const opening = Math.max(1, Math.round(cells * easeInOut((clock - scan.startedAt) / 300)));
545
+ return [
546
+ ...firefly(theme, clock),
547
+ [` ${m.scanning(scan.done, scan.total)} `, { fg: "text" }],
548
+ ...shimmer(theme, scan.total > 0 ? scan.done / scan.total : 1, opening, clock),
549
+ [` ${formatDuration(clock - scan.startedAt, lang)}`, { fg: "muted" }],
550
+ ];
551
+ }
552
+ const since = clock - scan.endedAt;
553
+ const fresh = since < SCAN_SETTLE_MS;
554
+ const text = m.scanDone(scan.total, formatDuration(scan.endedAt - scan.startedAt, lang));
555
+ const segments = [
556
+ [theme.glyphs.ok, { fg: "ok", bold: fresh }],
557
+ [` ${text}`, { fg: fresh ? "ok" : "muted" }],
558
+ ];
559
+ if (fresh) {
560
+ const fold = since < SCAN_FOLD_AT ? 1 : 1 - easeInOut((since - SCAN_FOLD_AT) / SCAN_FOLD_MS);
561
+ const shown = Math.round(cells * fold);
562
+ const side = Math.floor((cells - shown) / 2);
563
+ segments.push([` ${" ".repeat(side)}`], [theme.glyphs.bar.repeat(shown), { fg: "ok" }]);
564
+ }
565
+ return segments;
566
+ }
567
+ /**
568
+ * Line between the header and the list: deletion or scan progress, and the error count.
569
+ *
570
+ * @param state - Frame state, read only
571
+ * @param cols - Terminal width in cells
572
+ * @returns The painted line
573
+ */
574
+ function activityLine(state, cols) {
575
+ const { theme, lang, errors } = state;
576
+ const cells = Math.max(6, Math.min(30, Math.floor(cols / 4)));
577
+ const segments = [
578
+ [" "],
579
+ ...(state.deletion ? deletionActivity(state, cells) : scanActivity(state, cells)),
580
+ ];
581
+ if (errors.length > 0) {
582
+ segments.push([" "], [
583
+ `${theme.glyphs.err} ${messages(lang).errorsHint(errors.length)}`,
584
+ { fg: "err", bold: true },
585
+ ], [", e", { fg: "muted" }]);
586
+ }
587
+ return line(theme, segments, cols - SPARE);
588
+ }
589
+ /**
590
+ * Line above the footer: the deletion question, or the latest toast while it lasts.
591
+ *
592
+ * @param state - Frame state, read only
593
+ * @param cols - Terminal width in cells
594
+ * @returns The painted line, empty when there is nothing to say
595
+ */
596
+ function statusLine(state, cols) {
597
+ const { theme, lang, toast, clock, query, searching, sessions, total, states } = state;
598
+ const m = messages(lang);
599
+ // Deleted rows stay struck through until the next sort: skip them.
600
+ const shown = sessions.filter((session) => states.get(sessionKey(session)) !== "deleted");
601
+ const count = [` ${m.search.count(shown.length, total)}`, { fg: "muted" }];
602
+ if (searching) {
603
+ // While typing, the query end and caret always show.
604
+ const fixed = width(" / ") + width(theme.glyphs.caret);
605
+ const withCount = cols - SPARE - fixed - width(count[0]) >= 12;
606
+ const room = cols - SPARE - fixed - (withCount ? width(count[0]) : 0);
607
+ const typed = width(query) > room
608
+ ? theme.glyphs.ellipsis +
609
+ skip(query, width(query) - room + width(theme.glyphs.ellipsis))
610
+ : query;
611
+ return line(theme, [
612
+ [" /", { fg: "accent", bold: true }],
613
+ [` ${typed}`, { fg: "text", bold: true }],
614
+ [theme.glyphs.caret, { fg: "accent" }],
615
+ ...(withCount ? [count] : []),
616
+ ], cols - SPARE);
617
+ }
618
+ if (toast && toast.until > clock) {
619
+ return line(theme, [[" "], [toast.text, { fg: toast.tone, bold: true }]], cols - SPARE);
620
+ }
621
+ if (query) {
622
+ return line(theme, [
623
+ [" /", { fg: "accent", bold: true }],
624
+ [` ${query}`, { fg: "text" }],
625
+ count,
626
+ // Esc closes a panel first: show the hint only when it clears.
627
+ ...(state.confirming || state.helpOpen || state.errorsOpen
628
+ ? []
629
+ : [[` ${m.search.clearHint}`, { fg: "muted", dim: true }]]),
630
+ ], cols - SPARE);
631
+ }
632
+ return "";
633
+ }
634
+ // Footer keys per context; when narrow, the lowest priorities go first
635
+ const KEYS = {
636
+ help: [
637
+ ["arrows", "scroll", 1],
638
+ ["esc", "close", 9],
639
+ ],
640
+ search: [
641
+ ["enter", "keep", 6],
642
+ ["esc", "clear", 5],
643
+ ["arrows", "move", 3],
644
+ ],
645
+ errors: [
646
+ ["arrows", "scroll", 1],
647
+ ["esc", "close", 9],
648
+ ],
649
+ confirm: [
650
+ ["yes", "yes", 2],
651
+ ["no", "no", 9],
652
+ ],
653
+ deleting: [
654
+ ["arrows", "move", 1],
655
+ ["q", "stop", 9],
656
+ ],
657
+ main: [
658
+ ["arrows", "move", 3],
659
+ ["space", "mark", 5],
660
+ ["a", "all", 1],
661
+ ["a", "none", 1],
662
+ ["o", "old", 2],
663
+ ["sort", "sort", 2],
664
+ ["/", "search", 4],
665
+ ["i", "details", 3],
666
+ ["enter", "delete", 6],
667
+ ["e", "errors", 4],
668
+ ["esc", "clear", 8],
669
+ ["?", "help", 7],
670
+ ["q", "quit", 9],
671
+ ],
672
+ };
673
+ /**
674
+ * Keys that work in the current context; an action with nothing to act on is left out.
675
+ *
676
+ * @param state - Frame state, read only
677
+ * @returns Key, action and priority triples, in display order
678
+ */
679
+ function contextKeys(state) {
680
+ if (state.helpOpen)
681
+ return KEYS.help;
682
+ if (state.searching)
683
+ return KEYS.search;
684
+ if (state.errorsOpen)
685
+ return KEYS.errors;
686
+ if (state.confirming)
687
+ return KEYS.confirm;
688
+ if (state.deletion)
689
+ return KEYS.deleting;
690
+ const { stats, errors, sessions, marked } = state;
691
+ // a and o act on the rows shown, so a search narrows them too.
692
+ const shownMarked = sessions.some((session) => marked.has(sessionKey(session)));
693
+ const available = {
694
+ mark: sessions.length > 0,
695
+ all: sessions.length > 0 && !shownMarked,
696
+ none: shownMarked,
697
+ old: state.oldShown,
698
+ details: sessions.length > 0,
699
+ delete: stats.marked.count > 0,
700
+ errors: errors.length > 0,
701
+ clear: state.query !== "",
702
+ };
703
+ return KEYS.main.filter(([, label]) => available[label] ?? true);
704
+ }
705
+ /**
706
+ * Footer listing the keys of the current context; when the terminal is narrow, the gaps
707
+ * tighten first, then the least useful keys drop out.
708
+ *
709
+ * @param state - Frame state, read only
710
+ * @param cols - Terminal width in cells
711
+ * @returns The painted footer
712
+ */
713
+ function footer(state, cols) {
714
+ const { theme, lang } = state;
715
+ const m = messages(lang);
716
+ let gap = 3;
717
+ const step = state.step > 0 ? theme.glyphs.sortDown : theme.glyphs.sortUp;
718
+ let items = contextKeys(state).map(([key, label, priority]) => {
719
+ const name = key in m.keyNames ? m.keyNames[key] : key;
720
+ const text = label === "mark" ? `${m.keys.mark} ${step}` : m.keys[label];
721
+ return { name, label: text, priority };
722
+ });
723
+ const total = () => items.reduce((sum, item) => sum + width(`${item.name} ${item.label}`) + gap, -gap);
724
+ const room = cols - SPARE - 1;
725
+ if (total() > room)
726
+ gap = 2;
727
+ while (items.length > 1 && total() > room) {
728
+ const lowest = Math.min(...items.map((item) => item.priority));
729
+ const index = items.findIndex((item) => item.priority === lowest);
730
+ items = items.filter((_, i) => i !== index);
731
+ }
732
+ const segments = [[" "]];
733
+ items.forEach((item, i) => {
734
+ if (i > 0)
735
+ segments.push([" ".repeat(gap)]);
736
+ segments.push([item.name, { fg: "accent", bold: true }], [` ${item.label}`, { fg: "muted" }]);
737
+ });
738
+ return line(theme, segments, cols - SPARE);
739
+ }
740
+ /**
741
+ * Panel listing the failed deletions with their reason, in place of the list.
742
+ *
743
+ * @param state - Frame state with errors; its errorsScroll is clamped in place
744
+ * @param cols - Terminal width in cells
745
+ * @param height - Rows available, borders included
746
+ * @returns The panel lines
747
+ */
748
+ function errorsPanel(state, cols, height) {
749
+ const { theme, lang, errors, errorsScroll } = state;
750
+ const { box } = theme.glyphs;
751
+ const border = (text) => theme.paint(text, { fg: "err" });
752
+ const inner = Math.max(10, cols - SPARE - 4);
753
+ const title = ` ${messages(lang).errorsTitle(errors.length)} `;
754
+ const lines = [
755
+ ` ${border(`${box.tl}${box.h}${title}${box.h.repeat(Math.max(0, inner - width(title) - 1))}${box.tr}`)}`,
756
+ ];
757
+ const body = errors.flatMap(({ session, message }) => [
758
+ [
759
+ [`${theme.glyphs.err} `, { fg: "err", bold: true }],
760
+ [`${session.project}, ${session.title || session.id}`, { fg: "text" }],
761
+ ],
762
+ [[" "], [message, { fg: "muted" }]],
763
+ ]);
764
+ const visible = Math.max(0, height - 2);
765
+ const scroll = Math.min(errorsScroll, Math.max(0, body.length - visible));
766
+ state.errorsScroll = scroll;
767
+ for (const segments of body.slice(scroll, scroll + visible)) {
768
+ lines.push(` ${border(box.v)} ${line(theme, segments, inner - 2, {}, true)} ${border(box.v)}`);
769
+ }
770
+ while (lines.length < height - 1)
771
+ lines.push(` ${border(box.v)}${" ".repeat(inner)}${border(box.v)}`);
772
+ lines.push(` ${border(`${box.bl}${box.h.repeat(inner)}${box.br}`)}`);
773
+ return lines;
774
+ }
775
+ /**
776
+ * Builds a whole frame, keeping the cursor visible and the error panel in range.
777
+ *
778
+ * @param state - Frame state; top, errorsScroll and listHeight are written back
779
+ * @param cols - Terminal width in cells
780
+ * @param rows - Terminal height; under 40 x 8 the frame only says the terminal is too small
781
+ * @returns One string per terminal row
782
+ */
783
+ export function view(state, cols, rows) {
784
+ const { theme, lang } = state;
785
+ if (cols < MIN_COLS || rows < MIN_ROWS) {
786
+ const text = messages(lang).tooSmall(cols, rows, MIN_COLS, MIN_ROWS);
787
+ const lines = Array(Math.max(0, Math.floor(rows / 2) - 1)).fill("");
788
+ for (const part of text.split("\n")) {
789
+ const short = cut(part, cols - 1, theme.glyphs.ellipsis);
790
+ const indent = " ".repeat(Math.max(0, Math.floor((cols - width(short)) / 2)));
791
+ lines.push(indent + theme.paint(short, { fg: "warn", bold: true }));
792
+ }
793
+ return lines;
794
+ }
795
+ // The compact header gives the details the logo's rows.
796
+ const roomy = rows >= FULL_ROWS + (state.detailsOpen ? DETAILS_ROWS : 0) && theme.unicode;
797
+ let header = compactHeader(state, cols);
798
+ if (roomy && cols >= LOGO_WIDTH + STATS_WIDTH)
799
+ header = fullHeader(state, cols);
800
+ else if (roomy && cols >= LOGO_WIDTH + 2)
801
+ header = stackedHeader(state, cols);
802
+ const lines = [...header];
803
+ lines.push(activityLine(state, cols));
804
+ const listTop = lines.length;
805
+ let height = Math.max(1, rows - lines.length - 3);
806
+ // The details take the bottom of the list area.
807
+ const current = state.sessions[state.cursor];
808
+ let details = [];
809
+ if (state.detailsOpen && current && !state.errorsOpen && height - DETAILS_ROWS >= 3) {
810
+ details = detailsBox(state, current, sessionKey(current), cols);
811
+ height -= details.length;
812
+ }
813
+ if (state.errorsOpen) {
814
+ lines.push(...errorsPanel(state, cols, height + 1));
815
+ }
816
+ else if (state.sessions.length === 0 && state.query) {
817
+ lines.push(columnHeader(state, cols, projectWidth(state.sessions, cols)));
818
+ const text = cut(messages(lang).search.none(state.query), cols - SPARE - 2, theme.glyphs.ellipsis);
819
+ lines.push("", ` ${theme.paint(text, { fg: "muted" })}`);
820
+ }
821
+ else {
822
+ const project = projectWidth(state.sessions, cols);
823
+ // The embers take one row, kept free so the cursor never hides behind them.
824
+ const embers = embersActive(state) && height >= 3;
825
+ const shown = embers ? height - 1 : height;
826
+ let top = state.top;
827
+ if (state.cursor < top)
828
+ top = state.cursor;
829
+ if (state.cursor >= top + shown)
830
+ top = state.cursor - shown + 1;
831
+ state.top = Math.max(0, Math.min(top, Math.max(0, state.sessions.length - shown)));
832
+ // Embers rise under the last row, or at the bottom of a long list.
833
+ const withEmbers = embers;
834
+ const frontier = Math.min(state.sessions.length - state.top, shown);
835
+ if (!withEmbers) {
836
+ state.top = Math.max(0, Math.min(state.top, state.sessions.length - height));
837
+ }
838
+ state.listHeight = withEmbers ? shown : height;
839
+ lines.push(columnHeader(state, cols, project));
840
+ const rows = state.sessions
841
+ .slice(state.top, state.top + (withEmbers ? shown : height))
842
+ .map((session, i) => sessionRow(state, session, cols, project, {
843
+ prefix: true,
844
+ selected: state.top + i === state.cursor,
845
+ marked: state.marked.has(sessionKey(session)),
846
+ markable: state.markable(session),
847
+ rowState: state.states.get(sessionKey(session)),
848
+ }));
849
+ if (withEmbers)
850
+ rows.splice(frontier, 0, emberLine(state, cols));
851
+ lines.push(...rows);
852
+ }
853
+ while (lines.length < rows - 2 - details.length)
854
+ lines.push("");
855
+ lines.push(...details);
856
+ lines.push(statusLine(state, cols), footer(state, cols));
857
+ // Modal panels sit over the dimmed list.
858
+ const listEnd = rows - 2;
859
+ if (state.helpOpen) {
860
+ return overlay(theme, lines, helpBox(state, cols, listEnd - listTop), listTop, listEnd, cols);
861
+ }
862
+ if (state.confirming) {
863
+ const box = confirmBox(state, cols, listEnd - listTop);
864
+ return overlay(theme, lines, box, listTop, listEnd, cols);
865
+ }
866
+ return lines;
867
+ }
868
+ /**
869
+ * The plain table of `--list`, `--dry-run` and `--yes`.
870
+ *
871
+ * @param sessions - Sessions to print, in the order given
872
+ * @param theme - Theme of the output; plain text when it is not a terminal
873
+ * @param lang - Language of the headers and units
874
+ * @param now - Time of the scan, for ages
875
+ * @param cols - Width of the output
876
+ * @returns The header, one line per session, a blank line and the total
877
+ */
878
+ export function table(sessions, theme, lang, now, cols) {
879
+ const m = messages(lang);
880
+ const project = projectWidth(sessions, cols);
881
+ const context = { theme, lang, now, olderThan: Infinity, clock: 0 };
882
+ const head = line(theme, [
883
+ [fit(m.columns.size, SIZE_WIDTH, "right"), { fg: "muted" }],
884
+ [" "],
885
+ [fit(m.columns.age, AGE_WIDTH, "right"), { fg: "muted" }],
886
+ [" "],
887
+ [fit(m.columns.project, project, "left", theme.glyphs.ellipsis), { fg: "muted" }],
888
+ [" "],
889
+ [m.columns.title, { fg: "muted" }],
890
+ ], cols - SPARE);
891
+ const rows = sessions.map((session) => sessionRow(context, session, cols, project));
892
+ const total = sessions.reduce((sum, session) => sum + session.bytes, 0);
893
+ return [head, ...rows, "", m.totalLine(sessions.length, formatSize(total, lang))];
894
+ }
895
+ /**
896
+ * Summary printed once the interface is closed.
897
+ *
898
+ * @param result - Deleted sessions, freed bytes and failures of the run
899
+ * @param theme - Theme of the output: colors, depth and glyph set
900
+ * @param lang - Language of the texts
901
+ * @returns The lines to print; the tone of the second line grows with the freed space
902
+ */
903
+ export function exitSummary(result, theme, lang) {
904
+ const m = messages(lang);
905
+ const lines = [];
906
+ if (result.deleted === 0) {
907
+ lines.push(`${wordmark(theme)} ${theme.paint(m.exitNothing, { fg: "muted" })}`);
908
+ }
909
+ else {
910
+ const tone = result.freed >= GB ? 2 : result.freed >= 100 * MB ? 1 : 0;
911
+ const freed = m.exitFreed(formatSize(result.freed, lang), result.deleted);
912
+ lines.push(`${wordmark(theme)} ${theme.paint(freed, { fg: "ok", bold: true })}`, `${" ".repeat(10)}${theme.paint(m.exitTones[tone], { fg: "muted" })}`);
913
+ }
914
+ if (result.errors.length > 0) {
915
+ lines.push("", theme.paint(m.exitFailures(result.errors.length), { fg: "err", bold: true }));
916
+ for (const { session, message } of result.errors) {
917
+ lines.push(` ${theme.paint(theme.glyphs.err, { fg: "err" })} ${session.id} ${session.title}`);
918
+ lines.push(` ${theme.paint(message, { fg: "muted" })}`);
919
+ }
920
+ }
921
+ return lines;
922
+ }