use std::{
cell::RefCell,
collections::{BTreeMap, HashSet},
rc::Rc,
};
use arc_motion::{
CubicBezier, arc_spring_with_options, is_reduced_motion, motion_now, spring::SpringOptions,
};
use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, SpringSpec, Typography, oklab_mix};
use gpui_kit::{
AnyElement, App, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
ParentElement, PathBuilder, RenderOnce, Role, SharedString, Styled, Window,
base::StyledExt as _, canvas, div, point, prelude::*, px,
};
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum TimelineTone {
#[default]
Neutral,
Success,
Danger,
}
#[derive(Clone, Debug)]
pub struct TimelineEvent {
pub id: SharedString,
pub at_ms: i64,
pub actor: Option<SharedString>,
pub title: SharedString,
pub meta: Option<SharedString>,
pub detail: Option<SharedString>,
pub avatar_initials: Option<SharedString>,
pub tone: TimelineTone,
}
impl TimelineEvent {
pub fn new(id: impl Into<SharedString>, at_ms: i64, title: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
at_ms,
actor: None,
title: title.into(),
meta: None,
detail: None,
avatar_initials: None,
tone: TimelineTone::Neutral,
}
}
pub fn actor(mut self, actor: impl Into<SharedString>) -> Self {
let name: SharedString = actor.into();
if self.avatar_initials.is_none() {
let initials: String = name
.split_whitespace()
.filter_map(|w| w.chars().next())
.take(2)
.collect::<String>()
.to_uppercase();
if !initials.is_empty() {
self.avatar_initials = Some(SharedString::from(initials));
}
}
self.actor = Some(name);
self
}
pub fn meta(mut self, meta: impl Into<SharedString>) -> Self {
self.meta = Some(meta.into());
self
}
pub fn detail(mut self, detail: impl Into<SharedString>) -> Self {
self.detail = Some(detail.into());
self
}
pub fn avatar_initials(mut self, initials: impl Into<SharedString>) -> Self {
self.avatar_initials = Some(initials.into());
self
}
pub fn tone(mut self, tone: TimelineTone) -> Self {
self.tone = tone;
self
}
}
#[derive(Clone, Debug)]
pub struct TimelineDayGroup {
pub day_index: i64,
pub label: SharedString,
pub events: Vec<TimelineEvent>,
}
const DAY_MS: i64 = 86_400_000;
const HOUR_MS: i64 = 3_600_000;
fn civil_from_days(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) as u32;
let m = (if mp < 10 { mp + 3 } else { mp - 9 }) as u32;
let year = if m <= 2 { y + 1 } else { y };
(year, m, d)
}
fn format_day_label(day_index: i64, today_index: i64) -> SharedString {
if day_index == today_index {
return SharedString::from("Today");
}
if day_index == today_index - 1 {
return SharedString::from("Yesterday");
}
let (y, m, d) = civil_from_days(day_index);
const MONTHS: [&str; 12] = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
];
let mon = MONTHS
.get((m.saturating_sub(1)) as usize)
.copied()
.unwrap_or("Jan");
SharedString::from(format!("{mon} {d}, {y}"))
}
pub fn format_timeline_relative(at_ms: i64, now_ms: i64) -> SharedString {
let diff = (now_ms - at_ms).max(0);
let mins = diff / 60_000;
if mins < 1 {
SharedString::from("Now")
} else if mins < 60 {
SharedString::from(format!("{mins}m"))
} else if diff < 24 * HOUR_MS {
SharedString::from(format!("{}h", mins / 60))
} else {
let secs_in_day = at_ms.rem_euclid(DAY_MS) / 1000;
let h = secs_in_day / 3600;
let m = (secs_in_day % 3600) / 60;
SharedString::from(format!("{h:02}:{m:02}"))
}
}
pub fn group_timeline_events(events: &[TimelineEvent], now_ms: i64) -> Vec<TimelineDayGroup> {
let today_idx = now_ms.div_euclid(DAY_MS);
let mut sorted = events.to_vec();
sorted.sort_by_key(|event| std::cmp::Reverse(event.at_ms));
let mut by_day: BTreeMap<i64, Vec<TimelineEvent>> = BTreeMap::new();
for ev in sorted {
let idx = ev.at_ms.div_euclid(DAY_MS);
by_day.entry(idx).or_default().push(ev);
}
by_day
.into_iter()
.rev()
.map(|(day_index, list)| TimelineDayGroup {
day_index,
label: format_day_label(day_index, today_idx),
events: list,
})
.collect()
}
fn paint_chevron_down(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
let rad = angle_deg.to_radians();
let (c, s) = (rad.cos(), rad.sin());
let rot = |dx: f32, dy: f32| point(px(cx + dx * c - dy * s), px(cy + dx * s + dy * c));
let mut pb = PathBuilder::stroke(px(1.6));
pb.move_to(rot(-3.8, -1.8));
pb.line_to(rot(0.0, 2.2));
pb.line_to(rot(3.8, -1.8));
if let Ok(path) = pb.build() {
window.paint_path(path, color);
}
}
fn paint_tone_glyph(cx: f32, cy: f32, tone: TimelineTone, color: Hsla, window: &mut Window) {
match tone {
TimelineTone::Success => {
let mut pb = PathBuilder::stroke(px(1.8));
pb.move_to(point(px(cx - 4.0), px(cy + 0.4)));
pb.line_to(point(px(cx - 1.2), px(cy + 3.2)));
pb.line_to(point(px(cx + 4.4), px(cy - 3.0)));
if let Ok(p) = pb.build() {
window.paint_path(p, color);
}
}
TimelineTone::Danger => {
let mut pb = PathBuilder::stroke(px(1.8));
pb.move_to(point(px(cx), px(cy - 4.0)));
pb.line_to(point(px(cx), px(cy + 1.0)));
if let Ok(p) = pb.build() {
window.paint_path(p, color);
}
let dot = gpui_kit::Bounds::new(
point(px(cx - 1.1), px(cy + 2.6)),
gpui_kit::size(px(2.2), px(2.2)),
);
window.paint_quad(gpui_kit::fill(dot, color).corner_radii(px(1.1)));
}
TimelineTone::Neutral => {
let dot = gpui_kit::Bounds::new(
point(px(cx - 3.0), px(cy - 3.0)),
gpui_kit::size(px(6.0), px(6.0)),
);
window.paint_quad(gpui_kit::fill(dot, color).corner_radii(px(3.0)));
}
}
}
#[derive(Clone)]
struct TimelineInternal {
expanded: HashSet<SharedString>,
focused_id: Option<SharedString>,
mounted_at: f64,
known_ids: HashSet<SharedString>,
fresh_times: std::collections::HashMap<SharedString, f64>,
focus_handle: FocusHandle,
}
#[derive(IntoElement)]
pub struct Timeline {
id: ElementId,
label: SharedString,
events: Vec<TimelineEvent>,
now_ms: i64,
default_expanded: Vec<SharedString>,
}
impl Timeline {
pub fn new(
id: impl Into<ElementId>,
label: impl Into<SharedString>,
events: impl IntoIterator<Item = TimelineEvent>,
now_ms: i64,
) -> Self {
Self {
id: id.into(),
label: label.into(),
events: events.into_iter().collect(),
now_ms,
default_expanded: Vec::new(),
}
}
pub fn default_expanded(
mut self,
ids: impl IntoIterator<Item = impl Into<SharedString>>,
) -> Self {
self.default_expanded = ids.into_iter().map(Into::into).collect();
self
}
}
impl RenderOnce for Timeline {
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 groups = group_timeline_events(&self.events, self.now_ms);
let initial_ids: HashSet<SharedString> = self.events.iter().map(|e| e.id.clone()).collect();
let state_cell = window
.use_keyed_state(
ElementId::NamedChild(self.id.clone().into(), SharedString::from("tl-state")),
cx,
|_, cx| {
Rc::new(RefCell::new(TimelineInternal {
expanded: self.default_expanded.iter().cloned().collect(),
focused_id: None,
mounted_at: now,
known_ids: initial_ids,
fresh_times: std::collections::HashMap::new(),
focus_handle: cx.focus_handle(),
}))
},
)
.read(cx)
.clone();
let (expanded_set, focused_id, mounted_at, fresh_map, focus_handle) = {
let mut st = state_cell.borrow_mut();
for ev in &self.events {
if !st.known_ids.contains(&ev.id) {
st.known_ids.insert(ev.id.clone());
st.fresh_times.insert(ev.id.clone(), now);
}
}
let elapsed_mount = (now - st.mounted_at).max(0.0);
if !reduced && elapsed_mount < 1.1 {
window.request_animation_frame();
}
if !reduced && st.fresh_times.values().any(|t| (now - *t) < 0.5) {
window.request_animation_frame();
}
(
st.expanded.clone(),
st.focused_id.clone(),
st.mounted_at,
st.fresh_times.clone(),
st.focus_handle.clone(),
)
};
let expandable_order: Vec<SharedString> = groups
.iter()
.flat_map(|g| g.events.iter())
.filter(|e| e.detail.is_some())
.map(|e| e.id.clone())
.collect();
let state_for_key = state_cell.clone();
let exp_order_for_key = expandable_order.clone();
let mut root = div()
.id(self.id.clone())
.w_full()
.flex()
.flex_col()
.gap(Spacing::S5)
.track_focus(&focus_handle)
.role(Role::List)
.aria_label(self.label.clone())
.on_key_down(move |ev: &KeyDownEvent, window, _cx| {
if exp_order_for_key.is_empty() {
return;
}
let key = ev.keystroke.key.as_str();
let mut st = state_for_key.borrow_mut();
let cur_idx = st
.focused_id
.as_ref()
.and_then(|id| exp_order_for_key.iter().position(|x| x == id))
.unwrap_or(0);
match key {
"down" => {
let next = (cur_idx + 1).min(exp_order_for_key.len() - 1);
st.focused_id = Some(exp_order_for_key[next].clone());
window.refresh();
}
"up" => {
let next = cur_idx.saturating_sub(1);
st.focused_id = Some(exp_order_for_key[next].clone());
window.refresh();
}
"home" => {
st.focused_id = Some(exp_order_for_key[0].clone());
window.refresh();
}
"end" => {
st.focused_id = exp_order_for_key.last().cloned();
window.refresh();
}
"enter" | "space" => {
let id = st
.focused_id
.clone()
.unwrap_or_else(|| exp_order_for_key[0].clone());
if !st.expanded.remove(&id) {
st.expanded.insert(id);
}
window.refresh();
}
_ => {}
}
});
let mut global_row_idx = 0usize;
for group in groups {
let count_text = format!("{}", group.events.len());
let mut section = div().w_full().flex().flex_col().gap(Spacing::S2).child(
div()
.flex()
.flex_row()
.items_center()
.justify_between()
.pb(Spacing::S1)
.border_b_1()
.border_color(colors.border)
.child(
div()
.text_size(Typography::TEXT_XS)
.font_medium()
.text_color(colors.text_muted)
.child(group.label.clone()),
)
.child(
div()
.px(px(7.0))
.py(px(1.0))
.rounded(Radii::PILL)
.bg(colors.surface_muted)
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(count_text),
),
);
let row_count = group.events.len();
let mut list = div().w_full().flex().flex_col();
for (idx, ev) in group.events.into_iter().enumerate() {
let is_last = idx + 1 == row_count;
let has_detail = ev.detail.is_some();
let is_open = has_detail && expanded_set.contains(&ev.id);
let is_focused = focused_id.as_ref() == Some(&ev.id);
let stagger_delay = (global_row_idx as f64) * 0.06;
global_row_idx += 1;
let reveal_t = if reduced {
1.0
} else {
let dt = (now - mounted_at - stagger_delay).max(0.0);
CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample((dt / 0.28).clamp(0.0, 1.0) as f32)
};
let fresh_offset_y: f32 = if let Some(&t0) = fresh_map.get(&ev.id) {
if reduced {
0.0
} else {
let p = CubicBezier::new(0.16, 1.0, 0.3, 1.0)
.sample(((now - t0).max(0.0) / 0.30).clamp(0.0, 1.0) as f32);
-10.0 * (1.0 - p)
}
} else {
0.0
};
let chev_deg = arc_spring_with_options(
(
self.id.clone(),
SharedString::from(format!("tl-chev-{}", ev.id)),
),
if is_open { 180.0 } else { 0.0 },
SpringOptions::new(SpringSpec::visual(0.22, 0.0)),
window,
cx,
)
.value;
let (marker_bg, marker_fg) = if ev.avatar_initials.is_some() {
(
oklab_mix(colors.accent, colors.surface_muted, 0.16),
colors.accent,
)
} else {
match ev.tone {
TimelineTone::Success => (
oklab_mix(colors.success, colors.surface_muted, 0.18),
colors.success,
),
TimelineTone::Danger => (
oklab_mix(colors.danger, colors.surface_muted, 0.18),
colors.danger,
),
TimelineTone::Neutral => (colors.surface_muted, colors.text_muted),
}
};
let marker_el: AnyElement = if let Some(initials) = ev.avatar_initials.clone() {
div()
.w(px(28.0))
.h(px(28.0))
.rounded(Radii::PILL)
.bg(marker_bg)
.border_1()
.border_color(colors.border)
.flex()
.items_center()
.justify_center()
.text_size(px(11.0))
.font_medium()
.text_color(marker_fg)
.child(initials)
.into_any_element()
} else {
let tone = ev.tone;
div()
.w(px(28.0))
.h(px(28.0))
.rounded(Radii::PILL)
.bg(marker_bg)
.border_1()
.border_color(colors.border)
.child(
canvas(
|_, _, _| {},
move |bounds, _, window, _| {
let cx_p = f32::from(bounds.origin.x)
+ f32::from(bounds.size.width) * 0.5;
let cy_p = f32::from(bounds.origin.y)
+ f32::from(bounds.size.height) * 0.5;
paint_tone_glyph(cx_p, cy_p, tone, marker_fg, window);
},
)
.w_full()
.h_full(),
)
.into_any_element()
};
let rail_col = colors.border;
let rail_progress = reveal_t;
let left_rail = div()
.w(px(28.0))
.flex_none()
.flex()
.flex_col()
.items_center()
.child(marker_el)
.when(!is_last, |this| {
this.child(
div()
.w(px(2.0))
.flex_1()
.min_h(px(18.0))
.mt(px(4.0))
.mb(px(2.0))
.child(
canvas(
|_, _, _| {},
move |bounds, _, window, _| {
let h = f32::from(bounds.size.height) * rail_progress;
if h <= 0.5 {
return;
}
let seg = gpui_kit::Bounds::new(
bounds.origin,
gpui_kit::size(bounds.size.width, px(h)),
);
window.paint_quad(gpui_kit::fill(seg, rail_col));
},
)
.w_full()
.h_full(),
),
)
});
let time_label = format_timeline_relative(ev.at_ms, self.now_ms);
let title_line = div()
.flex()
.flex_row()
.flex_wrap()
.items_baseline()
.gap(px(5.0))
.when_some(ev.actor.clone(), |this, actor| {
this.child(
div()
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(colors.foreground)
.child(actor),
)
})
.child(
div()
.text_size(Typography::TEXT_SM)
.text_color(if ev.actor.is_some() {
colors.text_secondary
} else {
colors.foreground
})
.child(ev.title.clone()),
);
let ev_id_click = ev.id.clone();
let st_click = state_cell.clone();
let fh_click = focus_handle.clone();
let chev_col = colors.text_muted;
let mut header = div()
.w_full()
.px(Spacing::S2)
.py(px(5.0))
.rounded(Radii::CONTROL)
.flex()
.flex_row()
.items_start()
.justify_between()
.gap(Spacing::S3)
.when(is_focused, |this| {
this.bg(oklab_mix(colors.accent, colors.surface, 0.08))
})
.when(has_detail, |this| {
this.cursor_pointer()
.hover(|h| h.bg(colors.surface_muted))
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
window.focus(&fh_click, cx);
let mut st = st_click.borrow_mut();
st.focused_id = Some(ev_id_click.clone());
if !st.expanded.remove(&ev_id_click) {
st.expanded.insert(ev_id_click.clone());
}
window.refresh();
})
})
.child(
div()
.flex_1()
.min_w(px(0.0))
.flex()
.flex_col()
.gap(px(2.0))
.child(title_line)
.when_some(ev.meta.clone(), |this, meta| {
this.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(meta),
)
}),
)
.child(
div()
.flex_none()
.flex()
.flex_row()
.items_center()
.gap(Spacing::S2)
.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(time_label),
)
.when(has_detail, |this| {
this.child(
div().w(px(16.0)).h(px(16.0)).child(
canvas(
|_, _, _| {},
move |bounds, _, window, _| {
let cx_p = f32::from(bounds.origin.x)
+ f32::from(bounds.size.width) * 0.5;
let cy_p = f32::from(bounds.origin.y)
+ f32::from(bounds.size.height) * 0.5;
paint_chevron_down(
cx_p, cy_p, chev_deg, chev_col, window,
);
},
)
.w_full()
.h_full(),
),
)
}),
);
if fresh_offset_y.abs() > 0.1 {
header = header.mt(px(fresh_offset_y));
}
let mut body = div()
.flex_1()
.min_w(px(0.0))
.pb(if is_last { px(0.0) } else { Spacing::S3 })
.flex()
.flex_col()
.child(header);
if is_open && let Some(detail) = ev.detail {
body = body.child(
div()
.mt(Spacing::S2)
.ml(Spacing::S2)
.p(Spacing::S3)
.rounded(Radii::CONTROL)
.border_1()
.border_color(colors.border)
.bg(colors.surface_muted)
.text_size(Typography::TEXT_SM)
.text_color(colors.text_secondary)
.child(detail),
);
}
list = list.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("tl-row-{}", ev.id)),
))
.w_full()
.flex()
.flex_row()
.items_stretch()
.gap(Spacing::S3)
.opacity(reveal_t)
.role(Role::ListItem)
.child(left_rail)
.child(body),
);
}
section = section.child(list);
root = root.child(section);
}
root
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn groups_by_day_descending_and_formats_relative_times() {
let now_ms = 1_750_000_000_000_i64; let events = vec![
TimelineEvent::new("old", now_ms - DAY_MS - 3_600_000, "Yesterday deploy"),
TimelineEvent::new("recent", now_ms - 120_000, "Merged PR"),
TimelineEvent::new("newest", now_ms - 10_000, "Build green"),
];
let groups = group_timeline_events(&events, now_ms);
assert_eq!(groups.len(), 2);
assert_eq!(groups[0].label.as_ref(), "Today");
assert_eq!(groups[0].events[0].id.as_ref(), "newest");
assert_eq!(groups[0].events[1].id.as_ref(), "recent");
assert_eq!(groups[1].label.as_ref(), "Yesterday");
assert_eq!(
format_timeline_relative(now_ms - 10_000, now_ms).as_ref(),
"Now"
);
assert_eq!(
format_timeline_relative(now_ms - 300_000, now_ms).as_ref(),
"5m"
);
assert_eq!(
format_timeline_relative(now_ms - 7_200_000, now_ms).as_ref(),
"2h"
);
}
}