Skip to main content

gpui_component/chart/
radar_chart.rs

1use std::{
2    f32::consts::{PI, TAU},
3    hash::Hash,
4    rc::Rc,
5};
6
7use gpui::ColorExt as _;
8use gpui::{
9    AnyElement, App, AvailableSpace, Background, Bounds, ElementId, Hsla, IntoElement, Pixels,
10    Point, SharedString, TextAlign, Window, point, px,
11};
12use gpui_component_macros::IntoPlot;
13use num_traits::Zero;
14
15use crate::{
16    ActiveTheme,
17    plot::{
18        Plot, PlotAppear,
19        label::{PlotLabel, TEXT_SIZE, Text},
20        polygon,
21        scale::{PlotValue, Scale, ScaleLinear},
22        shape::RadialLine,
23        tooltip::{Dot, Tooltip, TooltipState},
24    },
25};
26
27use super::{ChartAppear, HOVER_DOT_SIZE, HOVER_HALO_SIZE, TooltipContent, caller_id};
28
29const HALF_PI: f32 = PI / 2.;
30
31/// The default extra gap (in pixels) between the outer grid ring and the labels.
32const DEFAULT_LABEL_GAP: f32 = 10.;
33
34/// The default number of concentric grid rings.
35const DEFAULT_GRID_LEVELS: usize = 4;
36
37/// The label of one radar dimension, returned by [`RadarChart::label`].
38pub enum RadarLabel {
39    /// Plain text, drawn by the plot's own text layer: honors
40    /// [`RadarChart::label_color`] and supplies the tooltip title.
41    Text(SharedString),
42    /// A custom element, measured at its natural size and anchored like a text
43    /// label. [`RadarChart::label_color`] does not apply, and it supplies no
44    /// tooltip title.
45    Element(AnyElement),
46}
47
48impl From<&'static str> for RadarLabel {
49    fn from(text: &'static str) -> Self {
50        Self::Text(text.into())
51    }
52}
53
54impl From<String> for RadarLabel {
55    fn from(text: String) -> Self {
56        Self::Text(text.into())
57    }
58}
59
60impl From<SharedString> for RadarLabel {
61    fn from(text: SharedString) -> Self {
62        Self::Text(text)
63    }
64}
65
66impl From<AnyElement> for RadarLabel {
67    fn from(element: AnyElement) -> Self {
68        Self::Element(element)
69    }
70}
71
72/// A radar (spider) chart.
73///
74/// Each datum is one dimension (a spoke), placed clockwise around the center
75/// starting at 12 o'clock. Add one series per [`RadarChart::value`] call; each
76/// series is drawn as a closed polygon connecting its values on every spoke.
77#[derive(IntoPlot)]
78pub struct RadarChart<T, Y>
79where
80    T: 'static,
81    Y: PlotValue,
82{
83    data: Vec<T>,
84    values: Vec<Rc<dyn Fn(&T) -> Y>>,
85    strokes: Vec<Hsla>,
86    fills: Vec<Background>,
87    names: Vec<SharedString>,
88    tooltip_content: TooltipContent<T>,
89    label: Option<Rc<dyn Fn(&T) -> RadarLabel + 'static>>,
90    /// The text of each dimension's label, resolved once per frame in `prepaint`;
91    /// element labels leave `None`. Read by `paint` (to draw them) and `tooltip`
92    /// (as the title), so the label closure runs once per dimension per frame.
93    label_texts: Vec<Option<SharedString>>,
94    label_color: Option<Hsla>,
95    label_gap: f32,
96    max_value: Option<Y>,
97    outer_radius: f32,
98    grid: bool,
99    grid_levels: usize,
100    dot: bool,
101    id: ElementId,
102    interactive: bool,
103    appear: ChartAppear,
104}
105
106impl<T, Y> RadarChart<T, Y>
107where
108    Y: PlotValue,
109{
110    #[track_caller]
111    pub fn new<I>(data: I) -> Self
112    where
113        I: IntoIterator<Item = T>,
114    {
115        Self {
116            data: data.into_iter().collect(),
117            values: vec![],
118            strokes: vec![],
119            fills: vec![],
120            names: vec![],
121            tooltip_content: TooltipContent::default(),
122            label: None,
123            label_texts: vec![],
124            label_color: None,
125            label_gap: DEFAULT_LABEL_GAP,
126            max_value: None,
127            outer_radius: 0.,
128            grid: true,
129            grid_levels: DEFAULT_GRID_LEVELS,
130            dot: false,
131            id: caller_id(),
132            interactive: true,
133            appear: ChartAppear::default(),
134        }
135    }
136
137    /// Name this chart's [`ElementId`], replacing the default taken from the
138    /// construction site.
139    ///
140    /// Pass one where a single construction site renders several of these
141    /// charts as siblings: they share the default id, and with it one hover
142    /// state and one path cache. The id must be unique among those siblings.
143    pub fn id(mut self, id: impl Into<ElementId>) -> Self {
144        self.id = id.into();
145        self
146    }
147
148    /// Turn this chart's interactive layer on or off. On by default.
149    ///
150    /// The layer is the hitbox under the cursor and what it drives: a dot per
151    /// series marks the hovered dimension, and a tooltip shows a row each. Turn
152    /// it off for a chart that only decorates, or one an element above it wants
153    /// the cursor for: without a hitbox it neither answers the mouse nor takes
154    /// the hover from what sits over it.
155    pub fn interactive(mut self, interactive: bool) -> Self {
156        self.interactive = interactive;
157        self
158    }
159
160    /// Draw the data in the first time this chart is painted. On by default.
161    ///
162    /// The theme sets how long it takes, and the system's reduced-motion
163    /// setting skips it. Turn it off for a chart that is painted again and
164    /// again as it scrolls in and out of view, such as one in each row of a
165    /// long list, where it would draw in every time.
166    pub fn appear(mut self, appear: bool) -> Self {
167        self.appear.set_enabled(appear);
168        self
169    }
170
171    /// Draw the data in again whenever `key` changes, such as the symbol or
172    /// period a chart shows.
173    ///
174    /// Without one the data draws in once, and later data paints in place.
175    pub fn appear_key(mut self, key: impl Hash) -> Self {
176        self.appear.set_key(key);
177        self
178    }
179
180    /// Set the name of the most recently added series, shown in its tooltip row.
181    ///
182    /// Call after the matching [`RadarChart::value`]
183    /// (e.g. `.value(..).stroke(..).name("Desktop")`).
184    pub fn name(mut self, name: impl Into<SharedString>) -> Self {
185        self.names.push(name.into());
186        self
187    }
188
189    /// Set the hover tooltip's title for a datum, instead of its dimension label.
190    pub fn tooltip_title(mut self, title: impl Fn(&T) -> SharedString + 'static) -> Self {
191        self.tooltip_content.set_title(title);
192        self
193    }
194
195    /// Set the text of each tooltip row's value; the raw number by default.
196    ///
197    /// The closure receives the datum, the row's index (the series' index in the order `value`
198    /// added them) and the value the row reads.
199    pub fn tooltip_value(
200        mut self,
201        value: impl Fn(&T, usize, f64) -> SharedString + 'static,
202    ) -> Self {
203        self.tooltip_content.set_value(value);
204        self
205    }
206
207    /// Color each tooltip row's value, such as green or red by its sign; the
208    /// tooltip's text color by default.
209    ///
210    /// The closure receives the same arguments as
211    /// [`tooltip_value`](Self::tooltip_value).
212    pub fn tooltip_value_color<H>(mut self, color: impl Fn(&T, usize, f64) -> H + 'static) -> Self
213    where
214        H: Into<Hsla>,
215    {
216        self.tooltip_content.set_value_color(color);
217        self
218    }
219
220    /// Draw the tooltip box's content for a datum yourself, in place of the
221    /// title and rows, for a layout they cannot express such as a table.
222    ///
223    /// The dots and where the box sits stay the chart's, and
224    /// [`tooltip_title`](Self::tooltip_title), [`tooltip_value`](Self::tooltip_value)
225    /// and [`tooltip_value_color`](Self::tooltip_value_color) no longer apply.
226    pub fn tooltip_content<E>(
227        mut self,
228        content: impl Fn(&T, &mut Window, &mut App) -> E + 'static,
229    ) -> Self
230    where
231        E: IntoElement,
232    {
233        self.tooltip_content.set_content(content);
234        self
235    }
236
237    /// Add a series to the radar chart.
238    ///
239    /// Call multiple times to overlay multiple series, each paired with the
240    /// matching [`RadarChart::stroke`] and [`RadarChart::fill`] calls.
241    pub fn value(mut self, value: impl Fn(&T) -> Y + 'static) -> Self {
242        self.values.push(Rc::new(value));
243        self
244    }
245
246    /// Set the stroke color of the most recently added series.
247    ///
248    /// Defaults to the theme chart colors, cycled per series.
249    pub fn stroke(mut self, stroke: impl Into<Hsla>) -> Self {
250        self.strokes.push(stroke.into());
251        self
252    }
253
254    /// Set the fill color of the most recently added series.
255    ///
256    /// Defaults to the series stroke color with 0.3 opacity.
257    pub fn fill(mut self, fill: impl Into<Background>) -> Self {
258        self.fills.push(fill.into());
259        self
260    }
261
262    /// Set the label for each dimension, shown outside the outer ring.
263    ///
264    /// Return a string for a plain text label, or `element.into_any_element()`
265    /// for a custom one; see [`RadarLabel`] for how the two differ.
266    ///
267    /// ```ignore
268    /// RadarChart::new(data).label(|d| d.month.clone())
269    ///
270    /// RadarChart::new(data).label(|d| {
271    ///     v_flex()
272    ///         .items_center()
273    ///         .child(Icon::new(IconName::Star).xsmall())
274    ///         .child(d.month.clone())
275    ///         .into_any_element()
276    /// })
277    /// ```
278    pub fn label<L>(mut self, label: impl Fn(&T) -> L + 'static) -> Self
279    where
280        L: Into<RadarLabel> + 'static,
281    {
282        self.label = Some(Rc::new(move |d| label(d).into()));
283        self
284    }
285
286    /// Set the text label color (defaults to `cx.theme().muted_foreground`).
287    ///
288    /// Element labels style themselves; this does not apply to them.
289    pub fn label_color(mut self, color: impl Into<Hsla>) -> Self {
290        self.label_color = Some(color.into());
291        self
292    }
293
294    /// Set the extra gap between the outer ring and the labels
295    /// (defaults to 10px).
296    pub fn label_gap(mut self, gap: f32) -> Self {
297        self.label_gap = gap;
298        self
299    }
300
301    /// Set the value at the outer ring.
302    ///
303    /// Defaults to the maximum value across all series.
304    pub fn max_value(mut self, max_value: Y) -> Self {
305        self.max_value = Some(max_value);
306        self
307    }
308
309    /// Set the outer radius of the radar chart.
310    ///
311    /// Defaults to 40% of the bounds height.
312    pub fn outer_radius(mut self, outer_radius: f32) -> Self {
313        self.outer_radius = outer_radius;
314        self
315    }
316
317    /// Show or hide the grid rings and spokes.
318    ///
319    /// Default is true.
320    pub fn grid(mut self, grid: bool) -> Self {
321        self.grid = grid;
322        self
323    }
324
325    /// Set the number of concentric grid rings (defaults to 4).
326    pub fn grid_levels(mut self, grid_levels: usize) -> Self {
327        self.grid_levels = grid_levels.max(1);
328        self
329    }
330
331    /// Show dots on the vertices of each series.
332    pub fn dot(mut self) -> Self {
333        self.dot = true;
334        self
335    }
336
337    /// The stroke color of the series at the given index, set or default.
338    ///
339    /// Defaults to the theme chart colors, cycled per series.
340    fn series_stroke(&self, ix: usize, cx: &App) -> Hsla {
341        self.series_stroke_from(&Self::palette(cx), ix)
342    }
343
344    /// The theme chart colors the series cycle through by default.
345    fn palette(cx: &App) -> [Hsla; 5] {
346        [
347            cx.theme().chart_1,
348            cx.theme().chart_2,
349            cx.theme().chart_3,
350            cx.theme().chart_4,
351            cx.theme().chart_5,
352        ]
353    }
354
355    /// The stroke color of the series at the given index, set or from `palette`.
356    fn series_stroke_from(&self, palette: &[Hsla; 5], ix: usize) -> Hsla {
357        self.strokes
358            .get(ix)
359            .copied()
360            .unwrap_or(palette[ix % palette.len()])
361    }
362
363    /// The resolved outer radius for the given bounds.
364    fn resolve_outer_radius(&self, bounds: &Bounds<Pixels>) -> f32 {
365        if self.outer_radius.is_zero() {
366            bounds.size.height.as_f32() * 0.4
367        } else {
368            self.outer_radius
369        }
370    }
371
372    /// Where the label of dimension `ix` attaches, in bounds-relative coordinates,
373    /// plus the outward radial direction at that dimension (a unit vector).
374    ///
375    /// The anchor sits on the label ring at the dimension's angle; callers offset
376    /// their own box from it along `direction`. Shared by `prepaint` and `paint`
377    /// so element and text labels land in the same place.
378    fn label_anchor(
379        &self,
380        ix: usize,
381        outer_radius: f32,
382        bounds: &Bounds<Pixels>,
383    ) -> (Point<f32>, Point<f32>) {
384        let label_radius = outer_radius + self.label_gap;
385        let angle = ix as f32 * TAU / self.data.len() as f32 - HALF_PI;
386        let direction = point(angle.cos(), angle.sin());
387
388        let anchor = point(
389            bounds.size.width.as_f32() / 2. + label_radius * direction.x,
390            bounds.size.height.as_f32() / 2. + label_radius * direction.y,
391        );
392
393        (anchor, direction)
394    }
395
396    /// Build the radius scale from the center to the outer ring.
397    ///
398    /// The domain includes zero so non-negative data starts at the center.
399    /// Shared by `paint` and `tooltip_state` so the two stay in sync.
400    fn scale(&self, outer_radius: f32) -> ScaleLinear<Y> {
401        let domain = if let Some(max_value) = self.max_value {
402            vec![Y::zero(), max_value]
403        } else {
404            self.data
405                .iter()
406                .flat_map(|d| self.values.iter().map(|value_fn| value_fn(d)))
407                .chain(Some(Y::zero()))
408                .collect()
409        };
410
411        ScaleLinear::new(domain, [0., outer_radius])
412    }
413
414    /// Map a cursor position to the nearest spoke index, or `None` when the
415    /// cursor is outside the radar.
416    fn hovered_index(&self, position: Point<Pixels>, bounds: Bounds<Pixels>) -> Option<usize> {
417        let n = self.data.len();
418        if n == 0 {
419            return None;
420        }
421
422        let outer_radius = self.resolve_outer_radius(&bounds);
423        let dx = position.x.as_f32() - bounds.size.width.as_f32() / 2.;
424        let dy = position.y.as_f32() - bounds.size.height.as_f32() / 2.;
425        if dx.hypot(dy) > outer_radius + self.label_gap {
426            return None;
427        }
428
429        // Screen angle -> chart angle (0 at 12 o'clock, clockwise).
430        let angle = (dy.atan2(dx) + HALF_PI).rem_euclid(TAU);
431        Some((angle * n as f32 / TAU).round() as usize % n)
432    }
433}
434
435impl<T, Y> Plot for RadarChart<T, Y>
436where
437    Y: PlotValue,
438{
439    /// Resolve every dimension's label, keeping the text ones for `paint` and
440    /// laying out the element ones here (measuring is illegal in `paint`).
441    fn prepaint(
442        &mut self,
443        bounds: Bounds<Pixels>,
444        window: &mut Window,
445        cx: &mut App,
446    ) -> Vec<AnyElement> {
447        self.label_texts.clear();
448
449        // Same guard as `paint`: without a series nothing is drawn at all.
450        let n = self.data.len();
451        if n == 0 || self.values.is_empty() {
452            return vec![];
453        }
454        let Some(label_fn) = self.label.clone() else {
455            return vec![];
456        };
457
458        let outer_radius = self.resolve_outer_radius(&bounds);
459        let mut texts = Vec::with_capacity(n);
460        let mut elements = vec![];
461
462        for (ix, d) in self.data.iter().enumerate() {
463            match label_fn(d) {
464                RadarLabel::Text(text) => texts.push(Some(text)),
465                RadarLabel::Element(mut element) => {
466                    texts.push(None);
467
468                    // Only `AvailableSpace::Definite` makes text wrap, so this
469                    // measures the label at its natural, unwrapped size.
470                    let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
471                    let (anchor, direction) = self.label_anchor(ix, outer_radius, &bounds);
472
473                    // Push the box radially outward until its inner edge meets the
474                    // anchor, so a tall label clears the ring instead of straddling
475                    // it. Reduces to "centered on the anchor" across that axis when
476                    // the dimension is square-on to it.
477                    let origin = bounds.origin
478                        + point(
479                            px(anchor.x + (direction.x - 1.) * size.width.as_f32() / 2.),
480                            px(anchor.y + (direction.y - 1.) * size.height.as_f32() / 2.),
481                        );
482
483                    element.prepaint_at(origin, window, cx);
484                    elements.push(element);
485                }
486            }
487        }
488
489        self.label_texts = texts;
490
491        elements
492    }
493
494    fn paint(&mut self, bounds: Bounds<Pixels>, window: &mut Window, cx: &mut App) {
495        let n = self.data.len();
496        if n == 0 || self.values.is_empty() {
497            return;
498        }
499
500        let outer_radius = self.resolve_outer_radius(&bounds);
501        let angle_step = TAU / n as f32;
502        let center_x = bounds.size.width.as_f32() / 2.;
503        let center_y = bounds.size.height.as_f32() / 2.;
504        let scale = self.scale(outer_radius);
505
506        // Draw grid rings and spokes
507        if self.grid {
508            let stroke = cx.theme().chart_grid;
509
510            for level in 1..=self.grid_levels {
511                let radius = outer_radius * level as f32 / self.grid_levels as f32;
512                RadialLine::new()
513                    .data(0..n)
514                    .angle(move |_, i| Some(i as f32 * angle_step))
515                    .radius(move |_, _| Some(radius))
516                    .closed()
517                    .stroke(stroke)
518                    .paint(&bounds, window);
519            }
520
521            for i in 0..n {
522                let angle = i as f32 * angle_step - HALF_PI;
523                let points = [
524                    point(center_x, center_y),
525                    point(
526                        center_x + outer_radius * angle.cos(),
527                        center_y + outer_radius * angle.sin(),
528                    ),
529                ];
530                if let Some(path) = polygon(&points, &bounds) {
531                    window.paint_path(path, stroke);
532                }
533            }
534        }
535
536        // Draw series. They grow out of the center as the chart appears.
537        let appear = self.appear.get().progress();
538        for (i, value_fn) in self.values.iter().enumerate() {
539            let stroke = self.series_stroke(i, cx);
540            let fill = self
541                .fills
542                .get(i)
543                .copied()
544                .unwrap_or_else(|| stroke.opacity(0.3).into());
545
546            let scale = scale.clone();
547            let value_fn = value_fn.clone();
548            let mut line = RadialLine::new()
549                .data(&self.data)
550                .angle(move |_, i| Some(i as f32 * angle_step))
551                .radius(move |d, _| scale.tick(&value_fn(d)).map(|r| r * appear))
552                .closed()
553                .fill(fill)
554                .stroke(stroke)
555                .stroke_width(2.);
556            if self.dot {
557                line = line.dot().dot_size(8.).dot_fill(stroke);
558            }
559            line.paint(&bounds, window);
560        }
561
562        // Draw the text labels outside the outer ring; `prepaint` resolved them and
563        // already placed the element ones.
564        let label_color = self.label_color.unwrap_or(cx.theme().muted_foreground);
565        let labels = self
566            .label_texts
567            .iter()
568            .enumerate()
569            .filter_map(|(ix, text)| {
570                let text = text.clone()?;
571                let (anchor, direction) = self.label_anchor(ix, outer_radius, &bounds);
572
573                // Labels on the right are left-aligned, on the left right-aligned,
574                // and near the vertical axis centered. `direction` is a unit vector,
575                // so the epsilon only absorbs float noise at 12 and 6 o'clock.
576                let align = if direction.x > 1e-3 {
577                    TextAlign::Left
578                } else if direction.x < -1e-3 {
579                    TextAlign::Right
580                } else {
581                    TextAlign::Center
582                };
583
584                Some(
585                    Text::new(
586                        text,
587                        point(px(anchor.x), px(anchor.y - TEXT_SIZE / 2.)),
588                        label_color,
589                    )
590                    .align(align),
591                )
592            });
593
594        PlotLabel::new(labels.collect()).paint(&bounds, window, cx);
595    }
596
597    fn id(&self) -> Option<ElementId> {
598        Some(self.id.clone())
599    }
600
601    fn interactive(&self) -> bool {
602        self.interactive
603    }
604
605    fn appear(&mut self, appear: PlotAppear, _window: &mut Window, _cx: &mut App) {
606        self.appear.update(appear);
607    }
608
609    fn appear_generation(&self) -> Option<u64> {
610        self.appear.generation()
611    }
612
613    fn tooltip_state(
614        &self,
615        position: Point<Pixels>,
616        bounds: Bounds<Pixels>,
617        _cx: &App,
618    ) -> Option<TooltipState> {
619        if self.values.is_empty() {
620            return None;
621        }
622        let index = self.hovered_index(position, bounds)?;
623        let d = self.data.get(index)?;
624
625        let outer_radius = self.resolve_outer_radius(&bounds);
626        let scale = self.scale(outer_radius);
627        let center_x = bounds.size.width.as_f32() / 2.;
628        let center_y = bounds.size.height.as_f32() / 2.;
629        let angle = index as f32 * TAU / self.data.len() as f32 - HALF_PI;
630
631        // One dot per series at the hovered dimension's vertex.
632        let dots = self
633            .values
634            .iter()
635            .filter_map(|value_fn| {
636                let radius = scale.tick(&value_fn(d))?;
637                Some(point(
638                    px(center_x + radius * angle.cos()),
639                    px(center_y + radius * angle.sin()),
640                ))
641            })
642            .collect();
643
644        Some(TooltipState::new(index, position, dots))
645    }
646
647    fn tooltip(
648        &self,
649        state: &TooltipState,
650        cursor: Point<Pixels>,
651        bounds: Bounds<Pixels>,
652        window: &mut Window,
653        cx: &mut App,
654    ) -> Option<AnyElement> {
655        let d = self.data.get(state.index)?;
656
657        let dot_stroke = cx.theme().background;
658
659        // No crosshair: a radar has no cartesian axis to snap to; the dots mark
660        // the hovered dimension's vertices instead.
661        let tooltip =
662            Tooltip::new(cursor, bounds.size)
663                .gap(px(8.))
664                .dots(state.dots.iter().enumerate().map(|(i, p)| {
665                    Dot::new(*p)
666                        .size(HOVER_DOT_SIZE)
667                        .halo(HOVER_HALO_SIZE)
668                        .stroke(dot_stroke)
669                        .fill(self.series_stroke(i, cx))
670                }));
671
672        let palette = Self::palette(cx);
673        let tooltip = self.tooltip_content.apply(
674            tooltip,
675            d,
676            // Filled by `prepaint`, which runs first; element labels leave no title.
677            || self.label_texts.get(state.index).cloned().flatten(),
678            // One row per series: swatch + label + value.
679            || {
680                self.values
681                    .iter()
682                    .enumerate()
683                    .map(|(i, value_fn)| {
684                        let name = self.names.get(i).cloned().unwrap_or_default();
685                        Some((
686                            self.series_stroke_from(&palette, i),
687                            name,
688                            value_fn(d).to_f64()?,
689                        ))
690                    })
691                    .collect::<Option<Vec<_>>>()
692            },
693            window,
694            cx,
695        )?;
696
697        Some(tooltip.into_any_element())
698    }
699}
700
701#[cfg(test)]
702mod tests {
703    use super::*;
704
705    #[derive(Clone)]
706    struct Item {
707        subject: SharedString,
708        a: f64,
709        b: f64,
710    }
711
712    #[test]
713    fn test_radar_chart_builder() {
714        let data = vec![
715            Item {
716                subject: "Sales".into(),
717                a: 80.,
718                b: 60.,
719            },
720            Item {
721                subject: "Marketing".into(),
722                a: 50.,
723                b: 90.,
724            },
725        ];
726
727        let chart = RadarChart::new(data.clone())
728            .label(|d| d.subject.clone())
729            .value(|d| d.a)
730            .stroke(gpui::red())
731            .fill(gpui::red())
732            .name("A")
733            .value(|d| d.b)
734            .max_value(100.)
735            .outer_radius(120.)
736            .label_gap(8.)
737            .grid(false)
738            .grid_levels(5)
739            .dot()
740            .id("radar");
741
742        assert_eq!(chart.data.len(), 2);
743        assert_eq!(chart.values.len(), 2);
744        assert_eq!(chart.strokes.len(), 1);
745        assert_eq!(chart.fills.len(), 1);
746        assert_eq!(chart.names.len(), 1);
747        assert!(chart.label.is_some());
748        assert_eq!(chart.max_value, Some(100.));
749        assert_eq!(chart.outer_radius, 120.);
750        assert_eq!(chart.label_gap, 8.);
751        assert!(!chart.grid);
752        assert_eq!(chart.grid_levels, 5);
753        assert!(chart.dot);
754        assert_eq!(chart.id, gpui::ElementId::Name("radar".into()));
755
756        let values = (chart.values[0](&data[0]), chart.values[1](&data[0]));
757        assert_eq!(values, (80., 60.));
758    }
759
760    /// Every string form the `label` closure may return lands on the text path,
761    /// which is what keeps `label_color` and the tooltip title working.
762    #[test]
763    fn test_radar_label_from_text() {
764        let labels = [
765            RadarLabel::from("Sales"),
766            RadarLabel::from("Sales".to_string()),
767            RadarLabel::from(SharedString::from("Sales")),
768        ];
769
770        for label in labels {
771            assert!(matches!(label, RadarLabel::Text(text) if text == "Sales"));
772        }
773    }
774
775    #[test]
776    fn test_radar_chart_grid_levels_min() {
777        let chart: RadarChart<Item, f64> = RadarChart::new(vec![]).grid_levels(0);
778        assert_eq!(chart.grid_levels, 1);
779    }
780
781    #[test]
782    fn test_radar_chart_hovered_index() {
783        let data = (0..4)
784            .map(|i| Item {
785                subject: format!("S{}", i).into(),
786                a: 50.,
787                b: 50.,
788            })
789            .collect::<Vec<_>>();
790
791        // Bounds 200x200 => center (100, 100), default outer radius 80,
792        // hover region 80 + 10 (label gap) = 90.
793        let chart: RadarChart<Item, f64> = RadarChart::new(data).value(|d| d.a);
794        let bounds = gpui::Bounds::new(point(px(0.), px(0.)), gpui::size(px(200.), px(200.)));
795
796        // The four spokes point at 12, 3, 6 and 9 o'clock.
797        assert_eq!(
798            chart.hovered_index(point(px(100.), px(30.)), bounds),
799            Some(0)
800        );
801        assert_eq!(
802            chart.hovered_index(point(px(170.), px(100.)), bounds),
803            Some(1)
804        );
805        assert_eq!(
806            chart.hovered_index(point(px(100.), px(170.)), bounds),
807            Some(2)
808        );
809        assert_eq!(
810            chart.hovered_index(point(px(30.), px(100.)), bounds),
811            Some(3)
812        );
813
814        // Nearest spoke wins between two spokes.
815        assert_eq!(
816            chart.hovered_index(point(px(110.), px(40.)), bounds),
817            Some(0)
818        );
819        assert_eq!(
820            chart.hovered_index(point(px(160.), px(90.)), bounds),
821            Some(1)
822        );
823
824        // Outside the radar.
825        assert_eq!(chart.hovered_index(point(px(100.), px(5.)), bounds), None);
826        assert_eq!(chart.hovered_index(point(px(5.), px(5.)), bounds), None);
827    }
828}