arc-ui 0.4.0

Physics-first native Rust desktop UI component library & charts for GPUI (120+ interactive components ported from Arc).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! `LineChart`: multi-series trend chart with smooth monotone / linear curves, faint area wash,
//! dashed reference series, interactive legend toggle with Y-axis rescaling, spring crosshair,
//! and auto-flipping floating tooltip.

use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;

use arc_motion::{arc_spring_with_options, is_reduced_motion, motion_now, spring::SpringOptions};
use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, SpringSpec, Typography, oklab_mix};
use gpui_kit::{
    App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
    MouseDownEvent, MouseMoveEvent, ParentElement, Pixels, Point, RenderOnce, Role, SharedString,
    Styled, Window, base::StyledExt as _, canvas, div, fill, point, prelude::*, px, size,
};

use super::common::{
    build_area_fill, build_circle_fill, build_dashed_polyline, build_polyline_stroke,
    chart_series_color, format_compact, format_grouped, nice_scale, sample_curve_at,
    sample_monotone_curve, slice_polyline_by_progress,
};

pub const LINE_CHART_TOP_PAD: f32 = 12.0;

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum LineCurve {
    #[default]
    Smooth,
    Linear,
}

#[derive(Clone, Debug)]
pub struct LineChartSeries {
    pub key: SharedString,
    pub label: SharedString,
    pub color: Option<Hsla>,
    pub dashed: bool,
    pub area: Option<bool>,
}

impl LineChartSeries {
    pub fn new(key: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
        Self {
            key: key.into(),
            label: label.into(),
            color: None,
            dashed: false,
            area: None,
        }
    }

    pub fn color(mut self, color: Hsla) -> Self {
        self.color = Some(color);
        self
    }

    pub fn dashed(mut self, dashed: bool) -> Self {
        self.dashed = dashed;
        self
    }

    pub fn area(mut self, area: bool) -> Self {
        self.area = Some(area);
        self
    }
}

#[derive(Clone, Debug)]
pub struct LineChartDatum {
    pub key: SharedString,
    pub label: SharedString,
    pub axis_label: Option<SharedString>,
    pub values: HashMap<SharedString, f64>,
}

impl LineChartDatum {
    pub fn new(key: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
        Self {
            key: key.into(),
            label: label.into(),
            axis_label: None,
            values: HashMap::new(),
        }
    }

    pub fn axis_label(mut self, label: impl Into<SharedString>) -> Self {
        self.axis_label = Some(label.into());
        self
    }

    pub fn value(mut self, series_key: impl Into<SharedString>, val: f64) -> Self {
        self.values.insert(series_key.into(), val);
        self
    }
}

/// Compute `(min, max)` across all visible series in `data`.
pub fn line_chart_visible_extents(
    data: &[LineChartDatum],
    series: &[LineChartSeries],
    hidden: &HashSet<SharedString>,
) -> Option<(f64, f64)> {
    let mut lo = f64::INFINITY;
    let mut hi = f64::NEG_INFINITY;
    for s in series {
        if hidden.contains(&s.key) {
            continue;
        }
        for d in data {
            let v = d.values.get(&s.key).copied().unwrap_or(0.0);
            lo = lo.min(v);
            hi = hi.max(v);
        }
    }
    if lo.is_finite() && hi.is_finite() {
        Some((lo, hi))
    } else {
        None
    }
}

/// Choose evenly thinned X-axis label indices counted back from the latest datum.
pub fn line_chart_axis_picks(data: &[LineChartDatum], width: f32) -> Vec<usize> {
    let labeled: Vec<usize> = data
        .iter()
        .enumerate()
        .filter_map(|(i, d)| d.axis_label.as_ref().map(|_| i))
        .collect();
    if width <= 20.0 || labeled.is_empty() {
        return Vec::new();
    }
    let room = (width / 76.0).floor().max(2.0) as usize;
    let stride = labeled.len().div_ceil(room).max(1);
    let mut out: Vec<usize> = labeled
        .into_iter()
        .rev()
        .enumerate()
        .filter_map(|(rank, i)| if rank % stride == 0 { Some(i) } else { None })
        .collect();
    out.reverse();
    out
}

