use std::collections::HashMap; use topcoat::context::Cx; use forge_core::store::contributions::{ContributionItem, ContributionKind}; use forge_core::time::stamp_to_unix; use topcoat::Result; use topcoat::view::{View, component, view}; use super::{civil_from_days, days_from_civil, now_unix, relative_time}; use crate::i18n::Lang; use crate::i18n::misc::{self as g, K}; pub const WEEKS: usize = 53; const LEVEL_CLASS: [&str; 5] = ["cell l0", "cell l1", "cell l2", "cell l3", "cell l4"]; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Day { pub date: (i64, i64, i64), pub count: u64, pub level: u8, } #[derive(Clone, Debug, PartialEq, Eq)] pub struct DayDetail { pub date: (i64, i64, i64), pub items: Vec, } #[derive(Clone, Debug, PartialEq, Eq)] pub struct Calendar { pub weeks: Vec<[Option; 7]>, pub months: Vec<(usize, i64)>, pub first_day: (i64, i64, i64), pub today: (i64, i64, i64), pub total: u64, pub current_streak: u64, pub longest_streak: u64, pub best_day: u64, } pub fn level(count: u64) -> u8 { match count { 0 => 0, 1..=3 => 1, 4..=7 => 2, 8..=12 => 3, _ => 4, } } pub fn build(counts: &[(String, u32)], today: (i64, i64, i64)) -> Calendar { let today_days = days_from_civil(today.0, today.1, today.2); let by_day: HashMap = counts .iter() .filter_map(|(date, count)| parse_date(date).map(|days| (days, u64::from(*count)))) .collect(); let count_on = |days: i64| by_day.get(&days).copied().unwrap_or(0); let this_monday = today_days - i64::from(weekday(today_days)); let first_days = this_monday - 7 * (WEEKS as i64 - 1); let mut weeks = Vec::with_capacity(WEEKS); let mut months = Vec::new(); let (mut total, mut best_day, mut longest, mut run) = (0, 0, 0, 0); for column in 0..WEEKS { let mut week: [Option; 7] = Default::default(); for (row, slot) in week.iter_mut().enumerate() { let days = first_days + (column * 7 + row) as i64; if days > today_days { continue; } let count = count_on(days); let date = civil_from_days(days); if date.2 == 1 { months.push((column, date.1)); } total += count; best_day = best_day.max(count); run = if count > 0 { run + 1 } else { 0 }; longest = longest.max(run); *slot = Some(Day { date, count, level: level(count), }); } weeks.push(week); } let today_count = count_on(today_days); let mut cursor = if today_count > 0 { today_days } else { today_days - 1 }; let mut current_streak = 0; while cursor >= first_days && count_on(cursor) > 0 { current_streak += 1; cursor -= 1; } Calendar { weeks, months, first_day: civil_from_days(first_days), today, total, current_streak, longest_streak: longest, best_day, } } fn parse_date(text: &str) -> Option { let bytes = text.as_bytes(); if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' { return None; } let year: i64 = text.get(0..4)?.parse().ok()?; let month: i64 = text.get(5..7)?.parse().ok()?; let day: i64 = text.get(8..10)?.parse().ok()?; let days = days_from_civil(year, month, day); (civil_from_days(days) == (year, month, day)).then_some(days) } fn weekday(days: i64) -> u8 { (days + 3).rem_euclid(7) as u8 } struct CellView { class: String, href: Option, title: String, arrive: Option, } struct DayRow { before: String, href: Option, link: String, after: String, updated: String, relative: String, } struct DayEntry { row: DayRow, pushes: Vec, } struct DayView { heading: String, rows: Vec, } fn day_href(base: &str, date: (i64, i64, i64), selected: bool) -> String { if selected { format!("{base}#contributions-h") } else { format!( "{base}?day={:04}-{:02}-{:02}#contributions-h", date.0, date.1, date.2 ) } } fn item_repo(item: &ContributionItem) -> String { format!("{}/{}", item.repo_owner, item.repo_name) } fn item_branch(item: &ContributionItem) -> &str { item.ref_name .strip_prefix("refs/heads/") .unwrap_or(&item.ref_name) } fn day_row(lang: Lang, item: &ContributionItem, now: i64) -> DayRow { let repo = item_repo(item); let (before, after) = g::day_item_words(lang, item.kind, item_branch(item), &repo); let (href, link) = match item.kind { ContributionKind::Push => (Some(format!("/{repo}")), repo.clone()), ContributionKind::Issue | ContributionKind::Comment => ( Some(format!("/{repo}/issues/{}", item.number)), format!("#{} {}", item.number, item.title), ), ContributionKind::Pull => ( Some(format!("/{repo}/pulls/{}", item.number)), format!("#{} {}", item.number, item.title), ), ContributionKind::CoAuthored => { if item.title.is_empty() { (None, item.commit.chars().take(7).collect()) } else { ( Some(format!("/{repo}/commit/{}", item.commit)), item.title.clone(), ) } } }; DayRow { before, href, link, after, updated: item.created_at.clone(), relative: relative_time(lang, stamp_to_unix(&item.created_at).unwrap_or(now), now), } } #[component] async fn day_line(cx: &Cx, row: DayRow) -> Result { Ok(view! { (row.before.as_str()) if let Some(href) = row.href { (row.link.as_str()) } else { (row.link.as_str()) } (row.after.as_str()) }) } fn group_first_seen<'a>( items: impl IntoIterator, key: impl Fn(&ContributionItem) -> Option, ) -> Vec> { let mut groups: Vec> = Vec::new(); let mut index: HashMap = HashMap::new(); for item in items { if let Some(k) = key(item) { if let Some(&i) = index.get(&k) { groups[i].push(item); continue; } index.insert(k, groups.len()); } groups.push(vec![item]); } groups } fn branch_row(lang: Lang, pushes: &[&ContributionItem], now: i64) -> DayRow { let mut row = day_row(lang, pushes[0], now); if pushes.len() > 1 { (row.before, row.after) = g::push_group_words(lang, item_branch(pushes[0]), pushes.len()); } row } fn day_entries(lang: Lang, items: &[ContributionItem], now: i64) -> Vec { let by_repo = group_first_seen(items, |item| { (item.kind == ContributionKind::Push).then(|| item_repo(item)) }); by_repo .into_iter() .map(|group| { if group.len() == 1 { return DayEntry { row: day_row(lang, group[0], now), pushes: Vec::new(), }; } let branches = group_first_seen(group.iter().copied(), |item| { Some(item_branch(item).to_owned()) }); if branches.len() == 1 { return DayEntry { row: branch_row(lang, &group, now), pushes: group.iter().map(|item| day_row(lang, item, now)).collect(), }; } let mut row = day_row(lang, group[0], now); (row.before, row.after) = g::push_repo_group_words(lang, branches.len(), group.len()); DayEntry { row, pushes: branches.iter().map(|b| branch_row(lang, b, now)).collect(), } }) .collect() } #[component] pub async fn contribution_calendar( cx: &Cx, calendar: Calendar, selected: Option, lang: Lang, base: String, live: Option, ) -> Result { let range = { let from = g::date_text( lang, calendar.first_day.0, calendar.first_day.1, calendar.first_day.2, ); let to = g::date_text(lang, calendar.today.0, calendar.today.1, calendar.today.2); g::date_range(lang, &from, &to) }; let summary = g::heatmap_summary( lang, calendar.total, calendar.current_streak, calendar.longest_streak, ); let total = g::thousands(lang, calendar.total); let current = g::streak_days(lang, calendar.current_streak); let longest = g::streak_days(lang, calendar.longest_streak); let best = g::contributions_count(lang, calendar.best_day); let mon = g::t(lang, K::MonLabel); let wed = g::t(lang, K::WedLabel); let fri = g::t(lang, K::FriLabel); let less = g::t(lang, K::Less); let more = g::t(lang, K::More); let empty_day = g::t(lang, K::NoContributionsDay); let now = now_unix(); let selected_date = selected.as_ref().map(|detail| detail.date); let day = selected.map(|detail| DayView { heading: g::contributions_on_day( lang, &g::date_text(lang, detail.date.0, detail.date.1, detail.date.2), ), rows: day_entries(lang, &detail.items, now), }); let mut month_slots = vec![String::new(); WEEKS]; for (column, month) in &calendar.months { month_slots[*column] = g::month_abbrev(lang, *month).to_owned(); } let cells: Vec = calendar .weeks .iter() .flat_map(|week| week.iter()) .map(|slot| match slot { Some(day) => { let picked = selected_date == Some(day.date); let level = LEVEL_CLASS[usize::from(day.level)]; CellView { class: if picked { format!("{level} selected") } else { level.to_owned() }, href: Some(day_href(&base, day.date, picked)), title: g::contributions_on( lang, day.count, &g::date_text(lang, day.date.0, day.date.1, day.date.2), ), arrive: (day.count > 0).then(|| { format!( "{:04}-{:02}-{:02}:{}", day.date.0, day.date.1, day.date.2, day.count ) }), } } None => CellView { class: "cell blank".to_owned(), href: None, title: String::new(), arrive: None, }, }) .collect(); Ok(view! {

