1use crate::capabilities::data::palette::default_color;
2use crate::capabilities::foundation::theme::use_theme;
3use gpui::{prelude::FluentBuilder as _, *};
4
5#[derive(Clone)]
6pub struct RadarDataset {
7 pub label: SharedString,
8 pub values: Vec<f64>,
11 pub color: Option<Hsla>,
12}
13
14impl RadarDataset {
15 pub fn new(label: impl Into<SharedString>, values: Vec<f64>) -> Self {
16 Self {
17 label: label.into(),
18 values,
19 color: None,
20 }
21 }
22
23 pub fn color(mut self, color: Hsla) -> Self {
24 self.color = Some(color);
25 self
26 }
27}
28
29#[derive(Copy, Clone, Default, PartialEq, Eq)]
30pub enum RadarChartSize {
31 Sm,
32 #[default]
33 Md,
34 Lg,
35 Custom(u32),
36}
37
38impl RadarChartSize {
39 fn to_pixels(self) -> Pixels {
40 match self {
41 RadarChartSize::Sm => px(200.0),
42 RadarChartSize::Md => px(300.0),
43 RadarChartSize::Lg => px(400.0),
44 RadarChartSize::Custom(s) => px(s as f32),
45 }
46 }
47}
48
49struct PaintData {
50 axes: Vec<SharedString>,
51 datasets: Vec<RadarDataset>,
52 show_grid: bool,
53 grid_levels: usize,
54 fill_opacity: f32,
55 grid_color: Hsla,
56 _text_color: Hsla,
57 label_padding: f32,
58}
59
60#[derive(IntoElement)]
61pub struct RadarChart {
62 axes: Vec<SharedString>,
63 datasets: Vec<RadarDataset>,
64 size: RadarChartSize,
65 show_grid: bool,
66 show_legend: bool,
67 grid_levels: usize,
68 fill_opacity: f32,
69 style: StyleRefinement,
70}
71
72impl RadarChart {
73 pub fn new() -> Self {
74 Self {
75 axes: Vec::new(),
76 datasets: Vec::new(),
77 size: RadarChartSize::default(),
78 show_grid: true,
79 show_legend: true,
80 grid_levels: 5,
81 fill_opacity: 0.2,
82 style: StyleRefinement::default(),
83 }
84 }
85
86 pub fn axes(mut self, axes: Vec<impl Into<SharedString>>) -> Self {
87 self.axes = axes.into_iter().map(|a| a.into()).collect();
88 self
89 }
90
91 pub fn dataset(mut self, dataset: RadarDataset) -> Self {
92 self.datasets.push(dataset);
93 self
94 }
95
96 pub fn datasets(mut self, datasets: Vec<RadarDataset>) -> Self {
97 self.datasets = datasets;
98 self
99 }
100
101 pub fn size(mut self, size: RadarChartSize) -> Self {
102 self.size = size;
103 self
104 }
105
106 pub fn show_grid(mut self, show: bool) -> Self {
107 self.show_grid = show;
108 self
109 }
110
111 pub fn show_legend(mut self, show: bool) -> Self {
112 self.show_legend = show;
113 self
114 }
115
116 pub fn grid_levels(mut self, levels: usize) -> Self {
117 self.grid_levels = levels.max(2);
118 self
119 }
120
121 pub fn fill_opacity(mut self, opacity: f32) -> Self {
122 self.fill_opacity = opacity.clamp(0.0, 1.0);
123 self
124 }
125}
126
127impl Default for RadarChart {
128 fn default() -> Self {
129 Self::new()
130 }
131}
132
133impl Styled for RadarChart {
134 fn style(&mut self) -> &mut StyleRefinement {
135 &mut self.style
136 }
137}
138
139fn angle_for_axis(index: usize, total: usize) -> f32 {
140 -std::f32::consts::FRAC_PI_2 + (index as f32 / total as f32) * std::f32::consts::TAU
141}
142
143impl RenderOnce for RadarChart {
144 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
145 let theme = use_theme(cx);
146 let user_style = self.style;
147 let chart_size = self.size.to_pixels();
148 let show_legend = self.show_legend && self.datasets.len() > 1;
149 let datasets_for_legend = self.datasets.clone();
150 let text_color = theme.tokens.muted_foreground;
151 let label_padding: f32 = 30.0;
152
153 let n_axes = self.axes.len();
154
155 if n_axes < 3 {
156 return div()
157 .size(chart_size)
158 .flex()
159 .items_center()
160 .justify_center()
161 .child(
162 div()
163 .text_sm()
164 .text_color(theme.tokens.muted_foreground)
165 .child("Need at least 3 axes"),
166 )
167 .map(|this| {
168 let mut d = this;
169 d.style().refine(&user_style);
170 d
171 })
172 .into_any_element();
173 }
174
175 let paint_data = PaintData {
176 axes: self.axes.clone(),
177 datasets: self.datasets,
178 show_grid: self.show_grid,
179 grid_levels: self.grid_levels,
180 fill_opacity: self.fill_opacity,
181 grid_color: theme.tokens.border,
182 _text_color: text_color,
183 label_padding,
184 };
185
186 let axis_labels = self.axes.clone();
187
188 div()
189 .flex()
190 .flex_col()
191 .items_center()
192 .map(|this| {
193 let mut d = this;
194 d.style().refine(&user_style);
195 d
196 })
197 .child(
198 div()
199 .size(chart_size)
200 .relative()
201 .child(
202 canvas(
203 move |_bounds, _window, _cx| paint_data,
204 move |bounds, data, window, _cx| {
205 if bounds.size.width <= px(0.0) || bounds.size.height <= px(0.0) {
206 return;
207 }
208
209 let n = data.axes.len();
210 if n < 3 {
211 return;
212 }
213
214 let cx_f = bounds.left() + bounds.size.width * 0.5;
215 let cy_f = bounds.top() + bounds.size.height * 0.5;
216 let max_radius = (bounds.size.width.min(bounds.size.height) * 0.5)
217 - px(data.label_padding);
218
219 if max_radius <= px(0.0) {
220 return;
221 }
222
223 if data.show_grid {
224 for level in 1..=data.grid_levels {
225 let radius =
226 max_radius * (level as f32 / data.grid_levels as f32);
227 let mut builder = PathBuilder::stroke(px(1.0));
228 for i in 0..=n {
229 let angle = angle_for_axis(i % n, n);
230 let pt = point(
231 cx_f + radius * angle.cos(),
232 cy_f + radius * angle.sin(),
233 );
234 if i == 0 {
235 builder.move_to(pt);
236 } else {
237 builder.line_to(pt);
238 }
239 }
240 if let Ok(path) = builder.build() {
241 window.paint_path(path, data.grid_color.opacity(0.2));
242 }
243 }
244
245 for i in 0..n {
246 let angle = angle_for_axis(i, n);
247 let mut builder = PathBuilder::stroke(px(1.0));
248 builder.move_to(point(cx_f, cy_f));
249 builder.line_to(point(
250 cx_f + max_radius * angle.cos(),
251 cy_f + max_radius * angle.sin(),
252 ));
253 if let Ok(path) = builder.build() {
254 window.paint_path(path, data.grid_color.opacity(0.3));
255 }
256 }
257 }
258
259 for (ds_idx, ds) in data.datasets.iter().enumerate() {
260 if ds.values.is_empty() {
261 continue;
262 }
263 let color = ds.color.unwrap_or_else(|| default_color(ds_idx));
264
265 let pts: Vec<Point<Pixels>> = (0..n)
266 .map(|i| {
267 let val = ds
268 .values
269 .get(i)
270 .copied()
271 .unwrap_or(0.0)
272 .clamp(0.0, 1.0);
273 let angle = angle_for_axis(i, n);
274 let radius = max_radius * val as f32;
275 point(
276 cx_f + radius * angle.cos(),
277 cy_f + radius * angle.sin(),
278 )
279 })
280 .collect();
281
282 if pts.len() >= 3 {
283 let mut fill_builder = PathBuilder::fill();
284 fill_builder.move_to(pts[0]);
285 for pt in pts.iter().skip(1) {
286 fill_builder.line_to(*pt);
287 }
288 fill_builder.close();
289 if let Ok(path) = fill_builder.build() {
290 window
291 .paint_path(path, color.opacity(data.fill_opacity));
292 }
293
294 let mut stroke_builder = PathBuilder::stroke(px(2.0));
295 stroke_builder.move_to(pts[0]);
296 for pt in pts.iter().skip(1) {
297 stroke_builder.line_to(*pt);
298 }
299 stroke_builder.line_to(pts[0]);
300 if let Ok(path) = stroke_builder.build() {
301 window.paint_path(path, color);
302 }
303
304 let dot_size = px(6.0);
305 for pt in &pts {
306 window.paint_quad(fill(
307 Bounds::centered_at(*pt, size(dot_size, dot_size)),
308 color,
309 ));
310 }
311 }
312 }
313 },
314 )
315 .size_full(),
316 )
317 .children(axis_labels.iter().enumerate().map(|(i, label)| {
318 let angle = angle_for_axis(i, n_axes);
319 let label_dist = 0.5 + label_padding / (chart_size / px(1.0));
320 let left_frac = 0.5 + label_dist * angle.cos();
321 let top_frac = 0.5 + label_dist * angle.sin();
322 div()
323 .absolute()
324 .left(relative(left_frac))
325 .top(relative(top_frac))
326 .ml(px(-20.0))
327 .mt(px(-8.0))
328 .text_size(px(11.0))
329 .text_color(text_color)
330 .child(label.clone())
331 })),
332 )
333 .when(show_legend, |this| {
334 this.child(
335 div()
336 .flex()
337 .flex_wrap()
338 .gap(px(16.0))
339 .py(px(8.0))
340 .justify_center()
341 .children(datasets_for_legend.iter().enumerate().map(|(i, ds)| {
342 let color = ds.color.unwrap_or_else(|| default_color(i));
343 div()
344 .flex()
345 .items_center()
346 .gap(px(6.0))
347 .child(div().size(px(12.0)).rounded(px(2.0)).bg(color))
348 .child(
349 div()
350 .text_xs()
351 .text_color(text_color)
352 .child(ds.label.clone()),
353 )
354 })),
355 )
356 })
357 .into_any_element()
358 }
359}