/// Map pointer x to nearest datum index.
pub fn line_chart_index_at(x: f32, left: f32, width: f32, count: usize) -> usize {
    if count <= 1 || width <= 1e-4 {
        return 0;
    }
    let frac = ((x - left) / width).clamp(0.0, 1.0);
    (frac * (count - 1) as f32).round() as usize
}

struct LineChartState {
    active: Option<usize>,
    own_hidden: HashSet<SharedString>,
    mounted_at_secs: Option<f64>,
    plot_bounds: Option<Bounds<Pixels>>,
    focus: FocusHandle,
}

#[derive(IntoElement)]
pub struct LineChart {
    id: ElementId,
    label: SharedString,
    series: Vec<LineChartSeries>,
    data: Vec<LineChartDatum>,
    unit: SharedString,
    height: f32,
    curve: LineCurve,
    legend: Option<bool>,
    loading: bool,
    empty_label: SharedString,
}

impl LineChart {
    pub fn new(
        id: impl Into<ElementId>,
        label: impl Into<SharedString>,
        series: Vec<LineChartSeries>,
        data: Vec<LineChartDatum>,
    ) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            series,
            data,
            unit: SharedString::default(),
            height: 220.0,
            curve: LineCurve::Smooth,
            legend: None,
            loading: false,
            empty_label: SharedString::from("No data for this range"),
        }
    }

    pub fn unit(mut self, unit: impl Into<SharedString>) -> Self {
        self.unit = unit.into();
        self
    }

    pub fn height(mut self, px_val: f32) -> Self {
        self.height = px_val.clamp(120.0, 420.0);
        self
    }

    pub fn curve(mut self, curve: LineCurve) -> Self {
        self.curve = curve;
        self
    }

    pub fn legend(mut self, show: bool) -> Self {
        self.legend = Some(show);
        self
    }

    pub fn loading(mut self, loading: bool) -> Self {
        self.loading = loading;
        self
    }

    pub fn empty_label(mut self, label: impl Into<SharedString>) -> Self {
        self.empty_label = label.into();
        self
    }
}

impl RenderOnce for LineChart {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = cx.arc_theme().clone();
        let colors = theme.colors;
        let reduced = is_reduced_motion(cx);
        let now = motion_now(cx);

        let count = self.data.len();
        let last = count.saturating_sub(1);
        let show_legend = self.legend.unwrap_or(self.series.len() > 1);

        let state = window.use_keyed_state(
            SharedString::from(format!("arc-linechart-state-{:?}", self.id)),
            cx,
            |_w, cx| {
                Rc::new(RefCell::new(LineChartState {
                    active: None,
                    own_hidden: HashSet::new(),
                    mounted_at_secs: None,
                    plot_bounds: None,
                    focus: cx.focus_handle(),
                }))
            },
        );
        let st_rc = state.read(cx).clone();
        let (active_idx, hidden_set, focus_handle, draw_progress, plot_w) = {
            let mut st = st_rc.borrow_mut();
            let start = *st.mounted_at_secs.get_or_insert(now);
            let progress = if reduced {
                1.0
            } else {
                let dur = 0.7f64;
                let t = ((now - start) / dur).clamp(0.0, 1.0) as f32;
                let eased = if t < 0.5 {
                    4.0 * t * t * t
                } else {
                    1.0 - (-2.0 * t + 2.0).powi(3) * 0.5
                };
                if t < 1.0 {
                    window.request_animation_frame();
                }
                eased
            };
            let w: f32 = st.plot_bounds.map(|b| b.size.width.into()).unwrap_or(520.0);
            (
                st.active.filter(|_| count > 0).map(|i| i.min(last)),
                st.own_hidden.clone(),
                st.focus.clone(),
                progress,
                w,
            )
        };

        let extents = line_chart_visible_extents(&self.data, &self.series, &hidden_set)
            .unwrap_or((0.0, 100.0));
        let scale = nice_scale(extents.0, extents.1, 4);

        let anim_min = arc_spring_with_options(
            SharedString::from(format!("arc-linechart-min-{:?}", self.id)),
            scale.min as f32,
            SpringOptions::new(SpringSpec::visual(0.36, 0.0)),
            window,
            cx,
        )
        .value;
        let anim_max = arc_spring_with_options(
            SharedString::from(format!("arc-linechart-max-{:?}", self.id)),
            scale.max as f32,
            SpringOptions::new(SpringSpec::visual(0.36, 0.0)),
            window,
            cx,
        )
        .value;

