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
31const DEFAULT_LABEL_GAP: f32 = 10.;
33
34const DEFAULT_GRID_LEVELS: usize = 4;
36
37pub enum RadarLabel {
39 Text(SharedString),
42 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#[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 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 pub fn id(mut self, id: impl Into<ElementId>) -> Self {
144 self.id = id.into();
145 self
146 }
147
148 pub fn interactive(mut self, interactive: bool) -> Self {
156 self.interactive = interactive;
157 self
158 }
159
160 pub fn appear(mut self, appear: bool) -> Self {
167 self.appear.set_enabled(appear);
168 self
169 }
170
171 pub fn appear_key(mut self, key: impl Hash) -> Self {
176 self.appear.set_key(key);
177 self
178 }
179
180 pub fn name(mut self, name: impl Into<SharedString>) -> Self {
185 self.names.push(name.into());
186 self
187 }
188
189 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 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 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 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 pub fn value(mut self, value: impl Fn(&T) -> Y + 'static) -> Self {
242 self.values.push(Rc::new(value));
243 self
244 }
245
246 pub fn stroke(mut self, stroke: impl Into<Hsla>) -> Self {
250 self.strokes.push(stroke.into());
251 self
252 }
253
254 pub fn fill(mut self, fill: impl Into<Background>) -> Self {
258 self.fills.push(fill.into());
259 self
260 }
261
262 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 pub fn label_color(mut self, color: impl Into<Hsla>) -> Self {
290 self.label_color = Some(color.into());
291 self
292 }
293
294 pub fn label_gap(mut self, gap: f32) -> Self {
297 self.label_gap = gap;
298 self
299 }
300
301 pub fn max_value(mut self, max_value: Y) -> Self {
305 self.max_value = Some(max_value);
306 self
307 }
308
309 pub fn outer_radius(mut self, outer_radius: f32) -> Self {
313 self.outer_radius = outer_radius;
314 self
315 }
316
317 pub fn grid(mut self, grid: bool) -> Self {
321 self.grid = grid;
322 self
323 }
324
325 pub fn grid_levels(mut self, grid_levels: usize) -> Self {
327 self.grid_levels = grid_levels.max(1);
328 self
329 }
330
331 pub fn dot(mut self) -> Self {
333 self.dot = true;
334 self
335 }
336
337 fn series_stroke(&self, ix: usize, cx: &App) -> Hsla {
341 self.series_stroke_from(&Self::palette(cx), ix)
342 }
343
344 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 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 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 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 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 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 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 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 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 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
471 let (anchor, direction) = self.label_anchor(ix, outer_radius, &bounds);
472
473 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 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 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 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 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 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 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 || self.label_texts.get(state.index).cloned().flatten(),
678 || {
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 #[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 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 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 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 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}