1use std::rc::Rc;
11
12use arc_motion::{is_reduced_motion, motion_now};
13use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, Typography, oklab_mix};
14use gpui_kit::{
15 AnyElement, App, Bounds, ElementId, FocusHandle, Hsla, InteractiveElement as _, IntoElement,
16 KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, ParentElement, Pixels, RenderOnce,
17 Role, SharedString, Styled, Window, base::StyledExt as _, canvas, div, prelude::*, px,
18};
19
20use super::common::{ChartSpring, format_grouped};
21
22const CELL_SIZE: f32 = 12.0;
23const CELL_GAP: f32 = 3.0;
24const CELL_STEP: f32 = CELL_SIZE + CELL_GAP;
25const WEEKDAY_W: f32 = 30.0;
26const MONTH_H: f32 = 18.0;
27
28#[derive(Clone, Debug)]
30pub struct ActivityDay {
31 pub date: SharedString,
32 pub count: u32,
33}
34
35impl ActivityDay {
36 pub fn new(date: impl Into<SharedString>, count: u32) -> Self {
37 Self {
38 date: date.into(),
39 count,
40 }
41 }
42}
43
44#[derive(Clone, Debug)]
46pub struct ActivityUnit {
47 pub one: SharedString,
48 pub other: SharedString,
49}
50
51impl ActivityUnit {
52 pub fn new(one: impl Into<SharedString>, other: impl Into<SharedString>) -> Self {
53 Self {
54 one: one.into(),
55 other: other.into(),
56 }
57 }
58
59 pub fn noun(&self, count: u64) -> &str {
60 if count == 1 {
61 self.one.as_ref()
62 } else {
63 self.other.as_ref()
64 }
65 }
66}
67
68impl Default for ActivityUnit {
69 fn default() -> Self {
70 Self::new("contribution", "contributions")
71 }
72}
73
74pub fn parse_iso_day(iso: &str) -> Option<i64> {
76 let mut parts = iso.split('-');
77 let y: i64 = parts.next()?.parse().ok()?;
78 let m: u32 = parts.next()?.parse().ok()?;
79 let d: u32 = parts.next()?.parse().ok()?;
80 if !(1..=12).contains(&m) || !(1..=31).contains(&d) {
81 return None;
82 }
83 Some(days_from_civil(y, m, d))
84}
85
86pub fn civil_from_day(z: i64) -> (i64, u32, u32) {
88 let z = z + 719_468;
89 let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
90 let doe = (z - era * 146_097) as u64;
91 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
92 let y = yoe as i64 + era * 400;
93 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
94 let mp = (5 * doy + 2) / 153;
95 let d = doy - (153 * mp + 2) / 5 + 1;
96 let m = if mp < 10 { mp + 3 } else { mp - 9 };
97 let y = if m <= 2 { y + 1 } else { y };
98 (y, m as u32, d as u32)
99}
100
101fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
102 let y = if m <= 2 { y - 1 } else { y };
103 let era = if y >= 0 { y } else { y - 399 } / 400;
104 let yoe = (y - era * 400) as u64;
105 let m_adj = if m > 2 { m - 3 } else { m + 9 } as u64;
106 let doy = (153 * m_adj + 2) / 5 + (d as u64) - 1;
107 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
108 era * 146_097 + (doe as i64) - 719_468
109}
110
111pub fn format_iso_day(day: i64) -> String {
113 let (y, m, d) = civil_from_day(day);
114 format!("{y:04}-{m:02}-{d:02}")
115}
116
117pub fn weekday_of_day(day: i64) -> usize {
119 (day + 4).rem_euclid(7) as usize
120}
121
122fn month_short(m: u32) -> &'static str {
123 match m {
124 1 => "Jan",
125 2 => "Feb",
126 3 => "Mar",
127 4 => "Apr",
128 5 => "May",
129 6 => "Jun",
130 7 => "Jul",
131 8 => "Aug",
132 9 => "Sep",
133 10 => "Oct",
134 11 => "Nov",
135 _ => "Dec",
136 }
137}
138
139fn weekday_short(dow: usize) -> &'static str {
140 match dow % 7 {
141 0 => "Sun",
142 1 => "Mon",
143 2 => "Tue",
144 3 => "Wed",
145 4 => "Thu",
146 5 => "Fri",
147 _ => "Sat",
148 }
149}
150
151#[derive(Clone, Debug)]
153pub struct ActivityHeatmapModel {
154 pub start_day: i64,
155 pub length: usize,
156 pub lead: usize,
157 pub weeks: usize,
158 pub total: u64,
159 pub counts: Vec<u32>,
160 pub levels: Vec<u8>,
161 pub thresholds: [u32; 3],
162 pub months: Vec<(usize, &'static str)>,
163 pub per_level: [usize; 5],
164}
165
166pub fn build_activity_heatmap_model(
168 days: &[ActivityDay],
169 week_starts_on: u8,
170 thresholds: Option<[u32; 3]>,
171) -> ActivityHeatmapModel {
172 let parsed: Vec<(i64, u32)> = days
173 .iter()
174 .filter_map(|d| parse_iso_day(d.date.as_ref()).map(|day| (day, d.count)))
175 .collect();
176
177 let start_day = parsed
178 .iter()
179 .map(|&(d, _)| d)
180 .min()
181 .unwrap_or_else(|| days_from_civil(2025, 1, 1));
182 let end_day = parsed.iter().map(|&(d, _)| d).max().unwrap_or(start_day);
183 let length = if parsed.is_empty() {
184 0
185 } else {
186 (end_day - start_day + 1).max(0) as usize
187 };
188
189 let mut counts = vec![0u32; length];
190 for (day, count) in parsed {
191 let idx = (day - start_day) as usize;
192 if idx < length {
193 counts[idx] = counts[idx].saturating_add(count);
194 }
195 }
196
197 let max_count = counts.iter().copied().max().unwrap_or(0);
198 let bounds = thresholds.unwrap_or_else(|| {
199 [
200 ((max_count as f64 * 0.25).ceil() as u32).max(1),
201 ((max_count as f64 * 0.50).ceil() as u32).max(2),
202 ((max_count as f64 * 0.75).ceil() as u32).max(3),
203 ]
204 });
205
206 let levels: Vec<u8> = counts
207 .iter()
208 .map(|&c| {
209 if c == 0 {
210 0
211 } else if c <= bounds[0] {
212 1
213 } else if c <= bounds[1] {
214 2
215 } else if c <= bounds[2] {
216 3
217 } else {
218 4
219 }
220 })
221 .collect();
222
223 let wso = (week_starts_on % 7) as usize;
224 let lead = (weekday_of_day(start_day) + 7 - wso) % 7;
225 let weeks = (lead + length).div_ceil(7).max(1);
226
227 let mut months: Vec<(usize, &'static str)> = Vec::new();
228 for idx in 0..length {
229 let (_, m, d) = civil_from_day(start_day + idx as i64);
230 if idx == 0 || d == 1 {
231 let col = (lead + idx) / 7;
232 months.push((col, month_short(m)));
233 }
234 }
235 if months.len() > 1 && months[1].0.saturating_sub(months[0].0) < 3 {
237 months.remove(0);
238 }
239
240 let mut per_level = [0usize; 5];
241 for &lvl in &levels {
242 per_level[(lvl as usize).min(4)] += 1;
243 }
244 let total: u64 = counts.iter().map(|&c| c as u64).sum();
245
246 ActivityHeatmapModel {
247 start_day,
248 length,
249 lead,
250 weeks,
251 total,
252 counts,
253 levels,
254 thresholds: bounds,
255 months,
256 per_level,
257 }
258}
259
260#[derive(Clone)]
261struct HeatmapState {
262 focus_handle: FocusHandle,
263 hover_index: Option<usize>,
264 preview_level: Option<u8>,
265 pinned_level: Option<u8>,
266 grid_bounds: Bounds<Pixels>,
267 reveal_spring: ChartSpring,
268 last_tick: f64,
269}
270
271type DateSelectHandler = Rc<dyn Fn(SharedString, &mut Window, &mut App)>;
272
273#[derive(IntoElement)]
275pub struct ActivityHeatmap {
276 id: ElementId,
277 days: Vec<ActivityDay>,
278 label: SharedString,
279 period: SharedString,
280 unit: ActivityUnit,
281 thresholds: Option<[u32; 3]>,
282 week_starts_on: u8,
283 selected_date: Option<SharedString>,
284 on_select_date: Option<DateSelectHandler>,
285 actions: Option<AnyElement>,
286}
287
288impl ActivityHeatmap {
289 pub fn new(
290 id: impl Into<ElementId>,
291 days: Vec<ActivityDay>,
292 label: impl Into<SharedString>,
293 period: impl Into<SharedString>,
294 ) -> Self {
295 Self {
296 id: id.into(),
297 days,
298 label: label.into(),
299 period: period.into(),
300 unit: ActivityUnit::default(),
301 thresholds: None,
302 week_starts_on: 0,
303 selected_date: None,
304 on_select_date: None,
305 actions: None,
306 }
307 }
308
309 pub fn unit(mut self, unit: ActivityUnit) -> Self {
310 self.unit = unit;
311 self
312 }
313
314 pub fn thresholds(mut self, thresholds: [u32; 3]) -> Self {
315 self.thresholds = Some(thresholds);
316 self
317 }
318
319 pub fn week_starts_on(mut self, day: u8) -> Self {
321 self.week_starts_on = day % 7;
322 self
323 }
324
325 pub fn selected_date(mut self, date: Option<impl Into<SharedString>>) -> Self {
326 self.selected_date = date.map(Into::into);
327 self
328 }
329
330 pub fn on_select_date(
331 mut self,
332 f: impl Fn(SharedString, &mut Window, &mut App) + 'static,
333 ) -> Self {
334 self.on_select_date = Some(Rc::new(f));
335 self
336 }
337
338 pub fn actions(mut self, actions: impl IntoElement) -> Self {
339 self.actions = Some(actions.into_any_element());
340 self
341 }
342}
343
344impl RenderOnce for ActivityHeatmap {
345 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
346 let theme = cx.arc_theme().clone();
347 let colors = theme.colors;
348 let reduced = is_reduced_motion(cx);
349 let now = motion_now(cx);
350
351 let model = build_activity_heatmap_model(&self.days, self.week_starts_on, self.thresholds);
352 let state = window.use_keyed_state(
353 ElementId::NamedChild(self.id.clone().into(), "__heatmap-state".into()),
354 cx,
355 |_w, cx| HeatmapState {
356 focus_handle: cx.focus_handle(),
357 hover_index: None,
358 preview_level: None,
359 pinned_level: None,
360 grid_bounds: Bounds::default(),
361 reveal_spring: {
362 let mut sp = ChartSpring::new(if reduced { 1.0 } else { 0.0 });
363 sp.set_target(1.0);
364 sp
365 },
366 last_tick: now,
367 },
368 );
369
370 let mut running = false;
371 state.update(cx, |s, _cx| {
372 let dt = (now - s.last_tick).clamp(0.0, 0.05);
373 s.last_tick = now;
374 if reduced {
375 s.reveal_spring.snap(1.0);
376 } else if dt > 0.0 && !s.reveal_spring.is_settled() {
377 s.reveal_spring.step(0.68, 0.0, dt as f32);
378 }
379 running = !s.reveal_spring.is_settled();
380 });
381 if running {
382 window.request_animation_frame();
383 }
384
385 let snap = state.read(cx).clone();
386 let highlight_level = snap.preview_level.or(snap.pinned_level);
387 let reveal_p = snap.reveal_spring.position().clamp(0.0, 1.0);
388
389 let selected_index: Option<usize> = self
390 .selected_date
391 .as_deref()
392 .and_then(parse_iso_day)
393 .and_then(|d| {
394 let idx = d - model.start_day;
395 if idx >= 0 && (idx as usize) < model.length {
396 Some(idx as usize)
397 } else {
398 None
399 }
400 });
401
402 let level_color = |level: u8| -> Hsla {
404 match level {
405 0 => colors.surface_muted,
406 1 => oklab_mix(colors.series.series_1, colors.surface_muted, 0.28),
407 2 => oklab_mix(colors.series.series_1, colors.surface_muted, 0.52),
408 3 => oklab_mix(colors.series.series_1, colors.surface_muted, 0.76),
409 _ => colors.series.series_1,
410 }
411 };
412
413 let summary_text = format!(
415 "{} {}",
416 format_grouped(model.total as f64, 0),
417 self.unit.noun(model.total)
418 );
419 let mut header = div()
420 .w_full()
421 .flex()
422 .items_center()
423 .justify_between()
424 .gap(Spacing::S3)
425 .mb(Spacing::S3)
426 .child(
427 div()
428 .flex()
429 .items_baseline()
430 .gap(px(5.0))
431 .child(
432 div()
433 .text_size(Typography::TEXT_SM)
434 .font_semibold()
435 .text_color(colors.foreground)
436 .child(summary_text),
437 )
438 .child(
439 div()
440 .text_size(px(13.0))
441 .text_color(colors.text_muted)
442 .child(format!("in {}", self.period)),
443 ),
444 );
445 if let Some(actions) = self.actions {
446 header = header.child(actions);
447 }
448
449 let grid_w = (model.weeks as f32 * CELL_STEP - CELL_GAP).max(CELL_SIZE);
451 let grid_h = 7.0 * CELL_STEP - CELL_GAP;
452
453 let mut months_row = div()
455 .relative()
456 .ml(px(WEEKDAY_W))
457 .w(px(grid_w))
458 .h(px(MONTH_H));
459 for &(col, mlabel) in &model.months {
460 months_row = months_row.child(
461 div()
462 .absolute()
463 .left(px(col as f32 * CELL_STEP))
464 .top(px(0.0))
465 .text_size(px(11.0))
466 .text_color(colors.text_muted)
467 .child(mlabel),
468 );
469 }
470
471 let mut weekdays_col = div()
473 .relative()
474 .w(px(WEEKDAY_W))
475 .h(px(grid_h))
476 .flex_shrink_0();
477 for row in 0..7 {
478 let dow = (row + self.week_starts_on as usize) % 7;
479 if dow % 2 == 1 {
480 weekdays_col = weekdays_col.child(
481 div()
482 .absolute()
483 .left(px(0.0))
484 .top(px(row as f32 * CELL_STEP - 1.0))
485 .text_size(px(10.0))
486 .text_color(colors.text_muted)
487 .child(weekday_short(dow)),
488 );
489 }
490 }
491
492 let bounds_state = state.clone();
494 let bounds_tracker = canvas(
495 move |bounds, _w, cx| {
496 bounds_state.update(cx, |s, _cx| {
497 s.grid_bounds = bounds;
498 });
499 },
500 |_, _, _, _| {},
501 )
502 .absolute()
503 .inset_0();
504
505 let lead = model.lead;
506 let length = model.length;
507 let weeks = model.weeks;
508 let start_day = model.start_day;
509 let on_select = self.on_select_date.clone();
510
511 let cell_at = move |lx: f32, ly: f32| -> Option<usize> {
512 let col = (lx / CELL_STEP).floor() as isize;
513 let row = (ly / CELL_STEP).floor() as isize;
514 if col < 0 || col >= weeks as isize || !(0..7).contains(&row) {
515 return None;
516 }
517 let raw = (col as usize) * 7 + (row as usize);
518 if raw < lead {
519 return None;
520 }
521 let idx = raw - lead;
522 if idx < length { Some(idx) } else { None }
523 };
524
525 let move_state = state.clone();
526 let down_state = state.clone();
527 let down_cb = on_select.clone();
528 let key_state = state.clone();
529 let key_cb = on_select.clone();
530
531 let mut grid = div()
532 .id(self.id.clone())
533 .role(Role::Group)
534 .aria_label(self.label.clone())
535 .track_focus(&snap.focus_handle)
536 .relative()
537 .w(px(grid_w))
538 .h(px(grid_h))
539 .on_mouse_move(move |ev: &MouseMoveEvent, _w, cx| {
540 move_state.update(cx, |s, cx| {
541 let b = s.grid_bounds;
542 let lx: f32 = (ev.position.x - b.origin.x).into();
543 let ly: f32 = (ev.position.y - b.origin.y).into();
544 let bw: f32 = b.size.width.into();
545 let bh: f32 = b.size.height.into();
546 if lx < 0.0 || ly < 0.0 || lx > bw || ly > bh {
547 if s.hover_index.is_some() {
548 s.hover_index = None;
549 cx.notify();
550 }
551 return;
552 }
553 let next = cell_at(lx, ly);
554 if s.hover_index != next {
555 s.hover_index = next;
556 cx.notify();
557 }
558 });
559 })
560 .on_mouse_down(MouseButton::Left, move |ev: &MouseDownEvent, window, cx| {
561 let (fh, hit) = {
562 let s = down_state.read(cx);
563 let b = s.grid_bounds;
564 let lx: f32 = (ev.position.x - b.origin.x).into();
565 let ly: f32 = (ev.position.y - b.origin.y).into();
566 (s.focus_handle.clone(), cell_at(lx, ly))
567 };
568 window.focus(&fh, cx);
569 down_state.update(cx, |s, cx| {
570 s.hover_index = hit;
571 cx.notify();
572 });
573 if let (Some(idx), Some(cb)) = (hit, &down_cb) {
574 cb(
575 SharedString::from(format_iso_day(start_day + idx as i64)),
576 window,
577 cx,
578 );
579 }
580 })
581 .on_key_down(move |ev: &KeyDownEvent, window, cx| {
582 if length == 0 {
583 return;
584 }
585 let key = ev.keystroke.key.as_str();
586 let current = key_state
587 .read(cx)
588 .hover_index
589 .or(selected_index)
590 .unwrap_or(length.saturating_sub(1));
591
592 if key == "escape" {
593 key_state.update(cx, |s, cx| {
594 s.hover_index = None;
595 cx.notify();
596 });
597 return;
598 }
599 if key == "enter" || key == "space" {
600 cx.stop_propagation();
601 if let Some(cb) = &key_cb {
602 cb(
603 SharedString::from(format_iso_day(start_day + current as i64)),
604 window,
605 cx,
606 );
607 }
608 return;
609 }
610
611 let next = match key {
612 "up" => Some(current.saturating_sub(1)),
613 "down" => Some((current + 1).min(length - 1)),
614 "left" => Some(current.saturating_sub(7)),
615 "right" => Some((current + 7).min(length - 1)),
616 "home" => Some(0),
617 "end" => Some(length - 1),
618 _ => None,
619 };
620 if let Some(n) = next {
621 cx.stop_propagation();
622 key_state.update(cx, |s, cx| {
623 s.hover_index = Some(n);
624 cx.notify();
625 });
626 }
627 })
628 .child(bounds_tracker);
629
630 let max_diag = (model.weeks.saturating_sub(1) + 6).max(1) as f32;
632 for idx in 0..model.length {
633 let slot = idx + model.lead;
634 let col = slot / 7;
635 let row = slot % 7;
636 let lvl = model.levels[idx];
637 let diag = (col + row) as f32 / max_diag;
638 let delay = diag * 0.34;
639 let local_p = ((reveal_p - delay) / (1.0 - delay).max(0.01)).clamp(0.0, 1.0);
640 let dimmed = highlight_level.map(|h| h != lvl).unwrap_or(false);
641 let is_hovered = snap.hover_index == Some(idx);
642 let alpha = local_p * if dimmed { 0.22 } else { 1.0 };
643
644 let mut cell = div()
645 .absolute()
646 .left(px(col as f32 * CELL_STEP))
647 .top(px(row as f32 * CELL_STEP))
648 .w(px(CELL_SIZE))
649 .h(px(CELL_SIZE))
650 .rounded(px(2.5))
651 .bg(level_color(lvl).opacity(alpha))
652 .cursor_pointer();
653
654 if lvl == 0 {
655 cell = cell
656 .border_1()
657 .border_color(colors.border.opacity(alpha * 0.45));
658 }
659 if is_hovered {
660 cell = cell.border_1().border_color(colors.foreground);
661 }
662 grid = grid.child(cell);
663 }
664
665 if let Some(sel_idx) = selected_index {
667 let slot = sel_idx + model.lead;
668 let col = slot / 7;
669 let row = slot % 7;
670 grid = grid.child(
671 div()
672 .absolute()
673 .left(px(col as f32 * CELL_STEP - 2.0))
674 .top(px(row as f32 * CELL_STEP - 2.0))
675 .w(px(CELL_SIZE + 4.0))
676 .h(px(CELL_SIZE + 4.0))
677 .rounded(px(4.0))
678 .border_2()
679 .border_color(colors.foreground),
680 );
681 }
682
683 if let Some(idx) = snap.hover_index.filter(|&i| i < model.length) {
685 let slot = idx + model.lead;
686 let col = slot / 7;
687 let row = slot % 7;
688 let cx_px = col as f32 * CELL_STEP + CELL_SIZE * 0.5;
689 let cy_px = row as f32 * CELL_STEP;
690 let count = model.counts[idx];
691 let day = model.start_day + idx as i64;
692 let (y, m, d) = civil_from_day(day);
693 let dow = weekday_short(weekday_of_day(day));
694 let primary = if count > 0 {
695 format!(
696 "{} {}",
697 format_grouped(count as f64, 0),
698 self.unit.noun(count as u64)
699 )
700 } else {
701 format!("No {}", self.unit.other)
702 };
703 let secondary = format!("{dow}, {} {d}, {y}", month_short(m));
704
705 let tip_w = 168.0f32;
706 let tip_h = 48.0f32;
707 let left = (cx_px - tip_w * 0.5).clamp(0.0, (grid_w - tip_w).max(0.0));
708 let top = if cy_px - tip_h - 8.0 >= -MONTH_H {
709 cy_px - tip_h - 8.0
710 } else {
711 cy_px + CELL_SIZE + 8.0
712 };
713
714 grid = grid.child(
715 div()
716 .absolute()
717 .left(px(left))
718 .top(px(top))
719 .w(px(tip_w))
720 .px(Spacing::S2)
721 .py(px(6.0))
722 .rounded(Radii::CONTROL)
723 .bg(colors.surface_raised)
724 .border_1()
725 .border_color(colors.border)
726 .shadow_md()
727 .flex()
728 .flex_col()
729 .gap(px(1.0))
730 .child(
731 div()
732 .text_size(Typography::TEXT_XS)
733 .font_semibold()
734 .text_color(colors.foreground)
735 .child(primary),
736 )
737 .child(
738 div()
739 .text_size(px(11.0))
740 .text_color(colors.text_muted)
741 .child(secondary),
742 ),
743 );
744 }
745
746 let calendar = div().w_full().overflow_hidden().child(
748 div()
749 .flex()
750 .flex_col()
751 .child(months_row)
752 .child(div().flex().items_start().child(weekdays_col).child(grid)),
753 );
754
755 let [t1, t2, t3] = model.thresholds;
757 let caption = if let Some(lvl) = highlight_level {
758 let days_n = model.per_level[(lvl as usize).min(4)];
759 let day_word = if days_n == 1 { "day" } else { "days" };
760 let range_desc = match lvl {
761 0 => format!("no {}", self.unit.other),
762 1 => {
763 if t1 == 1 {
764 format!("1 {}", self.unit.one)
765 } else {
766 format!("1–{t1} {}", self.unit.other)
767 }
768 }
769 2 => format!("{}–{t2} {}", t1 + 1, self.unit.other),
770 3 => format!("{}–{t3} {}", t2 + 1, self.unit.other),
771 _ => format!("{}+ {}", t3 + 1, self.unit.other),
772 };
773 format!(
774 "{} {day_word} with {range_desc}",
775 format_grouped(days_n as f64, 0)
776 )
777 } else {
778 String::new()
779 };
780
781 let mut swatches = div().flex().items_center().gap(px(4.0));
782 for lvl in 0u8..=4 {
783 let hover_st = state.clone();
784 let click_st = state.clone();
785 let is_pinned = snap.pinned_level == Some(lvl);
786 let is_hl = highlight_level == Some(lvl);
787
788 swatches = swatches.child(
789 div()
790 .id(ElementId::NamedChild(
791 self.id.clone().into(),
792 SharedString::from(format!("heatmap-level-{lvl}")),
793 ))
794 .w(px(12.0))
795 .h(px(12.0))
796 .rounded(px(2.5))
797 .bg(level_color(lvl))
798 .border_1()
799 .border_color(if is_pinned || is_hl {
800 colors.foreground
801 } else {
802 colors.border.opacity(0.6)
803 })
804 .cursor_pointer()
805 .on_hover(move |hovered, _w, cx| {
806 hover_st.update(cx, |s, cx| {
807 if *hovered {
808 s.preview_level = Some(lvl);
809 } else if s.preview_level == Some(lvl) {
810 s.preview_level = None;
811 }
812 cx.notify();
813 });
814 })
815 .on_mouse_down(MouseButton::Left, move |_, _w, cx| {
816 click_st.update(cx, |s, cx| {
817 s.pinned_level = if s.pinned_level == Some(lvl) {
818 None
819 } else {
820 Some(lvl)
821 };
822 cx.notify();
823 });
824 }),
825 );
826 }
827
828 let footer = div()
829 .w_full()
830 .mt(Spacing::S3)
831 .flex()
832 .items_center()
833 .justify_between()
834 .gap(Spacing::S3)
835 .child(
836 div()
837 .text_size(px(11.0))
838 .text_color(colors.text_muted)
839 .min_h(px(16.0))
840 .child(caption),
841 )
842 .child(
843 div()
844 .flex()
845 .items_center()
846 .gap(px(6.0))
847 .text_size(px(11.0))
848 .text_color(colors.text_muted)
849 .child("Less")
850 .child(swatches)
851 .child("More"),
852 );
853
854 div()
855 .w_full()
856 .flex()
857 .flex_col()
858 .child(header)
859 .child(calendar)
860 .child(footer)
861 }
862}
863
864#[cfg(test)]
865mod tests {
866 use super::*;
867
868 #[test]
869 fn activity_heatmap_calendar_and_quartile_levels() {
870 let d = parse_iso_day("2025-01-01").unwrap();
871 assert_eq!(format_iso_day(d), "2025-01-01");
872 assert_eq!(weekday_of_day(d), 3);
874
875 let days = vec![
876 ActivityDay::new("2025-01-01", 0),
877 ActivityDay::new("2025-01-02", 2),
878 ActivityDay::new("2025-01-04", 12), ];
880 let model = build_activity_heatmap_model(&days, 0, None);
881 assert_eq!(model.length, 4);
882 assert_eq!(model.counts, vec![0, 2, 0, 12]);
883 assert_eq!(model.total, 14);
884 assert_eq!(model.thresholds, [3, 6, 9]);
886 assert_eq!(model.levels, vec![0, 1, 0, 4]);
887 assert_eq!(model.per_level, [2, 1, 0, 0, 1]);
888 }
889}