        let scrubbing = active_idx.is_some();
        let cursor_target = active_idx
            .map(|i| {
                if last > 0 {
                    i as f32 / last as f32
                } else {
                    0.5
                }
            })
            .unwrap_or(1.0);
        let cursor_norm = arc_spring_with_options(
            SharedString::from(format!("arc-linechart-cursor-{:?}", self.id)),
            cursor_target,
            SpringOptions::new(SpringSpec::visual(0.22, 0.0)),
            window,
            cx,
        )
        .value
        .clamp(0.0, 1.0);

        let smooth = self.curve == LineCurve::Smooth;

        // Precompute curves + animated presence per series
        struct RenderSeries {
            color: Hsla,
            dashed: bool,
            area: bool,
            presence: f32,
            curve: Vec<(f64, f64)>,
        }
        let mut render_series = Vec::with_capacity(self.series.len());
        for (idx, s) in self.series.iter().enumerate() {
            let visible = !hidden_set.contains(&s.key);
            let presence = arc_spring_with_options(
                SharedString::from(format!("arc-linechart-vis-{:?}-{}", self.id, s.key)),
                if visible { 1.0 } else { 0.0 },
                SpringOptions::new(SpringSpec::visual(0.32, 0.0)),
                window,
                cx,
            )
            .value
            .clamp(0.0, 1.0);
            let vals: Vec<f64> = self
                .data
                .iter()
                .map(|d| d.values.get(&s.key).copied().unwrap_or(0.0))
                .collect();
            let color = s.color.unwrap_or_else(|| chart_series_color(&colors, idx));
            let area = s.area.unwrap_or(idx == 0);
            render_series.push(RenderSeries {
                color,
                dashed: s.dashed,
                area,
                presence,
                curve: sample_monotone_curve(&vals, smooth, 160),
            });
        }

        let grid_color = colors.border_subtle;
        let crosshair_color = colors.border_strong;
        let surface_color = colors.surface;
        let ticks = scale.ticks.clone();
        let plot_height = self.height;
        let loading_alpha = if self.loading { 0.45 } else { 1.0 };

        let st_paint = st_rc.clone();
        let st_down = st_rc.clone();
        let st_move = st_rc.clone();
        let st_leave = st_rc.clone();
        let st_key = st_rc.clone();

        let plot_canvas = canvas(
            move |bounds, _w, _cx| {
                st_paint.borrow_mut().plot_bounds = Some(bounds);
                bounds
            },
            move |bounds, _, window, _cx| {
                let left: f32 = bounds.origin.x.into();
                let top: f32 = bounds.origin.y.into();
                let w: f32 = bounds.size.width.into();
                let h: f32 = bounds.size.height.into();
                if w <= 2.0 || h <= 2.0 {
                    return;
                }
                let span = (anim_max - anim_min).abs().max(1e-4);
                let usable_h = (h - LINE_CHART_TOP_PAD).max(8.0);
                let to_y = |v: f32| -> f32 {
                    top + LINE_CHART_TOP_PAD + (1.0 - (v - anim_min) / span) * usable_h
                };

                // Gridlines
                for &t in &ticks {
                    let y = to_y(t as f32).round();
                    if y >= top && y <= top + h {
                        window.paint_quad(fill(
                            Bounds::new(point(px(left), px(y)), size(px(w), px(1.0))),
                            grid_color,
                        ));
                    }
                }

                // Series paths (areas first, then strokes)
                for rs in &render_series {
                    if rs.presence <= 0.02 || rs.curve.len() < 2 {
                        continue;
                    }
                    let pts: Vec<Point<Pixels>> = rs
                        .curve
                        .iter()
                        .map(|&(xn, yv)| {
                            let y_val = anim_min + (yv as f32 - anim_min) * rs.presence;
                            point(px(left + xn as f32 * w), px(to_y(y_val)))
                        })
                        .collect();
                    let drawn_pts = slice_polyline_by_progress(&pts, draw_progress);
                    if rs.area {
                        let area_col = oklab_mix(rs.color, surface_color, 0.14)
                            .alpha(0.24 * rs.presence * loading_alpha);
                        if let Some(area_path) = build_area_fill(&drawn_pts, px(top + h)) {
                            window.paint_path(area_path, area_col);
                        }
                    }
                    let stroke_col = rs.color.alpha(rs.color.a * rs.presence * loading_alpha);
                    if rs.dashed {
                        for dash in build_dashed_polyline(&drawn_pts, 2.0, 5.0, 4.0) {
                            window.paint_path(dash, stroke_col);
                        }
                    } else if let Some(path) = build_polyline_stroke(&drawn_pts, 2.2) {
                        window.paint_path(path, stroke_col);
                    }
                }

                // Crosshair + per-series dots while scrubbing
                if scrubbing && count > 0 {
                    let cx_px = left + cursor_norm * w;
                    window.paint_quad(fill(
                        Bounds::new(point(px(cx_px - 0.5), px(top)), size(px(1.0), px(h))),
                        crosshair_color,
                    ));
                    for rs in &render_series {
                        if rs.presence <= 0.3 || rs.curve.is_empty() {
                            continue;
                        }
                        let val = sample_curve_at(&rs.curve, cursor_norm as f64) as f32;
                        let y_val = anim_min + (val - anim_min) * rs.presence;
                        let cy_px = to_y(y_val);
                        if let Some(halo) = build_circle_fill(cx_px, cy_px, 5.2, 16) {
                            window.paint_path(halo, surface_color);
                        }
                        if let Some(dot) = build_circle_fill(cx_px, cy_px, 3.6, 16) {
                            window.paint_path(dot, rs.color.alpha(rs.color.a * rs.presence));
                        }
                    }
                }
            },
        )
        .w_full()
        .h(px(plot_height));

