forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

heatmap.rs766 lines, 29.5 KiBHistoryRawDownload
1//! Contribution calendar: the last 53 weeks of daily contribution counts, one column per
2//! week (Monday first), with the four summary stats, month labels and the motivating line.
3//!
4//! `build` is pure date and streak maths over the counts from the store. `contribution_calendar`
5//! draws it with classes only (CSP): the grid placement comes from CSS (`grid-auto-flow: column`
6//! with seven rows), so every cell is an element and the blank slots keep the columns aligned.
7//! Each day is a link to `?day=` (a plain link, no script): the page then lists
8//! that day's contributions under the calendar, and clicking the selected day again clears it.
9
10use std::collections::HashMap;
11use topcoat::context::Cx;
12
13use forge_core::store::contributions::{ContributionItem, ContributionKind};
14use forge_core::time::stamp_to_unix;
15use topcoat::Result;
16use topcoat::view::{View, component, view};
17
18use super::{civil_from_days, now_unix, relative_time};
19use crate::i18n::Lang;
20use crate::i18n::misc::{self as g, K};
21
22/// Columns in the calendar: the week of today plus the 52 weeks before it.
23pub const WEEKS: usize = 53;
24
25/// Class of a cell at each level 0-4. Level 0 is "no contributions".
26const LEVEL_CLASS: [&str; 5] = ["cell l0", "cell l1", "cell l2", "cell l3", "cell l4"];
27
28/// One day in the calendar. `date` is `(year, month, day)`.
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub struct Day {
31 pub date: (i64, i64, i64),
32 pub count: u64,
33 pub level: u8,
34}
35
36/// The day picked in the calendar: its date and the contributions made on it, newest first.
37#[derive(Clone, Debug, PartialEq, Eq)]
38pub struct DayDetail {
39 pub date: (i64, i64, i64),
40 pub items: Vec<ContributionItem>,
41}
42
43/// The calendar as the component draws it. `weeks[c][r]` is the day in column `c` (a week,
44/// Monday first) and row `r` (0 = Monday, 6 = Sunday); `None` for the days after today.
45#[derive(Clone, Debug, PartialEq, Eq)]
46pub struct Calendar {
47 pub weeks: Vec<[Option<Day>; 7]>,
48 /// Column and month number (1-12) where a month label starts: the first column that holds
49 /// the 1st of that month.
50 pub months: Vec<(usize, i64)>,
51 /// First day shown (the Monday that starts column 0).
52 pub first_day: (i64, i64, i64),
53 /// Today, the last day shown.
54 pub today: (i64, i64, i64),
55 /// Contributions in the window.
56 pub total: u64,
57 /// Consecutive days with at least one contribution, ending today; or ending yesterday when
58 /// today has none (so an unfinished day does not break the streak).
59 pub current_streak: u64,
60 /// The longest run of days with at least one contribution in the window.
61 pub longest_streak: u64,
62 /// The highest count on a single day.
63 pub best_day: u64,
64 /// Today's count.
65 pub today_count: u64,
66}
67
68/// Level for a day's count: 0 for none, then fixed buckets 1-3 (1), 4-7 (2), 8-12 (3) and 13 or
69/// more (4). Fixed buckets, rather than quartiles of the year, so a colour means the same count
70/// on every page load.
71pub fn level(count: u64) -> u8 {
72 match count {
73 0 => 0,
74 1..=3 => 1,
75 4..=7 => 2,
76 8..=12 => 3,
77 _ => 4,
78 }
79}
80
81/// Builds the calendar for the 53 weeks ending with today's week. `counts` holds
82/// `(YYYY-MM-DD, count)` pairs, ascending, as the store returns them; dates outside the window
83/// and after today are ignored, and malformed dates are skipped. `today` is `(year, month, day)`.
84pub fn build(counts: &[(String, u32)], today: (i64, i64, i64)) -> Calendar {
85 let today_days = days_from_civil(today.0, today.1, today.2);
86 let by_day: HashMap<i64, u64> = counts
87 .iter()
88 .filter_map(|(date, count)| parse_date(date).map(|days| (days, u64::from(*count))))
89 .collect();
90 let count_on = |days: i64| by_day.get(&days).copied().unwrap_or(0);
91
92 // Column 0 starts on the Monday that is WEEKS - 1 weeks before the Monday of today's week.
93 let this_monday = today_days - i64::from(weekday(today_days));
94 let first_days = this_monday - 7 * (WEEKS as i64 - 1);
95
96 let mut weeks = Vec::with_capacity(WEEKS);
97 let mut months = Vec::new();
98 let (mut total, mut best_day, mut longest, mut run) = (0, 0, 0, 0);
99 for column in 0..WEEKS {
100 let mut week: [Option<Day>; 7] = Default::default();
101 for (row, slot) in week.iter_mut().enumerate() {
102 let days = first_days + (column * 7 + row) as i64;
103 if days > today_days {
104 continue;
105 }
106 let count = count_on(days);
107 let date = civil_from_days(days);
108 if date.2 == 1 {
109 months.push((column, date.1));
110 }
111 total += count;
112 best_day = best_day.max(count);
113 run = if count > 0 { run + 1 } else { 0 };
114 longest = longest.max(run);
115 *slot = Some(Day {
116 date,
117 count,
118 level: level(count),
119 });
120 }
121 weeks.push(week);
122 }
123
124 // The current streak starts at today, or at yesterday when today has no contributions yet.
125 let today_count = count_on(today_days);
126 let mut cursor = if today_count > 0 {
127 today_days
128 } else {
129 today_days - 1
130 };
131 let mut current_streak = 0;
132 while cursor >= first_days && count_on(cursor) > 0 {
133 current_streak += 1;
134 cursor -= 1;
135 }
136
137 Calendar {
138 weeks,
139 months,
140 first_day: civil_from_days(first_days),
141 today,
142 total,
143 current_streak,
144 longest_streak: longest,
145 best_day,
146 today_count,
147 }
148}
149
150/// Parses a strict `YYYY-MM-DD` date into days since 1970-01-01. Rejects impossible dates such as
151/// 2027-02-29, by converting back and comparing.
152fn parse_date(text: &str) -> Option<i64> {
153 let bytes = text.as_bytes();
154 if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' {
155 return None;
156 }
157 let year: i64 = text.get(0..4)?.parse().ok()?;
158 let month: i64 = text.get(5..7)?.parse().ok()?;
159 let day: i64 = text.get(8..10)?.parse().ok()?;
160 let days = days_from_civil(year, month, day);
161 (civil_from_days(days) == (year, month, day)).then_some(days)
162}
163
164/// Days since 1970-01-01 for `(year, month, day)`. Howard Hinnant's days-from-civil algorithm, the
165/// inverse of `civil_from_days`.
166fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
167 let y = if month <= 2 { year - 1 } else { year };
168 let era = y.div_euclid(400);
169 let yoe = y - era * 400;
170 let mp = (month + 9) % 12;
171 let doy = (153 * mp + 2) / 5 + day - 1;
172 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
173 era * 146_097 + doe - 719_468
174}
175
176/// Monday = 0 through Sunday = 6. 1970-01-01 was a Thursday.
177fn weekday(days: i64) -> u8 {
178 (days + 3).rem_euclid(7) as u8
179}
180
181/// One grid slot as the view draws it. Days link to their contributions; blank slots do not.
182struct CellView {
183 class: String,
184 href: Option<String>,
185 title: String,
186 /// `{date}:{count}` for a day with contributions, so a raised count animates once on a live update.
187 arrive: Option<String>,
188}
189
190/// One line of the selected day's list, with its strings ready for the view.
191struct DayRow {
192 before: String,
193 /// None when the row has no page to open: a pruned commit, whose hash stays plain text.
194 href: Option<String>,
195 link: String,
196 after: String,
197 updated: String,
198 relative: String,
199}
200
201/// One entry in the selected day's list: a single contribution, or a group of pushes to one branch
202/// of one repo. `row` is the entry's own line (for a group, its newest push, with the count), and
203/// `pushes` lists the group's pushes, newest first; it is empty for a single contribution.
204struct DayEntry {
205 row: DayRow,
206 pushes: Vec<DayRow>,
207}
208
209/// The selected day's heading and entries, ready for the view.
210struct DayView {
211 heading: String,
212 rows: Vec<DayEntry>,
213}
214
215/// The link for a calendar day: the day's contributions below the calendar, or back to the
216/// plain calendar when the day is the selected one. `base` is the profile's path, without a query.
217/// The anchor brings a full page load back to the calendar; nav.js swaps in place and keeps the
218/// scroll (`data-keep-scroll`), so it is not used there.
219fn day_href(base: &str, date: (i64, i64, i64), selected: bool) -> String {
220 if selected {
221 format!("{base}#contributions-h")
222 } else {
223 format!(
224 "{base}?day={:04}-{:02}-{:02}#contributions-h",
225 date.0, date.1, date.2
226 )
227 }
228}
229
230/// The repo an item landed in, as `owner/name`.
231fn item_repo(item: &ContributionItem) -> String {
232 format!("{}/{}", item.repo_owner, item.repo_name)
233}
234
235/// The branch a push went to: its ref without `refs/heads/`. Empty for everything else.
236fn item_branch(item: &ContributionItem) -> &str {
237 item.ref_name
238 .strip_prefix("refs/heads/")
239 .unwrap_or(&item.ref_name)
240}
241
242/// The row for one contribution in the selected day's list.
243fn day_row(lang: Lang, item: &ContributionItem, now: i64) -> DayRow {
244 let repo = item_repo(item);
245 let (before, after) = g::day_item_words(lang, item.kind, item_branch(item), &repo);
246 let (href, link) = match item.kind {
247 ContributionKind::Push => (Some(format!("/{repo}")), repo.clone()),
248 ContributionKind::Issue | ContributionKind::Comment => (
249 Some(format!("/{repo}/issues/{}", item.number)),
250 format!("#{} {}", item.number, item.title),
251 ),
252 ContributionKind::Pull => (
253 Some(format!("/{repo}/pulls/{}", item.number)),
254 format!("#{} {}", item.number, item.title),
255 ),
256 ContributionKind::CoAuthored => {
257 // A pruned commit has its title blanked by the job that prunes it: keep the hash, unlinked.
258 if item.title.is_empty() {
259 (None, item.commit.chars().take(7).collect())
260 } else {
261 (
262 Some(format!("/{repo}/commit/{}", item.commit)),
263 item.title.clone(),
264 )
265 }
266 }
267 };
268 DayRow {
269 before,
270 href,
271 link,
272 after,
273 updated: item.created_at.clone(),
274 relative: relative_time(lang, stamp_to_unix(&item.created_at).unwrap_or(now), now),
275 }
276}
277
278/// Items split into runs that share a key, in the order each key is first met. Items without a
279/// key (`None`) are each their own run.
280fn group_first_seen<'a>(
281 items: impl IntoIterator<Item = &'a ContributionItem>,
282 key: impl Fn(&ContributionItem) -> Option<String>,
283) -> Vec<Vec<&'a ContributionItem>> {
284 let mut groups: Vec<Vec<&ContributionItem>> = Vec::new();
285 let mut index: HashMap<String, usize> = HashMap::new();
286 for item in items {
287 if let Some(k) = key(item) {
288 if let Some(&i) = index.get(&k) {
289 groups[i].push(item);
290 continue;
291 }
292 index.insert(k, groups.len());
293 }
294 groups.push(vec![item]);
295 }
296 groups
297}
298
299/// The row for a branch's pushes: the newest push, with the count when there is more than one.
300fn branch_row(lang: Lang, pushes: &[&ContributionItem], now: i64) -> DayRow {
301 let mut row = day_row(lang, pushes[0], now);
302 if pushes.len() > 1 {
303 (row.before, row.after) = g::push_group_words(lang, item_branch(pushes[0]), pushes.len());
304 }
305 row
306}
307
308/// The selected day's entries, newest first. Pushes to one repo are grouped under the newest of
309/// them: a group on one branch lists its pushes, a group across branches lists one row per branch.
310/// Every other contribution is its own entry. The items come newest first, so the first push met
311/// for a repo or branch is its most recent one, and the entries keep that order.
312fn day_entries(lang: Lang, items: &[ContributionItem], now: i64) -> Vec<DayEntry> {
313 let by_repo = group_first_seen(items, |item| {
314 (item.kind == ContributionKind::Push).then(|| item_repo(item))
315 });
316 by_repo
317 .into_iter()
318 .map(|group| {
319 if group.len() == 1 {
320 return DayEntry {
321 row: day_row(lang, group[0], now),
322 pushes: Vec::new(),
323 };
324 }
325 let branches = group_first_seen(group.iter().copied(), |item| {
326 Some(item_branch(item).to_owned())
327 });
328 if branches.len() == 1 {
329 return DayEntry {
330 row: branch_row(lang, &group, now),
331 pushes: group.iter().map(|item| day_row(lang, item, now)).collect(),
332 };
333 }
334 let mut row = day_row(lang, group[0], now);
335 (row.before, row.after) = g::push_repo_group_words(lang, branches.len(), group.len());
336 DayEntry {
337 row,
338 pushes: branches.iter().map(|b| branch_row(lang, b, now)).collect(),
339 }
340 })
341 .collect()
342}
343
344/// The contribution card: heading and date range, the four stats, the month labels and the
345/// 53-week grid, then the motivating line and the Less/More legend, then the selected day's
346/// contributions when a day is picked. `base` is the profile's path the day links point at. `live`
347/// is the stream URL the card re-renders on; it is set on a person's overview only.
348#[component]
349pub async fn contribution_calendar(
350 cx: &Cx,
351 calendar: Calendar,
352 selected: Option<DayDetail>,
353 lang: Lang,
354 base: String,
355 live: Option<String>,
356) -> Result<impl View> {
357 let range = {
358 let from = g::date_text(
359 lang,
360 calendar.first_day.0,
361 calendar.first_day.1,
362 calendar.first_day.2,
363 );
364 let to = g::date_text(lang, calendar.today.0, calendar.today.1, calendar.today.2);
365 g::date_range(lang, &from, &to)
366 };
367 let summary = g::heatmap_summary(
368 lang,
369 calendar.total,
370 calendar.current_streak,
371 calendar.longest_streak,
372 );
373 let total = g::thousands(lang, calendar.total);
374 let current = g::streak_days(lang, calendar.current_streak);
375 let longest = g::streak_days(lang, calendar.longest_streak);
376 let best = g::contributions_count(lang, calendar.best_day);
377 let mon = g::t(lang, K::MonLabel);
378 let wed = g::t(lang, K::WedLabel);
379 let fri = g::t(lang, K::FriLabel);
380 let less = g::t(lang, K::Less);
381 let more = g::t(lang, K::More);
382 let empty_day = g::t(lang, K::NoContributionsDay);
383 let now = now_unix();
384 let selected_date = selected.as_ref().map(|detail| detail.date);
385 let day = selected.map(|detail| DayView {
386 heading: g::contributions_on_day(
387 lang,
388 &g::date_text(lang, detail.date.0, detail.date.1, detail.date.2),
389 ),
390 rows: day_entries(lang, &detail.items, now),
391 });
392
393 // Month labels: one slot per column, empty where no label starts.
394 let mut month_slots = vec![String::new(); WEEKS];
395 for (column, month) in &calendar.months {
396 month_slots[*column] = g::month_abbrev(lang, *month).to_owned();
397 }
398
399 // Cells in column order (7 per column), so auto-flow puts each day in its row.
400 let cells: Vec<CellView> = calendar
401 .weeks
402 .iter()
403 .flat_map(|week| week.iter())
404 .map(|slot| match slot {
405 Some(day) => {
406 let picked = selected_date == Some(day.date);
407 let level = LEVEL_CLASS[usize::from(day.level)];
408 CellView {
409 class: if picked {
410 format!("{level} selected")
411 } else {
412 level.to_owned()
413 },
414 href: Some(day_href(&base, day.date, picked)),
415 title: g::contributions_on(
416 lang,
417 day.count,
418 &g::date_text(lang, day.date.0, day.date.1, day.date.2),
419 ),
420 arrive: (day.count > 0).then(|| {
421 format!(
422 "{:04}-{:02}-{:02}:{}",
423 day.date.0, day.date.1, day.date.2, day.count
424 )
425 }),
426 }
427 }
428 None => CellView {
429 class: "cell blank".to_owned(),
430 href: None,
431 title: String::new(),
432 arrive: None,
433 },
434 })
435 .collect();
436
437 Ok(view! {
438 <section class="heat" aria-labelledby="contributions-h" data-live=(live.as_deref())>
439 <div class="heat-head">
440 <div>
441 <h2 id="contributions-h">(g::t(lang, K::ContributionsTitle))</h2>
442 <p class="muted small">(range.as_str())</p>
443 </div>
444 <div class="heat-stats">
445 <div class="heat-stat">
446 <b>(total.as_str())</b>
447 <span>(g::t(lang, K::ContributionsLastYear))</span>
448 </div>
449 <div class="heat-stat">
450 <b class="accent">(current.as_str())</b>
451 <span>(g::t(lang, K::CurrentStreak))</span>
452 </div>
453 <div class="heat-stat">
454 <b>(longest.as_str())</b>
455 <span>(g::t(lang, K::LongestStreak))</span>
456 </div>
457 <div class="heat-stat">
458 <b>(best.as_str())</b>
459 <span>(g::t(lang, K::BestDay))</span>
460 </div>
461 </div>
462 </div>
463 <div class="heat-scroll">
464 <div class="heat-body">
465 <div class="heat-days" aria-hidden="true">
466 <span>(mon)</span>
467 <span></span>
468 <span>(wed)</span>
469 <span></span>
470 <span>(fri)</span>
471 <span></span>
472 <span></span>
473 </div>
474 <div>
475 <div class="heat-months" aria-hidden="true">
476 for label in month_slots.into_iter() {
477 <span>(label.as_str())</span>
478 }
479 </div>
480 <div class="heat-grid" role="group" aria-label=(summary.as_str())>
481 for cell in cells.into_iter() {
482 if let Some(href) = cell.href {
483 <a class=(cell.class.as_str()) href=(href.as_str()) title=(cell.title.as_str()) data-keep-scroll="true" data-arrive=(cell.arrive.as_deref())></a>
484 } else {
485 <span class=(cell.class.as_str()) title=(cell.title.as_str())></span>
486 }
487 }
488 </div>
489 </div>
490 </div>
491 </div>
492 <div class="heat-foot">
493 <div class="legend" aria-hidden="true">
494 <span>(less)</span>
495 <span class="cell l0"></span>
496 <span class="cell l1"></span>
497 <span class="cell l2"></span>
498 <span class="cell l3"></span>
499 <span class="cell l4"></span>
500 <span>(more)</span>
501 </div>
502 </div>
503 if let Some(day) = day {
504 <div class="heat-day">
505 <h3>(day.heading.as_str())</h3>
506 if day.rows.is_empty() {
507 <p class="muted">(empty_day)</p>
508 } else {
509 <ul>
510 for entry in day.rows.into_iter() {
511 if entry.pushes.is_empty() {
512 <li>
513 <span>(entry.row.before.as_str())</span>
514 if let Some(href) = entry.row.href {
515 <a href=(href.as_str())>(entry.row.link.as_str())</a>
516 } else {
517 <span>(entry.row.link.as_str())</span>
518 }
519 <span>(entry.row.after.as_str())</span>
520 <time data-rel="true" datetime=(entry.row.updated.as_str())>(entry.row.relative.as_str())</time>
521 </li>
522 } else {
523 <li class="day-group">
524 <details>
525 <summary>
526 <span>(entry.row.before.as_str())</span>
527 if let Some(href) = entry.row.href {
528 <a href=(href.as_str())>(entry.row.link.as_str())</a>
529 } else {
530 <span>(entry.row.link.as_str())</span>
531 }
532 <span>(entry.row.after.as_str())</span>
533 <time data-rel="true" datetime=(entry.row.updated.as_str())>(entry.row.relative.as_str())</time>
534 </summary>
535 <ul>
536 for push in entry.pushes.into_iter() {
537 <li>
538 <span>(push.before.as_str())</span>
539 if let Some(href) = push.href {
540 <a href=(href.as_str())>(push.link.as_str())</a>
541 } else {
542 <span>(push.link.as_str())</span>
543 }
544 <span>(push.after.as_str())</span>
545 <time data-rel="true" datetime=(push.updated.as_str())>(push.relative.as_str())</time>
546 </li>
547 }
548 </ul>
549 </details>
550 </li>
551 }
552 }
553 </ul>
554 }
555 </div>
556 }
557 </section>
558 })
559}
560
561#[cfg(test)]
562mod tests {
563 use super::*;
564
565 const TODAY: (i64, i64, i64) = (2026, 10, 16);
566
567 fn counts(pairs: &[(&str, u32)]) -> Vec<(String, u32)> {
568 pairs.iter().map(|(d, n)| ((*d).to_owned(), *n)).collect()
569 }
570
571 fn day(cal: &Calendar, date: (i64, i64, i64)) -> Day {
572 cal.weeks
573 .iter()
574 .flatten()
575 .flatten()
576 .find(|d| d.date == date)
577 .copied()
578 .expect("day is in the window")
579 }
580
581 #[test]
582 fn empty_input_gives_an_empty_calendar() {
583 let cal = build(&[], TODAY);
584 assert_eq!(cal.weeks.len(), WEEKS);
585 assert_eq!(cal.total, 0);
586 assert_eq!(cal.current_streak, 0);
587 assert_eq!(cal.longest_streak, 0);
588 assert_eq!(cal.best_day, 0);
589 assert_eq!(cal.today_count, 0);
590 assert!(cal.weeks.iter().flatten().flatten().all(|d| d.level == 0));
591 }
592
593 #[test]
594 fn streak_ending_today_counts_today() {
595 let cal = build(
596 &counts(&[("2026-10-14", 2), ("2026-10-15", 1), ("2026-10-16", 5)]),
597 TODAY,
598 );
599 assert_eq!(cal.current_streak, 3);
600 assert_eq!(cal.longest_streak, 3);
601 assert_eq!(cal.today_count, 5);
602 assert_eq!(cal.total, 8);
603 }
604
605 #[test]
606 fn streak_ending_yesterday_survives_an_empty_today() {
607 let cal = build(
608 &counts(&[("2026-10-13", 1), ("2026-10-14", 1), ("2026-10-15", 1)]),
609 TODAY,
610 );
611 assert_eq!(cal.today_count, 0);
612 assert_eq!(cal.current_streak, 3);
613 }
614
615 #[test]
616 fn a_gap_or_an_old_run_ends_the_current_streak() {
617 // (case, counts, current streak, longest streak)
618 type Case<'a> = (&'a str, &'a [(&'a str, u32)], u64, u64);
619 let cases: [Case<'_>; 2] = [
620 ("old run", &[("2026-10-01", 3), ("2026-10-02", 3)], 0, 2),
621 (
622 "gap then two days",
623 &[
624 ("2026-09-20", 1),
625 ("2026-09-21", 1),
626 ("2026-09-22", 1),
627 ("2026-09-23", 1),
628 ("2026-09-24", 1),
629 ("2026-10-15", 2),
630 ("2026-10-16", 2),
631 ],
632 2,
633 5,
634 ),
635 ];
636 for (name, input, current, longest) in cases {
637 let cal = build(&counts(input), TODAY);
638 assert_eq!(cal.current_streak, current, "case {name}");
639 assert_eq!(cal.longest_streak, longest, "case {name}");
640 }
641 }
642
643 #[test]
644 fn best_day_is_the_highest_single_count() {
645 let cal = build(
646 &counts(&[("2026-10-01", 4), ("2026-10-02", 23), ("2026-10-03", 9)]),
647 TODAY,
648 );
649 assert_eq!(cal.best_day, 23);
650 assert_eq!(cal.total, 36);
651 }
652
653 #[test]
654 fn levels_follow_the_fixed_buckets() {
655 assert_eq!(
656 [0, 1, 3, 4, 7, 8, 12, 13, 500].map(level),
657 [0, 1, 1, 2, 2, 3, 3, 4, 4]
658 );
659 let cal = build(&counts(&[("2026-10-16", 8), ("2026-10-15", 1)]), TODAY);
660 assert_eq!(day(&cal, TODAY).level, 3);
661 assert_eq!(day(&cal, (2026, 10, 15)).level, 1);
662 assert_eq!(day(&cal, (2026, 10, 14)).level, 0);
663 }
664
665 #[test]
666 fn window_is_53_monday_first_weeks_ending_this_week() {
667 let cal = build(&[], TODAY);
668 // Today is a Friday: the last column holds Mon..Fri and the two weekend slots are blank.
669 assert_eq!(cal.first_day, (2025, 10, 13));
670 let first = cal.weeks[0][0].expect("first Monday is shown");
671 assert_eq!(first.date, (2025, 10, 13));
672 assert_eq!(weekday(days_from_civil(2025, 10, 13)), 0);
673 let last = &cal.weeks[WEEKS - 1];
674 assert_eq!(last[4].expect("today").date, TODAY);
675 assert!(last[5].is_none() && last[6].is_none());
676 assert_eq!(last[0].expect("Monday of this week").date, (2026, 10, 12));
677 }
678
679 #[test]
680 fn counts_outside_the_window_and_in_the_future_are_ignored() {
681 let cal = build(
682 &counts(&[("2025-10-12", 7), ("2025-10-13", 2), ("2026-10-17", 9)]),
683 TODAY,
684 );
685 assert_eq!(cal.total, 2);
686 assert_eq!(cal.best_day, 2);
687 assert_eq!(cal.current_streak, 0);
688 }
689
690 #[test]
691 fn malformed_dates_are_skipped() {
692 let cal = build(
693 &counts(&[
694 ("2026-02-30", 4),
695 ("2026/10/16", 4),
696 ("nope", 4),
697 ("2026-10-16", 1),
698 ]),
699 TODAY,
700 );
701 assert_eq!(cal.total, 1);
702 }
703
704 #[test]
705 fn month_labels_start_at_the_first_column_holding_the_first() {
706 let cal = build(&[], TODAY);
707 // 2025-11-01 is 19 days after the first Monday, so column 2; 2026-10-01 is column 50.
708 assert_eq!(cal.months[0], (2, 11));
709 assert!(cal.months.contains(&(50, 10)));
710 assert_eq!(cal.months.len(), 12);
711 }
712
713 #[test]
714 fn leap_day_is_a_real_date() {
715 let cal = build(
716 &counts(&[("2028-02-29", 4), ("2028-03-01", 1)]),
717 (2028, 3, 1),
718 );
719 assert_eq!(cal.total, 5);
720 assert_eq!(cal.current_streak, 2);
721 assert_eq!(
722 days_from_civil(2028, 3, 1) - days_from_civil(2028, 2, 28),
723 2
724 );
725 assert_eq!(parse_date("2027-02-29"), None);
726 assert_eq!(parse_date("2028-02-29"), Some(days_from_civil(2028, 2, 29)));
727 assert_eq!(civil_from_days(days_from_civil(2000, 2, 29)), (2000, 2, 29));
728 }
729
730 #[test]
731 fn pushes_to_one_repo_group_by_branch_under_the_newest() {
732 let item = |kind, ref_name: &str, at: &str| ContributionItem {
733 kind,
734 repo_owner: "Tahinli".to_owned(),
735 repo_name: "forge".to_owned(),
736 created_at: at.to_owned(),
737 ref_name: ref_name.to_owned(),
738 number: 0,
739 title: String::new(),
740 commit: String::new(),
741 };
742 let push = |branch: &str, at: &str| item(ContributionKind::Push, branch, at);
743 let items = [
744 push("refs/heads/main", "2026-10-16T12:00:00Z"),
745 push("refs/heads/main", "2026-10-16T11:00:00Z"),
746 item(ContributionKind::Issue, "", "2026-10-16T10:30:00Z"),
747 push("refs/heads/dev", "2026-10-16T09:00:00Z"),
748 push("refs/heads/main", "2026-10-16T08:00:00Z"),
749 ];
750 let entries = day_entries(Lang::En, &items, 0);
751 let shape: Vec<usize> = entries.iter().map(|e| e.pushes.len()).collect();
752 assert_eq!(shape, [2, 0]);
753 assert_eq!(entries[0].row.updated, "2026-10-16T12:00:00Z");
754 assert_eq!(entries[0].row.before, "Pushed 4 times to 2 branches in");
755 assert_eq!(entries[0].pushes[0].before, "Pushed 3 times to main in");
756 assert_eq!(entries[0].pushes[1].before, "Pushed to dev in");
757 }
758
759 #[test]
760 fn days_from_civil_inverts_civil_from_days() {
761 for days in [-1, 0, 1, 10_957, 20_454, 47_000] {
762 let (y, m, d) = civil_from_days(days);
763 assert_eq!(days_from_civil(y, m, d), days);
764 }
765 }
766}