Skip to main content

arc_ui/chart/
line_chart.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! `LineChart`: multi-series trend chart with smooth monotone / linear curves, faint area wash,
3//! dashed reference series, interactive legend toggle with Y-axis rescaling, spring crosshair,
4//! and auto-flipping floating tooltip.
5
6use std::cell::RefCell;
7use std::collections::{HashMap, HashSet};
8use std::rc::Rc;
9
10use arc_motion::{arc_spring_with_options, is_reduced_motion, motion_now, spring::SpringOptions};
11use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, SpringSpec, Typography, oklab_mix};
12use gpui_kit::{
13    App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
14    MouseDownEvent, MouseMoveEvent, ParentElement, Pixels, Point, RenderOnce, Role, SharedString,
15    Styled, Window, base::StyledExt as _, canvas, div, fill, point, prelude::*, px, size,
16};
17
18use super::common::{
19    build_area_fill, build_circle_fill, build_dashed_polyline, build_polyline_stroke,
20    chart_series_color, format_compact, format_grouped, nice_scale, sample_curve_at,
21    sample_monotone_curve, slice_polyline_by_progress,
22};
23
24pub const LINE_CHART_TOP_PAD: f32 = 12.0;
25
26#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
27pub enum LineCurve {
28    #[default]
29    Smooth,
30    Linear,
31}
32
33#[derive(Clone, Debug)]
34pub struct LineChartSeries {
35    pub key: SharedString,
36    pub label: SharedString,
37    pub color: Option<Hsla>,
38    pub dashed: bool,
39    pub area: Option<bool>,
40}
41
42impl LineChartSeries {
43    pub fn new(key: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
44        Self {
45            key: key.into(),
46            label: label.into(),
47            color: None,
48            dashed: false,
49            area: None,
50        }
51    }
52
53    pub fn color(mut self, color: Hsla) -> Self {
54        self.color = Some(color);
55        self
56    }
57
58    pub fn dashed(mut self, dashed: bool) -> Self {
59        self.dashed = dashed;
60        self
61    }
62
63    pub fn area(mut self, area: bool) -> Self {
64        self.area = Some(area);
65        self
66    }
67}
68
69#[derive(Clone, Debug)]
70pub struct LineChartDatum {
71    pub key: SharedString,
72    pub label: SharedString,
73    pub axis_label: Option<SharedString>,
74    pub values: HashMap<SharedString, f64>,
75}
76
77impl LineChartDatum {
78    pub fn new(key: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
79        Self {
80            key: key.into(),
81            label: label.into(),
82            axis_label: None,
83            values: HashMap::new(),
84        }
85    }
86
87    pub fn axis_label(mut self, label: impl Into<SharedString>) -> Self {
88        self.axis_label = Some(label.into());
89        self
90    }
91
92    pub fn value(mut self, series_key: impl Into<SharedString>, val: f64) -> Self {
93        self.values.insert(series_key.into(), val);
94        self
95    }
96}
97
98/// Compute `(min, max)` across all visible series in `data`.
99pub fn line_chart_visible_extents(
100    data: &[LineChartDatum],
101    series: &[LineChartSeries],
102    hidden: &HashSet<SharedString>,
103) -> Option<(f64, f64)> {
104    let mut lo = f64::INFINITY;
105    let mut hi = f64::NEG_INFINITY;
106    for s in series {
107        if hidden.contains(&s.key) {
108            continue;
109        }
110        for d in data {
111            let v = d.values.get(&s.key).copied().unwrap_or(0.0);
112            lo = lo.min(v);
113            hi = hi.max(v);
114        }
115    }
116    if lo.is_finite() && hi.is_finite() {
117        Some((lo, hi))
118    } else {
119        None
120    }
121}
122
123/// Choose evenly thinned X-axis label indices counted back from the latest datum.
124pub fn line_chart_axis_picks(data: &[LineChartDatum], width: f32) -> Vec<usize> {
125    let labeled: Vec<usize> = data
126        .iter()
127        .enumerate()
128        .filter_map(|(i, d)| d.axis_label.as_ref().map(|_| i))
129        .collect();
130    if width <= 20.0 || labeled.is_empty() {
131        return Vec::new();
132    }
133    let room = (width / 76.0).floor().max(2.0) as usize;
134    let stride = labeled.len().div_ceil(room).max(1);
135    let mut out: Vec<usize> = labeled
136        .into_iter()
137        .rev()
138        .enumerate()
139        .filter_map(|(rank, i)| if rank % stride == 0 { Some(i) } else { None })
140        .collect();
141    out.reverse();
142    out
143}
144
145/// Map pointer x to nearest datum index.
146pub fn line_chart_index_at(x: f32, left: f32, width: f32, count: usize) -> usize {
147    if count <= 1 || width <= 1e-4 {
148        return 0;
149    }
150    let frac = ((x - left) / width).clamp(0.0, 1.0);
151    (frac * (count - 1) as f32).round() as usize
152}
153
154struct LineChartState {
155    active: Option<usize>,
156    own_hidden: HashSet<SharedString>,
157    mounted_at_secs: Option<f64>,
158    plot_bounds: Option<Bounds<Pixels>>,
159    focus: FocusHandle,
160}
161
162#[derive(IntoElement)]
163pub struct LineChart {
164    id: ElementId,
165    label: SharedString,
166    series: Vec<LineChartSeries>,
167    data: Vec<LineChartDatum>,
168    unit: SharedString,
169    height: f32,
170    curve: LineCurve,
171    legend: Option<bool>,
172    loading: bool,
173    empty_label: SharedString,
174}
175
176impl LineChart {
177    pub fn new(
178        id: impl Into<ElementId>,
179        label: impl Into<SharedString>,
180        series: Vec<LineChartSeries>,
181        data: Vec<LineChartDatum>,
182    ) -> Self {
183        Self {
184            id: id.into(),
185            label: label.into(),
186            series,
187            data,
188            unit: SharedString::default(),
189            height: 220.0,
190            curve: LineCurve::Smooth,
191            legend: None,
192            loading: false,
193            empty_label: SharedString::from("No data for this range"),
194        }
195    }
196
197    pub fn unit(mut self, unit: impl Into<SharedString>) -> Self {
198        self.unit = unit.into();
199        self
200    }
201
202    pub fn height(mut self, px_val: f32) -> Self {
203        self.height = px_val.clamp(120.0, 420.0);
204        self
205    }
206
207    pub fn curve(mut self, curve: LineCurve) -> Self {
208        self.curve = curve;
209        self
210    }
211
212    pub fn legend(mut self, show: bool) -> Self {
213        self.legend = Some(show);
214        self
215    }
216
217    pub fn loading(mut self, loading: bool) -> Self {
218        self.loading = loading;
219        self
220    }
221
222    pub fn empty_label(mut self, label: impl Into<SharedString>) -> Self {
223        self.empty_label = label.into();
224        self
225    }
226}
227
228impl RenderOnce for LineChart {
229    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
230        let theme = cx.arc_theme().clone();
231        let colors = theme.colors;
232        let reduced = is_reduced_motion(cx);
233        let now = motion_now(cx);
234
235        let count = self.data.len();
236        let last = count.saturating_sub(1);
237        let show_legend = self.legend.unwrap_or(self.series.len() > 1);
238
239        let state = window.use_keyed_state(
240            SharedString::from(format!("arc-linechart-state-{:?}", self.id)),
241            cx,
242            |_w, cx| {
243                Rc::new(RefCell::new(LineChartState {
244                    active: None,
245                    own_hidden: HashSet::new(),
246                    mounted_at_secs: None,
247                    plot_bounds: None,
248                    focus: cx.focus_handle(),
249                }))
250            },
251        );
252        let st_rc = state.read(cx).clone();
253        let (active_idx, hidden_set, focus_handle, draw_progress, plot_w) = {
254            let mut st = st_rc.borrow_mut();
255            let start = *st.mounted_at_secs.get_or_insert(now);
256            let progress = if reduced {
257                1.0
258            } else {
259                let dur = 0.7f64;
260                let t = ((now - start) / dur).clamp(0.0, 1.0) as f32;
261                let eased = if t < 0.5 {
262                    4.0 * t * t * t
263                } else {
264                    1.0 - (-2.0 * t + 2.0).powi(3) * 0.5
265                };
266                if t < 1.0 {
267                    window.request_animation_frame();
268                }
269                eased
270            };
271            let w: f32 = st.plot_bounds.map(|b| b.size.width.into()).unwrap_or(520.0);
272            (
273                st.active.filter(|_| count > 0).map(|i| i.min(last)),
274                st.own_hidden.clone(),
275                st.focus.clone(),
276                progress,
277                w,
278            )
279        };
280
281        let extents = line_chart_visible_extents(&self.data, &self.series, &hidden_set)
282            .unwrap_or((0.0, 100.0));
283        let scale = nice_scale(extents.0, extents.1, 4);
284
285        let anim_min = arc_spring_with_options(
286            SharedString::from(format!("arc-linechart-min-{:?}", self.id)),
287            scale.min as f32,
288            SpringOptions::new(SpringSpec::visual(0.36, 0.0)),
289            window,
290            cx,
291        )
292        .value;
293        let anim_max = arc_spring_with_options(
294            SharedString::from(format!("arc-linechart-max-{:?}", self.id)),
295            scale.max as f32,
296            SpringOptions::new(SpringSpec::visual(0.36, 0.0)),
297            window,
298            cx,
299        )
300        .value;
301
302        let scrubbing = active_idx.is_some();
303        let cursor_target = active_idx
304            .map(|i| {
305                if last > 0 {
306                    i as f32 / last as f32
307                } else {
308                    0.5
309                }
310            })
311            .unwrap_or(1.0);
312        let cursor_norm = arc_spring_with_options(
313            SharedString::from(format!("arc-linechart-cursor-{:?}", self.id)),
314            cursor_target,
315            SpringOptions::new(SpringSpec::visual(0.22, 0.0)),
316            window,
317            cx,
318        )
319        .value
320        .clamp(0.0, 1.0);
321
322        let smooth = self.curve == LineCurve::Smooth;
323
324        // Precompute curves + animated presence per series
325        struct RenderSeries {
326            color: Hsla,
327            dashed: bool,
328            area: bool,
329            presence: f32,
330            curve: Vec<(f64, f64)>,
331        }
332        let mut render_series = Vec::with_capacity(self.series.len());
333        for (idx, s) in self.series.iter().enumerate() {
334            let visible = !hidden_set.contains(&s.key);
335            let presence = arc_spring_with_options(
336                SharedString::from(format!("arc-linechart-vis-{:?}-{}", self.id, s.key)),
337                if visible { 1.0 } else { 0.0 },
338                SpringOptions::new(SpringSpec::visual(0.32, 0.0)),
339                window,
340                cx,
341            )
342            .value
343            .clamp(0.0, 1.0);
344            let vals: Vec<f64> = self
345                .data
346                .iter()
347                .map(|d| d.values.get(&s.key).copied().unwrap_or(0.0))
348                .collect();
349            let color = s.color.unwrap_or_else(|| chart_series_color(&colors, idx));
350            let area = s.area.unwrap_or(idx == 0);
351            render_series.push(RenderSeries {
352                color,
353                dashed: s.dashed,
354                area,
355                presence,
356                curve: sample_monotone_curve(&vals, smooth, 160),
357            });
358        }
359
360        let grid_color = colors.border_subtle;
361        let crosshair_color = colors.border_strong;
362        let surface_color = colors.surface;
363        let ticks = scale.ticks.clone();
364        let plot_height = self.height;
365        let loading_alpha = if self.loading { 0.45 } else { 1.0 };
366
367        let st_paint = st_rc.clone();
368        let st_down = st_rc.clone();
369        let st_move = st_rc.clone();
370        let st_leave = st_rc.clone();
371        let st_key = st_rc.clone();
372
373        let plot_canvas = canvas(
374            move |bounds, _w, _cx| {
375                st_paint.borrow_mut().plot_bounds = Some(bounds);
376                bounds
377            },
378            move |bounds, _, window, _cx| {
379                let left: f32 = bounds.origin.x.into();
380                let top: f32 = bounds.origin.y.into();
381                let w: f32 = bounds.size.width.into();
382                let h: f32 = bounds.size.height.into();
383                if w <= 2.0 || h <= 2.0 {
384                    return;
385                }
386                let span = (anim_max - anim_min).abs().max(1e-4);
387                let usable_h = (h - LINE_CHART_TOP_PAD).max(8.0);
388                let to_y = |v: f32| -> f32 {
389                    top + LINE_CHART_TOP_PAD + (1.0 - (v - anim_min) / span) * usable_h
390                };
391
392                // Gridlines
393                for &t in &ticks {
394                    let y = to_y(t as f32).round();
395                    if y >= top && y <= top + h {
396                        window.paint_quad(fill(
397                            Bounds::new(point(px(left), px(y)), size(px(w), px(1.0))),
398                            grid_color,
399                        ));
400                    }
401                }
402
403                // Series paths (areas first, then strokes)
404                for rs in &render_series {
405                    if rs.presence <= 0.02 || rs.curve.len() < 2 {
406                        continue;
407                    }
408                    let pts: Vec<Point<Pixels>> = rs
409                        .curve
410                        .iter()
411                        .map(|&(xn, yv)| {
412                            let y_val = anim_min + (yv as f32 - anim_min) * rs.presence;
413                            point(px(left + xn as f32 * w), px(to_y(y_val)))
414                        })
415                        .collect();
416                    let drawn_pts = slice_polyline_by_progress(&pts, draw_progress);
417                    if rs.area {
418                        let area_col = oklab_mix(rs.color, surface_color, 0.14)
419                            .alpha(0.24 * rs.presence * loading_alpha);
420                        if let Some(area_path) = build_area_fill(&drawn_pts, px(top + h)) {
421                            window.paint_path(area_path, area_col);
422                        }
423                    }
424                    let stroke_col = rs.color.alpha(rs.color.a * rs.presence * loading_alpha);
425                    if rs.dashed {
426                        for dash in build_dashed_polyline(&drawn_pts, 2.0, 5.0, 4.0) {
427                            window.paint_path(dash, stroke_col);
428                        }
429                    } else if let Some(path) = build_polyline_stroke(&drawn_pts, 2.2) {
430                        window.paint_path(path, stroke_col);
431                    }
432                }
433
434                // Crosshair + per-series dots while scrubbing
435                if scrubbing && count > 0 {
436                    let cx_px = left + cursor_norm * w;
437                    window.paint_quad(fill(
438                        Bounds::new(point(px(cx_px - 0.5), px(top)), size(px(1.0), px(h))),
439                        crosshair_color,
440                    ));
441                    for rs in &render_series {
442                        if rs.presence <= 0.3 || rs.curve.is_empty() {
443                            continue;
444                        }
445                        let val = sample_curve_at(&rs.curve, cursor_norm as f64) as f32;
446                        let y_val = anim_min + (val - anim_min) * rs.presence;
447                        let cy_px = to_y(y_val);
448                        if let Some(halo) = build_circle_fill(cx_px, cy_px, 5.2, 16) {
449                            window.paint_path(halo, surface_color);
450                        }
451                        if let Some(dot) = build_circle_fill(cx_px, cy_px, 3.6, 16) {
452                            window.paint_path(dot, rs.color.alpha(rs.color.a * rs.presence));
453                        }
454                    }
455                }
456            },
457        )
458        .w_full()
459        .h(px(plot_height));
460
461        // Floating tooltip when scrubbing (auto-flips left/right at plot midpoint)
462        let tooltip_el = active_idx.and_then(|idx| self.data.get(idx)).map(|datum| {
463            let cx_px = cursor_norm * plot_w;
464            let tip_w = 168.0f32;
465            let flip_left = cx_px + 14.0 + tip_w > plot_w;
466            let left_px = if flip_left {
467                (cx_px - 14.0 - tip_w).max(4.0)
468            } else {
469                (cx_px + 14.0).min((plot_w - tip_w).max(4.0))
470            };
471            let unit_suffix = if self.unit.is_empty() {
472                String::new()
473            } else {
474                format!(" {}", self.unit)
475            };
476
477            let mut card = div()
478                .absolute()
479                .left(px(left_px))
480                .top(px(12.0))
481                .w(px(tip_w))
482                .p(Spacing::S2)
483                .rounded(Radii::CONTROL)
484                .border_1()
485                .border_color(colors.border)
486                .bg(colors.surface_raised)
487                .flex()
488                .flex_col()
489                .gap(px(4.0))
490                .child(
491                    div()
492                        .text_size(Typography::TEXT_XS)
493                        .font_semibold()
494                        .text_color(colors.foreground)
495                        .child(datum.label.clone()),
496                );
497
498            for (s_idx, s) in self.series.iter().enumerate() {
499                if hidden_set.contains(&s.key) {
500                    continue;
501                }
502                let val = datum.values.get(&s.key).copied().unwrap_or(0.0);
503                let col = s
504                    .color
505                    .unwrap_or_else(|| chart_series_color(&colors, s_idx));
506                card = card.child(
507                    div()
508                        .flex()
509                        .items_center()
510                        .justify_between()
511                        .gap(Spacing::S2)
512                        .child(
513                            div()
514                                .flex()
515                                .items_center()
516                                .gap(px(6.0))
517                                .child(div().w(px(7.0)).h(px(7.0)).rounded(Radii::PILL).bg(col))
518                                .child(
519                                    div()
520                                        .text_size(Typography::TEXT_XS)
521                                        .text_color(colors.text_secondary)
522                                        .child(s.label.clone()),
523                                ),
524                        )
525                        .child(
526                            div()
527                                .text_size(Typography::TEXT_XS)
528                                .font_medium()
529                                .text_color(colors.foreground)
530                                .child(format!("{}{}", format_grouped(val, 1), unit_suffix)),
531                        ),
532                );
533            }
534            card
535        });
536
537        // Y-axis ticks on left
538        let usable_h = (plot_height - LINE_CHART_TOP_PAD).max(8.0);
539        let span = (anim_max - anim_min).abs().max(1e-4);
540        let mut y_axis = div().w(px(44.0)).h(px(plot_height)).flex_none().relative();
541        for &t in &scale.ticks {
542            let y = (LINE_CHART_TOP_PAD + (1.0 - (t as f32 - anim_min) / span) * usable_h - 7.0)
543                .clamp(0.0, (plot_height - 14.0).max(0.0));
544            y_axis = y_axis.child(
545                div()
546                    .absolute()
547                    .top(px(y))
548                    .right(px(6.0))
549                    .text_size(Typography::TEXT_XS)
550                    .text_color(colors.text_muted)
551                    .child(format_compact(t)),
552            );
553        }
554
555        // X-axis labels
556        let axis_picks = line_chart_axis_picks(&self.data, plot_w);
557        let mut x_axis = div().w_full().h(px(20.0)).relative();
558        if last > 0 {
559            for idx in axis_picks {
560                if let Some(ref text) = self.data[idx].axis_label {
561                    let frac = idx as f32 / last as f32;
562                    let left_px = (frac * plot_w - 28.0).clamp(0.0, (plot_w - 56.0).max(0.0));
563                    x_axis = x_axis.child(
564                        div()
565                            .absolute()
566                            .left(px(left_px))
567                            .top(px(2.0))
568                            .w(px(56.0))
569                            .flex()
570                            .justify_center()
571                            .text_size(Typography::TEXT_XS)
572                            .text_color(if active_idx == Some(idx) {
573                                colors.foreground
574                            } else {
575                                colors.text_muted
576                            })
577                            .child(text.clone()),
578                    );
579                }
580            }
581        }
582
583        // Legend chips
584        let legend_row = if show_legend {
585            let mut row = div().flex().items_center().flex_wrap().gap(Spacing::S2);
586            for (idx, s) in self.series.iter().enumerate() {
587                let is_hidden = hidden_set.contains(&s.key);
588                let col = s.color.unwrap_or_else(|| chart_series_color(&colors, idx));
589                let key = s.key.clone();
590                let st_toggle = st_rc.clone();
591                row = row.child(
592                    div()
593                        .id(SharedString::from(format!(
594                            "arc-linechart-leg-{:?}-{}",
595                            self.id, idx
596                        )))
597                        .px(Spacing::S2)
598                        .py(px(3.0))
599                        .rounded(Radii::PILL)
600                        .border_1()
601                        .border_color(if is_hidden {
602                            colors.border_subtle
603                        } else {
604                            colors.border
605                        })
606                        .bg(if is_hidden {
607                            colors.surface
608                        } else {
609                            colors.surface_muted
610                        })
611                        .cursor_pointer()
612                        .flex()
613                        .items_center()
614                        .gap(px(6.0))
615                        .on_mouse_down(MouseButton::Left, move |_, window, _cx| {
616                            let mut st = st_toggle.borrow_mut();
617                            if !st.own_hidden.remove(&key) {
618                                st.own_hidden.insert(key.clone());
619                            }
620                            window.refresh();
621                        })
622                        .child(
623                            div()
624                                .w(px(10.0))
625                                .h(px(3.0))
626                                .rounded(Radii::PILL)
627                                .bg(if is_hidden { colors.border_strong } else { col }),
628                        )
629                        .child(
630                            div()
631                                .text_size(Typography::TEXT_XS)
632                                .font_medium()
633                                .text_color(if is_hidden {
634                                    colors.text_muted
635                                } else {
636                                    colors.foreground
637                                })
638                                .child(s.label.clone()),
639                        ),
640                );
641            }
642            Some(row)
643        } else {
644            None
645        };
646
647        div()
648            .id(self.id)
649            .w_full()
650            .p(Spacing::S5)
651            .rounded(Radii::PANEL)
652            .border_1()
653            .border_color(colors.border)
654            .bg(colors.surface)
655            .flex()
656            .flex_col()
657            .gap(Spacing::S3)
658            .child(
659                div()
660                    .flex()
661                    .items_center()
662                    .justify_between()
663                    .flex_wrap()
664                    .gap(Spacing::S2)
665                    .child(
666                        div()
667                            .text_size(Typography::TEXT_SM)
668                            .font_semibold()
669                            .text_color(colors.foreground)
670                            .child(self.label),
671                    )
672                    .when_some(legend_row, |this, leg| this.child(leg)),
673            )
674            .child(if count == 0 {
675                div()
676                    .w_full()
677                    .h(px(plot_height))
678                    .flex()
679                    .items_center()
680                    .justify_center()
681                    .text_size(Typography::TEXT_SM)
682                    .text_color(colors.text_muted)
683                    .child(self.empty_label)
684                    .into_any_element()
685            } else {
686                div()
687                    .w_full()
688                    .flex()
689                    .items_start()
690                    .child(y_axis)
691                    .child(
692                        div()
693                            .flex_1()
694                            .min_w_0()
695                            .flex()
696                            .flex_col()
697                            .child(
698                                div()
699                                    .id(SharedString::from(format!("arc-linechart-plot-{}", count)))
700                                    .relative()
701                                    .w_full()
702                                    .h(px(plot_height))
703                                    .track_focus(&focus_handle)
704                                    .role(Role::Slider)
705                                    .cursor_pointer()
706                                    .on_mouse_down(
707                                        MouseButton::Left,
708                                        move |ev: &MouseDownEvent, window, _cx| {
709                                            let bounds = st_down.borrow().plot_bounds;
710                                            if let Some(b) = bounds {
711                                                let x: f32 = ev.position.x.into();
712                                                let left: f32 = b.origin.x.into();
713                                                let w: f32 = b.size.width.into();
714                                                st_down.borrow_mut().active =
715                                                    Some(line_chart_index_at(x, left, w, count));
716                                                window.refresh();
717                                            }
718                                        },
719                                    )
720                                    .on_mouse_move(move |ev: &MouseMoveEvent, window, _cx| {
721                                        let bounds = st_move.borrow().plot_bounds;
722                                        if let Some(b) = bounds {
723                                            let x: f32 = ev.position.x.into();
724                                            let y: f32 = ev.position.y.into();
725                                            let left: f32 = b.origin.x.into();
726                                            let top: f32 = b.origin.y.into();
727                                            let w: f32 = b.size.width.into();
728                                            let h: f32 = b.size.height.into();
729                                            let inside = x >= left
730                                                && x <= left + w
731                                                && y >= top
732                                                && y <= top + h;
733                                            let next = if inside {
734                                                Some(line_chart_index_at(x, left, w, count))
735                                            } else {
736                                                None
737                                            };
738                                            let mut st = st_move.borrow_mut();
739                                            if st.active != next {
740                                                st.active = next;
741                                                window.refresh();
742                                            }
743                                        }
744                                    })
745                                    .on_hover(move |hovered, window, _cx| {
746                                        if !*hovered {
747                                            let mut st = st_leave.borrow_mut();
748                                            if st.active.is_some() {
749                                                st.active = None;
750                                                window.refresh();
751                                            }
752                                        }
753                                    })
754                                    .on_key_down(move |ev: &KeyDownEvent, window, _cx| {
755                                        let mut st = st_key.borrow_mut();
756                                        let cur = st.active.unwrap_or(last);
757                                        let next = match ev.keystroke.key.as_str() {
758                                            "escape" => {
759                                                st.active = None;
760                                                window.refresh();
761                                                return;
762                                            }
763                                            "left" | "down" => cur.saturating_sub(1),
764                                            "right" | "up" => (cur + 1).min(last),
765                                            "home" => 0,
766                                            "end" => last,
767                                            _ => return,
768                                        };
769                                        st.active = Some(next);
770                                        window.refresh();
771                                    })
772                                    .child(plot_canvas)
773                                    .when_some(tooltip_el, |this, tip| this.child(tip)),
774                            )
775                            .child(x_axis),
776                    )
777                    .into_any_element()
778            })
779    }
780}
781
782#[cfg(test)]
783mod tests {
784    use super::*;
785
786    #[test]
787    fn line_chart_extents_and_axis_picks() {
788        let series = vec![
789            LineChartSeries::new("a", "Current"),
790            LineChartSeries::new("b", "Previous").dashed(true),
791        ];
792        let data = vec![
793            LineChartDatum::new("d1", "Day 1")
794                .axis_label("Sep 1")
795                .value("a", 120.0)
796                .value("b", 80.0),
797            LineChartDatum::new("d2", "Day 2")
798                .axis_label("Sep 2")
799                .value("a", 240.0)
800                .value("b", 90.0),
801            LineChartDatum::new("d3", "Day 3")
802                .axis_label("Sep 3")
803                .value("a", 180.0)
804                .value("b", 110.0),
805        ];
806        let hidden = HashSet::new();
807        assert_eq!(
808            line_chart_visible_extents(&data, &series, &hidden),
809            Some((80.0, 240.0))
810        );
811
812        let mut hide_a = HashSet::new();
813        hide_a.insert(SharedString::from("a"));
814        assert_eq!(
815            line_chart_visible_extents(&data, &series, &hide_a),
816            Some((80.0, 110.0))
817        );
818
819        let picks = line_chart_axis_picks(&data, 320.0);
820        assert_eq!(*picks.last().unwrap(), 2);
821        assert_eq!(line_chart_index_at(50.0, 0.0, 100.0, 3), 1);
822    }
823}