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