        // Floating tooltip when scrubbing (auto-flips left/right at plot midpoint)
        let tooltip_el = active_idx.and_then(|idx| self.data.get(idx)).map(|datum| {
            let cx_px = cursor_norm * plot_w;
            let tip_w = 168.0f32;
            let flip_left = cx_px + 14.0 + tip_w > plot_w;
            let left_px = if flip_left {
                (cx_px - 14.0 - tip_w).max(4.0)
            } else {
                (cx_px + 14.0).min((plot_w - tip_w).max(4.0))
            };
            let unit_suffix = if self.unit.is_empty() {
                String::new()
            } else {
                format!(" {}", self.unit)
            };

            let mut card = div()
                .absolute()
                .left(px(left_px))
                .top(px(12.0))
                .w(px(tip_w))
                .p(Spacing::S2)
                .rounded(Radii::CONTROL)
                .border_1()
                .border_color(colors.border)
                .bg(colors.surface_raised)
                .flex()
                .flex_col()
                .gap(px(4.0))
                .child(
                    div()
                        .text_size(Typography::TEXT_XS)
                        .font_semibold()
                        .text_color(colors.foreground)
                        .child(datum.label.clone()),
                );

            for (s_idx, s) in self.series.iter().enumerate() {
                if hidden_set.contains(&s.key) {
                    continue;
                }
                let val = datum.values.get(&s.key).copied().unwrap_or(0.0);
                let col = s
                    .color
                    .unwrap_or_else(|| chart_series_color(&colors, s_idx));
                card = card.child(
                    div()
                        .flex()
                        .items_center()
                        .justify_between()
                        .gap(Spacing::S2)
                        .child(
                            div()
                                .flex()
                                .items_center()
                                .gap(px(6.0))
                                .child(div().w(px(7.0)).h(px(7.0)).rounded(Radii::PILL).bg(col))
                                .child(
                                    div()
                                        .text_size(Typography::TEXT_XS)
                                        .text_color(colors.text_secondary)
                                        .child(s.label.clone()),
                                ),
                        )
                        .child(
                            div()
                                .text_size(Typography::TEXT_XS)
                                .font_medium()
                                .text_color(colors.foreground)
                                .child(format!("{}{}", format_grouped(val, 1), unit_suffix)),
                        ),
                );
            }
            card
        });

