use std::rc::Rc;
use arc_motion::{is_reduced_motion, motion_now};
use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, Typography, oklab_mix};
use gpui_kit::{
AnyElement, App, Bounds, ElementId, FocusHandle, Hsla, InteractiveElement as _, IntoElement,
KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, ParentElement, Pixels, RenderOnce,
Role, SharedString, Styled, Window, base::StyledExt as _, canvas, div, prelude::*, px,
};
use super::common::{ChartSpring, format_grouped};
const CELL_SIZE: f32 = 12.0;
const CELL_GAP: f32 = 3.0;
const CELL_STEP: f32 = CELL_SIZE + CELL_GAP;
const WEEKDAY_W: f32 = 30.0;
const MONTH_H: f32 = 18.0;
#[derive(Clone, Debug)]
pub struct ActivityDay {
pub date: SharedString,
pub count: u32,
}
impl ActivityDay {
pub fn new(date: impl Into<SharedString>, count: u32) -> Self {
Self {
date: date.into(),
count,
}
}
}
#[derive(Clone, Debug)]
pub struct ActivityUnit {
pub one: SharedString,
pub other: SharedString,
}
impl ActivityUnit {
pub fn new(one: impl Into<SharedString>, other: impl Into<SharedString>) -> Self {
Self {
one: one.into(),
other: other.into(),
}
}
pub fn noun(&self, count: u64) -> &str {
if count == 1 {
self.one.as_ref()
} else {
self.other.as_ref()
}
}
}
impl Default for ActivityUnit {
fn default() -> Self {
Self::new("contribution", "contributions")
}
}
pub fn parse_iso_day(iso: &str) -> Option<i64> {
let mut parts = iso.split('-');
let y: i64 = parts.next()?.parse().ok()?;
let m: u32 = parts.next()?.parse().ok()?;
let d: u32 = parts.next()?.parse().ok()?;
if !(1..=12).contains(&m) || !(1..=31).contains(&d) {
return None;
}
Some(days_from_civil(y, m, d))
}
pub fn civil_from_day(z: i64) -> (i64, u32, u32) {
let z = z + 719_468;
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
let doe = (z - era * 146_097) as u64;
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
let y = yoe as i64 + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = if m <= 2 { y + 1 } else { y };
(y, m as u32, d as u32)
}
fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
let y = if m <= 2 { y - 1 } else { y };
let era = if y >= 0 { y } else { y - 399 } / 400;
let yoe = (y - era * 400) as u64;
let m_adj = if m > 2 { m - 3 } else { m + 9 } as u64;
let doy = (153 * m_adj + 2) / 5 + (d as u64) - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
era * 146_097 + (doe as i64) - 719_468
}
pub fn format_iso_day(day: i64) -> String {
let (y, m, d) = civil_from_day(day);
format!("{y:04}-{m:02}-{d:02}")
}
pub fn weekday_of_day(day: i64) -> usize {
(day + 4).rem_euclid(7) as usize
}
fn month_short(m: u32) -> &'static str {
match m {
1 => "Jan",
2 => "Feb",
3 => "Mar",
4 => "Apr",
5 => "May",
6 => "Jun",
7 => "Jul",
8 => "Aug",
9 => "Sep",
10 => "Oct",
11 => "Nov",
_ => "Dec",
}
}
fn weekday_short(dow: usize) -> &'static str {
match dow % 7 {
0 => "Sun",
1 => "Mon",
2 => "Tue",
3 => "Wed",
4 => "Thu",
5 => "Fri",
_ => "Sat",
}
}
#[derive(Clone, Debug)]
pub struct ActivityHeatmapModel {
pub start_day: i64,
pub length: usize,
pub lead: usize,
pub weeks: usize,
pub total: u64,
pub counts: Vec<u32>,
pub levels: Vec<u8>,
pub thresholds: [u32; 3],
pub months: Vec<(usize, &'static str)>,
pub per_level: [usize; 5],
}
pub fn build_activity_heatmap_model(
days: &[ActivityDay],
week_starts_on: u8,
thresholds: Option<[u32; 3]>,
) -> ActivityHeatmapModel {
let parsed: Vec<(i64, u32)> = days
.iter()
.filter_map(|d| parse_iso_day(d.date.as_ref()).map(|day| (day, d.count)))
.collect();
let start_day = parsed
.iter()
.map(|&(d, _)| d)
.min()
.unwrap_or_else(|| days_from_civil(2025, 1, 1));
let end_day = parsed.iter().map(|&(d, _)| d).max().unwrap_or(start_day);
let length = if parsed.is_empty() {
0
} else {
(end_day - start_day + 1).max(0) as usize
};
let mut counts = vec![0u32; length];
for (day, count) in parsed {
let idx = (day - start_day) as usize;
if idx < length {
counts[idx] = counts[idx].saturating_add(count);
}
}
let max_count = counts.iter().copied().max().unwrap_or(0);
let bounds = thresholds.unwrap_or_else(|| {
[
((max_count as f64 * 0.25).ceil() as u32).max(1),
((max_count as f64 * 0.50).ceil() as u32).max(2),
((max_count as f64 * 0.75).ceil() as u32).max(3),
]
});
let levels: Vec<u8> = counts
.iter()
.map(|&c| {
if c == 0 {
0
} else if c <= bounds[0] {
1
} else if c <= bounds[1] {
2
} else if c <= bounds[2] {
3
} else {
4
}
})
.collect();
let wso = (week_starts_on % 7) as usize;
let lead = (weekday_of_day(start_day) + 7 - wso) % 7;
let weeks = (lead + length).div_ceil(7).max(1);
let mut months: Vec<(usize, &'static str)> = Vec::new();
for idx in 0..length {
let (_, m, d) = civil_from_day(start_day + idx as i64);
if idx == 0 || d == 1 {
let col = (lead + idx) / 7;
months.push((col, month_short(m)));
}
}
if months.len() > 1 && months[1].0.saturating_sub(months[0].0) < 3 {
months.remove(0);
}
let mut per_level = [0usize; 5];
for &lvl in &levels {
per_level[(lvl as usize).min(4)] += 1;
}
let total: u64 = counts.iter().map(|&c| c as u64).sum();
ActivityHeatmapModel {
start_day,
length,
lead,
weeks,
total,
counts,
levels,
thresholds: bounds,
months,
per_level,
}
}
#[derive(Clone)]
struct HeatmapState {
focus_handle: FocusHandle,
hover_index: Option<usize>,
preview_level: Option<u8>,
pinned_level: Option<u8>,
grid_bounds: Bounds<Pixels>,
reveal_spring: ChartSpring,
last_tick: f64,
}
type DateSelectHandler = Rc<dyn Fn(SharedString, &mut Window, &mut App)>;
#[derive(IntoElement)]
pub struct ActivityHeatmap {
id: ElementId,
days: Vec<ActivityDay>,
label: SharedString,
period: SharedString,
unit: ActivityUnit,
thresholds: Option<[u32; 3]>,
week_starts_on: u8,
selected_date: Option<SharedString>,
on_select_date: Option<DateSelectHandler>,
actions: Option<AnyElement>,
}
impl ActivityHeatmap {
pub fn new(
id: impl Into<ElementId>,
days: Vec<ActivityDay>,
label: impl Into<SharedString>,
period: impl Into<SharedString>,
) -> Self {
Self {
id: id.into(),
days,
label: label.into(),
period: period.into(),
unit: ActivityUnit::default(),
thresholds: None,
week_starts_on: 0,
selected_date: None,
on_select_date: None,
actions: None,
}
}
pub fn unit(mut self, unit: ActivityUnit) -> Self {
self.unit = unit;
self
}
pub fn thresholds(mut self, thresholds: [u32; 3]) -> Self {
self.thresholds = Some(thresholds);
self
}
pub fn week_starts_on(mut self, day: u8) -> Self {
self.week_starts_on = day % 7;
self
}
pub fn selected_date(mut self, date: Option<impl Into<SharedString>>) -> Self {
self.selected_date = date.map(Into::into);
self
}
pub fn on_select_date(
mut self,
f: impl Fn(SharedString, &mut Window, &mut App) + 'static,
) -> Self {
self.on_select_date = Some(Rc::new(f));
self
}
pub fn actions(mut self, actions: impl IntoElement) -> Self {
self.actions = Some(actions.into_any_element());
self
}
}
impl RenderOnce for ActivityHeatmap {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let reduced = is_reduced_motion(cx);
let now = motion_now(cx);
let model = build_activity_heatmap_model(&self.days, self.week_starts_on, self.thresholds);
let state = window.use_keyed_state(
ElementId::NamedChild(self.id.clone().into(), "__heatmap-state".into()),
cx,
|_w, cx| HeatmapState {
focus_handle: cx.focus_handle(),
hover_index: None,
preview_level: None,
pinned_level: None,
grid_bounds: Bounds::default(),
reveal_spring: {
let mut sp = ChartSpring::new(if reduced { 1.0 } else { 0.0 });
sp.set_target(1.0);
sp
},
last_tick: now,
},
);
let mut running = false;
state.update(cx, |s, _cx| {
let dt = (now - s.last_tick).clamp(0.0, 0.05);
s.last_tick = now;
if reduced {
s.reveal_spring.snap(1.0);
} else if dt > 0.0 && !s.reveal_spring.is_settled() {
s.reveal_spring.step(0.68, 0.0, dt as f32);
}
running = !s.reveal_spring.is_settled();
});
if running {
window.request_animation_frame();
}
let snap = state.read(cx).clone();
let highlight_level = snap.preview_level.or(snap.pinned_level);
let reveal_p = snap.reveal_spring.position().clamp(0.0, 1.0);
let selected_index: Option<usize> = self
.selected_date
.as_deref()
.and_then(parse_iso_day)
.and_then(|d| {
let idx = d - model.start_day;
if idx >= 0 && (idx as usize) < model.length {
Some(idx as usize)
} else {
None
}
});
let level_color = |level: u8| -> Hsla {
match level {
0 => colors.surface_muted,
1 => oklab_mix(colors.series.series_1, colors.surface_muted, 0.28),
2 => oklab_mix(colors.series.series_1, colors.surface_muted, 0.52),
3 => oklab_mix(colors.series.series_1, colors.surface_muted, 0.76),
_ => colors.series.series_1,
}
};
let summary_text = format!(
"{} {}",
format_grouped(model.total as f64, 0),
self.unit.noun(model.total)
);
let mut header = div()
.w_full()
.flex()
.items_center()
.justify_between()
.gap(Spacing::S3)
.mb(Spacing::S3)
.child(
div()
.flex()
.items_baseline()
.gap(px(5.0))
.child(
div()
.text_size(Typography::TEXT_SM)
.font_semibold()
.text_color(colors.foreground)
.child(summary_text),
)
.child(
div()
.text_size(px(13.0))
.text_color(colors.text_muted)
.child(format!("in {}", self.period)),
),
);
if let Some(actions) = self.actions {
header = header.child(actions);
}
let grid_w = (model.weeks as f32 * CELL_STEP - CELL_GAP).max(CELL_SIZE);
let grid_h = 7.0 * CELL_STEP - CELL_GAP;
let mut months_row = div()
.relative()
.ml(px(WEEKDAY_W))
.w(px(grid_w))
.h(px(MONTH_H));
for &(col, mlabel) in &model.months {
months_row = months_row.child(
div()
.absolute()
.left(px(col as f32 * CELL_STEP))
.top(px(0.0))
.text_size(px(11.0))
.text_color(colors.text_muted)
.child(mlabel),
);
}
let mut weekdays_col = div()
.relative()
.w(px(WEEKDAY_W))
.h(px(grid_h))
.flex_shrink_0();
for row in 0..7 {
let dow = (row + self.week_starts_on as usize) % 7;
if dow % 2 == 1 {
weekdays_col = weekdays_col.child(
div()
.absolute()
.left(px(0.0))
.top(px(row as f32 * CELL_STEP - 1.0))
.text_size(px(10.0))
.text_color(colors.text_muted)
.child(weekday_short(dow)),
);
}
}
let bounds_state = state.clone();
let bounds_tracker = canvas(
move |bounds, _w, cx| {
bounds_state.update(cx, |s, _cx| {
s.grid_bounds = bounds;
});
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
let lead = model.lead;
let length = model.length;
let weeks = model.weeks;
let start_day = model.start_day;
let on_select = self.on_select_date.clone();
let cell_at = move |lx: f32, ly: f32| -> Option<usize> {
let col = (lx / CELL_STEP).floor() as isize;
let row = (ly / CELL_STEP).floor() as isize;
if col < 0 || col >= weeks as isize || !(0..7).contains(&row) {
return None;
}
let raw = (col as usize) * 7 + (row as usize);
if raw < lead {
return None;
}
let idx = raw - lead;
if idx < length { Some(idx) } else { None }
};
let move_state = state.clone();
let down_state = state.clone();
let down_cb = on_select.clone();
let key_state = state.clone();
let key_cb = on_select.clone();
let mut grid = div()
.id(self.id.clone())
.role(Role::Group)
.aria_label(self.label.clone())
.track_focus(&snap.focus_handle)
.relative()
.w(px(grid_w))
.h(px(grid_h))
.on_mouse_move(move |ev: &MouseMoveEvent, _w, cx| {
move_state.update(cx, |s, cx| {
let b = s.grid_bounds;
let lx: f32 = (ev.position.x - b.origin.x).into();
let ly: f32 = (ev.position.y - b.origin.y).into();
let bw: f32 = b.size.width.into();
let bh: f32 = b.size.height.into();
if lx < 0.0 || ly < 0.0 || lx > bw || ly > bh {
if s.hover_index.is_some() {
s.hover_index = None;
cx.notify();
}
return;
}
let next = cell_at(lx, ly);
if s.hover_index != next {
s.hover_index = next;
cx.notify();
}
});
})
.on_mouse_down(MouseButton::Left, move |ev: &MouseDownEvent, window, cx| {
let (fh, hit) = {
let s = down_state.read(cx);
let b = s.grid_bounds;
let lx: f32 = (ev.position.x - b.origin.x).into();
let ly: f32 = (ev.position.y - b.origin.y).into();
(s.focus_handle.clone(), cell_at(lx, ly))
};
window.focus(&fh, cx);
down_state.update(cx, |s, cx| {
s.hover_index = hit;
cx.notify();
});
if let (Some(idx), Some(cb)) = (hit, &down_cb) {
cb(
SharedString::from(format_iso_day(start_day + idx as i64)),
window,
cx,
);
}
})
.on_key_down(move |ev: &KeyDownEvent, window, cx| {
if length == 0 {
return;
}
let key = ev.keystroke.key.as_str();
let current = key_state
.read(cx)
.hover_index
.or(selected_index)
.unwrap_or(length.saturating_sub(1));
if key == "escape" {
key_state.update(cx, |s, cx| {
s.hover_index = None;
cx.notify();
});
return;
}
if key == "enter" || key == "space" {
cx.stop_propagation();
if let Some(cb) = &key_cb {
cb(
SharedString::from(format_iso_day(start_day + current as i64)),
window,
cx,
);
}
return;
}
let next = match key {
"up" => Some(current.saturating_sub(1)),
"down" => Some((current + 1).min(length - 1)),
"left" => Some(current.saturating_sub(7)),
"right" => Some((current + 7).min(length - 1)),
"home" => Some(0),
"end" => Some(length - 1),
_ => None,
};
if let Some(n) = next {
cx.stop_propagation();
key_state.update(cx, |s, cx| {
s.hover_index = Some(n);
cx.notify();
});
}
})
.child(bounds_tracker);
let max_diag = (model.weeks.saturating_sub(1) + 6).max(1) as f32;
for idx in 0..model.length {
let slot = idx + model.lead;
let col = slot / 7;
let row = slot % 7;
let lvl = model.levels[idx];
let diag = (col + row) as f32 / max_diag;
let delay = diag * 0.34;
let local_p = ((reveal_p - delay) / (1.0 - delay).max(0.01)).clamp(0.0, 1.0);
let dimmed = highlight_level.map(|h| h != lvl).unwrap_or(false);
let is_hovered = snap.hover_index == Some(idx);
let alpha = local_p * if dimmed { 0.22 } else { 1.0 };
let mut cell = div()
.absolute()
.left(px(col as f32 * CELL_STEP))
.top(px(row as f32 * CELL_STEP))
.w(px(CELL_SIZE))
.h(px(CELL_SIZE))
.rounded(px(2.5))
.bg(level_color(lvl).opacity(alpha))
.cursor_pointer();
if lvl == 0 {
cell = cell
.border_1()
.border_color(colors.border.opacity(alpha * 0.45));
}
if is_hovered {
cell = cell.border_1().border_color(colors.foreground);
}
grid = grid.child(cell);
}
if let Some(sel_idx) = selected_index {
let slot = sel_idx + model.lead;
let col = slot / 7;
let row = slot % 7;
grid = grid.child(
div()
.absolute()
.left(px(col as f32 * CELL_STEP - 2.0))
.top(px(row as f32 * CELL_STEP - 2.0))
.w(px(CELL_SIZE + 4.0))
.h(px(CELL_SIZE + 4.0))
.rounded(px(4.0))
.border_2()
.border_color(colors.foreground),
);
}
if let Some(idx) = snap.hover_index.filter(|&i| i < model.length) {
let slot = idx + model.lead;
let col = slot / 7;
let row = slot % 7;
let cx_px = col as f32 * CELL_STEP + CELL_SIZE * 0.5;
let cy_px = row as f32 * CELL_STEP;
let count = model.counts[idx];
let day = model.start_day + idx as i64;
let (y, m, d) = civil_from_day(day);
let dow = weekday_short(weekday_of_day(day));
let primary = if count > 0 {
format!(
"{} {}",
format_grouped(count as f64, 0),
self.unit.noun(count as u64)
)
} else {
format!("No {}", self.unit.other)
};
let secondary = format!("{dow}, {} {d}, {y}", month_short(m));
let tip_w = 168.0f32;
let tip_h = 48.0f32;
let left = (cx_px - tip_w * 0.5).clamp(0.0, (grid_w - tip_w).max(0.0));
let top = if cy_px - tip_h - 8.0 >= -MONTH_H {
cy_px - tip_h - 8.0
} else {
cy_px + CELL_SIZE + 8.0
};
grid = grid.child(
div()
.absolute()
.left(px(left))
.top(px(top))
.w(px(tip_w))
.px(Spacing::S2)
.py(px(6.0))
.rounded(Radii::CONTROL)
.bg(colors.surface_raised)
.border_1()
.border_color(colors.border)
.shadow_md()
.flex()
.flex_col()
.gap(px(1.0))
.child(
div()
.text_size(Typography::TEXT_XS)
.font_semibold()
.text_color(colors.foreground)
.child(primary),
)
.child(
div()
.text_size(px(11.0))
.text_color(colors.text_muted)
.child(secondary),
),
);
}
let calendar = div().w_full().overflow_hidden().child(
div()
.flex()
.flex_col()
.child(months_row)
.child(div().flex().items_start().child(weekdays_col).child(grid)),
);
let [t1, t2, t3] = model.thresholds;
let caption = if let Some(lvl) = highlight_level {
let days_n = model.per_level[(lvl as usize).min(4)];
let day_word = if days_n == 1 { "day" } else { "days" };
let range_desc = match lvl {
0 => format!("no {}", self.unit.other),
1 => {
if t1 == 1 {
format!("1 {}", self.unit.one)
} else {
format!("1–{t1} {}", self.unit.other)
}
}
2 => format!("{}–{t2} {}", t1 + 1, self.unit.other),
3 => format!("{}–{t3} {}", t2 + 1, self.unit.other),
_ => format!("{}+ {}", t3 + 1, self.unit.other),
};
format!(
"{} {day_word} with {range_desc}",
format_grouped(days_n as f64, 0)
)
} else {
String::new()
};
let mut swatches = div().flex().items_center().gap(px(4.0));
for lvl in 0u8..=4 {
let hover_st = state.clone();
let click_st = state.clone();
let is_pinned = snap.pinned_level == Some(lvl);
let is_hl = highlight_level == Some(lvl);
swatches = swatches.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("heatmap-level-{lvl}")),
))
.w(px(12.0))
.h(px(12.0))
.rounded(px(2.5))
.bg(level_color(lvl))
.border_1()
.border_color(if is_pinned || is_hl {
colors.foreground
} else {
colors.border.opacity(0.6)
})
.cursor_pointer()
.on_hover(move |hovered, _w, cx| {
hover_st.update(cx, |s, cx| {
if *hovered {
s.preview_level = Some(lvl);
} else if s.preview_level == Some(lvl) {
s.preview_level = None;
}
cx.notify();
});
})
.on_mouse_down(MouseButton::Left, move |_, _w, cx| {
click_st.update(cx, |s, cx| {
s.pinned_level = if s.pinned_level == Some(lvl) {
None
} else {
Some(lvl)
};
cx.notify();
});
}),
);
}
let footer = div()
.w_full()
.mt(Spacing::S3)
.flex()
.items_center()
.justify_between()
.gap(Spacing::S3)
.child(
div()
.text_size(px(11.0))
.text_color(colors.text_muted)
.min_h(px(16.0))
.child(caption),
)
.child(
div()
.flex()
.items_center()
.gap(px(6.0))
.text_size(px(11.0))
.text_color(colors.text_muted)
.child("Less")
.child(swatches)
.child("More"),
);
div()
.w_full()
.flex()
.flex_col()
.child(header)
.child(calendar)
.child(footer)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn activity_heatmap_calendar_and_quartile_levels() {
let d = parse_iso_day("2025-01-01").unwrap();
assert_eq!(format_iso_day(d), "2025-01-01");
assert_eq!(weekday_of_day(d), 3);
let days = vec![
ActivityDay::new("2025-01-01", 0),
ActivityDay::new("2025-01-02", 2),
ActivityDay::new("2025-01-04", 12), ];
let model = build_activity_heatmap_model(&days, 0, None);
assert_eq!(model.length, 4);
assert_eq!(model.counts, vec![0, 2, 0, 12]);
assert_eq!(model.total, 14);
assert_eq!(model.thresholds, [3, 6, 9]);
assert_eq!(model.levels, vec![0, 1, 0, 4]);
assert_eq!(model.per_level, [2, 1, 0, 0, 1]);
}
}