1use crate::capabilities::data::{chart::is_finite_data_point, palette::default_color};
2use crate::capabilities::foundation::theme::use_theme;
3use gpui::{prelude::FluentBuilder as _, *};
4
5#[derive(Clone, Debug)]
6pub struct AreaChartSeries {
7 pub label: SharedString,
8 pub points: Vec<(f64, f64)>,
9 pub color: Option<Hsla>,
10}
11
12impl AreaChartSeries {
13 pub fn new(label: impl Into<SharedString>, points: Vec<(f64, f64)>) -> Self {
14 Self {
15 label: label.into(),
16 points,
17 color: None,
18 }
19 }
20
21 pub fn color(mut self, color: Hsla) -> Self {
22 self.color = Some(color);
23 self
24 }
25}
26
27#[derive(Copy, Clone, Default, PartialEq, Eq)]
28pub enum AreaChartSize {
29 Sm,
30 #[default]
31 Md,
32 Lg,
33 Custom(u32, u32),
34}
35
36impl AreaChartSize {
37 fn dimensions(self) -> (Pixels, Pixels) {
38 match self {
39 AreaChartSize::Sm => (px(300.0), px(180.0)),
40 AreaChartSize::Md => (px(500.0), px(280.0)),
41 AreaChartSize::Lg => (px(700.0), px(400.0)),
42 AreaChartSize::Custom(w, h) => (px(w as f32), px(h as f32)),
43 }
44 }
45}
46
47#[derive(Copy, Clone, Default, PartialEq, Eq)]
48pub enum AreaChartMode {
49 #[default]
50 Overlaid,
51 Stacked,
52}
53
54struct AreaChartRange {
55 x_min: f64,
56 x_max: f64,
57 y_min: f64,
58 y_max: f64,
59}
60
61impl AreaChartRange {
62 fn from_series(series: &[AreaChartSeries], mode: AreaChartMode) -> Self {
63 if series.is_empty() {
64 return Self {
65 x_min: 0.0,
66 x_max: 1.0,
67 y_min: 0.0,
68 y_max: 1.0,
69 };
70 }
71
72 let mut x_min = f64::MAX;
73 let mut x_max = f64::MIN;
74 let y_min = 0.0_f64;
75 let mut y_max = f64::MIN;
76
77 for s in series {
78 for &(x, y) in &s.points {
79 if !is_finite_data_point(x, y) {
80 continue;
81 }
82 x_min = x_min.min(x);
83 x_max = x_max.max(x);
84 if mode == AreaChartMode::Overlaid {
85 y_max = y_max.max(y);
86 }
87 }
88 }
89
90 if mode == AreaChartMode::Stacked && !series.is_empty() {
91 let max_len = series.iter().map(|s| s.points.len()).max().unwrap_or(0);
92 for i in 0..max_len {
93 let stacked: f64 = series
94 .iter()
95 .filter_map(|series| series.points.get(i))
96 .filter(|&&(x, y)| is_finite_data_point(x, y))
97 .map(|&(_, y)| y)
98 .sum();
99 y_max = y_max.max(stacked);
100 }
101 }
102
103 if x_min == f64::MAX {
104 x_min = 0.0;
105 x_max = 1.0;
106 }
107 if y_max == f64::MIN {
108 y_max = 1.0;
109 }
110 if (x_max - x_min).abs() < f64::EPSILON {
111 x_max = x_min + 1.0;
112 }
113 if (y_max - y_min).abs() < f64::EPSILON {
114 y_max = y_min + 1.0;
115 }
116
117 Self {
118 x_min,
119 x_max,
120 y_min,
121 y_max,
122 }
123 }
124
125 fn normalize_x(&self, x: f64) -> f32 {
126 if !x.is_finite() {
127 return 0.0;
128 }
129 ((x - self.x_min) / (self.x_max - self.x_min)) as f32
130 }
131
132 fn normalize_y(&self, y: f64) -> f32 {
133 if !y.is_finite() {
134 return 0.0;
135 }
136 ((y - self.y_min) / (self.y_max - self.y_min)) as f32
137 }
138}
139
140struct PaintData {
141 series: Vec<AreaChartSeries>,
142 show_grid: bool,
143 _show_x_axis: bool,
144 _show_y_axis: bool,
145 mode: AreaChartMode,
146 _x_labels: Vec<SharedString>,
147 y_label_count: usize,
148 grid_color: Hsla,
149 _text_color: Hsla,
150 fill_opacity: f32,
151}
152
153#[derive(IntoElement)]
154pub struct AreaChart {
155 series: Vec<AreaChartSeries>,
156 size: AreaChartSize,
157 mode: AreaChartMode,
158 show_grid: bool,
159 show_x_axis: bool,
160 show_y_axis: bool,
161 show_legend: bool,
162 x_labels: Vec<SharedString>,
163 y_label_count: usize,
164 fill_opacity: f32,
165 style: StyleRefinement,
166}
167
168impl AreaChart {
169 pub fn new() -> Self {
170 Self {
171 series: Vec::new(),
172 size: AreaChartSize::default(),
173 mode: AreaChartMode::default(),
174 show_grid: true,
175 show_x_axis: true,
176 show_y_axis: true,
177 show_legend: true,
178 x_labels: Vec::new(),
179 y_label_count: 5,
180 fill_opacity: 0.25,
181 style: StyleRefinement::default(),
182 }
183 }
184
185 pub fn series(mut self, s: AreaChartSeries) -> Self {
186 self.series.push(s);
187 self
188 }
189
190 pub fn add_series(mut self, s: AreaChartSeries) -> Self {
191 self.series.push(s);
192 self
193 }
194
195 pub fn size(mut self, size: AreaChartSize) -> Self {
196 self.size = size;
197 self
198 }
199
200 pub fn mode(mut self, mode: AreaChartMode) -> Self {
201 self.mode = mode;
202 self
203 }
204
205 pub fn stacked(mut self) -> Self {
206 self.mode = AreaChartMode::Stacked;
207 self
208 }
209
210 pub fn show_grid(mut self, show: bool) -> Self {
211 self.show_grid = show;
212 self
213 }
214
215 pub fn show_x_axis(mut self, show: bool) -> Self {
216 self.show_x_axis = show;
217 self
218 }
219
220 pub fn show_y_axis(mut self, show: bool) -> Self {
221 self.show_y_axis = show;
222 self
223 }
224
225 pub fn show_legend(mut self, show: bool) -> Self {
226 self.show_legend = show;
227 self
228 }
229
230 pub fn x_labels(mut self, labels: Vec<impl Into<SharedString>>) -> Self {
231 self.x_labels = labels.into_iter().map(|l| l.into()).collect();
232 self
233 }
234
235 pub fn y_label_count(mut self, count: usize) -> Self {
236 self.y_label_count = count.max(2);
237 self
238 }
239
240 pub fn fill_opacity(mut self, opacity: f32) -> Self {
241 self.fill_opacity = opacity.clamp(0.0, 1.0);
242 self
243 }
244}
245
246impl Default for AreaChart {
247 fn default() -> Self {
248 Self::new()
249 }
250}
251
252impl Styled for AreaChart {
253 fn style(&mut self) -> &mut StyleRefinement {
254 &mut self.style
255 }
256}
257
258fn format_value(value: f64) -> String {
259 if value.abs() >= 1000.0 {
260 format!("{:.0}k", value / 1000.0)
261 } else if value.abs() >= 1.0 {
262 format!("{:.0}", value)
263 } else {
264 format!("{:.2}", value)
265 }
266}
267
268impl RenderOnce for AreaChart {
269 fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
270 let theme = use_theme(cx);
271 let user_style = self.style;
272 let (chart_w, chart_h) = self.size.dimensions();
273
274 let padding_left: f32 = if self.show_y_axis { 50.0 } else { 10.0 };
275 let padding_right: f32 = 20.0;
276 let padding_top: f32 = 20.0;
277 let padding_bottom: f32 = if self.show_x_axis { 40.0 } else { 10.0 };
278
279 let series_for_legend = self.series.clone();
280 let show_legend = self.show_legend && self.series.len() > 1;
281
282 let range = AreaChartRange::from_series(&self.series, self.mode);
283 let y_labels: Vec<String> = if self.show_y_axis {
284 (0..=self.y_label_count)
285 .map(|i| {
286 let normalized = i as f64 / self.y_label_count as f64;
287 let value = range.y_min + (range.y_max - range.y_min) * (1.0 - normalized);
288 format_value(value)
289 })
290 .collect()
291 } else {
292 Vec::new()
293 };
294
295 let text_color = theme.tokens.muted_foreground;
296
297 let paint_data = PaintData {
298 series: self.series,
299 show_grid: self.show_grid,
300 _show_x_axis: self.show_x_axis,
301 _show_y_axis: self.show_y_axis,
302 mode: self.mode,
303 _x_labels: self.x_labels.clone(),
304 y_label_count: self.y_label_count,
305 grid_color: theme.tokens.border,
306 _text_color: text_color,
307 fill_opacity: self.fill_opacity,
308 };
309
310 div()
311 .flex()
312 .flex_col()
313 .w(chart_w)
314 .map(|this| {
315 let mut d = this;
316 d.style().refine(&user_style);
317 d
318 })
319 .child(
320 div()
321 .h(chart_h)
322 .w_full()
323 .relative()
324 .child(
325 canvas(
326 move |_bounds, _window, _cx| paint_data,
327 move |bounds, data, window, _cx| {
328 if bounds.size.width <= px(0.0) || bounds.size.height <= px(0.0) {
329 return;
330 }
331
332 let range = AreaChartRange::from_series(&data.series, data.mode);
333
334 let chart_left = bounds.left() + px(padding_left);
335 let chart_right = bounds.right() - px(padding_right);
336 let chart_top = bounds.top() + px(padding_top);
337 let chart_bottom = bounds.bottom() - px(padding_bottom);
338 let chart_width = chart_right - chart_left;
339 let chart_height = chart_bottom - chart_top;
340
341 if chart_width <= px(0.0) || chart_height <= px(0.0) {
342 return;
343 }
344
345 if data.show_grid {
346 let grid_lines = data.y_label_count;
347 for i in 0..=grid_lines {
348 let y = chart_top
349 + chart_height * (i as f32 / grid_lines as f32);
350 let mut builder = PathBuilder::stroke(px(1.0));
351 builder.move_to(point(chart_left, y));
352 builder.line_to(point(chart_right, y));
353 if let Ok(path) = builder.build() {
354 window.paint_path(path, data.grid_color.opacity(0.2));
355 }
356 }
357
358 for i in 0..=grid_lines {
359 let x = chart_left
360 + chart_width * (i as f32 / grid_lines as f32);
361 let mut builder = PathBuilder::stroke(px(1.0));
362 builder.move_to(point(x, chart_top));
363 builder.line_to(point(x, chart_bottom));
364 if let Ok(path) = builder.build() {
365 window.paint_path(path, data.grid_color.opacity(0.2));
366 }
367 }
368 }
369
370 match data.mode {
371 AreaChartMode::Overlaid => {
372 for (idx, s) in data.series.iter().enumerate().rev() {
373 if s.points.len() < 2 {
374 continue;
375 }
376 let color =
377 s.color.unwrap_or_else(|| default_color(idx));
378
379 let screen_pts: Vec<Point<Pixels>> = s
380 .points
381 .iter()
382 .filter(|&&(x, y)| is_finite_data_point(x, y))
383 .map(|&(x, y)| {
384 let sx = chart_left
385 + chart_width * range.normalize_x(x);
386 let sy = chart_bottom
387 - chart_height * range.normalize_y(y);
388 point(sx, sy)
389 })
390 .collect();
391 if screen_pts.len() < 2 {
392 continue;
393 }
394
395 let mut fill_builder = PathBuilder::fill();
396 fill_builder
397 .move_to(point(screen_pts[0].x, chart_bottom));
398 fill_builder.line_to(screen_pts[0]);
399 for pt in screen_pts.iter().skip(1) {
400 fill_builder.line_to(*pt);
401 }
402 fill_builder.line_to(point(
403 screen_pts.last().unwrap().x,
404 chart_bottom,
405 ));
406 fill_builder.close();
407 if let Ok(path) = fill_builder.build() {
408 window.paint_path(
409 path,
410 color.opacity(data.fill_opacity),
411 );
412 }
413
414 let mut stroke_builder = PathBuilder::stroke(px(2.0));
415 stroke_builder.move_to(screen_pts[0]);
416 for pt in screen_pts.iter().skip(1) {
417 stroke_builder.line_to(*pt);
418 }
419 if let Ok(path) = stroke_builder.build() {
420 window.paint_path(path, color);
421 }
422 }
423 }
424 AreaChartMode::Stacked => {
425 let max_len = data
426 .series
427 .iter()
428 .map(|s| s.points.len())
429 .max()
430 .unwrap_or(0);
431 if max_len < 2 {
432 return;
433 }
434
435 let mut cumulative = vec![0.0_f64; max_len];
436 let mut baselines: Vec<Vec<Point<Pixels>>> = Vec::new();
437
438 let x_values: Vec<f64> = (0..max_len)
439 .map(|i| {
440 data.series
441 .iter()
442 .filter_map(|series| series.points.get(i))
443 .find(|&&(x, y)| is_finite_data_point(x, y))
444 .map(|&(x, _)| x)
445 .unwrap_or(i as f64)
446 })
447 .collect();
448
449 let base_pts: Vec<Point<Pixels>> = x_values
450 .iter()
451 .map(|&x| {
452 let sx =
453 chart_left + chart_width * range.normalize_x(x);
454 point(sx, chart_bottom)
455 })
456 .collect();
457 baselines.push(base_pts);
458
459 for (idx, s) in data.series.iter().enumerate() {
460 let color =
461 s.color.unwrap_or_else(|| default_color(idx));
462
463 for (i, &(x, y)) in s.points.iter().enumerate() {
464 if i < max_len && is_finite_data_point(x, y) {
465 cumulative[i] += y;
466 }
467 }
468
469 let top_pts: Vec<Point<Pixels>> = (0..max_len)
470 .map(|i| {
471 let sx = chart_left
472 + chart_width
473 * range.normalize_x(x_values[i]);
474 let sy = chart_bottom
475 - chart_height
476 * range.normalize_y(cumulative[i]);
477 point(sx, sy)
478 })
479 .collect();
480
481 let bottom_pts = baselines.last().unwrap();
482
483 let mut fill_builder = PathBuilder::fill();
484 fill_builder.move_to(bottom_pts[0]);
485 for pt in top_pts.iter() {
486 fill_builder.line_to(*pt);
487 }
488 for pt in bottom_pts.iter().rev() {
489 fill_builder.line_to(*pt);
490 }
491 fill_builder.close();
492 if let Ok(path) = fill_builder.build() {
493 window.paint_path(
494 path,
495 color.opacity(data.fill_opacity),
496 );
497 }
498
499 let mut stroke_builder = PathBuilder::stroke(px(2.0));
500 stroke_builder.move_to(top_pts[0]);
501 for pt in top_pts.iter().skip(1) {
502 stroke_builder.line_to(*pt);
503 }
504 if let Ok(path) = stroke_builder.build() {
505 window.paint_path(path, color);
506 }
507
508 baselines.push(top_pts);
509 }
510 }
511 }
512 },
513 )
514 .size_full(),
515 )
516 .when(self.show_y_axis, |this| {
517 this.children(y_labels.iter().enumerate().map(|(i, label)| {
518 let tick_count = y_labels.len().saturating_sub(1).max(1);
519 let top_percent = i as f32 / tick_count as f32;
520 div()
521 .absolute()
522 .left(px(4.0))
523 .top(relative(top_percent))
524 .mt(px(padding_top - 6.0))
525 .text_size(px(11.0))
526 .text_color(text_color)
527 .child(label.clone())
528 }))
529 })
530 .when(self.show_x_axis && !self.x_labels.is_empty(), |this| {
531 let num_labels = self.x_labels.len();
532 this.children(self.x_labels.iter().enumerate().map(|(i, label)| {
533 let left_percent = if num_labels == 1 {
534 0.5
535 } else {
536 i as f32 / (num_labels - 1) as f32
537 };
538 let chart_w_f32 = chart_w / px(1.0);
539 let chart_frac = 1.0 - (padding_left + padding_right) / chart_w_f32;
540 let adjusted_left =
541 padding_left / chart_w_f32 + left_percent * chart_frac;
542 div()
543 .absolute()
544 .bottom(px(8.0))
545 .left(relative(adjusted_left))
546 .ml(px(-15.0))
547 .text_size(px(11.0))
548 .text_color(text_color)
549 .child(label.clone())
550 }))
551 }),
552 )
553 .when(show_legend, |this| {
554 this.child(
555 div()
556 .flex()
557 .flex_wrap()
558 .gap(px(16.0))
559 .px(px(padding_left))
560 .py(px(8.0))
561 .children(series_for_legend.iter().enumerate().map(|(i, s)| {
562 let color = s.color.unwrap_or_else(|| default_color(i));
563 div()
564 .flex()
565 .items_center()
566 .gap(px(6.0))
567 .child(div().size(px(12.0)).rounded(px(2.0)).bg(color))
568 .child(
569 div()
570 .text_xs()
571 .text_color(text_color)
572 .child(s.label.clone()),
573 )
574 })),
575 )
576 })
577 }
578}
579
580#[cfg(test)]
581mod tests {
582 use super::{AreaChartMode, AreaChartRange, AreaChartSeries};
583
584 #[test]
585 fn range_ignores_non_finite_points_in_overlaid_and_stacked_modes() {
586 let series = vec![
587 AreaChartSeries::new("first", vec![(0.0, 1.0), (f64::NAN, 2.0), (2.0, 3.0)]),
588 AreaChartSeries::new("second", vec![(0.0, 2.0), (1.0, f64::INFINITY), (2.0, 4.0)]),
589 ];
590
591 let overlaid = AreaChartRange::from_series(&series, AreaChartMode::Overlaid);
592 assert_eq!(
593 (
594 overlaid.x_min,
595 overlaid.x_max,
596 overlaid.y_min,
597 overlaid.y_max
598 ),
599 (0.0, 2.0, 0.0, 4.0)
600 );
601 assert!(overlaid.normalize_x(f64::NAN).is_finite());
602 assert!(overlaid.normalize_y(f64::INFINITY).is_finite());
603
604 let stacked = AreaChartRange::from_series(&series, AreaChartMode::Stacked);
605 assert!(stacked.x_min.is_finite());
606 assert!(stacked.x_max.is_finite());
607 assert!(stacked.y_max.is_finite());
608 }
609}