Skip to main content

arc_ui/data/
timeline.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/timeline/timeline.tsx` & `.module.css`
3//!
4//! P6 Component #9: `timeline`
5//!
6//! - Vertical activity feed grouped by day (`Today` / `Yesterday` / formatted date) with
7//!   descending chronological order, rolling per-day update count, semantic tone markers,
8//!   animated connector rail segments, expandable row details (`Enter`/`Space` or click),
9//!   and keyboard vertical focus navigation (`ArrowUp`/`ArrowDown`/`Home`/`End`).
10
11use std::{
12    cell::RefCell,
13    collections::{BTreeMap, HashSet},
14    rc::Rc,
15};
16
17use arc_motion::{
18    CubicBezier, arc_spring_with_options, is_reduced_motion, motion_now, spring::SpringOptions,
19};
20use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, SpringSpec, Typography, oklab_mix};
21use gpui_kit::{
22    AnyElement, App, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
23    ParentElement, PathBuilder, RenderOnce, Role, SharedString, Styled, Window,
24    base::StyledExt as _, canvas, div, point, prelude::*, px,
25};
26
27/// Status tone for a system event marker.
28#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
29pub enum TimelineTone {
30    #[default]
31    Neutral,
32    Success,
33    Danger,
34}
35
36/// One event entry displayed in [`Timeline`].
37#[derive(Clone, Debug)]
38pub struct TimelineEvent {
39    pub id: SharedString,
40    /// Epoch milliseconds when this event happened.
41    pub at_ms: i64,
42    /// Optional human actor name shown before the title.
43    pub actor: Option<SharedString>,
44    /// What happened.
45    pub title: SharedString,
46    /// Optional short metadata line (PR, commit, build).
47    pub meta: Option<SharedString>,
48    /// Optional expandable detail text shown when toggled open.
49    pub detail: Option<SharedString>,
50    /// Optional initials badge for a human actor (when absent, uses tone marker).
51    pub avatar_initials: Option<SharedString>,
52    /// Semantic tone when rendered as a system event.
53    pub tone: TimelineTone,
54}
55
56impl TimelineEvent {
57    pub fn new(id: impl Into<SharedString>, at_ms: i64, title: impl Into<SharedString>) -> Self {
58        Self {
59            id: id.into(),
60            at_ms,
61            actor: None,
62            title: title.into(),
63            meta: None,
64            detail: None,
65            avatar_initials: None,
66            tone: TimelineTone::Neutral,
67        }
68    }
69
70    pub fn actor(mut self, actor: impl Into<SharedString>) -> Self {
71        let name: SharedString = actor.into();
72        if self.avatar_initials.is_none() {
73            let initials: String = name
74                .split_whitespace()
75                .filter_map(|w| w.chars().next())
76                .take(2)
77                .collect::<String>()
78                .to_uppercase();
79            if !initials.is_empty() {
80                self.avatar_initials = Some(SharedString::from(initials));
81            }
82        }
83        self.actor = Some(name);
84        self
85    }
86
87    pub fn meta(mut self, meta: impl Into<SharedString>) -> Self {
88        self.meta = Some(meta.into());
89        self
90    }
91
92    pub fn detail(mut self, detail: impl Into<SharedString>) -> Self {
93        self.detail = Some(detail.into());
94        self
95    }
96
97    pub fn avatar_initials(mut self, initials: impl Into<SharedString>) -> Self {
98        self.avatar_initials = Some(initials.into());
99        self
100    }
101
102    pub fn tone(mut self, tone: TimelineTone) -> Self {
103        self.tone = tone;
104        self
105    }
106}
107
108/// Day group produced by [`group_timeline_events`].
109#[derive(Clone, Debug)]
110pub struct TimelineDayGroup {
111    pub day_index: i64,
112    pub label: SharedString,
113    pub events: Vec<TimelineEvent>,
114}
115
116const DAY_MS: i64 = 86_400_000;
117const HOUR_MS: i64 = 3_600_000;
118
119/// Converts epoch milliseconds (UTC) into a civil `(year, month, day)` triple (Howard Hinnant algorithm).
120fn civil_from_days(z: i64) -> (i64, u32, u32) {
121    let z = z + 719_468;
122    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
123    let doe = (z - era * 146_097) as u64;
124    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
125    let y = yoe as i64 + era * 400;
126    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
127    let mp = (5 * doy + 2) / 153;
128    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
129    let m = (if mp < 10 { mp + 3 } else { mp - 9 }) as u32;
130    let year = if m <= 2 { y + 1 } else { y };
131    (year, m, d)
132}
133
134fn format_day_label(day_index: i64, today_index: i64) -> SharedString {
135    if day_index == today_index {
136        return SharedString::from("Today");
137    }
138    if day_index == today_index - 1 {
139        return SharedString::from("Yesterday");
140    }
141    let (y, m, d) = civil_from_days(day_index);
142    const MONTHS: [&str; 12] = [
143        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
144    ];
145    let mon = MONTHS
146        .get((m.saturating_sub(1)) as usize)
147        .copied()
148        .unwrap_or("Jan");
149    SharedString::from(format!("{mon} {d}, {y}"))
150}
151
152/// Formats relative time label (`Now`, `12m`, `3h`, or `HH:MM`) relative to `now_ms`.
153pub fn format_timeline_relative(at_ms: i64, now_ms: i64) -> SharedString {
154    let diff = (now_ms - at_ms).max(0);
155    let mins = diff / 60_000;
156    if mins < 1 {
157        SharedString::from("Now")
158    } else if mins < 60 {
159        SharedString::from(format!("{mins}m"))
160    } else if diff < 24 * HOUR_MS {
161        SharedString::from(format!("{}h", mins / 60))
162    } else {
163        let secs_in_day = at_ms.rem_euclid(DAY_MS) / 1000;
164        let h = secs_in_day / 3600;
165        let m = (secs_in_day % 3600) / 60;
166        SharedString::from(format!("{h:02}:{m:02}"))
167    }
168}
169
170/// Groups events by UTC day in reverse chronological order (newest day and newest event first).
171pub fn group_timeline_events(events: &[TimelineEvent], now_ms: i64) -> Vec<TimelineDayGroup> {
172    let today_idx = now_ms.div_euclid(DAY_MS);
173    let mut sorted = events.to_vec();
174    sorted.sort_by_key(|event| std::cmp::Reverse(event.at_ms));
175    let mut by_day: BTreeMap<i64, Vec<TimelineEvent>> = BTreeMap::new();
176    for ev in sorted {
177        let idx = ev.at_ms.div_euclid(DAY_MS);
178        by_day.entry(idx).or_default().push(ev);
179    }
180    by_day
181        .into_iter()
182        .rev()
183        .map(|(day_index, list)| TimelineDayGroup {
184            day_index,
185            label: format_day_label(day_index, today_idx),
186            events: list,
187        })
188        .collect()
189}
190
191fn paint_chevron_down(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
192    let rad = angle_deg.to_radians();
193    let (c, s) = (rad.cos(), rad.sin());
194    let rot = |dx: f32, dy: f32| point(px(cx + dx * c - dy * s), px(cy + dx * s + dy * c));
195    let mut pb = PathBuilder::stroke(px(1.6));
196    pb.move_to(rot(-3.8, -1.8));
197    pb.line_to(rot(0.0, 2.2));
198    pb.line_to(rot(3.8, -1.8));
199    if let Ok(path) = pb.build() {
200        window.paint_path(path, color);
201    }
202}
203
204fn paint_tone_glyph(cx: f32, cy: f32, tone: TimelineTone, color: Hsla, window: &mut Window) {
205    match tone {
206        TimelineTone::Success => {
207            let mut pb = PathBuilder::stroke(px(1.8));
208            pb.move_to(point(px(cx - 4.0), px(cy + 0.4)));
209            pb.line_to(point(px(cx - 1.2), px(cy + 3.2)));
210            pb.line_to(point(px(cx + 4.4), px(cy - 3.0)));
211            if let Ok(p) = pb.build() {
212                window.paint_path(p, color);
213            }
214        }
215        TimelineTone::Danger => {
216            let mut pb = PathBuilder::stroke(px(1.8));
217            pb.move_to(point(px(cx), px(cy - 4.0)));
218            pb.line_to(point(px(cx), px(cy + 1.0)));
219            if let Ok(p) = pb.build() {
220                window.paint_path(p, color);
221            }
222            let dot = gpui_kit::Bounds::new(
223                point(px(cx - 1.1), px(cy + 2.6)),
224                gpui_kit::size(px(2.2), px(2.2)),
225            );
226            window.paint_quad(gpui_kit::fill(dot, color).corner_radii(px(1.1)));
227        }
228        TimelineTone::Neutral => {
229            let dot = gpui_kit::Bounds::new(
230                point(px(cx - 3.0), px(cy - 3.0)),
231                gpui_kit::size(px(6.0), px(6.0)),
232            );
233            window.paint_quad(gpui_kit::fill(dot, color).corner_radii(px(3.0)));
234        }
235    }
236}
237
238#[derive(Clone)]
239struct TimelineInternal {
240    expanded: HashSet<SharedString>,
241    focused_id: Option<SharedString>,
242    mounted_at: f64,
243    known_ids: HashSet<SharedString>,
244    fresh_times: std::collections::HashMap<SharedString, f64>,
245    focus_handle: FocusHandle,
246}
247
248/// Vertical day-grouped activity timeline with expandable details (`timeline`).
249#[derive(IntoElement)]
250pub struct Timeline {
251    id: ElementId,
252    label: SharedString,
253    events: Vec<TimelineEvent>,
254    now_ms: i64,
255    default_expanded: Vec<SharedString>,
256}
257
258impl Timeline {
259    pub fn new(
260        id: impl Into<ElementId>,
261        label: impl Into<SharedString>,
262        events: impl IntoIterator<Item = TimelineEvent>,
263        now_ms: i64,
264    ) -> Self {
265        Self {
266            id: id.into(),
267            label: label.into(),
268            events: events.into_iter().collect(),
269            now_ms,
270            default_expanded: Vec::new(),
271        }
272    }
273
274    pub fn default_expanded(
275        mut self,
276        ids: impl IntoIterator<Item = impl Into<SharedString>>,
277    ) -> Self {
278        self.default_expanded = ids.into_iter().map(Into::into).collect();
279        self
280    }
281}
282
283impl RenderOnce for Timeline {
284    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
285        let theme = cx.arc_theme().clone();
286        let colors = theme.colors;
287        let reduced = is_reduced_motion(cx);
288        let now = motion_now(cx);
289        let groups = group_timeline_events(&self.events, self.now_ms);
290
291        let initial_ids: HashSet<SharedString> = self.events.iter().map(|e| e.id.clone()).collect();
292        let state_cell = window
293            .use_keyed_state(
294                ElementId::NamedChild(self.id.clone().into(), SharedString::from("tl-state")),
295                cx,
296                |_, cx| {
297                    Rc::new(RefCell::new(TimelineInternal {
298                        expanded: self.default_expanded.iter().cloned().collect(),
299                        focused_id: None,
300                        mounted_at: now,
301                        known_ids: initial_ids,
302                        fresh_times: std::collections::HashMap::new(),
303                        focus_handle: cx.focus_handle(),
304                    }))
305                },
306            )
307            .read(cx)
308            .clone();
309
310        let (expanded_set, focused_id, mounted_at, fresh_map, focus_handle) = {
311            let mut st = state_cell.borrow_mut();
312            for ev in &self.events {
313                if !st.known_ids.contains(&ev.id) {
314                    st.known_ids.insert(ev.id.clone());
315                    st.fresh_times.insert(ev.id.clone(), now);
316                }
317            }
318            let elapsed_mount = (now - st.mounted_at).max(0.0);
319            if !reduced && elapsed_mount < 1.1 {
320                window.request_animation_frame();
321            }
322            if !reduced && st.fresh_times.values().any(|t| (now - *t) < 0.5) {
323                window.request_animation_frame();
324            }
325            (
326                st.expanded.clone(),
327                st.focused_id.clone(),
328                st.mounted_at,
329                st.fresh_times.clone(),
330                st.focus_handle.clone(),
331            )
332        };
333
334        let expandable_order: Vec<SharedString> = groups
335            .iter()
336            .flat_map(|g| g.events.iter())
337            .filter(|e| e.detail.is_some())
338            .map(|e| e.id.clone())
339            .collect();
340
341        let state_for_key = state_cell.clone();
342        let exp_order_for_key = expandable_order.clone();
343
344        let mut root = div()
345            .id(self.id.clone())
346            .w_full()
347            .flex()
348            .flex_col()
349            .gap(Spacing::S5)
350            .track_focus(&focus_handle)
351            .role(Role::List)
352            .aria_label(self.label.clone())
353            .on_key_down(move |ev: &KeyDownEvent, window, _cx| {
354                if exp_order_for_key.is_empty() {
355                    return;
356                }
357                let key = ev.keystroke.key.as_str();
358                let mut st = state_for_key.borrow_mut();
359                let cur_idx = st
360                    .focused_id
361                    .as_ref()
362                    .and_then(|id| exp_order_for_key.iter().position(|x| x == id))
363                    .unwrap_or(0);
364                match key {
365                    "down" => {
366                        let next = (cur_idx + 1).min(exp_order_for_key.len() - 1);
367                        st.focused_id = Some(exp_order_for_key[next].clone());
368                        window.refresh();
369                    }
370                    "up" => {
371                        let next = cur_idx.saturating_sub(1);
372                        st.focused_id = Some(exp_order_for_key[next].clone());
373                        window.refresh();
374                    }
375                    "home" => {
376                        st.focused_id = Some(exp_order_for_key[0].clone());
377                        window.refresh();
378                    }
379                    "end" => {
380                        st.focused_id = exp_order_for_key.last().cloned();
381                        window.refresh();
382                    }
383                    "enter" | "space" => {
384                        let id = st
385                            .focused_id
386                            .clone()
387                            .unwrap_or_else(|| exp_order_for_key[0].clone());
388                        if !st.expanded.remove(&id) {
389                            st.expanded.insert(id);
390                        }
391                        window.refresh();
392                    }
393                    _ => {}
394                }
395            });
396
397        let mut global_row_idx = 0usize;
398        for group in groups {
399            let count_text = format!("{}", group.events.len());
400            let mut section = div().w_full().flex().flex_col().gap(Spacing::S2).child(
401                div()
402                    .flex()
403                    .flex_row()
404                    .items_center()
405                    .justify_between()
406                    .pb(Spacing::S1)
407                    .border_b_1()
408                    .border_color(colors.border)
409                    .child(
410                        div()
411                            .text_size(Typography::TEXT_XS)
412                            .font_medium()
413                            .text_color(colors.text_muted)
414                            .child(group.label.clone()),
415                    )
416                    .child(
417                        div()
418                            .px(px(7.0))
419                            .py(px(1.0))
420                            .rounded(Radii::PILL)
421                            .bg(colors.surface_muted)
422                            .text_size(Typography::TEXT_XS)
423                            .text_color(colors.text_muted)
424                            .child(count_text),
425                    ),
426            );
427
428            let row_count = group.events.len();
429            let mut list = div().w_full().flex().flex_col();
430
431            for (idx, ev) in group.events.into_iter().enumerate() {
432                let is_last = idx + 1 == row_count;
433                let has_detail = ev.detail.is_some();
434                let is_open = has_detail && expanded_set.contains(&ev.id);
435                let is_focused = focused_id.as_ref() == Some(&ev.id);
436
437                let stagger_delay = (global_row_idx as f64) * 0.06;
438                global_row_idx += 1;
439                let reveal_t = if reduced {
440                    1.0
441                } else {
442                    let dt = (now - mounted_at - stagger_delay).max(0.0);
443                    CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample((dt / 0.28).clamp(0.0, 1.0) as f32)
444                };
445                let fresh_offset_y: f32 = if let Some(&t0) = fresh_map.get(&ev.id) {
446                    if reduced {
447                        0.0
448                    } else {
449                        let p = CubicBezier::new(0.16, 1.0, 0.3, 1.0)
450                            .sample(((now - t0).max(0.0) / 0.30).clamp(0.0, 1.0) as f32);
451                        -10.0 * (1.0 - p)
452                    }
453                } else {
454                    0.0
455                };
456
457                let chev_deg = arc_spring_with_options(
458                    (
459                        self.id.clone(),
460                        SharedString::from(format!("tl-chev-{}", ev.id)),
461                    ),
462                    if is_open { 180.0 } else { 0.0 },
463                    SpringOptions::new(SpringSpec::visual(0.22, 0.0)),
464                    window,
465                    cx,
466                )
467                .value;
468
469                let (marker_bg, marker_fg) = if ev.avatar_initials.is_some() {
470                    (
471                        oklab_mix(colors.accent, colors.surface_muted, 0.16),
472                        colors.accent,
473                    )
474                } else {
475                    match ev.tone {
476                        TimelineTone::Success => (
477                            oklab_mix(colors.success, colors.surface_muted, 0.18),
478                            colors.success,
479                        ),
480                        TimelineTone::Danger => (
481                            oklab_mix(colors.danger, colors.surface_muted, 0.18),
482                            colors.danger,
483                        ),
484                        TimelineTone::Neutral => (colors.surface_muted, colors.text_muted),
485                    }
486                };
487
488                let marker_el: AnyElement = if let Some(initials) = ev.avatar_initials.clone() {
489                    div()
490                        .w(px(28.0))
491                        .h(px(28.0))
492                        .rounded(Radii::PILL)
493                        .bg(marker_bg)
494                        .border_1()
495                        .border_color(colors.border)
496                        .flex()
497                        .items_center()
498                        .justify_center()
499                        .text_size(px(11.0))
500                        .font_medium()
501                        .text_color(marker_fg)
502                        .child(initials)
503                        .into_any_element()
504                } else {
505                    let tone = ev.tone;
506                    div()
507                        .w(px(28.0))
508                        .h(px(28.0))
509                        .rounded(Radii::PILL)
510                        .bg(marker_bg)
511                        .border_1()
512                        .border_color(colors.border)
513                        .child(
514                            canvas(
515                                |_, _, _| {},
516                                move |bounds, _, window, _| {
517                                    let cx_p = f32::from(bounds.origin.x)
518                                        + f32::from(bounds.size.width) * 0.5;
519                                    let cy_p = f32::from(bounds.origin.y)
520                                        + f32::from(bounds.size.height) * 0.5;
521                                    paint_tone_glyph(cx_p, cy_p, tone, marker_fg, window);
522                                },
523                            )
524                            .w_full()
525                            .h_full(),
526                        )
527                        .into_any_element()
528                };
529
530                let rail_col = colors.border;
531                let rail_progress = reveal_t;
532                let left_rail = div()
533                    .w(px(28.0))
534                    .flex_none()
535                    .flex()
536                    .flex_col()
537                    .items_center()
538                    .child(marker_el)
539                    .when(!is_last, |this| {
540                        this.child(
541                            div()
542                                .w(px(2.0))
543                                .flex_1()
544                                .min_h(px(18.0))
545                                .mt(px(4.0))
546                                .mb(px(2.0))
547                                .child(
548                                    canvas(
549                                        |_, _, _| {},
550                                        move |bounds, _, window, _| {
551                                            let h = f32::from(bounds.size.height) * rail_progress;
552                                            if h <= 0.5 {
553                                                return;
554                                            }
555                                            let seg = gpui_kit::Bounds::new(
556                                                bounds.origin,
557                                                gpui_kit::size(bounds.size.width, px(h)),
558                                            );
559                                            window.paint_quad(gpui_kit::fill(seg, rail_col));
560                                        },
561                                    )
562                                    .w_full()
563                                    .h_full(),
564                                ),
565                        )
566                    });
567
568                let time_label = format_timeline_relative(ev.at_ms, self.now_ms);
569                let title_line = div()
570                    .flex()
571                    .flex_row()
572                    .flex_wrap()
573                    .items_baseline()
574                    .gap(px(5.0))
575                    .when_some(ev.actor.clone(), |this, actor| {
576                        this.child(
577                            div()
578                                .text_size(Typography::TEXT_SM)
579                                .font_medium()
580                                .text_color(colors.foreground)
581                                .child(actor),
582                        )
583                    })
584                    .child(
585                        div()
586                            .text_size(Typography::TEXT_SM)
587                            .text_color(if ev.actor.is_some() {
588                                colors.text_secondary
589                            } else {
590                                colors.foreground
591                            })
592                            .child(ev.title.clone()),
593                    );
594
595                let ev_id_click = ev.id.clone();
596                let st_click = state_cell.clone();
597                let fh_click = focus_handle.clone();
598                let chev_col = colors.text_muted;
599
600                let mut header = div()
601                    .w_full()
602                    .px(Spacing::S2)
603                    .py(px(5.0))
604                    .rounded(Radii::CONTROL)
605                    .flex()
606                    .flex_row()
607                    .items_start()
608                    .justify_between()
609                    .gap(Spacing::S3)
610                    .when(is_focused, |this| {
611                        this.bg(oklab_mix(colors.accent, colors.surface, 0.08))
612                    })
613                    .when(has_detail, |this| {
614                        this.cursor_pointer()
615                            .hover(|h| h.bg(colors.surface_muted))
616                            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
617                                window.focus(&fh_click, cx);
618                                let mut st = st_click.borrow_mut();
619                                st.focused_id = Some(ev_id_click.clone());
620                                if !st.expanded.remove(&ev_id_click) {
621                                    st.expanded.insert(ev_id_click.clone());
622                                }
623                                window.refresh();
624                            })
625                    })
626                    .child(
627                        div()
628                            .flex_1()
629                            .min_w(px(0.0))
630                            .flex()
631                            .flex_col()
632                            .gap(px(2.0))
633                            .child(title_line)
634                            .when_some(ev.meta.clone(), |this, meta| {
635                                this.child(
636                                    div()
637                                        .text_size(Typography::TEXT_XS)
638                                        .text_color(colors.text_muted)
639                                        .child(meta),
640                                )
641                            }),
642                    )
643                    .child(
644                        div()
645                            .flex_none()
646                            .flex()
647                            .flex_row()
648                            .items_center()
649                            .gap(Spacing::S2)
650                            .child(
651                                div()
652                                    .text_size(Typography::TEXT_XS)
653                                    .text_color(colors.text_muted)
654                                    .child(time_label),
655                            )
656                            .when(has_detail, |this| {
657                                this.child(
658                                    div().w(px(16.0)).h(px(16.0)).child(
659                                        canvas(
660                                            |_, _, _| {},
661                                            move |bounds, _, window, _| {
662                                                let cx_p = f32::from(bounds.origin.x)
663                                                    + f32::from(bounds.size.width) * 0.5;
664                                                let cy_p = f32::from(bounds.origin.y)
665                                                    + f32::from(bounds.size.height) * 0.5;
666                                                paint_chevron_down(
667                                                    cx_p, cy_p, chev_deg, chev_col, window,
668                                                );
669                                            },
670                                        )
671                                        .w_full()
672                                        .h_full(),
673                                    ),
674                                )
675                            }),
676                    );
677
678                if fresh_offset_y.abs() > 0.1 {
679                    header = header.mt(px(fresh_offset_y));
680                }
681
682                let mut body = div()
683                    .flex_1()
684                    .min_w(px(0.0))
685                    .pb(if is_last { px(0.0) } else { Spacing::S3 })
686                    .flex()
687                    .flex_col()
688                    .child(header);
689
690                if is_open && let Some(detail) = ev.detail {
691                    body = body.child(
692                        div()
693                            .mt(Spacing::S2)
694                            .ml(Spacing::S2)
695                            .p(Spacing::S3)
696                            .rounded(Radii::CONTROL)
697                            .border_1()
698                            .border_color(colors.border)
699                            .bg(colors.surface_muted)
700                            .text_size(Typography::TEXT_SM)
701                            .text_color(colors.text_secondary)
702                            .child(detail),
703                    );
704                }
705
706                list = list.child(
707                    div()
708                        .id(ElementId::NamedChild(
709                            self.id.clone().into(),
710                            SharedString::from(format!("tl-row-{}", ev.id)),
711                        ))
712                        .w_full()
713                        .flex()
714                        .flex_row()
715                        .items_stretch()
716                        .gap(Spacing::S3)
717                        .opacity(reveal_t)
718                        .role(Role::ListItem)
719                        .child(left_rail)
720                        .child(body),
721                );
722            }
723
724            section = section.child(list);
725            root = root.child(section);
726        }
727
728        root
729    }
730}
731
732#[cfg(test)]
733mod tests {
734    use super::*;
735
736    #[test]
737    fn groups_by_day_descending_and_formats_relative_times() {
738        let now_ms = 1_750_000_000_000_i64; // arbitrary fixed epoch
739        let events = vec![
740            TimelineEvent::new("old", now_ms - DAY_MS - 3_600_000, "Yesterday deploy"),
741            TimelineEvent::new("recent", now_ms - 120_000, "Merged PR"),
742            TimelineEvent::new("newest", now_ms - 10_000, "Build green"),
743        ];
744        let groups = group_timeline_events(&events, now_ms);
745        assert_eq!(groups.len(), 2);
746        assert_eq!(groups[0].label.as_ref(), "Today");
747        assert_eq!(groups[0].events[0].id.as_ref(), "newest");
748        assert_eq!(groups[0].events[1].id.as_ref(), "recent");
749        assert_eq!(groups[1].label.as_ref(), "Yesterday");
750        assert_eq!(
751            format_timeline_relative(now_ms - 10_000, now_ms).as_ref(),
752            "Now"
753        );
754        assert_eq!(
755            format_timeline_relative(now_ms - 300_000, now_ms).as_ref(),
756            "5m"
757        );
758        assert_eq!(
759            format_timeline_relative(now_ms - 7_200_000, now_ms).as_ref(),
760            "2h"
761        );
762    }
763}