        // Y-axis ticks on left
        let usable_h = (plot_height - LINE_CHART_TOP_PAD).max(8.0);
        let span = (anim_max - anim_min).abs().max(1e-4);
        let mut y_axis = div().w(px(44.0)).h(px(plot_height)).flex_none().relative();
        for &t in &scale.ticks {
            let y = (LINE_CHART_TOP_PAD + (1.0 - (t as f32 - anim_min) / span) * usable_h - 7.0)
                .clamp(0.0, (plot_height - 14.0).max(0.0));
            y_axis = y_axis.child(
                div()
                    .absolute()
                    .top(px(y))
                    .right(px(6.0))
                    .text_size(Typography::TEXT_XS)
                    .text_color(colors.text_muted)
                    .child(format_compact(t)),
            );
        }

        // X-axis labels
        let axis_picks = line_chart_axis_picks(&self.data, plot_w);
        let mut x_axis = div().w_full().h(px(20.0)).relative();
        if last > 0 {
            for idx in axis_picks {
                if let Some(ref text) = self.data[idx].axis_label {
                    let frac = idx as f32 / last as f32;
                    let left_px = (frac * plot_w - 28.0).clamp(0.0, (plot_w - 56.0).max(0.0));
                    x_axis = x_axis.child(
                        div()
                            .absolute()
                            .left(px(left_px))
                            .top(px(2.0))
                            .w(px(56.0))
                            .flex()
                            .justify_center()
                            .text_size(Typography::TEXT_XS)
                            .text_color(if active_idx == Some(idx) {
                                colors.foreground
                            } else {
                                colors.text_muted
                            })
                            .child(text.clone()),
                    );
                }
            }
        }

        // Legend chips
        let legend_row = if show_legend {
            let mut row = div().flex().items_center().flex_wrap().gap(Spacing::S2);
            for (idx, s) in self.series.iter().enumerate() {
                let is_hidden = hidden_set.contains(&s.key);
                let col = s.color.unwrap_or_else(|| chart_series_color(&colors, idx));
                let key = s.key.clone();
                let st_toggle = st_rc.clone();
                row = row.child(
                    div()
                        .id(SharedString::from(format!(
                            "arc-linechart-leg-{:?}-{}",
                            self.id, idx
                        )))
                        .px(Spacing::S2)
                        .py(px(3.0))
                        .rounded(Radii::PILL)
                        .border_1()
                        .border_color(if is_hidden {
                            colors.border_subtle
                        } else {
                            colors.border
                        })
                        .bg(if is_hidden {
                            colors.surface
                        } else {
                            colors.surface_muted
                        })
                        .cursor_pointer()
                        .flex()
                        .items_center()
                        .gap(px(6.0))
                        .on_mouse_down(MouseButton::Left, move |_, window, _cx| {
                            let mut st = st_toggle.borrow_mut();
                            if !st.own_hidden.remove(&key) {
                                st.own_hidden.insert(key.clone());
                            }
                            window.refresh();
                        })
                        .child(
                            div()
                                .w(px(10.0))
                                .h(px(3.0))
                                .rounded(Radii::PILL)
                                .bg(if is_hidden { colors.border_strong } else { col }),
                        )
                        .child(
                            div()
                                .text_size(Typography::TEXT_XS)
                                .font_medium()
                                .text_color(if is_hidden {
                                    colors.text_muted
                                } else {
                                    colors.foreground
                                })
                                .child(s.label.clone()),
                        ),
                );
            }
            Some(row)
        } else {
            None
        };

