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