(g::t(lang, K::ContributionsTitle))

(range.as_str())

(total.as_str()) (g::t(lang, K::ContributionsLastYear))
(current.as_str()) (g::t(lang, K::CurrentStreak))
(longest.as_str()) (g::t(lang, K::LongestStreak))
(best.as_str()) (g::t(lang, K::BestDay))
for cell in cells.into_iter() { if let Some(href) = cell.href { } else { } }
if let Some(day) = day {

(day.heading.as_str())

if day.rows.is_empty() {

(empty_day)

} else {
    for entry in day.rows.into_iter() { if entry.pushes.is_empty() {
  • day_line(row: entry.row)
  • } else {
  • day_line(row: entry.row)
      for push in entry.pushes.into_iter() {
    • day_line(row: push)
    • }
  • } }
}
}
}) } #[cfg(test)] mod tests { use super::*; const TODAY: (i64, i64, i64) = (2026, 10, 16); fn counts(pairs: &[(&str, u32)]) -> Vec<(String, u32)> { pairs.iter().map(|(d, n)| ((*d).to_owned(), *n)).collect() } #[test] fn empty_input_gives_an_empty_calendar() { let cal = build(&[], TODAY); assert_eq!(cal.weeks.len(), WEEKS); assert_eq!(cal.total, 0); assert_eq!(cal.current_streak, 0); assert_eq!(cal.longest_streak, 0); assert_eq!(cal.best_day, 0); assert!(cal.weeks.iter().flatten().flatten().all(|d| d.level == 0)); } #[test] fn streak_ending_today_counts_today() { let cal = build( &counts(&[("2026-10-14", 2), ("2026-10-15", 1), ("2026-10-16", 5)]), TODAY, ); assert_eq!(cal.current_streak, 3); assert_eq!(cal.longest_streak, 3); assert_eq!(cal.total, 8); } #[test] fn streak_ending_yesterday_survives_an_empty_today() { let cal = build( &counts(&[("2026-10-13", 1), ("2026-10-14", 1), ("2026-10-15", 1)]), TODAY, ); assert_eq!(cal.current_streak, 3); } #[test] fn a_gap_or_an_old_run_ends_the_current_streak() { type Case<'a> = (&'a str, &'a [(&'a str, u32)], u64, u64); let cases: [Case<'_>; 2] = [ ("old run", &[("2026-10-01", 3), ("2026-10-02", 3)], 0, 2), ( "gap then two days", &[ ("2026-09-20", 1), ("2026-09-21", 1), ("2026-09-22", 1), ("2026-09-23", 1), ("2026-09-24", 1), ("2026-10-15", 2), ("2026-10-16", 2), ], 2, 5, ), ]; for (name, input, current, longest) in cases { let cal = build(&counts(input), TODAY); assert_eq!(cal.current_streak, current, "case {name}"); assert_eq!(cal.longest_streak, longest, "case {name}"); } } #[test] fn best_day_is_the_highest_single_count() { let cal = build( &counts(&[("2026-10-01", 4), ("2026-10-02", 23), ("2026-10-03", 9)]), TODAY, ); assert_eq!(cal.best_day, 23); assert_eq!(cal.total, 36); } #[test] fn window_is_53_monday_first_weeks_ending_this_week() { let cal = build(&[], TODAY); assert_eq!(cal.first_day, (2025, 10, 13)); let first = cal.weeks[0][0].expect("first Monday is shown"); assert_eq!(first.date, (2025, 10, 13)); assert_eq!(weekday(days_from_civil(2025, 10, 13)), 0); let last = &cal.weeks[WEEKS - 1]; assert_eq!(last[4].expect("today").date, TODAY); assert!(last[5].is_none() && last[6].is_none()); assert_eq!(last[0].expect("Monday of this week").date, (2026, 10, 12)); } #[test] fn counts_outside_the_window_and_in_the_future_are_ignored() { let cal = build( &counts(&[("2025-10-12", 7), ("2025-10-13", 2), ("2026-10-17", 9)]), TODAY, ); assert_eq!(cal.total, 2); assert_eq!(cal.best_day, 2); assert_eq!(cal.current_streak, 0); } #[test] fn malformed_dates_are_skipped() { let cal = build( &counts(&[ ("2026-02-30", 4), ("2026/10/16", 4), ("nope", 4), ("2026-10-16", 1), ]), TODAY, ); assert_eq!(cal.total, 1); } #[test] fn leap_day_is_a_real_date() { let cal = build( &counts(&[("2028-02-29", 4), ("2028-03-01", 1)]), (2028, 3, 1), ); assert_eq!(cal.total, 5); assert_eq!(cal.current_streak, 2); assert_eq!( days_from_civil(2028, 3, 1) - days_from_civil(2028, 2, 28), 2 ); assert_eq!(parse_date("2027-02-29"), None); assert_eq!(parse_date("2028-02-29"), Some(days_from_civil(2028, 2, 29))); assert_eq!(civil_from_days(days_from_civil(2000, 2, 29)), (2000, 2, 29)); } #[test] fn pushes_to_one_repo_group_by_branch_under_the_newest() { let item = |kind, ref_name: &str, at: &str| ContributionItem { kind, repo_owner: "Tahinli".to_owned(), repo_name: "forge".to_owned(), created_at: at.to_owned(), ref_name: ref_name.to_owned(), number: 0, title: String::new(), commit: String::new(), }; let push = |branch: &str, at: &str| item(ContributionKind::Push, branch, at); let items = [ push("refs/heads/main", "2026-10-16T12:00:00Z"), push("refs/heads/main", "2026-10-16T11:00:00Z"), item(ContributionKind::Issue, "", "2026-10-16T10:30:00Z"), push("refs/heads/dev", "2026-10-16T09:00:00Z"), push("refs/heads/main", "2026-10-16T08:00:00Z"), ]; let entries = day_entries(Lang::En, &items, 0); let shape: Vec = entries.iter().map(|e| e.pushes.len()).collect(); assert_eq!(shape, [2, 0]); assert_eq!(entries[0].row.updated, "2026-10-16T12:00:00Z"); assert_eq!(entries[0].row.before, "Pushed 4 times to 2 branches in"); assert_eq!(entries[0].pushes[0].before, "Pushed 3 times to main in"); assert_eq!(entries[0].pushes[1].before, "Pushed to dev in"); } #[test] fn days_from_civil_inverts_civil_from_days() { for days in [-1, 0, 1, 10_957, 20_454, 47_000] { let (y, m, d) = civil_from_days(days); assert_eq!(days_from_civil(y, m, d), days); } } }