        div()
            .id(self.id)
            .w_full()
            .p(Spacing::S5)
            .rounded(Radii::PANEL)
            .border_1()
            .border_color(colors.border)
            .bg(colors.surface)
            .flex()
            .flex_col()
            .gap(Spacing::S3)
            .child(
                div()
                    .flex()
                    .items_center()
                    .justify_between()
                    .flex_wrap()
                    .gap(Spacing::S2)
                    .child(
                        div()
                            .text_size(Typography::TEXT_SM)
                            .font_semibold()
                            .text_color(colors.foreground)
                            .child(self.label),
                    )
                    .when_some(legend_row, |this, leg| this.child(leg)),
            )
            .child(if count == 0 {
                div()
                    .w_full()
                    .h(px(plot_height))
                    .flex()
                    .items_center()
                    .justify_center()
                    .text_size(Typography::TEXT_SM)
                    .text_color(colors.text_muted)
                    .child(self.empty_label)
                    .into_any_element()
            } else {
                div()
                    .w_full()
                    .flex()
                    .items_start()
                    .child(y_axis)
                    .child(
                        div()
                            .flex_1()
                            .min_w_0()
                            .flex()
                            .flex_col()
                            .child(
                                div()
                                    .id(SharedString::from(format!("arc-linechart-plot-{}", count)))
                                    .relative()
                                    .w_full()
                                    .h(px(plot_height))
                                    .track_focus(&focus_handle)
                                    .role(Role::Slider)
                                    .cursor_pointer()
                                    .on_mouse_down(
                                        MouseButton::Left,
                                        move |ev: &MouseDownEvent, window, _cx| {
                                            let bounds = st_down.borrow().plot_bounds;
                                            if let Some(b) = bounds {
                                                let x: f32 = ev.position.x.into();
                                                let left: f32 = b.origin.x.into();
                                                let w: f32 = b.size.width.into();
                                                st_down.borrow_mut().active =
                                                    Some(line_chart_index_at(x, left, w, count));
                                                window.refresh();
                                            }
                                        },
                                    )
                                    .on_mouse_move(move |ev: &MouseMoveEvent, window, _cx| {
                                        let bounds = st_move.borrow().plot_bounds;
                                        if let Some(b) = bounds {
                                            let x: f32 = ev.position.x.into();
                                            let y: f32 = ev.position.y.into();
                                            let left: f32 = b.origin.x.into();
                                            let top: f32 = b.origin.y.into();
                                            let w: f32 = b.size.width.into();
                                            let h: f32 = b.size.height.into();
                                            let inside = x >= left
                                                && x <= left + w
                                                && y >= top
                                                && y <= top + h;
                                            let next = if inside {
                                                Some(line_chart_index_at(x, left, w, count))
                                            } else {
                                                None
                                            };
                                            let mut st = st_move.borrow_mut();
                                            if st.active != next {
                                                st.active = next;
                                                window.refresh();
                                            }
                                        }
                                    })
                                    .on_hover(move |hovered, window, _cx| {
                                        if !*hovered {
                                            let mut st = st_leave.borrow_mut();
                                            if st.active.is_some() {
                                                st.active = None;
                                                window.refresh();
                                            }
                                        }
                                    })
                                    .on_key_down(move |ev: &KeyDownEvent, window, _cx| {
                                        let mut st = st_key.borrow_mut();
                                        let cur = st.active.unwrap_or(last);
                                        let next = match ev.keystroke.key.as_str() {
                                            "escape" => {
                                                st.active = None;
                                                window.refresh();
                                                return;
                                            }
                                            "left" | "down" => cur.saturating_sub(1),
                                            "right" | "up" => (cur + 1).min(last),
                                            "home" => 0,
                                            "end" => last,
                                            _ => return,
                                        };
                                        st.active = Some(next);
                                        window.refresh();
                                    })
                                    .child(plot_canvas)
                                    .when_some(tooltip_el, |this, tip| this.child(tip)),
                            )
                            .child(x_axis),
                    )
                    .into_any_element()
            })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn line_chart_extents_and_axis_picks() {
        let series = vec![
            LineChartSeries::new("a", "Current"),
            LineChartSeries::new("b", "Previous").dashed(true),
        ];
        let data = vec![
            LineChartDatum::new("d1", "Day 1")
                .axis_label("Sep 1")
                .value("a", 120.0)
                .value("b", 80.0),
            LineChartDatum::new("d2", "Day 2")
                .axis_label("Sep 2")
                .value("a", 240.0)
                .value("b", 90.0),
            LineChartDatum::new("d3", "Day 3")
                .axis_label("Sep 3")
                .value("a", 180.0)
                .value("b", 110.0),
        ];
        let hidden = HashSet::new();
        assert_eq!(
            line_chart_visible_extents(&data, &series, &hidden),
            Some((80.0, 240.0))
        );

        let mut hide_a = HashSet::new();
        hide_a.insert(SharedString::from("a"));
        assert_eq!(
            line_chart_visible_extents(&data, &series, &hide_a),
            Some((80.0, 110.0))
        );

        let picks = line_chart_axis_picks(&data, 320.0);
        assert_eq!(*picks.last().unwrap(), 2);
        assert_eq!(line_chart_index_at(50.0, 0.0, 100.0, 3), 1);
    }
}