Skip to main content

arc_ui/chart/
brush_chart.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/brush-chart/brush-chart.tsx`
3//!
4//! `BrushChart` — focus + overview time-series chart with adaptive 7-point smoothed
5//! envelope band when zoomed out, crisp raw series when zoomed in, event annotation
6//! markers, interactive overview range window (pan, edge resize, drag-to-brush, double-click
7//! reset), spring-animated Y-axis rescaling, and keyboard scrubbing / windowing.
8
9use std::rc::Rc;
10
11use arc_motion::{is_reduced_motion, motion_now};
12use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, Typography, oklab_mix};
13use gpui_kit::{
14    App, Bounds, Context, ElementId, FocusHandle, Hsla, InteractiveElement as _, IntoElement,
15    KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, ParentElement, Pixels, RenderOnce,
16    Role, SharedString, Styled, Window, base::StyledExt as _, canvas, div, point, prelude::*, px,
17};
18
19use super::common::{
20    ChartSpring, build_area_fill, build_band_fill, build_circle_fill, build_polyline_stroke,
21    format_compact, format_grouped, nice_scale,
22};
23
24const DAY_MS: f64 = 86_400_000.0;
25const PLOT_TOP: f32 = 24.0;
26const GRIP_HIT: f32 = 12.0;
27
28/// One timestamped value in `BrushChart`.
29#[derive(Clone, Debug)]
30pub struct BrushChartDatum {
31    /// Epoch milliseconds (ascending order).
32    pub timestamp_ms: f64,
33    pub value: f64,
34}
35
36impl BrushChartDatum {
37    pub fn new(timestamp_ms: f64, value: f64) -> Self {
38        Self {
39            timestamp_ms,
40            value,
41        }
42    }
43}
44
45/// One event annotation marker rendered on both focus plot and overview strip.
46#[derive(Clone, Debug)]
47pub struct BrushChartAnnotation {
48    pub timestamp_ms: f64,
49    pub label: SharedString,
50    pub description: Option<SharedString>,
51}
52
53impl BrushChartAnnotation {
54    pub fn new(timestamp_ms: f64, label: impl Into<SharedString>) -> Self {
55        Self {
56            timestamp_ms,
57            label: label.into(),
58            description: None,
59        }
60    }
61
62    pub fn description(mut self, desc: impl Into<SharedString>) -> Self {
63        self.description = Some(desc.into());
64        self
65    }
66}
67
68#[derive(Clone, Debug)]
69pub struct SmoothedPoint {
70    pub t: f64,
71    pub value: f64,
72    pub low: f64,
73    pub high: f64,
74}
75
76/// Format UTC epoch milliseconds as short date (`"Sep 14, 2026"` or `"Sep 14"`).
77pub fn format_utc_date(ms: f64, include_year: bool) -> String {
78    let days = (ms / DAY_MS).floor() as i64;
79    let (y, m, d) = civil_from_days(days);
80    const MONTHS: [&str; 12] = [
81        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
82    ];
83    let mon = MONTHS[(m.clamp(1, 12) - 1) as usize];
84    if include_year {
85        format!("{mon} {d}, {y}")
86    } else {
87        format!("{mon} {d}")
88    }
89}
90
91/// Howard Hinnant's civil-from-days algorithm (days since 1970-01-01).
92pub(crate) fn civil_from_days(z: i64) -> (i32, u32, u32) {
93    let z = z + 719_468;
94    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
95    let doe = (z - era * 146_097) as u64;
96    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
97    let y = (yoe as i64) + era * 400;
98    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
99    let mp = (5 * doy + 2) / 153;
100    let d = doy - (153 * mp + 2) / 5 + 1;
101    let m = if mp < 10 { mp + 3 } else { mp - 9 };
102    let year = (y + if m <= 2 { 1 } else { 0 }) as i32;
103    (year, m as u32, d as u32)
104}
105
106/// Inverse of `civil_from_days`: days since 1970-01-01.
107#[cfg(test)]
108pub(crate) fn days_from_civil(y: i32, m: u32, d: u32) -> i64 {
109    let y = y as i64 - if m <= 2 { 1 } else { 0 };
110    let era = if y >= 0 { y } else { y - 399 } / 400;
111    let yoe = (y - era * 400) as u64;
112    let m = m as u64;
113    let d = d as u64;
114    let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;
115    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
116    era * 146_097 + doe as i64 - 719_468
117}
118
119/// Compute double-smoothed 7-point rolling average + envelope band matching Arc `BrushChart`.
120pub fn brush_smooth_series(data: &[BrushChartDatum]) -> Vec<SmoothedPoint> {
121    if data.is_empty() {
122        return Vec::new();
123    }
124    let n = data.len();
125    let mut raw = Vec::with_capacity(n);
126    for i in 0..n {
127        let lo_i = i.saturating_sub(3);
128        let hi_i = (i + 3).min(n - 1);
129        let mut sum = 0.0;
130        let mut low = f64::INFINITY;
131        let mut high = f64::NEG_INFINITY;
132        let mut cnt = 0.0;
133        for item in &data[lo_i..=hi_i] {
134            sum += item.value;
135            low = low.min(item.value);
136            high = high.max(item.value);
137            cnt += 1.0;
138        }
139        raw.push((sum / cnt, low, high));
140    }
141    let mut out = Vec::with_capacity(n);
142    for i in 0..n {
143        let lo_i = i.saturating_sub(3);
144        let hi_i = (i + 3).min(n - 1);
145        let mut sum_lo = 0.0;
146        let mut sum_hi = 0.0;
147        let mut cnt = 0.0;
148        for &(_, l, h) in &raw[lo_i..=hi_i] {
149            sum_lo += l;
150            sum_hi += h;
151            cnt += 1.0;
152        }
153        out.push(SmoothedPoint {
154            t: data[i].timestamp_ms,
155            value: raw[i].0,
156            low: sum_lo / cnt,
157            high: sum_hi / cnt,
158        });
159    }
160    out
161}
162
163/// First index with `data[i].timestamp_ms >= t`.
164pub fn brush_lower_bound(data: &[BrushChartDatum], t: f64) -> usize {
165    let mut lo = 0usize;
166    let mut hi = data.len();
167    while lo < hi {
168        let mid = (lo + hi) / 2;
169        if data[mid].timestamp_ms < t {
170            lo = mid + 1;
171        } else {
172            hi = mid;
173        }
174    }
175    lo
176}
177
178/// Pick clean calendar ticks across `[start, end]` fitting within `width`.
179pub fn brush_time_ticks(start: f64, end: f64, width: f32) -> Vec<(f64, String)> {
180    let span = (end - start).max(1.0);
181    let room = ((width / 82.0).floor() as usize).max(2);
182    for days in [1.0, 2.0, 7.0, 14.0, 30.0, 60.0, 90.0, 180.0] {
183        if span / (days * DAY_MS) <= room as f64 {
184            let step = days * DAY_MS;
185            let mut t = (start / DAY_MS).ceil() * DAY_MS;
186            let mut ticks = Vec::new();
187            while t <= end + 1.0 {
188                ticks.push((t, format_utc_date(t, days >= 90.0)));
189                t += step;
190            }
191            if !ticks.is_empty() {
192                return ticks;
193            }
194        }
195    }
196    vec![
197        (start, format_utc_date(start, true)),
198        (end, format_utc_date(end, true)),
199    ]
200}
201
202/// Clamp a brush `[start, end]` window inside `[first, last]` enforcing `min_span`.
203pub fn brush_fit_range(range: (f64, f64), whole: (f64, f64), min_span: f64) -> (f64, f64) {
204    let total = (whole.1 - whole.0).max(1.0);
205    let least = min_span.min(total).max(1.0);
206    let span = (range.1 - range.0).clamp(least, total);
207    let max_start = (whole.1 - span).max(whole.0);
208    let s = range.0.clamp(whole.0, max_start);
209    (s, s + span)
210}
211
212#[derive(Clone, Copy, Debug, Eq, PartialEq)]
213enum DragMode {
214    Start,
215    End,
216    Pan,
217    New,
218}
219
220#[derive(Clone, Copy, Debug)]
221struct StripDrag {
222    mode: DragMode,
223    anchor_t: f64,
224    from: (f64, f64),
225    moved: bool,
226    start_x: f32,
227}
228
229type OnRangeChangeFn = Rc<dyn Fn((f64, f64), &mut Window, &mut App)>;
230
231struct BrushChartState {
232    focus_handle: FocusHandle,
233    view: (f64, f64),
234    target_view: (f64, f64),
235    initialized: bool,
236    top_spring: ChartSpring,
237    reveal_spring: ChartSpring,
238    active_index: Option<usize>,
239    drag: Option<StripDrag>,
240    plot_bounds: Option<Bounds<Pixels>>,
241    strip_bounds: Option<Bounds<Pixels>>,
242    last_frame_secs: Option<f64>,
243    last_whole: (f64, f64),
244}
245
246impl BrushChartState {
247    fn new(cx: &mut Context<Self>) -> Self {
248        Self {
249            focus_handle: cx.focus_handle(),
250            view: (0.0, 1.0),
251            target_view: (0.0, 1.0),
252            initialized: false,
253            top_spring: ChartSpring::new(1.0),
254            reveal_spring: ChartSpring::new(0.0),
255            active_index: None,
256            drag: None,
257            plot_bounds: None,
258            strip_bounds: None,
259            last_frame_secs: None,
260            last_whole: (0.0, 1.0),
261        }
262    }
263}
264
265/// Arc `BrushChart` component.
266#[derive(IntoElement)]
267pub struct BrushChart {
268    id: ElementId,
269    label: SharedString,
270    data: Vec<BrushChartDatum>,
271    unit: SharedString,
272    annotations: Vec<BrushChartAnnotation>,
273    default_range: Option<(f64, f64)>,
274    min_span_ms: f64,
275    height: f32,
276    overview_height: f32,
277    empty_label: SharedString,
278    on_range_change: Option<OnRangeChangeFn>,
279}
280
281impl BrushChart {
282    pub fn new(
283        id: impl Into<ElementId>,
284        label: impl Into<SharedString>,
285        data: Vec<BrushChartDatum>,
286    ) -> Self {
287        Self {
288            id: id.into(),
289            label: label.into(),
290            data,
291            unit: SharedString::from(""),
292            annotations: Vec::new(),
293            default_range: None,
294            min_span_ms: 7.0 * DAY_MS,
295            height: 224.0,
296            overview_height: 52.0,
297            empty_label: SharedString::from("No data yet"),
298            on_range_change: None,
299        }
300    }
301
302    pub fn unit(mut self, unit: impl Into<SharedString>) -> Self {
303        self.unit = unit.into();
304        self
305    }
306
307    pub fn annotations(mut self, annotations: Vec<BrushChartAnnotation>) -> Self {
308        self.annotations = annotations;
309        self
310    }
311
312    pub fn default_range(mut self, start_ms: f64, end_ms: f64) -> Self {
313        self.default_range = Some((start_ms, end_ms));
314        self
315    }
316
317    pub fn min_span_ms(mut self, min_span_ms: f64) -> Self {
318        self.min_span_ms = min_span_ms.max(DAY_MS);
319        self
320    }
321
322    pub fn height(mut self, height: f32) -> Self {
323        self.height = height.max(120.0);
324        self
325    }
326
327    pub fn overview_height(mut self, height: f32) -> Self {
328        self.overview_height = height.max(36.0);
329        self
330    }
331
332    pub fn empty_label(mut self, label: impl Into<SharedString>) -> Self {
333        self.empty_label = label.into();
334        self
335    }
336
337    pub fn on_range_change(
338        mut self,
339        f: impl Fn((f64, f64), &mut Window, &mut App) + 'static,
340    ) -> Self {
341        self.on_range_change = Some(Rc::new(f));
342        self
343    }
344
345    fn format_val(&self, v: f64) -> String {
346        let base = format_grouped(v, 1);
347        if self.unit.is_empty() {
348            base
349        } else {
350            format!("{base} {}", self.unit)
351        }
352    }
353}
354
355impl RenderOnce for BrushChart {
356    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
357        let colors = cx.arc_theme().colors;
358        let reduced = is_reduced_motion(cx);
359        let now = motion_now(cx);
360
361        let state = window.use_keyed_state(
362            ElementId::NamedChild(self.id.clone().into(), "state".into()),
363            cx,
364            |_, cx| BrushChartState::new(cx),
365        );
366
367        let empty = self.data.len() < 2;
368        let whole = if empty {
369            (0.0, 1.0)
370        } else {
371            (
372                self.data.first().unwrap().timestamp_ms,
373                self.data.last().unwrap().timestamp_ms,
374            )
375        };
376        let smooth = brush_smooth_series(&self.data);
377
378        let mut animating = false;
379        let (view, top_now, reveal_val, active_idx, plot_w, strip_w) = state.update(cx, |st, _| {
380            let dt = st
381                .last_frame_secs
382                .map(|prev| (now - prev).clamp(0.0, 0.05) as f32)
383                .unwrap_or(0.016);
384            st.last_frame_secs = Some(now);
385
386            if !st.initialized || st.last_whole != whole {
387                let init_r = self.default_range.unwrap_or(whole);
388                let fitted = brush_fit_range(init_r, whole, self.min_span_ms);
389                st.view = fitted;
390                st.target_view = fitted;
391                st.last_whole = whole;
392                st.initialized = true;
393            }
394
395            // Glide view toward target_view when not dragging
396            if st.drag.is_none() {
397                if reduced {
398                    st.view = st.target_view;
399                } else {
400                    let alpha = (1.0 - (-12.0 * dt as f64).exp()).clamp(0.0, 1.0);
401                    let ds = st.target_view.0 - st.view.0;
402                    let de = st.target_view.1 - st.view.1;
403                    if ds.abs() + de.abs() > (whole.1 - whole.0) * 1e-4 {
404                        st.view.0 += ds * alpha;
405                        st.view.1 += de * alpha;
406                        animating = true;
407                    } else {
408                        st.view = st.target_view;
409                    }
410                }
411            }
412
413            // Compute visible peak and nice scale
414            let from = brush_lower_bound(&self.data, st.view.0).saturating_sub(1);
415            let to = (brush_lower_bound(&self.data, st.view.1) + 1).min(self.data.len());
416            let mut peak = 1.0f64;
417            for d in &self.data[from..to] {
418                peak = peak.max(d.value);
419            }
420            let sc = nice_scale(0.0, peak * 1.06, 4);
421            let target_top = sc.max as f32;
422            if reduced || st.top_spring.value <= 1.01 {
423                st.top_spring.snap(target_top);
424            } else if !st.top_spring.is_settled_at(target_top, 0.05) {
425                st.top_spring.step_to(target_top, 0.36, 0.0, dt);
426                animating = true;
427            }
428
429            // Pen-draw entrance
430            if empty || reduced {
431                st.reveal_spring.snap(1.0);
432            } else if !st.reveal_spring.is_settled_at(1.0, 0.002) {
433                st.reveal_spring.step_to(1.0, 0.85, 0.0, dt);
434                animating = true;
435            }
436
437            let pw = st
438                .plot_bounds
439                .map(|b| f32::from(b.size.width))
440                .unwrap_or(520.0)
441                .max(120.0);
442            let sw = st
443                .strip_bounds
444                .map(|b| f32::from(b.size.width))
445                .unwrap_or(520.0)
446                .max(120.0);
447
448            let idx = st.active_index.filter(|&i| i >= from && i < to);
449            (
450                st.view,
451                st.top_spring.value.max(1.0),
452                st.reveal_spring.value.clamp(0.0, 1.0),
453                idx,
454                pw,
455                sw,
456            )
457        });
458
459        if animating {
460            window.request_animation_frame();
461        }
462
463        let (start, end) = view;
464        let span = (end - start).max(1.0);
465        let from = brush_lower_bound(&self.data, start).saturating_sub(1);
466        let to = (brush_lower_bound(&self.data, end) + 1).min(self.data.len());
467        let mut peak = 1.0f64;
468        for d in &self.data[from..to] {
469            peak = peak.max(d.value);
470        }
471        let scale = nice_scale(0.0, peak * 1.06, 4);
472
473        // Adaptive detail factor: zoomed out shows 7-day trend + envelope band, zoomed in shows raw line
474        let px_per_point = if empty {
475            plot_w
476        } else {
477            (plot_w * ((whole.1 - whole.0) / span) as f32) / (self.data.len() - 1).max(1) as f32
478        };
479        let detail = ((px_per_point - 2.75) / 1.5).clamp(0.0, 1.0);
480
481        let accent = colors.series.series_1;
482        let grid_color = colors.border_subtle;
483        let baseline_color = colors.border;
484        let crosshair_color = oklab_mix(colors.foreground, colors.surface, 0.35);
485
486        // Main focus canvas
487        let paint_data = self.data.clone();
488        let paint_smooth = smooth.clone();
489        let paint_ticks = scale.ticks.clone();
490        let paint_annotations = self.annotations.clone();
491        let state_plot_bounds = state.clone();
492        let paint_h = self.height;
493
494        let main_canvas = canvas(
495            move |bounds, _, cx| {
496                state_plot_bounds.update(cx, |st, _| st.plot_bounds = Some(bounds));
497                bounds
498            },
499            move |bounds, _, window, _cx| {
500                let w = f32::from(bounds.size.width).max(1.0);
501                let h = f32::from(bounds.size.height).max(1.0);
502                let ox = f32::from(bounds.origin.x);
503                let oy = f32::from(bounds.origin.y);
504                let to_x = |t: f64| ox + (((t - start) / span) as f32) * w;
505                let to_y = |v: f64| oy + PLOT_TOP + (1.0 - (v as f32 / top_now)) * (h - PLOT_TOP);
506
507                // Gridlines
508                for &tick in &paint_ticks {
509                    let y = to_y(tick);
510                    let col = if tick.abs() < 1e-6 {
511                        baseline_color
512                    } else {
513                        grid_color
514                    };
515                    if let Some(p) = build_polyline_stroke(
516                        &[point(px(ox), px(y)), point(px(ox + w), px(y))],
517                        1.0,
518                    ) {
519                        window.paint_path(p, col);
520                    }
521                }
522
523                // Event annotation rules
524                for ev in &paint_annotations {
525                    if ev.timestamp_ms >= start && ev.timestamp_ms <= end {
526                        let ex = to_x(ev.timestamp_ms);
527                        if let Some(p) = build_polyline_stroke(
528                            &[
529                                point(px(ex), px(oy + PLOT_TOP - 8.0)),
530                                point(px(ex), px(oy + h)),
531                            ],
532                            1.0,
533                        ) {
534                            window
535                                .paint_path(p, oklab_mix(colors.foreground, colors.surface, 0.25));
536                        }
537                        if let Some(dot) = build_circle_fill(ex, oy + PLOT_TOP - 8.0, 3.0, 12) {
538                            window.paint_path(dot, accent);
539                        }
540                    }
541                }
542
543                if paint_data.len() >= 2 && to > from {
544                    let reveal_x = ox + w * reveal_val;
545                    let mut raw_pts = Vec::new();
546                    let mut trend_pts = Vec::new();
547                    let mut upper_pts = Vec::new();
548                    let mut lower_pts = Vec::new();
549                    for i in from..to {
550                        let px_x = to_x(paint_data[i].timestamp_ms);
551                        if px_x > reveal_x + 4.0 {
552                            break;
553                        }
554                        raw_pts.push(point(px(px_x), px(to_y(paint_data[i].value))));
555                        trend_pts.push(point(px(px_x), px(to_y(paint_smooth[i].value))));
556                        upper_pts.push(point(px(px_x), px(to_y(paint_smooth[i].high))));
557                        lower_pts.push(point(px(px_x), px(to_y(paint_smooth[i].low))));
558                    }
559
560                    // Zoomed-out band + trend
561                    if (1.0 - detail) > 0.02 {
562                        let band_a = (1.0 - detail) * 0.16;
563                        if let Some(band_p) = build_band_fill(&upper_pts, &lower_pts) {
564                            window.paint_path(
565                                band_p,
566                                Hsla {
567                                    a: accent.a * band_a,
568                                    ..accent
569                                },
570                            );
571                        }
572                        if let Some(tr_p) = build_polyline_stroke(&trend_pts, 2.0) {
573                            window.paint_path(
574                                tr_p,
575                                Hsla {
576                                    a: accent.a * (1.0 - detail),
577                                    ..accent
578                                },
579                            );
580                        }
581                    }
582
583                    // Zoomed-in raw line + soft area
584                    if detail > 0.02 {
585                        if let Some(area_p) = build_area_fill(&raw_pts, px(oy + h)) {
586                            window.paint_path(
587                                area_p,
588                                Hsla {
589                                    a: accent.a * 0.14 * detail,
590                                    ..accent
591                                },
592                            );
593                        }
594                        if let Some(line_p) = build_polyline_stroke(&raw_pts, 2.0) {
595                            window.paint_path(
596                                line_p,
597                                Hsla {
598                                    a: accent.a * detail,
599                                    ..accent
600                                },
601                            );
602                        }
603                    }
604                }
605
606                // Active crosshair + dot
607                if let Some(idx) = active_idx
608                    && let Some(d) = paint_data.get(idx)
609                {
610                    let s_val = paint_smooth.get(idx).map(|p| p.value).unwrap_or(d.value);
611                    let blend_v = s_val + (d.value - s_val) * detail as f64;
612                    let cx_px = to_x(d.timestamp_ms);
613                    let cy_px = to_y(blend_v);
614                    if let Some(ch) = build_polyline_stroke(
615                        &[
616                            point(px(cx_px), px(oy + PLOT_TOP - 8.0)),
617                            point(px(cx_px), px(oy + h)),
618                        ],
619                        1.0,
620                    ) {
621                        window.paint_path(ch, crosshair_color);
622                    }
623                    if let Some(outer) = build_circle_fill(cx_px, cy_px, 5.0, 16) {
624                        window.paint_path(outer, colors.surface);
625                    }
626                    if let Some(inner) = build_circle_fill(cx_px, cy_px, 3.5, 16) {
627                        window.paint_path(inner, accent);
628                    }
629                }
630            },
631        )
632        .size_full();
633
634        // Main plot pointer + keyboard handlers
635        let state_plot_move = state.clone();
636        let state_plot_hover = state.clone();
637        let state_plot_key = state.clone();
638        let move_data = self.data.clone();
639        let key_data_len = self.data.len();
640        let key_min_span = self.min_span_ms;
641        let key_on_range = self.on_range_change.clone();
642        let focus_handle = state.read(cx).focus_handle.clone();
643
644        // Event badges inside main plot
645        let mut annotation_labels = Vec::new();
646        let mut last_label_right = -100.0f32;
647        for ev in &self.annotations {
648            if ev.timestamp_ms >= start && ev.timestamp_ms <= end {
649                let x_px = (((ev.timestamp_ms - start) / span) as f32) * plot_w;
650                let w_est = (ev.label.len() as f32 * 6.4 + 10.0).max(40.0);
651                if x_px + 6.0 >= last_label_right && x_px + 6.0 + w_est <= plot_w {
652                    annotation_labels.push((x_px + 6.0, ev.label.clone()));
653                    last_label_right = x_px + 6.0 + w_est + 6.0;
654                }
655            }
656        }
657
658        // Tooltip
659        let tooltip_el = active_idx
660            .and_then(|idx| self.data.get(idx).map(|d| (idx, d)))
661            .map(|(idx, d)| {
662                let x_px = (((d.timestamp_ms - start) / span) as f32) * plot_w;
663                let tip_w = 184.0f32;
664                let left = if x_px + 14.0 + tip_w <= plot_w {
665                    x_px + 14.0
666                } else {
667                    (x_px - 14.0 - tip_w).max(4.0)
668                };
669                let prev = idx.checked_sub(7).and_then(|pi| self.data.get(pi));
670                let pct_change = prev.and_then(|p| {
671                    if p.value.abs() > 1e-6 {
672                        Some((d.value - p.value) / p.value * 100.0)
673                    } else {
674                        None
675                    }
676                });
677                let ev_at = self
678                    .annotations
679                    .iter()
680                    .find(|ev| (ev.timestamp_ms - d.timestamp_ms).abs() < DAY_MS * 0.5);
681
682                div()
683                    .absolute()
684                    .left(px(left))
685                    .top(px(PLOT_TOP + 6.0))
686                    .w(px(tip_w))
687                    .p(Spacing::S2)
688                    .rounded(Radii::CONTROL)
689                    .bg(colors.surface_raised)
690                    .border_1()
691                    .border_color(colors.border)
692                    .flex()
693                    .flex_col()
694                    .gap(px(2.0))
695                    .child(
696                        div()
697                            .text_size(Typography::TEXT_XS)
698                            .text_color(colors.text_muted)
699                            .child(format_utc_date(d.timestamp_ms, true)),
700                    )
701                    .child(
702                        div()
703                            .text_size(Typography::TEXT_SM)
704                            .font_semibold()
705                            .text_color(colors.foreground)
706                            .child(self.format_val(d.value)),
707                    )
708                    .when_some(pct_change, |this, pct| {
709                        let sign = if pct >= 0.0 { "+" } else { "−" };
710                        this.child(
711                            div()
712                                .text_size(Typography::TEXT_XS)
713                                .text_color(colors.text_secondary)
714                                .child(format!("{sign}{:.1}% vs 7d ago", pct.abs())),
715                        )
716                    })
717                    .when_some(ev_at, |this, ev| {
718                        this.child(
719                            div()
720                                .pt(px(2.0))
721                                .flex()
722                                .items_center()
723                                .gap(px(5.0))
724                                .child(div().size(px(6.0)).rounded(Radii::PILL).bg(accent))
725                                .child(
726                                    div()
727                                        .text_size(Typography::TEXT_XS)
728                                        .font_medium()
729                                        .text_color(colors.foreground)
730                                        .child(ev.label.clone()),
731                                ),
732                        )
733                    })
734            });
735
736        let mut main_plot = div()
737            .id(ElementId::NamedChild(self.id.clone().into(), "plot".into()))
738            .role(Role::Group)
739            .track_focus(&focus_handle)
740            .relative()
741            .flex_1()
742            .h(px(self.height))
743            .overflow_hidden()
744            .cursor_crosshair()
745            .on_mouse_move(move |event: &MouseMoveEvent, window, cx| {
746                if empty {
747                    return;
748                }
749                state_plot_move.update(cx, |st, _| {
750                    if let Some(bounds) = st.plot_bounds {
751                        let w = f32::from(bounds.size.width).max(1.0);
752                        let local_x = (f32::from(event.position.x) - f32::from(bounds.origin.x))
753                            .clamp(0.0, w);
754                        let t = st.view.0 + (local_x / w) as f64 * (st.view.1 - st.view.0);
755                        let nearest = if move_data.len() <= 1 {
756                            0
757                        } else {
758                            let at = brush_lower_bound(&move_data, t)
759                                .clamp(1, move_data.len().saturating_sub(1));
760                            if (t - move_data[at - 1].timestamp_ms).abs()
761                                < (move_data[at].timestamp_ms - t).abs()
762                            {
763                                at - 1
764                            } else {
765                                at
766                            }
767                        };
768                        st.active_index = Some(nearest);
769                    }
770                });
771                window.refresh();
772            })
773            .on_hover(move |hovered, window, cx| {
774                if !*hovered {
775                    state_plot_hover.update(cx, |st, _| st.active_index = None);
776                    window.refresh();
777                }
778            })
779            .on_key_down(move |event: &KeyDownEvent, window, cx| {
780                if empty || key_data_len == 0 {
781                    return;
782                }
783                let key = event.keystroke.key.as_str();
784                let mut range_changed = None;
785                let mut handled = true;
786                state_plot_key.update(cx, |st, _| {
787                    let cur = st.active_index.unwrap_or(to.saturating_sub(1));
788                    let page = ((to.saturating_sub(from)) / 8).max(1);
789                    let win = st.target_view.1 - st.target_view.0;
790                    match key {
791                        "escape" => {
792                            if st.active_index.is_some() {
793                                st.active_index = None;
794                            } else {
795                                st.target_view = whole;
796                                range_changed = Some(whole);
797                            }
798                        }
799                        "0" => {
800                            st.target_view = whole;
801                            range_changed = Some(whole);
802                        }
803                        "+" | "=" => {
804                            let next = brush_fit_range(
805                                (st.target_view.0 + win * 0.2, st.target_view.1 - win * 0.2),
806                                whole,
807                                key_min_span,
808                            );
809                            st.target_view = next;
810                            range_changed = Some(next);
811                        }
812                        "-" | "_" => {
813                            let next = brush_fit_range(
814                                (st.target_view.0 - win * 0.35, st.target_view.1 + win * 0.35),
815                                whole,
816                                key_min_span,
817                            );
818                            st.target_view = next;
819                            range_changed = Some(next);
820                        }
821                        "left" => {
822                            st.active_index = Some(cur.saturating_sub(1).max(from));
823                        }
824                        "right" => {
825                            st.active_index = Some((cur + 1).min(to.saturating_sub(1)));
826                        }
827                        "pageup" => {
828                            st.active_index = Some((cur + page).min(to.saturating_sub(1)));
829                        }
830                        "pagedown" => {
831                            st.active_index = Some(cur.saturating_sub(page).max(from));
832                        }
833                        "home" => {
834                            st.active_index = Some(from);
835                        }
836                        "end" => {
837                            st.active_index = Some(to.saturating_sub(1));
838                        }
839                        _ => handled = false,
840                    }
841                });
842                if handled {
843                    if let (Some(cb), Some(r)) = (&key_on_range, range_changed) {
844                        cb(r, window, cx);
845                    }
846                    cx.stop_propagation();
847                    window.refresh();
848                }
849            })
850            .child(main_canvas);
851
852        for (lx, lbl) in annotation_labels {
853            main_plot = main_plot.child(
854                div()
855                    .absolute()
856                    .left(px(lx))
857                    .top(px(4.0))
858                    .text_size(Typography::TEXT_XS)
859                    .font_medium()
860                    .text_color(colors.text_secondary)
861                    .child(lbl),
862            );
863        }
864
865        if let Some(tip) = tooltip_el {
866            main_plot = main_plot.child(tip);
867        }
868
869        if empty {
870            main_plot = main_plot.child(
871                div()
872                    .absolute()
873                    .inset_0()
874                    .flex()
875                    .items_center()
876                    .justify_center()
877                    .text_size(Typography::TEXT_SM)
878                    .text_color(colors.text_muted)
879                    .child(self.empty_label.clone()),
880            );
881        }
882
883        // Y-axis gutter on the right
884        let y_gutter = div()
885            .relative()
886            .w(px(44.0))
887            .h(px(self.height))
888            .flex_none()
889            .children(scale.ticks.iter().map(|&tick| {
890                let y = PLOT_TOP + (1.0 - (tick as f32 / top_now)) * (paint_h - PLOT_TOP);
891                div()
892                    .absolute()
893                    .right(px(0.0))
894                    .top(px((y - 7.0).clamp(0.0, (paint_h - 14.0).max(0.0))))
895                    .text_size(Typography::TEXT_XS)
896                    .text_color(colors.text_muted)
897                    .child(format_compact(tick))
898            }));
899
900        // X-axis calendar ticks
901        let x_ticks = if empty {
902            Vec::new()
903        } else {
904            brush_time_ticks(start, end, plot_w)
905        };
906        let x_axis = div()
907            .relative()
908            .w(px(plot_w))
909            .h(px(18.0))
910            .children(x_ticks.into_iter().map(|(t, lbl)| {
911                let x = (((t - start) / span) as f32 * plot_w - 28.0)
912                    .clamp(0.0, (plot_w - 56.0).max(0.0));
913                div()
914                    .absolute()
915                    .left(px(x))
916                    .top(px(0.0))
917                    .w(px(56.0))
918                    .flex()
919                    .justify_center()
920                    .text_size(Typography::TEXT_XS)
921                    .text_color(colors.text_muted)
922                    .child(lbl)
923            }));
924
925        // Overview brush strip
926        let whole_span = (whole.1 - whole.0).max(1.0);
927        let wx0 = (((start - whole.0) / whole_span) as f32 * strip_w).clamp(0.0, strip_w);
928        let wx1 = (((end - whole.0) / whole_span) as f32 * strip_w).clamp(wx0, strip_w);
929
930        let ov_smooth = smooth.clone();
931        let ov_annotations = self.annotations.clone();
932        let ov_h = self.overview_height;
933        let state_strip_bounds = state.clone();
934        let muted_line = oklab_mix(colors.foreground, colors.surface, 0.35);
935
936        let overview_canvas = canvas(
937            move |bounds, _, cx| {
938                state_strip_bounds.update(cx, |st, _| st.strip_bounds = Some(bounds));
939                bounds
940            },
941            move |bounds, _, window, _cx| {
942                let w = f32::from(bounds.size.width).max(1.0);
943                let h = f32::from(bounds.size.height).max(1.0);
944                let ox = f32::from(bounds.origin.x);
945                let oy = f32::from(bounds.origin.y);
946                if ov_smooth.len() < 2 {
947                    return;
948                }
949                let max_v = ov_smooth.iter().map(|p| p.value).fold(1.0f64, f64::max);
950                let to_ox = |t: f64| ox + (((t - whole.0) / whole_span) as f32) * w;
951                let to_oy = |v: f64| oy + 4.0 + (1.0 - (v / max_v) as f32) * (h - 6.0);
952
953                let all_pts: Vec<_> = ov_smooth
954                    .iter()
955                    .map(|p| point(px(to_ox(p.t)), px(to_oy(p.value))))
956                    .collect();
957                if let Some(area) = build_area_fill(&all_pts, px(oy + h)) {
958                    window.paint_path(
959                        area,
960                        Hsla {
961                            a: muted_line.a * 0.25,
962                            ..muted_line
963                        },
964                    );
965                }
966                if let Some(line) = build_polyline_stroke(&all_pts, 1.25) {
967                    window.paint_path(line, muted_line);
968                }
969
970                let in_pts: Vec<_> = ov_smooth
971                    .iter()
972                    .filter(|p| p.t >= start && p.t <= end)
973                    .map(|p| point(px(to_ox(p.t)), px(to_oy(p.value))))
974                    .collect();
975                if let Some(area) = build_area_fill(&in_pts, px(oy + h)) {
976                    window.paint_path(
977                        area,
978                        Hsla {
979                            a: accent.a * 0.22,
980                            ..accent
981                        },
982                    );
983                }
984                if let Some(line) = build_polyline_stroke(&in_pts, 1.5) {
985                    window.paint_path(line, accent);
986                }
987
988                for ev in &ov_annotations {
989                    let ex = to_ox(ev.timestamp_ms);
990                    if let Some(dot) = build_circle_fill(ex, oy + h * 0.5, 2.5, 10) {
991                        window.paint_path(dot, accent);
992                    }
993                }
994            },
995        )
996        .size_full();
997
998        let state_s_down = state.clone();
999        let state_s_move = state.clone();
1000        let state_s_up = state.clone();
1001        let min_span_drag = self.min_span_ms;
1002        let move_on_range = self.on_range_change.clone();
1003        let up_on_range = self.on_range_change.clone();
1004
1005        let shade_col = Hsla {
1006            a: 0.45,
1007            ..colors.surface_muted
1008        };
1009        let strip_box = div()
1010            .id(ElementId::NamedChild(
1011                self.id.clone().into(),
1012                "strip".into(),
1013            ))
1014            .relative()
1015            .w_full()
1016            .h(px(ov_h))
1017            .rounded(Radii::CONTROL)
1018            .border_1()
1019            .border_color(colors.border)
1020            .bg(colors.surface_muted)
1021            .overflow_hidden()
1022            .cursor_grab()
1023            .on_mouse_down(
1024                MouseButton::Left,
1025                move |event: &MouseDownEvent, window, cx| {
1026                    if empty {
1027                        return;
1028                    }
1029                    if event.click_count >= 2 {
1030                        state_s_down.update(cx, |st, _| {
1031                            st.drag = None;
1032                            st.target_view = whole;
1033                        });
1034                        window.refresh();
1035                        return;
1036                    }
1037                    let fh = state_s_down.read(cx).focus_handle.clone();
1038                    window.focus(&fh, cx);
1039                    state_s_down.update(cx, |st, _| {
1040                        if let Some(bounds) = st.strip_bounds {
1041                            let w = f32::from(bounds.size.width).max(1.0);
1042                            let local_x = (f32::from(event.position.x)
1043                                - f32::from(bounds.origin.x))
1044                            .clamp(0.0, w);
1045                            let cur_wx0 = (((st.view.0 - whole.0) / whole_span) as f32) * w;
1046                            let cur_wx1 = (((st.view.1 - whole.0) / whole_span) as f32) * w;
1047                            let mode = if (local_x - cur_wx0).abs() <= GRIP_HIT
1048                                && local_x <= (cur_wx0 + cur_wx1) * 0.5
1049                            {
1050                                DragMode::Start
1051                            } else if (local_x - cur_wx1).abs() <= GRIP_HIT {
1052                                DragMode::End
1053                            } else if local_x > cur_wx0 && local_x < cur_wx1 {
1054                                DragMode::Pan
1055                            } else {
1056                                DragMode::New
1057                            };
1058                            let anchor_t = whole.0 + (local_x / w) as f64 * whole_span;
1059                            st.drag = Some(StripDrag {
1060                                mode,
1061                                anchor_t,
1062                                from: st.view,
1063                                moved: false,
1064                                start_x: f32::from(event.position.x),
1065                            });
1066                        }
1067                    });
1068                    window.refresh();
1069                },
1070            )
1071            .on_mouse_move(move |event: &MouseMoveEvent, window, cx| {
1072                let mut emitted = None;
1073                state_s_move.update(cx, |st, _| {
1074                    let Some(mut drag) = st.drag else {
1075                        return;
1076                    };
1077                    if !drag.moved && (f32::from(event.position.x) - drag.start_x).abs() < 2.5 {
1078                        return;
1079                    }
1080                    drag.moved = true;
1081                    st.drag = Some(drag);
1082                    let Some(bounds) = st.strip_bounds else {
1083                        return;
1084                    };
1085                    let w = f32::from(bounds.size.width).max(1.0);
1086                    let local_x =
1087                        (f32::from(event.position.x) - f32::from(bounds.origin.x)).clamp(0.0, w);
1088                    let t = whole.0 + (local_x / w) as f64 * whole_span;
1089                    let shift = t - drag.anchor_t;
1090                    let least = min_span_drag.min(whole_span);
1091                    let raw = match drag.mode {
1092                        DragMode::Pan => (drag.from.0 + shift, drag.from.1 + shift),
1093                        DragMode::Start => {
1094                            let hi = (drag.from.1 - least).max(whole.0);
1095                            (t.clamp(whole.0, hi), drag.from.1)
1096                        }
1097                        DragMode::End => {
1098                            let lo = (drag.from.0 + least).min(whole.1);
1099                            (drag.from.0, t.clamp(lo, whole.1))
1100                        }
1101                        DragMode::New => {
1102                            let lo = drag.anchor_t.min(t);
1103                            let hi = drag.anchor_t.max(t);
1104                            if hi - lo < least {
1105                                if t >= drag.anchor_t {
1106                                    (lo, lo + least)
1107                                } else {
1108                                    (hi - least, hi)
1109                                }
1110                            } else {
1111                                (lo, hi)
1112                            }
1113                        }
1114                    };
1115                    let fitted = brush_fit_range(raw, whole, min_span_drag);
1116                    st.view = fitted;
1117                    st.target_view = fitted;
1118                    emitted = Some(fitted);
1119                });
1120                if let (Some(cb), Some(r)) = (&move_on_range, emitted) {
1121                    cb(r, window, cx);
1122                }
1123                if emitted.is_some() {
1124                    window.refresh();
1125                }
1126            })
1127            .on_mouse_up(MouseButton::Left, move |_, window, cx| {
1128                let mut recentered = None;
1129                state_s_up.update(cx, |st, _| {
1130                    if let Some(drag) = st.drag.take()
1131                        && !drag.moved
1132                        && drag.mode == DragMode::New
1133                    {
1134                        let half = (st.view.1 - st.view.0) * 0.5;
1135                        let next = brush_fit_range(
1136                            (drag.anchor_t - half, drag.anchor_t + half),
1137                            whole,
1138                            min_span_drag,
1139                        );
1140                        st.target_view = next;
1141                        recentered = Some(next);
1142                    }
1143                });
1144                if let (Some(cb), Some(r)) = (&up_on_range, recentered) {
1145                    cb(r, window, cx);
1146                }
1147                window.refresh();
1148            })
1149            .child(overview_canvas)
1150            // Dimmed regions outside window
1151            .child(
1152                div()
1153                    .absolute()
1154                    .left(px(0.0))
1155                    .top(px(0.0))
1156                    .bottom(px(0.0))
1157                    .w(px(wx0.max(0.0)))
1158                    .bg(shade_col),
1159            )
1160            .child(
1161                div()
1162                    .absolute()
1163                    .left(px(wx1))
1164                    .right(px(0.0))
1165                    .top(px(0.0))
1166                    .bottom(px(0.0))
1167                    .bg(shade_col),
1168            )
1169            // Selected window border + left/right grips
1170            .child(
1171                div()
1172                    .absolute()
1173                    .left(px(wx0))
1174                    .w(px((wx1 - wx0).max(2.0)))
1175                    .top(px(0.0))
1176                    .bottom(px(0.0))
1177                    .border_1()
1178                    .border_color(accent)
1179                    .child(
1180                        div()
1181                            .absolute()
1182                            .left(px(-3.0))
1183                            .top(px((ov_h - 18.0) * 0.5))
1184                            .w(px(6.0))
1185                            .h(px(18.0))
1186                            .rounded(Radii::PILL)
1187                            .bg(colors.surface_raised)
1188                            .border_1()
1189                            .border_color(accent),
1190                    )
1191                    .child(
1192                        div()
1193                            .absolute()
1194                            .right(px(-3.0))
1195                            .top(px((ov_h - 18.0) * 0.5))
1196                            .w(px(6.0))
1197                            .h(px(18.0))
1198                            .rounded(Radii::PILL)
1199                            .bg(colors.surface_raised)
1200                            .border_1()
1201                            .border_color(accent),
1202                    ),
1203            );
1204
1205        let window_text = format!(
1206            "{} – {}",
1207            format_utc_date(start, true),
1208            format_utc_date(end, true)
1209        );
1210
1211        div()
1212            .id(self.id)
1213            .w_full()
1214            .flex()
1215            .flex_col()
1216            .gap(Spacing::S2)
1217            .p(Spacing::S4)
1218            .rounded(Radii::PANEL)
1219            .bg(colors.surface)
1220            .border_1()
1221            .border_color(colors.border_subtle)
1222            .child(
1223                div()
1224                    .flex()
1225                    .items_center()
1226                    .justify_between()
1227                    .gap(Spacing::S2)
1228                    .child(
1229                        div()
1230                            .text_size(Typography::TEXT_SM)
1231                            .font_semibold()
1232                            .text_color(colors.foreground)
1233                            .child(self.label),
1234                    )
1235                    .child(
1236                        div()
1237                            .text_size(Typography::TEXT_XS)
1238                            .text_color(colors.text_muted)
1239                            .child(window_text),
1240                    ),
1241            )
1242            .child(
1243                div()
1244                    .w_full()
1245                    .flex()
1246                    .items_stretch()
1247                    .gap(Spacing::S2)
1248                    .child(main_plot)
1249                    .child(y_gutter),
1250            )
1251            .child(x_axis)
1252            .child(strip_box)
1253    }
1254}
1255
1256#[cfg(test)]
1257mod tests {
1258    use super::*;
1259
1260    #[test]
1261    fn brush_chart_smoothing_window_clamping_and_ticks() {
1262        let base = days_from_civil(2026, 1, 1) as f64 * DAY_MS;
1263        let data: Vec<BrushChartDatum> = (0..60)
1264            .map(|i| BrushChartDatum::new(base + i as f64 * DAY_MS, 100.0 + (i % 7) as f64 * 12.0))
1265            .collect();
1266        let smoothed = brush_smooth_series(&data);
1267        assert_eq!(smoothed.len(), 60);
1268        for p in &smoothed {
1269            assert!(p.low <= p.value + 1e-6);
1270            assert!(p.high >= p.value - 1e-6);
1271        }
1272
1273        let whole = (base, base + 59.0 * DAY_MS);
1274        let fitted = brush_fit_range(
1275            (base - 10.0 * DAY_MS, base - 8.0 * DAY_MS),
1276            whole,
1277            7.0 * DAY_MS,
1278        );
1279        assert!((fitted.0 - whole.0).abs() < 1e-6);
1280        assert!((fitted.1 - fitted.0 - 7.0 * DAY_MS).abs() < 1e-6);
1281
1282        let preserved = brush_fit_range(
1283            (base - 10.0 * DAY_MS, base + 2.0 * DAY_MS),
1284            whole,
1285            7.0 * DAY_MS,
1286        );
1287        assert!((preserved.0 - whole.0).abs() < 1e-6);
1288        assert!((preserved.1 - preserved.0 - 12.0 * DAY_MS).abs() < 1e-6);
1289
1290        let ticks = brush_time_ticks(whole.0, whole.1, 480.0);
1291        assert!(ticks.len() >= 2);
1292        assert_eq!(format_utc_date(base, true), "Jan 1, 2026");
1293    }
1294}