Skip to main content

gpui_component/chart/
radar_chart.rs

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