git-vidi 0.1.0__py3-none-any.whl

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.
vidi/render.py ADDED
@@ -0,0 +1,399 @@
1
+ """Rich render helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import collections
6
+ import datetime as dt
7
+
8
+ from rich.console import Group
9
+ from rich.style import Style
10
+ from rich.table import Table
11
+ from rich.text import Text
12
+ from textual.color import Color
13
+
14
+ from .data import RANGE_PRESETS, build_date_grid
15
+ from .models import LanguageStat, ThemePalette
16
+ from .theme import make_style
17
+ from .utils import truncate_middle
18
+
19
+
20
+ def resolve_heatmap_colors(palette: ThemePalette) -> tuple[str, list[str]]:
21
+ is_dark = palette.background.brightness < 0.5
22
+ inactive_style = palette.background.blend(
23
+ palette.foreground,
24
+ 0.10 if is_dark else 0.14,
25
+ ).hex6
26
+ padding_style = palette.background.blend(
27
+ palette.panel,
28
+ 0.50 if is_dark else 0.45,
29
+ ).hex6
30
+ blend_steps = (0.28, 0.48, 0.68, 0.84) if is_dark else (0.30, 0.50, 0.70, 0.86)
31
+ active_styles = [
32
+ Color.parse(inactive_style).blend(palette.success, step).hex6
33
+ for step in blend_steps
34
+ ]
35
+ # heatmap_styles[0] is the zero-commit color and [1:] ramp toward success.
36
+ return padding_style, [inactive_style, *active_styles]
37
+
38
+
39
+ def render_contribution_graph(
40
+ commit_counts: collections.Counter[dt.date],
41
+ start_date: dt.date,
42
+ end_date: dt.date,
43
+ selected_day: dt.date | None,
44
+ palette: ThemePalette,
45
+ ) -> Group:
46
+ grid, _months, first_sunday = build_date_grid(commit_counts, start_date, end_date)
47
+ num_weeks = len(grid[0]) if grid else 0
48
+ header_width = max(num_weeks, 3)
49
+ month_line = [" "] * header_width
50
+ last_end = -4
51
+
52
+ is_full_year = (
53
+ start_date.month == 1
54
+ and start_date.day == 1
55
+ and end_date.month == 12
56
+ and end_date.day == 31
57
+ and start_date.year == end_date.year
58
+ )
59
+ # Fold Feb 29 into Feb 28 to keep the month labels on the same columns every year.
60
+ month_lengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
61
+ month_offsets = [0]
62
+ for month_length in month_lengths:
63
+ month_offsets.append(month_offsets[-1] + month_length)
64
+ total_days = max(1, (end_date - start_date).days)
65
+
66
+ def day_offset(day: dt.date) -> int:
67
+ if day.month == 2 and day.day == 29:
68
+ return month_offsets[2] - 1
69
+ return month_offsets[day.month - 1] + day.day - 1
70
+
71
+ def header_column(day: dt.date) -> int:
72
+ if is_full_year:
73
+ fraction = day_offset(day) / (month_offsets[-1] - 1)
74
+ else:
75
+ fraction = (day - start_date).days / total_days
76
+ return round(fraction * (header_width - 1))
77
+
78
+ month_cursor = dt.date(start_date.year, start_date.month, 1)
79
+ while month_cursor <= end_date:
80
+ next_month = (
81
+ dt.date(month_cursor.year + 1, 1, 1)
82
+ if month_cursor.month == 12
83
+ else dt.date(month_cursor.year, month_cursor.month + 1, 1)
84
+ )
85
+ month_end = next_month - dt.timedelta(days=1)
86
+ visible_start = max(month_cursor, start_date)
87
+ visible_end = min(month_end, end_date)
88
+ label = month_cursor.strftime("%b")
89
+ projected_start = header_column(visible_start)
90
+ projected_end = header_column(visible_end)
91
+ span_width = max(1, projected_end - projected_start + 1)
92
+ if span_width >= len(label):
93
+ index = projected_start + (span_width - len(label)) // 2
94
+ else:
95
+ index = projected_start
96
+ index = max(0, min(index, header_width - len(label)))
97
+ if index < last_end:
98
+ index = last_end
99
+ if index + len(label) > header_width:
100
+ month_cursor = next_month
101
+ continue
102
+ for offset, char in enumerate(label):
103
+ pos = index + offset
104
+ if pos < len(month_line):
105
+ month_line[pos] = char
106
+ last_end = index + len(label) + 1
107
+ month_cursor = next_month
108
+
109
+ header = Text(" " + "".join(month_line), style=make_style(palette.muted))
110
+
111
+ lines: list[Text] = [header]
112
+ day_labels = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
113
+ max_value = max((value for row in grid for value in row if value is not None), default=0)
114
+ padding_style, heatmap_styles = resolve_heatmap_colors(palette)
115
+ cell_char = "■"
116
+
117
+ for row_index, day_name in enumerate(day_labels):
118
+ line = Text(f"{day_name:<3} ", style=make_style(palette.muted))
119
+ for col_index, value in enumerate(grid[row_index]):
120
+ if value is None:
121
+ line.append(cell_char, style=padding_style)
122
+ continue
123
+ if value <= 0:
124
+ style = heatmap_styles[0]
125
+ elif max_value <= 1:
126
+ style = heatmap_styles[-1]
127
+ else:
128
+ ratio = value / max_value
129
+ bucket = min(4, max(1, int(round(ratio * 4))))
130
+ style = heatmap_styles[bucket]
131
+ cell_day = first_sunday + dt.timedelta(days=col_index * 7 + row_index)
132
+ if selected_day == cell_day:
133
+ selected_style = Color.parse(style).blend(palette.foreground, 0.25).hex6
134
+ line.append(cell_char, style=f"bold {selected_style}")
135
+ else:
136
+ line.append(cell_char, style=style)
137
+ lines.append(line)
138
+
139
+ legend = Text("Less ", style=make_style(palette.muted, bold=True))
140
+ for style in heatmap_styles:
141
+ legend.append(cell_char, style=style)
142
+ legend.append(" More", style=make_style(palette.muted, bold=True))
143
+
144
+ # Readout of the highlighted day's date and count, right-aligned to the graph.
145
+ if selected_day is not None:
146
+ count = int(commit_counts.get(selected_day, 0))
147
+ tail = "no commits" if count == 0 else ("1 commit" if count == 1 else f"{count} commits")
148
+ date_label = f"{selected_day.strftime('%a, %b')} {selected_day.day} {selected_day.year}"
149
+ graph_width = 4 + header_width
150
+ gap = max(2, graph_width - len(legend.plain) - len(date_label) - len(tail) - 3)
151
+ legend.append(" " * gap)
152
+ legend.append(date_label, style=make_style(palette.foreground))
153
+ legend.append(" · ", style=make_style(palette.muted))
154
+ legend.append(tail, style=make_style(palette.muted))
155
+
156
+ return Group(*lines, legend)
157
+
158
+
159
+ def graph_day_at(
160
+ start: dt.date, end: dt.date, column: int, row: int
161
+ ) -> dt.date | None:
162
+ """The day at a click position in the contribution graph, or None.
163
+
164
+ Row 0 is the month header and rows 1..7 are Sun..Sat. Columns 0..3 hold the
165
+ weekday label and columns 4+ the week cells, as render_contribution_graph
166
+ lays them out.
167
+ """
168
+ weekday = row - 1
169
+ week = column - 4
170
+ if not 0 <= weekday <= 6 or week < 0:
171
+ return None
172
+ days_to_prev_sunday = (start.weekday() + 1) % 7
173
+ first_sunday = start - dt.timedelta(days=days_to_prev_sunday)
174
+ day = first_sunday + dt.timedelta(days=week * 7 + weekday)
175
+ return day if start <= day <= end else None
176
+
177
+
178
+ def build_graph_title(
179
+ branch: str,
180
+ range_value: str,
181
+ year: int,
182
+ commit_count: int,
183
+ palette: ThemePalette,
184
+ ) -> Table:
185
+ range_label = {value: label for label, value in RANGE_PRESETS}.get(range_value, range_value)
186
+ status = Text()
187
+ status.append(branch, style=make_style(palette.foreground))
188
+ status.append(" · ", style=make_style(palette.muted))
189
+ status.append(range_label, style=make_style(palette.foreground))
190
+ status.append(" · ", style=make_style(palette.muted))
191
+ status.append(str(year), style=make_style(palette.foreground, bold=True))
192
+ status.append(" · ", style=make_style(palette.muted))
193
+ status.append(f"{commit_count} commits", style=make_style(palette.foreground))
194
+
195
+ title = Table.grid(expand=True)
196
+ title.add_column(ratio=1)
197
+ title.add_column(justify="right")
198
+ title.add_row(
199
+ Text("Contribution Activity", style=make_style(palette.muted, bold=True)),
200
+ status,
201
+ )
202
+ return title
203
+
204
+
205
+ def build_language_title(
206
+ language_stats: list[LanguageStat],
207
+ palette: ThemePalette,
208
+ ) -> Text:
209
+ total_files = sum(int(item.get("count", 0)) for item in language_stats)
210
+ title = Text()
211
+ title.append("Languages", style=make_style(palette.muted, bold=True))
212
+ title.append(" ", style=make_style(palette.muted))
213
+ title.append(
214
+ str(len(language_stats)),
215
+ style=make_style(palette.foreground, bold=True),
216
+ )
217
+ if total_files:
218
+ word = "file" if total_files == 1 else "files"
219
+ title.append(f" {total_files} {word}", style=make_style(palette.muted))
220
+ return title
221
+
222
+
223
+ LANGUAGE_ENTRY_SEPARATOR = 3
224
+
225
+
226
+ def _language_label_width(width: int) -> int:
227
+ return max(6, min(16, width // 3))
228
+
229
+
230
+ def _format_share(percentage: float) -> str:
231
+ # A nonzero share that rounds to 0 reads "<1%".
232
+ if percentage <= 0:
233
+ return "0%"
234
+ if round(percentage) == 0:
235
+ return "<1%"
236
+ return f"{percentage:.0f}%"
237
+
238
+
239
+ def _language_metric(item: LanguageStat) -> str:
240
+ # File count for the snapshot, with the share in parentheses.
241
+ return f"{int(item.get('count', 0))} ({_format_share(float(item['percentage']))})"
242
+
243
+
244
+ def _language_entry(
245
+ item: LanguageStat,
246
+ label_width: int,
247
+ palette: ThemePalette | None = None,
248
+ highlighted: bool = False,
249
+ ) -> Text:
250
+ """One legend entry, unstyled without a palette."""
251
+ if palette is None:
252
+ label_style = gap_style = metric_style = Style()
253
+ else:
254
+ label_style = make_style(
255
+ palette.primary if highlighted else palette.foreground, bold=highlighted
256
+ )
257
+ gap_style = make_style(palette.muted)
258
+ metric_style = make_style(
259
+ palette.primary if highlighted else palette.muted, bold=highlighted
260
+ )
261
+ return Text.assemble(
262
+ ("● ", str(item["color"])),
263
+ (truncate_middle(str(item["language"]), label_width), label_style),
264
+ (" ", gap_style),
265
+ (_language_metric(item), metric_style),
266
+ )
267
+
268
+
269
+ def language_legend_rows(language_stats: list[LanguageStat], width: int) -> list[list[int]]:
270
+ """Group language indices into the rows the wrapping legend will render."""
271
+ label_width = _language_label_width(width)
272
+ rows: list[list[int]] = []
273
+ current: list[int] = []
274
+ current_width = 0
275
+ for index, item in enumerate(language_stats):
276
+ entry_width = len(_language_entry(item, label_width).plain)
277
+ if current and current_width + LANGUAGE_ENTRY_SEPARATOR + entry_width > width:
278
+ rows.append(current)
279
+ current = []
280
+ current_width = 0
281
+ if current:
282
+ current_width += LANGUAGE_ENTRY_SEPARATOR
283
+ current.append(index)
284
+ current_width += entry_width
285
+ if current:
286
+ rows.append(current)
287
+ return rows
288
+
289
+
290
+ def language_index_at(
291
+ language_stats: list[LanguageStat], width: int, column: int, row: int
292
+ ) -> int | None:
293
+ """The language index at a click position (column, row) in the wrapped
294
+ legend, or None if the click missed every entry."""
295
+ rows = language_legend_rows(language_stats, width)
296
+ if not 0 <= row < len(rows):
297
+ return None
298
+ label_width = _language_label_width(width)
299
+ x = 0
300
+ for position, index in enumerate(rows[row]):
301
+ if position:
302
+ x += LANGUAGE_ENTRY_SEPARATOR
303
+ entry_width = len(_language_entry(language_stats[index], label_width).plain)
304
+ if x <= column < x + entry_width:
305
+ return index
306
+ x += entry_width
307
+ return None
308
+
309
+
310
+ def build_language_summary(
311
+ language_stats: list[LanguageStat],
312
+ palette: ThemePalette,
313
+ *,
314
+ width: int,
315
+ highlighted_index: int | None = None,
316
+ ) -> Group:
317
+ """Render the language breakdown as a compact, wrapping legend.
318
+
319
+ Entries flow left to right and wrap only when the next one would exceed the
320
+ panel width. The highlighted entry is drawn bold in the accent color.
321
+ """
322
+ if not language_stats:
323
+ return Group(Text("No language data", style=make_style(palette.muted)))
324
+
325
+ label_width = _language_label_width(width)
326
+ lines: list[Text] = []
327
+ for row in language_legend_rows(language_stats, width):
328
+ line = Text()
329
+ for position, index in enumerate(row):
330
+ if position:
331
+ line.append(" " * LANGUAGE_ENTRY_SEPARATOR, style=make_style(palette.muted))
332
+ line.append_text(
333
+ _language_entry(
334
+ language_stats[index], label_width, palette, index == highlighted_index
335
+ )
336
+ )
337
+ lines.append(line)
338
+ return Group(*lines)
339
+
340
+
341
+ def build_language_bar(
342
+ language_stats: list[LanguageStat],
343
+ palette: ThemePalette,
344
+ *,
345
+ width: int,
346
+ highlighted_index: int | None = None,
347
+ ) -> Text:
348
+ bar_width = max(8, width)
349
+ if not language_stats:
350
+ bar = Text()
351
+ bar.append("█" * bar_width, style=make_style(palette.surface))
352
+ return bar
353
+ total_percentage = sum(max(float(item["percentage"]), 0.0) for item in language_stats)
354
+ if total_percentage <= 0:
355
+ segment_widths = [0 for _item in language_stats]
356
+ segment_widths[0] = bar_width
357
+ else:
358
+ raw_widths = [
359
+ (max(float(item["percentage"]), 0.0) / total_percentage) * bar_width
360
+ for item in language_stats
361
+ ]
362
+ segment_widths = [int(raw) for raw in raw_widths]
363
+ remainder = bar_width - sum(segment_widths)
364
+ if remainder > 0:
365
+ order = sorted(
366
+ range(len(raw_widths)),
367
+ key=lambda index: raw_widths[index] - segment_widths[index],
368
+ reverse=True,
369
+ )
370
+ for index in order[:remainder]:
371
+ segment_widths[index] += 1
372
+
373
+ # Give every listed language at least one cell, borrowed from the widest segments.
374
+ if len(language_stats) <= bar_width:
375
+ for index in range(len(language_stats)):
376
+ if segment_widths[index] > 0:
377
+ continue
378
+ donor = max(range(len(segment_widths)), key=segment_widths.__getitem__)
379
+ if segment_widths[donor] <= 1:
380
+ break
381
+ segment_widths[donor] -= 1
382
+ segment_widths[index] = 1
383
+
384
+ bar = Text()
385
+ for index, (item, segment_width) in enumerate(zip(language_stats, segment_widths)):
386
+ if segment_width <= 0:
387
+ continue
388
+ color = str(item["color"])
389
+ if index == highlighted_index:
390
+ # Brighten the selected segment toward the foreground.
391
+ brightened = Color.parse(color).blend(palette.foreground, 0.35).hex6
392
+ bar.append("█" * segment_width, style=f"bold {brightened}")
393
+ else:
394
+ bar.append("█" * segment_width, style=color)
395
+
396
+ if not bar:
397
+ bar.append("█" * bar_width, style=make_style(palette.surface))
398
+
399
+ return bar