-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrender.ts
More file actions
348 lines (295 loc) · 12.9 KB
/
Copy pathrender.ts
File metadata and controls
348 lines (295 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
import { bold, dim, fg, fit, isColor, padStart, width, type RGB } from "./ansi.js";
import { SPARK, theme } from "./theme.js";
import type { Snapshot } from "./git.js";
export interface Layout {
cols: number;
rows: number;
heatWeeks: number;
sparkDays: number;
hotDays: number;
intervalMs: number;
paused: boolean;
}
/* ------------------------------------------------------------------ */
/* Panels */
/* ------------------------------------------------------------------ */
/**
* Draw a titled box. `body` lines are clipped/padded to the inner width, so
* callers never have to think about the frame.
*/
function panel(title: string, body: string[], total: number, height?: number): string[] {
const inner = Math.max(1, total - 4);
const b = (s: string) => fg(theme.border, s);
const cap = `─ ${title} `;
const top = b("╭") + fg(theme.accent, cap) + b("─".repeat(Math.max(0, total - 2 - width(cap)))) + b("╮");
const rows = height === undefined ? body : body.slice(0, Math.max(0, height - 2));
const lines = [top];
for (const line of rows) lines.push(`${b("│")} ${fit(line, inner)} ${b("│")}`);
if (height !== undefined) {
while (lines.length < height - 1) lines.push(`${b("│")} ${" ".repeat(inner)} ${b("│")}`);
}
lines.push(b("╰" + "─".repeat(Math.max(0, total - 2)) + "╯"));
return lines;
}
/** Join two panels horizontally, padding the shorter one. */
function beside(left: string[], right: string[], gap = 1): string[] {
const n = Math.max(left.length, right.length);
const lw = Math.max(0, ...left.map(width));
const out: string[] = [];
for (let i = 0; i < n; i++) {
const l = left[i] ?? "";
const r = right[i] ?? "";
out.push(l + " ".repeat(Math.max(0, lw - width(l)) + gap) + r);
}
return out;
}
/* ------------------------------------------------------------------ */
/* Small formatters */
/* ------------------------------------------------------------------ */
const num = (n: number) => n.toLocaleString("en-US");
/** Trim from the left, keeping the tail — the useful half of a file path. */
function tail(s: string, n: number): string {
return width(s) <= n ? s : "…" + s.slice(s.length - (n - 1));
}
const iso = (d: Date): string =>
`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
/** Bucket a count into a 0..4 heat level relative to the busiest day. */
function level(count: number, max: number): number {
if (count <= 0) return 0;
if (max <= 1) return 4;
const step = max / 4;
return Math.min(4, Math.max(1, Math.ceil(count / step)));
}
const heatColor = (lvl: number): RGB => theme.heat[lvl] ?? theme.heat[0]!;
/** Without colour the ramp has to live in the glyph, not the foreground. */
const HEAT_MONO = [" ", "░", "▒", "▓", "█"];
const heatGlyph = (lvl: number): string =>
isColor() ? "■" : (HEAT_MONO[lvl] ?? " ");
const heatCell = (lvl: number, cellW: number): string =>
fg(heatColor(lvl), heatGlyph(lvl)) + " ".repeat(cellW - 1);
/* ------------------------------------------------------------------ */
/* Widgets */
/* ------------------------------------------------------------------ */
function header(snap: Snapshot, layout: Layout): string[] {
const s = snap.status;
const bits: string[] = [
bold(fg(theme.accent, snap.name)),
fg(theme.muted, "⎇ ") + fg(theme.text, snap.branch),
fg(theme.muted, snap.head),
];
if (snap.upstream) {
if (snap.upstream.ahead) bits.push(fg(theme.good, `↑${snap.upstream.ahead}`));
if (snap.upstream.behind) bits.push(fg(theme.warn, `↓${snap.upstream.behind}`));
if (!snap.upstream.ahead && !snap.upstream.behind) bits.push(fg(theme.good, "in sync"));
} else {
bits.push(fg(theme.muted, "no upstream"));
}
const dirt: string[] = [];
if (s.conflicted) dirt.push(fg(theme.bad, `${s.conflicted} conflicted`));
if (s.staged) dirt.push(fg(theme.good, `${s.staged} staged`));
if (s.modified) dirt.push(fg(theme.warn, `${s.modified} modified`));
if (s.untracked) dirt.push(fg(theme.muted, `${s.untracked} untracked`));
bits.push(dirt.length ? dirt.join(fg(theme.border, " · ")) : fg(theme.good, "clean"));
const left = bits.join(fg(theme.border, " │ "));
const right = layout.paused
? fg(theme.warn, "paused")
: fg(theme.muted, `⟳ ${Math.round(layout.intervalMs / 1000)}s`);
const inner = Math.max(1, layout.cols - 4);
const pad = Math.max(1, inner - width(left) - width(right));
return panel("gitpulse", [left + " ".repeat(pad) + right], layout.cols);
}
function heatmap(snap: Snapshot, layout: Layout): string[] {
const inner = Math.max(1, layout.cols - 4);
const labelW = 4;
const cellW = inner - labelW >= 53 * 2 ? 2 : 1;
const weeks = Math.max(1, Math.min(layout.heatWeeks + 1, Math.floor((inner - labelW) / cellW)));
// Rightmost column is the current week; walk back `weeks` Sundays from there.
const today = new Date();
today.setHours(0, 0, 0, 0);
const start = new Date(today);
start.setDate(start.getDate() - today.getDay() - (weeks - 1) * 7);
let max = 0;
let total = 0;
const grid: (number | null)[][] = [];
for (let w = 0; w < weeks; w++) {
const col: (number | null)[] = [];
for (let d = 0; d < 7; d++) {
const day = new Date(start);
day.setDate(start.getDate() + w * 7 + d);
if (day > today) {
col.push(null);
continue;
}
const c = snap.byDay.get(iso(day)) ?? 0;
max = Math.max(max, c);
total += c;
col.push(c);
}
grid.push(col);
}
// Month ruler: label a week when its Sunday opens a new month.
const months = Array.from({ length: weeks * cellW }, () => " ");
let prevMonth = -1;
for (let w = 0; w < weeks; w++) {
const day = new Date(start);
day.setDate(start.getDate() + w * 7);
const m = day.getMonth();
if (m !== prevMonth) {
prevMonth = m;
const label = MONTHS[m] ?? "";
const at = w * cellW;
if (at + label.length <= months.length && (at === 0 || months[at - 1] === " ")) {
for (let i = 0; i < label.length; i++) months[at + i] = label[i] ?? " ";
}
}
}
const body: string[] = [fg(theme.muted, " ".repeat(labelW) + months.join(""))];
const dayNames = ["", "Mon", "", "Wed", "", "Fri", ""];
for (let d = 0; d < 7; d++) {
let row = fg(theme.muted, (dayNames[d] ?? "").padEnd(labelW));
for (let w = 0; w < weeks; w++) {
const c = grid[w]?.[d];
row += c === null || c === undefined ? " ".repeat(cellW) : heatCell(level(c, max), cellW);
}
body.push(row);
}
const legend =
fg(theme.muted, "less ") +
theme.heat.map((c, i) => fg(c, heatGlyph(i))).join("") +
fg(theme.muted, " more") +
fg(theme.border, " · ") +
fg(theme.muted, `busiest day ${num(max)}`);
body.push(padStart(legend, inner));
const title = `ACTIVITY · ${weeks - 1} weeks · ${num(total)} commits · ${num(snap.totalCommits)} all-time`;
return panel(title, body, layout.cols);
}
function sparkline(snap: Snapshot, layout: Layout): string[] {
const inner = Math.max(1, layout.cols - 4);
const days = Math.max(7, Math.min(layout.sparkDays, inner - 18));
const today = new Date();
today.setHours(0, 0, 0, 0);
const counts: number[] = [];
for (let i = days - 1; i >= 0; i--) {
const d = new Date(today);
d.setDate(today.getDate() - i);
counts.push(snap.byDay.get(iso(d)) ?? 0);
}
const peak = Math.max(0, ...counts);
const scale = Math.max(1, peak);
const spark = counts
.map((c) => {
const glyph =
c === 0
? "·"
: (SPARK[Math.min(SPARK.length - 1, Math.ceil((c / scale) * SPARK.length) - 1)] ?? "▁");
return fg(heatColor(level(c, scale)), glyph);
})
.join("");
const sum = counts.reduce((a, b) => a + b, 0);
const avg = (sum / days).toFixed(1);
const stats = fg(theme.muted, `peak ${num(peak)} · avg ${avg}/day`);
const line = spark + " ".repeat(Math.max(1, inner - days - width(stats))) + stats;
const axis = fg(theme.muted, `${days}d ago`) + " ".repeat(Math.max(1, days - 7 - 5)) + fg(theme.muted, "today");
return panel(`COMMITS PER DAY · ${num(sum)} in ${days}d`, [line, axis], layout.cols);
}
function authorsPanel(snap: Snapshot, total: number, height: number): string[] {
const inner = Math.max(1, total - 4);
const rows = Math.max(1, height - 2);
const shown = snap.authors.slice(0, rows);
const top = shown[0]?.commits ?? 1;
const countW = Math.max(...shown.map((a) => num(a.commits).length), 1);
const nameW = Math.min(16, Math.max(6, inner - countW - 12));
const barW = Math.max(3, inner - nameW - countW - 2);
const body = shown.map((a, i) => {
const color = theme.authors[i % theme.authors.length] ?? theme.accent;
const filled = Math.max(1, Math.round((a.commits / top) * barW));
const bar = fg(color, "█".repeat(filled)) + fg(theme.border, "░".repeat(barW - filled));
return `${fit(a.name, nameW)} ${bar} ${fg(theme.muted, padStart(num(a.commits), countW))}`;
});
if (body.length === 0) body.push(fg(theme.muted, "no commits in window"));
return panel(`AUTHORS · ${num(snap.authors.length)}`, body, total, height);
}
function hotFilesPanel(snap: Snapshot, total: number, height: number, hotDays: number): string[] {
const inner = Math.max(1, total - 4);
const rows = Math.max(1, height - 2);
const shown = snap.hotFiles.slice(0, rows);
const top = shown[0]?.touches ?? 1;
const countW = Math.max(...shown.map((f) => num(f.touches).length), 1);
const barW = Math.min(10, Math.max(3, Math.floor(inner / 4)));
const pathW = Math.max(6, inner - barW - countW - 2);
const body = shown.map((f) => {
const filled = Math.max(1, Math.round((f.touches / top) * barW));
const bar =
fg(heatColor(level(f.touches, top)), "█".repeat(filled)) +
fg(theme.border, "░".repeat(barW - filled));
const label = fit(fg(theme.text, tail(f.path, pathW)), pathW);
return `${label} ${bar} ${fg(theme.muted, padStart(num(f.touches), countW))}`;
});
if (body.length === 0) body.push(fg(theme.muted, `no file changes in ${hotDays}d`));
return panel(`HOT FILES · ${hotDays}d`, body, total, height);
}
function recentPanel(snap: Snapshot, layout: Layout, height: number): string[] {
const inner = Math.max(1, layout.cols - 4);
const rows = Math.max(1, height - 2);
const shown = snap.recent.slice(0, rows);
const whenW = Math.min(16, Math.max(...shown.map((c) => c.when.length), 1));
const authW = Math.min(16, Math.max(...shown.map((c) => c.author.length), 1));
const body = shown.map((c) => {
const rank = snap.authors.findIndex((a) => a.name === c.author);
const color = rank >= 0 ? theme.authors[rank % theme.authors.length] ?? theme.muted : theme.muted;
const left = `${fg(theme.warn, c.hash)} ${fg(theme.muted, fit(c.when, whenW))} ${fg(color, fit(c.author, authW))} `;
return left + fg(theme.text, fit(c.subject, Math.max(1, inner - width(left))));
});
if (body.length === 0) body.push(fg(theme.muted, "no commits yet"));
return panel("RECENT", body, layout.cols, height);
}
/* ------------------------------------------------------------------ */
/* Frame */
/* ------------------------------------------------------------------ */
/**
* Compose the full frame. Sections are added top-down while vertical budget
* remains, so a short terminal degrades gracefully instead of scrolling.
*/
export function render(snap: Snapshot, layout: Layout): string[] {
const out: string[] = [...header(snap, layout)];
const footer = 1;
const room = () => layout.rows - out.length - footer;
const heat = heatmap(snap, layout);
if (room() >= heat.length) out.push(...heat);
const spark = sparkline(snap, layout);
if (room() >= spark.length) out.push(...spark);
// Split the remaining space between the mid row and the commit log.
const left = room();
if (left >= 8) {
const midH = Math.min(10, Math.max(4, Math.floor(left / 2)));
const wide = layout.cols >= 88;
if (wide) {
const lw = Math.floor((layout.cols - 1) / 2);
const rw = layout.cols - 1 - lw;
out.push(
...beside(
authorsPanel(snap, lw, midH),
hotFilesPanel(snap, rw, midH, layout.hotDays),
),
);
} else {
out.push(...authorsPanel(snap, layout.cols, midH));
}
}
if (room() >= 4) out.push(...recentPanel(snap, layout, Math.min(14, room())));
while (out.length < layout.rows - footer) out.push("");
const hint = layout.paused ? "resume" : "pause";
out.push(
dim(
fg(
theme.muted,
fit(
` q quit · r refresh · space ${hint} · updated ${snap.collectedAt.toLocaleTimeString()}`,
layout.cols,
),
),
),
);
return out.slice(0, layout.rows);
}