Skip to main content

fc_ui/capabilities/data/
chart.rs

1use crate::capabilities::data::palette::default_color;
2use crate::capabilities::foundation::theme::use_theme;
3use gpui::{prelude::FluentBuilder as _, *};
4use std::rc::Rc;
5
6#[derive(Clone, Debug)]
7pub struct DataPoint {
8    pub x: f64,
9    pub y: f64,
10    pub label: Option<SharedString>,
11}
12
13impl DataPoint {
14    pub fn new(x: f64, y: f64) -> Self {
15        Self { x, y, label: None }
16    }
17
18    pub fn xy(x: f64, y: f64) -> Self {
19        Self::new(x, y)
20    }
21
22    pub fn labeled(x: f64, y: f64, label: impl Into<SharedString>) -> Self {
23        Self {
24            x,
25            y,
26            label: Some(label.into()),
27        }
28    }
29}
30
31/// Whether a data point can safely participate in range and geometry calculations.
32pub(crate) fn is_finite_data_point(x: f64, y: f64) -> bool {
33    x.is_finite() && y.is_finite()
34}
35
36#[derive(Clone, Debug)]
37pub struct DataRange {
38    pub x_min: f64,
39    pub x_max: f64,
40    pub y_min: f64,
41    pub y_max: f64,
42}
43
44impl DataRange {
45    /// Construct a finite range with ordered, non-zero axes.
46    pub fn new(x_min: f64, x_max: f64, y_min: f64, y_max: f64) -> Self {
47        let (x_min, x_max) = Self::finite_bounds(x_min, x_max);
48        let (y_min, y_max) = Self::finite_bounds(y_min, y_max);
49        Self {
50            x_min,
51            x_max,
52            y_min,
53            y_max,
54        }
55    }
56
57    fn empty() -> Self {
58        Self {
59            x_min: f64::MAX,
60            x_max: f64::MIN,
61            y_min: f64::MAX,
62            y_max: f64::MIN,
63        }
64    }
65
66    fn finite_bounds(min: f64, max: f64) -> (f64, f64) {
67        if !min.is_finite() || !max.is_finite() {
68            return (0.0, 1.0);
69        }
70
71        let (min, max) = if min <= max { (min, max) } else { (max, min) };
72        if (max - min).abs() < f64::EPSILON {
73            let padding = (min.abs() * 0.01).max(0.5);
74            let padded_min = (min - padding).max(f64::MIN);
75            let padded_max = (max + padding).min(f64::MAX);
76            (padded_min, padded_max)
77        } else {
78            (min, max)
79        }
80    }
81
82    pub fn from_points(points: &[DataPoint]) -> Self {
83        let mut x_min = f64::MAX;
84        let mut x_max = f64::MIN;
85        let mut y_min = f64::MAX;
86        let mut y_max = f64::MIN;
87        let mut has_finite_point = false;
88
89        for point in points {
90            if !is_finite_data_point(point.x, point.y) {
91                continue;
92            }
93            has_finite_point = true;
94            x_min = x_min.min(point.x);
95            x_max = x_max.max(point.x);
96            y_min = y_min.min(point.y);
97            y_max = y_max.max(point.y);
98        }
99
100        if !has_finite_point {
101            return Self::default();
102        }
103
104        if (x_max - x_min).abs() < f64::EPSILON {
105            x_max = x_min + 1.0;
106        }
107        if (y_max - y_min).abs() < f64::EPSILON {
108            y_max = y_min + 1.0;
109        }
110
111        Self::new(x_min, x_max, y_min, y_max)
112    }
113
114    pub fn extend(&mut self, other: &DataRange) {
115        self.x_min = self.x_min.min(other.x_min);
116        self.x_max = self.x_max.max(other.x_max);
117        self.y_min = self.y_min.min(other.y_min);
118        self.y_max = self.y_max.max(other.y_max);
119    }
120
121    pub fn normalize_x(&self, x: f64) -> f32 {
122        if !x.is_finite() {
123            return 0.0;
124        }
125        let (min, max) = Self::finite_bounds(self.x_min, self.x_max);
126        ((x - min) / (max - min)) as f32
127    }
128
129    pub fn normalize_y(&self, y: f64) -> f32 {
130        if !y.is_finite() {
131            return 0.0;
132        }
133        let (min, max) = Self::finite_bounds(self.y_min, self.y_max);
134        ((y - min) / (max - min)) as f32
135    }
136
137    pub fn with_padding(&self, padding: f64) -> Self {
138        let x_range = self.x_max - self.x_min;
139        let y_range = self.y_max - self.y_min;
140        Self::new(
141            self.x_min - x_range * padding,
142            self.x_max + x_range * padding,
143            self.y_min - y_range * padding,
144            self.y_max + y_range * padding,
145        )
146    }
147}
148
149impl Default for DataRange {
150    fn default() -> Self {
151        Self::new(0.0, 1.0, 0.0, 1.0)
152    }
153}
154
155#[derive(Clone, Default)]
156pub struct ChartPadding {
157    pub left: f32,
158    pub right: f32,
159    pub top: f32,
160    pub bottom: f32,
161}
162
163impl ChartPadding {
164    pub fn new(left: f32, right: f32, top: f32, bottom: f32) -> Self {
165        Self {
166            left,
167            right,
168            top,
169            bottom,
170        }
171    }
172
173    pub fn all(value: f32) -> Self {
174        Self::new(value, value, value, value)
175    }
176}
177
178#[derive(Clone)]
179pub struct ChartArea {
180    pub bounds: Bounds<Pixels>,
181    pub range: DataRange,
182    pub padding: ChartPadding,
183}
184
185impl ChartArea {
186    pub fn chart_left(&self) -> Pixels {
187        self.bounds.left() + px(self.padding.left)
188    }
189
190    pub fn chart_right(&self) -> Pixels {
191        self.bounds.right() - px(self.padding.right)
192    }
193
194    pub fn chart_top(&self) -> Pixels {
195        self.bounds.top() + px(self.padding.top)
196    }
197
198    pub fn chart_bottom(&self) -> Pixels {
199        self.bounds.bottom() - px(self.padding.bottom)
200    }
201
202    pub fn chart_width(&self) -> Pixels {
203        self.chart_right() - self.chart_left()
204    }
205
206    pub fn chart_height(&self) -> Pixels {
207        self.chart_bottom() - self.chart_top()
208    }
209
210    pub fn data_to_screen(&self, data_point: &DataPoint) -> Point<Pixels> {
211        let norm_x = self.range.normalize_x(data_point.x);
212        let norm_y = self.range.normalize_y(data_point.y);
213        let screen_x = self.chart_left() + self.chart_width() * norm_x;
214        let screen_y = self.chart_bottom() - self.chart_height() * norm_y;
215        point(screen_x, screen_y)
216    }
217
218    pub fn screen_to_data(&self, screen_point: Point<Pixels>) -> DataPoint {
219        let chart_width = self.chart_width();
220        let chart_height = self.chart_height();
221
222        let norm_x = (screen_point.x - self.chart_left()) / chart_width;
223        let norm_y = 1.0 - (screen_point.y - self.chart_top()) / chart_height;
224
225        let x = self.range.x_min + (self.range.x_max - self.range.x_min) * norm_x as f64;
226        let y = self.range.y_min + (self.range.y_max - self.range.y_min) * norm_y as f64;
227
228        DataPoint::new(x, y)
229    }
230}
231
232#[derive(Clone, Default)]
233pub enum AxisPosition {
234    #[default]
235    Left,
236    Right,
237    Top,
238    Bottom,
239}
240
241#[derive(Clone)]
242pub struct Axis {
243    /// Currently not rendered.
244    pub label: Option<SharedString>,
245    /// Currently not honored; the x-axis always renders on the bottom and the
246    /// y-axis on the left.
247    pub position: AxisPosition,
248    pub min: Option<f64>,
249    pub max: Option<f64>,
250    pub tick_count: usize,
251    pub tick_format: Option<Rc<dyn Fn(f64) -> String>>,
252    pub show_grid: bool,
253    /// Currently not rendered.
254    pub show_ticks: bool,
255    pub show_labels: bool,
256}
257
258impl Default for Axis {
259    fn default() -> Self {
260        Self {
261            label: None,
262            position: AxisPosition::default(),
263            min: None,
264            max: None,
265            tick_count: 5,
266            tick_format: None,
267            show_grid: true,
268            show_ticks: true,
269            show_labels: true,
270        }
271    }
272}
273
274impl Axis {
275    pub fn new() -> Self {
276        Self::default()
277    }
278
279    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
280        self.label = Some(label.into());
281        self
282    }
283
284    pub fn position(mut self, position: AxisPosition) -> Self {
285        self.position = position;
286        self
287    }
288
289    pub fn left(mut self) -> Self {
290        self.position = AxisPosition::Left;
291        self
292    }
293
294    pub fn right(mut self) -> Self {
295        self.position = AxisPosition::Right;
296        self
297    }
298
299    pub fn top(mut self) -> Self {
300        self.position = AxisPosition::Top;
301        self
302    }
303
304    pub fn bottom(mut self) -> Self {
305        self.position = AxisPosition::Bottom;
306        self
307    }
308
309    pub fn range(mut self, min: f64, max: f64) -> Self {
310        self.min = Some(min);
311        self.max = Some(max);
312        self
313    }
314
315    pub fn tick_count(mut self, count: usize) -> Self {
316        self.tick_count = count;
317        self
318    }
319
320    pub fn tick_format(mut self, format: impl Fn(f64) -> String + 'static) -> Self {
321        self.tick_format = Some(Rc::new(format));
322        self
323    }
324
325    pub fn show_grid(mut self, show: bool) -> Self {
326        self.show_grid = show;
327        self
328    }
329
330    pub fn show_ticks(mut self, show: bool) -> Self {
331        self.show_ticks = show;
332        self
333    }
334
335    pub fn show_labels(mut self, show: bool) -> Self {
336        self.show_labels = show;
337        self
338    }
339
340    fn format_value(&self, value: f64) -> String {
341        if let Some(ref format) = self.tick_format {
342            format(value)
343        } else if value.abs() >= 1000.0 {
344            format!("{:.0}k", value / 1000.0)
345        } else if value.abs() >= 1.0 {
346            format!("{:.0}", value)
347        } else {
348            format!("{:.2}", value)
349        }
350    }
351}
352
353#[derive(Clone, Default)]
354pub enum LegendPosition {
355    Top,
356    #[default]
357    Bottom,
358    Left,
359    Right,
360}
361
362#[derive(Clone)]
363pub struct Legend {
364    /// Currently not honored; the legend always renders below the chart.
365    pub position: LegendPosition,
366    pub show: bool,
367}
368
369impl Default for Legend {
370    fn default() -> Self {
371        Self {
372            position: LegendPosition::default(),
373            show: true,
374        }
375    }
376}
377
378impl Legend {
379    pub fn new() -> Self {
380        Self::default()
381    }
382
383    pub fn position(mut self, position: LegendPosition) -> Self {
384        self.position = position;
385        self
386    }
387
388    pub fn top(mut self) -> Self {
389        self.position = LegendPosition::Top;
390        self
391    }
392
393    pub fn bottom(mut self) -> Self {
394        self.position = LegendPosition::Bottom;
395        self
396    }
397
398    pub fn left(mut self) -> Self {
399        self.position = LegendPosition::Left;
400        self
401    }
402
403    pub fn right(mut self) -> Self {
404        self.position = LegendPosition::Right;
405        self
406    }
407
408    pub fn show(mut self, show: bool) -> Self {
409        self.show = show;
410        self
411    }
412
413    pub fn hide(mut self) -> Self {
414        self.show = false;
415        self
416    }
417}
418
419#[derive(Clone, Default)]
420pub struct TooltipConfig {
421    pub show: bool,
422    pub format: Option<Rc<dyn Fn(&DataPoint, &str) -> String>>,
423}
424
425impl TooltipConfig {
426    pub fn new() -> Self {
427        Self {
428            show: true,
429            format: None,
430        }
431    }
432
433    pub fn format(mut self, format: impl Fn(&DataPoint, &str) -> String + 'static) -> Self {
434        self.format = Some(Rc::new(format));
435        self
436    }
437
438    pub fn show(mut self, show: bool) -> Self {
439        self.show = show;
440        self
441    }
442
443    fn format_tooltip(&self, point: &DataPoint, series_name: &str) -> String {
444        if let Some(ref format) = self.format {
445            format(point, series_name)
446        } else {
447            let label = point
448                .label
449                .clone()
450                .unwrap_or_else(|| format!("x: {:.2}", point.x).into());
451            format!("{}: {} = {:.2}", series_name, label, point.y)
452        }
453    }
454}
455
456#[derive(Clone, Copy, Default)]
457pub enum SeriesType {
458    #[default]
459    Line,
460    Bar,
461    Area,
462    Scatter,
463}
464
465#[derive(Clone)]
466pub struct Series {
467    pub name: SharedString,
468    pub data: Vec<DataPoint>,
469    pub series_type: SeriesType,
470    pub color: Option<Hsla>,
471    pub stroke_width: f32,
472    pub show_points: bool,
473    pub point_radius: f32,
474    pub fill_opacity: f32,
475    pub smooth: bool,
476    pub bar_width: Option<f32>,
477}
478
479impl Series {
480    pub fn new(name: impl Into<SharedString>, data: Vec<DataPoint>) -> Self {
481        Self {
482            name: name.into(),
483            data,
484            series_type: SeriesType::Line,
485            color: None,
486            stroke_width: 2.0,
487            show_points: false,
488            point_radius: 4.0,
489            fill_opacity: 0.2,
490            smooth: false,
491            bar_width: None,
492        }
493    }
494
495    pub fn line(name: impl Into<SharedString>, data: Vec<DataPoint>) -> Self {
496        Self::new(name, data).series_type(SeriesType::Line)
497    }
498
499    pub fn bar(name: impl Into<SharedString>, data: Vec<DataPoint>) -> Self {
500        Self::new(name, data).series_type(SeriesType::Bar)
501    }
502
503    pub fn area(name: impl Into<SharedString>, data: Vec<DataPoint>) -> Self {
504        Self::new(name, data)
505            .series_type(SeriesType::Area)
506            .fill_opacity(0.3)
507    }
508
509    pub fn scatter(name: impl Into<SharedString>, data: Vec<DataPoint>) -> Self {
510        Self::new(name, data)
511            .series_type(SeriesType::Scatter)
512            .show_points(true)
513    }
514
515    pub fn series_type(mut self, series_type: SeriesType) -> Self {
516        self.series_type = series_type;
517        self
518    }
519
520    pub fn color(mut self, color: impl Into<Hsla>) -> Self {
521        self.color = Some(color.into());
522        self
523    }
524
525    pub fn stroke_width(mut self, width: f32) -> Self {
526        self.stroke_width = width;
527        self
528    }
529
530    pub fn show_points(mut self, show: bool) -> Self {
531        self.show_points = show;
532        self
533    }
534
535    pub fn point_radius(mut self, radius: f32) -> Self {
536        self.point_radius = radius;
537        self
538    }
539
540    pub fn fill_opacity(mut self, opacity: f32) -> Self {
541        self.fill_opacity = opacity.clamp(0.0, 1.0);
542        self
543    }
544
545    pub fn smooth(mut self, smooth: bool) -> Self {
546        self.smooth = smooth;
547        self
548    }
549
550    pub fn bar_width(mut self, width: f32) -> Self {
551        self.bar_width = Some(width);
552        self
553    }
554
555    pub fn data_range(&self) -> DataRange {
556        DataRange::from_points(&self.data)
557    }
558}
559
560struct HoveredPoint {
561    series_index: usize,
562    #[allow(dead_code)]
563    point_index: usize,
564    screen_pos: Point<Pixels>,
565    data_point: DataPoint,
566}
567
568struct ChartPaintState {
569    series: Vec<Series>,
570    x_axis: Axis,
571    y_axis: Axis,
572    tooltip: TooltipConfig,
573    grid_color: Hsla,
574    #[allow(dead_code)]
575    text_color: Hsla,
576    #[allow(dead_code)]
577    background: Hsla,
578    padding: ChartPadding,
579}
580
581#[derive(IntoElement)]
582pub struct Chart {
583    series: Vec<Series>,
584    x_axis: Axis,
585    y_axis: Axis,
586    legend: Legend,
587    tooltip: TooltipConfig,
588    style: StyleRefinement,
589}
590
591impl Default for Chart {
592    fn default() -> Self {
593        Self::new()
594    }
595}
596
597impl Chart {
598    pub fn new() -> Self {
599        Self {
600            series: Vec::new(),
601            x_axis: Axis::new().bottom(),
602            y_axis: Axis::new().left(),
603            legend: Legend::new(),
604            tooltip: TooltipConfig::new(),
605            style: StyleRefinement::default(),
606        }
607    }
608
609    pub fn series(mut self, series: Series) -> Self {
610        self.series.push(series);
611        self
612    }
613
614    pub fn add_series(mut self, series: Series) -> Self {
615        self.series.push(series);
616        self
617    }
618
619    pub fn x_axis(mut self, axis: Axis) -> Self {
620        self.x_axis = axis;
621        self
622    }
623
624    pub fn y_axis(mut self, axis: Axis) -> Self {
625        self.y_axis = axis;
626        self
627    }
628
629    pub fn legend(mut self, legend: Legend) -> Self {
630        self.legend = legend;
631        self
632    }
633
634    pub fn show_legend(mut self, show: bool) -> Self {
635        self.legend.show = show;
636        self
637    }
638
639    pub fn tooltip(mut self, tooltip: TooltipConfig) -> Self {
640        self.tooltip = tooltip;
641        self
642    }
643
644    pub fn show_tooltip(mut self, show: bool) -> Self {
645        self.tooltip.show = show;
646        self
647    }
648
649    fn compute_data_range(&self) -> DataRange {
650        let mut range = DataRange::empty();
651
652        for series in &self.series {
653            let series_range = series.data_range();
654            range.extend(&series_range);
655        }
656
657        if range.x_min == f64::MAX {
658            range = DataRange::new(0.0, 1.0, 0.0, 1.0);
659        }
660
661        if let Some(min) = self.x_axis.min {
662            range.x_min = min;
663        }
664        if let Some(max) = self.x_axis.max {
665            range.x_max = max;
666        }
667        if let Some(min) = self.y_axis.min {
668            range.y_min = min;
669        }
670        if let Some(max) = self.y_axis.max {
671            range.y_max = max;
672        }
673
674        DataRange::new(range.x_min, range.x_max, range.y_min, range.y_max)
675    }
676}
677
678impl Styled for Chart {
679    fn style(&mut self) -> &mut StyleRefinement {
680        &mut self.style
681    }
682}
683
684impl RenderOnce for Chart {
685    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
686        let theme = use_theme(cx);
687
688        let show_y_axis = self.y_axis.show_labels;
689        let show_x_axis = self.x_axis.show_labels;
690
691        let padding = ChartPadding::new(
692            if show_y_axis { 60.0 } else { 20.0 },
693            20.0,
694            20.0,
695            if show_x_axis { 40.0 } else { 20.0 },
696        );
697
698        let data_range = self.compute_data_range();
699        let user_style = self.style;
700        let series_for_legend = self.series.clone();
701        let legend = self.legend.clone();
702
703        let y_axis_clone = self.y_axis.clone();
704        let y_labels: Vec<String> = if show_y_axis {
705            (0..=self.y_axis.tick_count)
706                .map(|i| {
707                    let normalized = i as f64 / self.y_axis.tick_count as f64;
708                    let value = data_range.y_min
709                        + (data_range.y_max - data_range.y_min) * (1.0 - normalized);
710                    y_axis_clone.format_value(value)
711                })
712                .collect()
713        } else {
714            Vec::new()
715        };
716
717        let paint_state = ChartPaintState {
718            series: self.series,
719            x_axis: self.x_axis,
720            y_axis: self.y_axis,
721            tooltip: self.tooltip,
722            grid_color: theme.tokens.border,
723            text_color: theme.tokens.muted_foreground,
724            background: theme.tokens.background,
725            padding: padding.clone(),
726        };
727
728        let text_color = theme.tokens.muted_foreground;
729        let tooltip_bg = theme.tokens.popover;
730        let tooltip_border = theme.tokens.border;
731
732        div()
733            .flex()
734            .flex_col()
735            .size_full()
736            .min_h(px(250.0))
737            .map(|this| {
738                let mut d = this;
739                d.style().refine(&user_style);
740                d
741            })
742            .child(
743                div()
744                    .flex_1()
745                    .relative()
746                    .child(
747                        canvas(
748                            move |bounds, window, _cx| {
749                                let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
750                                (paint_state, data_range, bounds, hitbox)
751                            },
752                            move |bounds, (state, range, _, hitbox), window, cx| {
753                                let hitbox_for_event = hitbox.clone();
754                                window.on_mouse_event(
755                                    move |_event: &MouseMoveEvent, _phase, window, cx| {
756                                        if hitbox_for_event.is_hovered(window) {
757                                            cx.refresh_windows();
758                                        }
759                                    },
760                                );
761
762                                let mouse_pos = window.mouse_position();
763                                if bounds.size.width <= px(0.0) || bounds.size.height <= px(0.0) {
764                                    return;
765                                }
766
767                                let area = ChartArea {
768                                    bounds,
769                                    range: range.clone(),
770                                    padding: state.padding.clone(),
771                                };
772
773                                if area.chart_width() <= px(0.0) || area.chart_height() <= px(0.0) {
774                                    return;
775                                }
776
777                                if state.y_axis.show_grid {
778                                    for i in 0..=state.y_axis.tick_count {
779                                        let y = area.chart_top()
780                                            + area.chart_height()
781                                                * (i as f32 / state.y_axis.tick_count as f32);
782                                        let mut builder = PathBuilder::stroke(px(1.0));
783                                        builder.move_to(point(area.chart_left(), y));
784                                        builder.line_to(point(area.chart_right(), y));
785                                        if let Ok(path) = builder.build() {
786                                            window.paint_path(path, state.grid_color.opacity(0.2));
787                                        }
788                                    }
789                                }
790
791                                if state.x_axis.show_grid {
792                                    for i in 0..=state.x_axis.tick_count {
793                                        let x = area.chart_left()
794                                            + area.chart_width()
795                                                * (i as f32 / state.x_axis.tick_count as f32);
796                                        let mut builder = PathBuilder::stroke(px(1.0));
797                                        builder.move_to(point(x, area.chart_top()));
798                                        builder.line_to(point(x, area.chart_bottom()));
799                                        if let Ok(path) = builder.build() {
800                                            window.paint_path(path, state.grid_color.opacity(0.2));
801                                        }
802                                    }
803                                }
804
805                                let mut hovered_point: Option<HoveredPoint> = None;
806                                let hover_radius = px(15.0);
807
808                                for (series_index, series) in state.series.iter().enumerate() {
809                                    let color =
810                                        series.color.unwrap_or_else(|| default_color(series_index));
811
812                                    if series.data.is_empty() {
813                                        continue;
814                                    }
815
816                                    let screen_points: Vec<Point<Pixels>> = series
817                                        .data
818                                        .iter()
819                                        .map(|p| area.data_to_screen(p))
820                                        .collect();
821
822                                    match series.series_type {
823                                        SeriesType::Line | SeriesType::Area => {
824                                            if matches!(series.series_type, SeriesType::Area)
825                                                && screen_points.len() >= 2
826                                            {
827                                                let mut builder = PathBuilder::fill();
828                                                builder.move_to(point(
829                                                    screen_points[0].x,
830                                                    area.chart_bottom(),
831                                                ));
832                                                builder.line_to(screen_points[0]);
833
834                                                for pt in screen_points.iter().skip(1) {
835                                                    builder.line_to(*pt);
836                                                }
837
838                                                builder.line_to(point(
839                                                    screen_points.last().unwrap().x,
840                                                    area.chart_bottom(),
841                                                ));
842                                                builder.close();
843
844                                                if let Ok(path) = builder.build() {
845                                                    window.paint_path(
846                                                        path,
847                                                        color.opacity(series.fill_opacity),
848                                                    );
849                                                }
850                                            }
851
852                                            if screen_points.len() >= 2 {
853                                                let mut builder =
854                                                    PathBuilder::stroke(px(series.stroke_width));
855                                                builder.move_to(screen_points[0]);
856
857                                                if series.smooth && screen_points.len() >= 3 {
858                                                    for i in 0..screen_points.len() - 1 {
859                                                        let p0 = screen_points[i];
860                                                        let p1 = screen_points[i + 1];
861                                                        let ctrl_x = (p0.x + p1.x) * 0.5;
862                                                        builder.curve_to(p1, point(ctrl_x, p0.y));
863                                                    }
864                                                } else {
865                                                    for pt in screen_points.iter().skip(1) {
866                                                        builder.line_to(*pt);
867                                                    }
868                                                }
869
870                                                if let Ok(path) = builder.build() {
871                                                    window.paint_path(path, color);
872                                                }
873                                            }
874                                        }
875                                        SeriesType::Bar => {
876                                            let bar_width = series.bar_width.unwrap_or(20.0);
877                                            for (point_index, (data_pt, screen_pt)) in series
878                                                .data
879                                                .iter()
880                                                .zip(screen_points.iter())
881                                                .enumerate()
882                                            {
883                                                let bar_height = area.chart_bottom() - screen_pt.y;
884                                                let bar_bounds = Bounds::new(
885                                                    point(
886                                                        screen_pt.x - px(bar_width / 2.0),
887                                                        screen_pt.y,
888                                                    ),
889                                                    size(px(bar_width), bar_height),
890                                                );
891
892                                                window.paint_quad(fill(bar_bounds, color));
893
894                                                if bar_bounds.contains(&mouse_pos) {
895                                                    hovered_point = Some(HoveredPoint {
896                                                        series_index,
897                                                        point_index,
898                                                        screen_pos: *screen_pt,
899                                                        data_point: data_pt.clone(),
900                                                    });
901                                                }
902                                            }
903                                        }
904                                        SeriesType::Scatter => {}
905                                    }
906
907                                    if series.show_points
908                                        || matches!(series.series_type, SeriesType::Scatter)
909                                    {
910                                        let radius = px(series.point_radius);
911                                        for (point_index, (data_pt, screen_pt)) in
912                                            series.data.iter().zip(screen_points.iter()).enumerate()
913                                        {
914                                            let is_hovered = (mouse_pos.x - screen_pt.x).abs()
915                                                < hover_radius
916                                                && (mouse_pos.y - screen_pt.y).abs() < hover_radius;
917
918                                            let point_radius =
919                                                if is_hovered { radius * 1.5 } else { radius };
920
921                                            window.paint_quad(fill(
922                                                Bounds::centered_at(
923                                                    *screen_pt,
924                                                    size(point_radius * 2.0, point_radius * 2.0),
925                                                ),
926                                                color,
927                                            ));
928
929                                            if is_hovered && hovered_point.is_none() {
930                                                hovered_point = Some(HoveredPoint {
931                                                    series_index,
932                                                    point_index,
933                                                    screen_pos: *screen_pt,
934                                                    data_point: data_pt.clone(),
935                                                });
936                                            }
937                                        }
938                                    }
939                                }
940
941                                if state.tooltip.show && hitbox.is_hovered(window) {
942                                    if let Some(hp) = hovered_point {
943                                        let series = &state.series[hp.series_index];
944                                        let tooltip_text = state
945                                            .tooltip
946                                            .format_tooltip(&hp.data_point, &series.name);
947
948                                        let text_style = window.text_style();
949                                        let font = text_style.font();
950                                        let font_size = px(12.0);
951                                        let text_len = tooltip_text.len();
952
953                                        let text_run = TextRun {
954                                            len: text_len,
955                                            font,
956                                            color: text_color,
957                                            background_color: None,
958                                            underline: None,
959                                            strikethrough: None,
960                                        };
961
962                                        let shaped_line = window.text_system().shape_line(
963                                            tooltip_text.into(),
964                                            font_size,
965                                            &[text_run],
966                                            None,
967                                        );
968
969                                        let text_width = shaped_line.width;
970                                        let padding_h = px(12.0);
971                                        let padding_v = px(8.0);
972                                        let tooltip_width = text_width + padding_h * 2.0;
973                                        let tooltip_height = font_size + padding_v * 2.0;
974
975                                        let tooltip_x = (hp.screen_pos.x - tooltip_width / 2.0)
976                                            .max(bounds.left())
977                                            .min(bounds.right() - tooltip_width);
978                                        let tooltip_y = hp.screen_pos.y - tooltip_height - px(10.0);
979
980                                        let tooltip_bounds = Bounds::new(
981                                            point(tooltip_x, tooltip_y),
982                                            size(tooltip_width, tooltip_height),
983                                        );
984
985                                        window.paint_quad(quad(
986                                            tooltip_bounds,
987                                            px(6.0),
988                                            tooltip_bg,
989                                            px(1.0),
990                                            tooltip_border,
991                                            BorderStyle::default(),
992                                        ));
993
994                                        let text_origin =
995                                            point(tooltip_x + padding_h, tooltip_y + padding_v);
996                                        let _ =
997                                            shaped_line.paint(text_origin, font_size, window, cx);
998                                    }
999                                }
1000                            },
1001                        )
1002                        .size_full(),
1003                    )
1004                    .when(show_y_axis, |this| {
1005                        this.children(y_labels.iter().enumerate().map(|(i, label)| {
1006                            let tick_count = y_labels.len() - 1;
1007                            let top_percent = (i as f32 / tick_count.max(1) as f32) * 100.0;
1008                            div()
1009                                .absolute()
1010                                .left(px(4.0))
1011                                .top(relative(top_percent / 100.0))
1012                                .mt(px(padding.top - 6.0))
1013                                .text_size(px(11.0))
1014                                .text_color(text_color)
1015                                .child(label.clone())
1016                        }))
1017                    }),
1018            )
1019            .when(legend.show && series_for_legend.len() > 1, |this| {
1020                this.child(
1021                    div()
1022                        .flex()
1023                        .flex_wrap()
1024                        .gap(px(16.0))
1025                        .px(px(padding.left))
1026                        .py(px(12.0))
1027                        .justify_center()
1028                        .children(series_for_legend.iter().enumerate().map(|(i, s)| {
1029                            let color = s.color.unwrap_or_else(|| default_color(i));
1030                            div()
1031                                .flex()
1032                                .items_center()
1033                                .gap(px(6.0))
1034                                .child(div().size(px(12.0)).rounded(px(2.0)).bg(color))
1035                                .child(div().text_sm().text_color(text_color).child(s.name.clone()))
1036                        })),
1037                )
1038            })
1039    }
1040}
1041
1042#[cfg(test)]
1043mod tests {
1044    use super::{DataPoint, DataRange};
1045
1046    #[test]
1047    fn data_range_normalization_is_finite_for_invalid_public_inputs() {
1048        for range in [
1049            DataRange::new(1.0, 1.0, 2.0, 2.0),
1050            DataRange::new(2.0, -2.0, 4.0, -4.0),
1051            DataRange::new(f64::NAN, 1.0, 0.0, f64::INFINITY),
1052        ] {
1053            assert!(range.normalize_x(0.0).is_finite());
1054            assert!(range.normalize_y(0.0).is_finite());
1055            assert!(range.x_min < range.x_max);
1056            assert!(range.y_min < range.y_max);
1057        }
1058    }
1059
1060    #[test]
1061    fn extreme_finite_values_produce_finite_ranges() {
1062        for value in [f64::MAX, f64::MIN] {
1063            for range in [
1064                DataRange::new(value, value, 0.0, 1.0),
1065                DataRange::from_points(&[DataPoint::new(value, 0.0)]),
1066            ] {
1067                assert!(range.x_min.is_finite());
1068                assert!(range.x_max.is_finite());
1069                assert!(range.x_min < range.x_max);
1070                assert!(range.x_min <= value && value <= range.x_max);
1071                assert!(range.normalize_x(value).is_finite());
1072            }
1073        }
1074    }
1075
1076    #[test]
1077    fn data_range_ignores_non_finite_points() {
1078        let range = DataRange::from_points(&[
1079            DataPoint::new(f64::NAN, 1.0),
1080            DataPoint::new(2.0, f64::INFINITY),
1081            DataPoint::new(3.0, 4.0),
1082        ]);
1083
1084        assert!(range.x_min <= 3.0 && range.x_max >= 3.0);
1085        assert!(range.y_min <= 4.0 && range.y_max >= 4.0);
1086        assert!(range.normalize_x(3.0).is_finite());
1087        assert!(range.normalize_y(4.0).is_finite());
1088    }
1089
1090    #[test]
1091    fn single_finite_point_keeps_the_existing_one_unit_range() {
1092        let range = DataRange::from_points(&[DataPoint::new(3.0, 4.0)]);
1093
1094        assert_eq!(range.x_min, 3.0);
1095        assert_eq!(range.x_max, 4.0);
1096        assert_eq!(range.y_min, 4.0);
1097        assert_eq!(range.y_max, 5.0);
1098    }
1099
1100    #[test]
1101    fn data_range_defaults_when_no_points_are_finite() {
1102        let range = DataRange::from_points(&[
1103            DataPoint::new(f64::NAN, 1.0),
1104            DataPoint::new(2.0, f64::INFINITY),
1105        ]);
1106
1107        assert_eq!(range.x_min, 0.0);
1108        assert_eq!(range.x_max, 1.0);
1109        assert_eq!(range.y_min, 0.0);
1110        assert_eq!(range.y_max, 1.0);
1111    }
1112}