1use crate::{
7 Direction, ElementExt as _, TestSupportExt as _,
8 actions::{SelectFirst, SelectLast, SelectLeft, SelectRight},
9};
10use gpui::{
11 AnyElement, App, Bounds, Context, ElementId, Entity, EventEmitter, FocusHandle,
12 InteractiveElement, IntoElement, KeyBinding, MouseButton, ParentElement, Pixels, Point,
13 RenderOnce, Role, SharedString, StatefulInteractiveElement, StyleRefinement, Styled, Window,
14 div,
15};
16
17pub(crate) fn init(cx: &mut App) {
18 cx.bind_keys([
19 KeyBinding::new("left", SelectLeft, Some("Chart")),
20 KeyBinding::new("right", SelectRight, Some("Chart")),
21 KeyBinding::new("home", SelectFirst, Some("Chart")),
22 KeyBinding::new("end", SelectLast, Some("Chart")),
23 ]);
24}
25
26#[derive(Clone, Debug)]
28pub struct ChartSeries {
29 label: SharedString,
30 values: Vec<f64>,
31}
32impl ChartSeries {
33 pub fn new(label: impl Into<SharedString>, values: impl IntoIterator<Item = f64>) -> Self {
34 let values: Vec<_> = values.into_iter().collect();
35 assert!(
36 values.iter().all(|value| value.is_finite()),
37 "Chart values must be finite"
38 );
39 Self {
40 label: label.into(),
41 values,
42 }
43 }
44 pub fn label(&self) -> &SharedString {
45 &self.label
46 }
47 pub fn values(&self) -> &[f64] {
48 &self.values
49 }
50}
51
52#[derive(Clone, Debug, Eq, PartialEq)]
53pub enum ChartEvent {
54 Inspect(usize),
55 Visibility(usize, bool),
56}
57
58#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
64pub enum ChartLayout {
65 #[default]
67 Grouped,
68 Stacked,
70 Pie,
72 Radar,
74}
75
76pub struct ChartState {
81 categories: Vec<SharedString>,
82 series: Vec<ChartSeries>,
83 visible: Vec<bool>,
84 layout: ChartLayout,
85 range: (f64, f64),
86 inspected: Option<usize>,
87 focus: FocusHandle,
88 bounds: Bounds<Pixels>,
89}
90impl ChartState {
91 pub fn new<L: Into<SharedString>>(
92 categories: impl IntoIterator<Item = L>,
93 series: impl IntoIterator<Item = ChartSeries>,
94 cx: &mut Context<Self>,
95 ) -> Self {
96 let categories: Vec<_> = categories.into_iter().map(Into::into).collect();
97 let series: Vec<_> = series.into_iter().collect();
98 assert!(
99 series
100 .iter()
101 .all(|series| series.values.len() == categories.len()),
102 "Each chart series needs one value per category"
103 );
104 let visible = vec![true; series.len()];
105 let range = Self::data_range(&series, &visible, ChartLayout::Grouped);
106 Self {
107 inspected: (!categories.is_empty()).then_some(0),
108 visible,
109 layout: ChartLayout::Grouped,
110 range,
111 categories,
112 series,
113 focus: cx.focus_handle(),
114 bounds: Bounds::default(),
115 }
116 }
117 pub fn categories(&self) -> &[SharedString] {
118 &self.categories
119 }
120 pub fn series(&self) -> &[ChartSeries] {
121 &self.series
122 }
123 pub fn is_visible(&self, index: usize) -> bool {
124 self.visible[index]
125 }
126 pub fn inspected_index(&self) -> Option<usize> {
127 self.inspected
128 }
129 pub fn focus_handle(&self) -> &FocusHandle {
130 &self.focus
131 }
132
133 pub fn set_visible(
134 &mut self,
135 index: usize,
136 visible: bool,
137 window: &mut Window,
138 cx: &mut Context<Self>,
139 ) -> bool {
140 if self.visible[index] == visible {
141 return false;
142 }
143 self.visible[index] = visible;
144 self.range = Self::data_range(&self.series, &self.visible, self.layout);
145 cx.emit(ChartEvent::Visibility(index, visible));
146 cx.notify();
147 window.refresh();
148 true
149 }
150 pub fn layout(&self) -> ChartLayout {
151 self.layout
152 }
153 pub fn set_layout(
155 &mut self,
156 layout: ChartLayout,
157 window: &mut Window,
158 cx: &mut Context<Self>,
159 ) -> bool {
160 if self.layout == layout {
161 return false;
162 }
163 self.layout = layout;
164 self.range = Self::data_range(&self.series, &self.visible, layout);
165 cx.notify();
166 window.refresh();
167 true
168 }
169 pub fn inspect(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) -> bool {
170 if index >= self.categories.len() || self.inspected == Some(index) {
171 return false;
172 }
173 self.inspected = Some(index);
174 cx.emit(ChartEvent::Inspect(index));
175 cx.notify();
176 window.refresh();
177 true
178 }
179 pub fn range(&self) -> (f64, f64) {
182 self.range
183 }
184
185 fn data_range(series: &[ChartSeries], visible: &[bool], layout: ChartLayout) -> (f64, f64) {
186 let visible = || {
187 series
188 .iter()
189 .zip(visible)
190 .filter(|(_, visible)| **visible)
191 .map(|(series, _)| series)
192 };
193 let (min, max) = if layout == ChartLayout::Stacked {
194 let categories = series.first().map_or(0, |series| series.values.len());
195 (0..categories).fold((0_f64, 0_f64), |(min, max), category| {
196 let (negative, positive) =
197 visible().fold((0_f64, 0_f64), |(negative, positive), series| {
198 let value = series.values[category];
199 (negative + value.min(0.), positive + value.max(0.))
200 });
201 (min.min(negative), max.max(positive))
202 })
203 } else {
204 visible()
205 .flat_map(|series| series.values.iter())
206 .fold((0_f64, 0_f64), |(min, max), &value| {
207 (min.min(value), max.max(value))
208 })
209 };
210 if min == max { (0., 1.) } else { (min, max) }
211 }
212 pub fn stack_span(&self, series: usize, category: usize) -> Option<(f64, f64)> {
216 if !self.visible[series] {
217 return None;
218 }
219 let value = self.series[series].values[category];
220 let start = self.series[..series]
221 .iter()
222 .zip(&self.visible)
223 .filter(|(_, visible)| **visible)
224 .map(|(series, _)| series.values[category])
225 .filter(|earlier| (*earlier < 0.) == (value < 0.))
226 .sum::<f64>();
227 Some((start, start + value))
228 }
229 pub fn pie_slices(&self) -> Vec<(f32, f32)> {
233 let totals: Vec<f64> = (0..self.categories.len())
234 .map(|category| {
235 self.series
236 .iter()
237 .zip(&self.visible)
238 .filter(|(_, visible)| **visible)
239 .map(|(series, _)| series.values[category])
240 .sum::<f64>()
241 .max(0.)
242 })
243 .collect();
244 let sum: f64 = totals.iter().sum();
245 let mut start = 0_f64;
246 totals
247 .iter()
248 .map(|total| {
249 let end = if sum > 0. { start + total / sum } else { 0. };
250 let slice = (start as f32, end as f32);
251 start = end;
252 slice
253 })
254 .collect()
255 }
256 pub fn radar_turn(&self, category: usize) -> f32 {
258 category as f32 / self.categories.len().max(1) as f32
259 }
260 pub fn normalized_value(&self, value: f64) -> f32 {
262 let (min, max) = self.range();
263 let scale = min.abs().max(max.abs());
264 ((value / scale - min / scale) / (max / scale - min / scale)).clamp(0., 1.) as f32
265 }
266 pub fn inspected_description(&self) -> SharedString {
267 self.inspected_description_with(|value| value.to_string())
268 }
269
270 pub fn inspected_description_with(&self, format_value: impl Fn(f64) -> String) -> SharedString {
272 let Some(index) = self.inspected else {
273 return "No chart data".into();
274 };
275 let values = self
276 .series
277 .iter()
278 .zip(&self.visible)
279 .filter(|(_, visible)| **visible)
280 .map(|(series, _)| format!("{}: {}", series.label, format_value(series.values[index])))
281 .collect::<Vec<_>>()
282 .join(", ");
283 format!(
284 "{}: {}",
285 self.categories[index],
286 if values.is_empty() {
287 "No visible series"
288 } else {
289 &values
290 }
291 )
292 .into()
293 }
294 fn step(&mut self, forward: bool, window: &mut Window, cx: &mut Context<Self>) {
295 if !self.focus.is_focused(window) {
296 cx.propagate();
297 return;
298 }
299 if let Some(index) = self.inspected {
300 let next = if forward {
301 (index + 1).min(self.categories.len() - 1)
302 } else {
303 index.saturating_sub(1)
304 };
305 self.inspect(next, window, cx);
306 }
307 }
308
309 fn inspect_at_pointer(
310 &mut self,
311 position: Point<Pixels>,
312 direction: Direction,
313 window: &mut Window,
314 cx: &mut Context<Self>,
315 ) {
316 let count = self.categories.len();
317 if count == 0 || self.bounds.size.width <= gpui::px(0.) {
318 return;
319 }
320 let index = match self.layout {
321 ChartLayout::Grouped | ChartLayout::Stacked => {
322 let fraction = direction.physical_fraction(
323 ((position.x - self.bounds.left()) / self.bounds.size.width).clamp(0., 1.),
324 );
325 ((fraction * count as f32) as usize).min(count - 1)
326 }
327 ChartLayout::Pie | ChartLayout::Radar => {
328 let center = self.bounds.center();
329 let radius = f32::from(self.bounds.size.width.min(self.bounds.size.height)) / 2.;
330 let dx = f32::from(position.x - center.x);
331 let dy = f32::from(position.y - center.y);
332 if dx.hypot(dy) > radius {
333 return;
334 }
335 let tau = std::f32::consts::TAU;
336 let clockwise = dx.atan2(-dy).rem_euclid(tau) / tau;
337 let turn = if direction.is_rtl() {
338 (1. - clockwise).rem_euclid(1.)
339 } else {
340 clockwise
341 };
342 if self.layout == ChartLayout::Radar {
343 (turn * count as f32).round() as usize % count
344 } else {
345 let slices = self.pie_slices();
346 let Some(index) = slices
347 .iter()
348 .position(|(start, end)| start < end && (*start..*end).contains(&turn))
349 else {
350 return;
351 };
352 index
353 }
354 }
355 };
356 self.inspect(index, window, cx);
357 }
358}
359impl EventEmitter<ChartEvent> for ChartState {}
360
361#[derive(IntoElement)]
371pub struct Chart {
372 base: crate::ObservedElement<gpui::Stateful<gpui::Div>>,
373 state: Entity<ChartState>,
374 label: SharedString,
375 value_description: Option<SharedString>,
376 direction: Option<Direction>,
377}
378impl Chart {
379 pub fn new(
380 id: impl Into<ElementId>,
381 state: &Entity<ChartState>,
382 label: impl Into<SharedString>,
383 ) -> Self {
384 Self {
385 base: div().id(id).test_support(),
386 state: state.clone(),
387 label: label.into(),
388 value_description: None,
389 direction: None,
390 }
391 }
392 pub fn value_description(mut self, description: impl Into<SharedString>) -> Self {
394 self.value_description = Some(description.into());
395 self
396 }
397 pub fn direction(mut self, direction: Direction) -> Self {
398 self.direction = Some(direction);
399 self
400 }
401}
402impl Styled for Chart {
403 fn style(&mut self) -> &mut StyleRefinement {
404 self.base.style()
405 }
406}
407impl ParentElement for Chart {
408 fn extend(&mut self, children: impl IntoIterator<Item = AnyElement>) {
409 self.base.extend(children);
410 }
411}
412impl RenderOnce for Chart {
413 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
414 let direction = self.direction.unwrap_or_else(|| Direction::current(cx));
415 let model = self.state.read(cx);
416 let focus = model.focus.clone();
417 let description = self
418 .value_description
419 .unwrap_or_else(|| model.inspected_description());
420 let previous = self.state.clone();
421 let next = self.state.clone();
422 let first = self.state.clone();
423 let last = self.state.clone();
424 let geometry = self.state.clone();
425 self.base.role(Role::Group).aria_label(self.label).aria_value(description)
426 .aria_description("Use Left and Right to inspect categories. The accompanying data table contains all values.")
427 .track_focus(&focus).key_context("Chart")
428 .on_action(move |_:&SelectLeft,window,cx|{previous.update(cx,|state,cx|state.step(direction.horizontal_forward(false),window,cx));})
429 .on_action(move |_:&SelectRight,window,cx|{next.update(cx,|state,cx|state.step(direction.horizontal_forward(true),window,cx));})
430 .on_action(move |_:&SelectFirst,window,cx|{first.update(cx,|state,cx|{if state.focus.is_focused(window){state.inspect(0,window,cx);}else{cx.propagate();}});})
431 .on_action(move |_:&SelectLast,window,cx|{last.update(cx,|state,cx|{if state.focus.is_focused(window){if !state.categories.is_empty(){state.inspect(state.categories.len()-1,window,cx);}}else{cx.propagate();}});})
432 .on_mouse_down(MouseButton::Left,window.listener_for(&self.state,move |state,event: &gpui::MouseDownEvent,window,cx|{
433 state.focus.focus(window,cx);
434 state.inspect_at_pointer(event.position,direction,window,cx);
435 }))
436 .on_mouse_move(window.listener_for(&self.state,move |state,event: &gpui::MouseMoveEvent,window,cx|{
437 state.inspect_at_pointer(event.position,direction,window,cx);
438 }))
439 .on_prepaint(move |bounds,_,cx|geometry.update(cx,|state,_|state.bounds=bounds))
440 }
441}
442
443#[cfg(test)]
444mod tests {
445 use super::*;
446 use crate::Root;
447 use gpui::{AppContext as _, Render, Subscription, TestAppContext, point, px};
448 struct Harness {
449 state: Entity<ChartState>,
450 _subscription: Subscription,
451 }
452 impl Render for Harness {
453 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
454 Chart::new("chart", &self.state, "Session delta")
455 .w(px(300.))
456 .h(px(120.))
457 }
458 }
459 #[gpui::test]
460 fn inspection_and_legend_keep_exact_values_and_signed_domain(cx: &mut TestAppContext) {
461 cx.update(crate::init);
462 let (root, cx) = cx.add_window_view(|window, cx| {
463 let view = cx.new(|cx| {
464 let state = cx.new(|cx| {
465 ChartState::new(
466 ["Mon", "Tue", "Wed"],
467 [
468 ChartSeries::new("Desktop", [-10., 0., 20.]),
469 ChartSeries::new("Mobile", [5., 10., 15.]),
470 ],
471 cx,
472 )
473 });
474 let subscription = cx.observe(&state, |_, _, cx| cx.notify());
475 Harness {
476 state,
477 _subscription: subscription,
478 }
479 });
480 Root::new(view, window, cx)
481 });
482 let view = root
483 .read_with(cx, |root, _| root.view().clone())
484 .downcast::<Harness>()
485 .unwrap();
486 cx.update(|window, cx| {
487 window.activate_window();
488 let state = view.read(cx).state.clone();
489 state.read(cx).focus.clone().focus(window, cx);
490 window.draw(cx).clear(cx);
491 assert_eq!(state.read(cx).range(), (-10., 20.));
492 assert_eq!(state.read(cx).normalized_value(-10.), 0.);
493 assert_eq!(state.read(cx).normalized_value(20.), 1.);
494 });
495 cx.simulate_keystrokes("right");
496 cx.update(|_, cx| {
497 assert_eq!(
498 view.read(cx)
499 .state
500 .read(cx)
501 .inspected_description()
502 .as_ref(),
503 "Tue: Desktop: 0, Mobile: 10"
504 )
505 });
506 cx.simulate_mouse_move(point(px(290.), px(50.)), None, gpui::Modifiers::default());
507 cx.update(|window, cx| {
508 let state = view.read(cx).state.clone();
509 assert_eq!(state.read(cx).inspected_index(), Some(2));
510 state.update(cx, |state, cx| {
511 state.set_visible(0, false, window, cx);
512 assert_eq!(state.range(), (0., 15.));
513 assert_eq!(state.inspected_description().as_ref(), "Wed: Mobile: 15");
514 state.set_visible(1, false, window, cx);
515 assert_eq!(state.range(), (0., 1.));
516 assert_eq!(state.normalized_value(0.), 0.);
517 state.set_visible(0, true, window, cx);
518 assert_eq!(state.range(), (-10., 20.));
519 assert_eq!(state.normalized_value(20.), 1.);
520 });
521 });
522 cx.simulate_mouse_down(
523 point(px(10.), px(50.)),
524 MouseButton::Left,
525 gpui::Modifiers::default(),
526 );
527 cx.simulate_mouse_up(
528 point(px(10.), px(50.)),
529 MouseButton::Left,
530 gpui::Modifiers::default(),
531 );
532 cx.update(|window, cx| {
533 let state = view.read(cx).state.read(cx);
534 assert_eq!(
535 state.inspected_index(),
536 Some(0),
537 "a press inspects without an earlier move"
538 );
539 assert!(state.focus_handle().is_focused(window));
540 });
541 }
542
543 #[gpui::test]
544 fn layouts_share_stacked_ranges_and_radial_hit_testing(cx: &mut TestAppContext) {
545 cx.update(crate::init);
546 let (root, cx) = cx.add_window_view(|window, cx| {
547 let view = cx.new(|cx| {
548 let state = cx.new(|cx| {
549 ChartState::new(
550 ["Mon", "Tue", "Wed"],
551 [
552 ChartSeries::new("Desktop", [-10., 0., 20.]),
553 ChartSeries::new("Mobile", [5., 10., 15.]),
554 ],
555 cx,
556 )
557 });
558 let subscription = cx.observe(&state, |_, _, cx| cx.notify());
559 Harness {
560 state,
561 _subscription: subscription,
562 }
563 });
564 Root::new(view, window, cx)
565 });
566 let state = root
567 .read_with(cx, |root, _| root.view().clone())
568 .downcast::<Harness>()
569 .unwrap()
570 .read_with(cx, |view, _| view.state.clone());
571 cx.update(|window, cx| {
572 state.update(cx, |state, cx| {
573 assert!(state.set_layout(ChartLayout::Stacked, window, cx));
574 assert_eq!(state.range(), (-10., 35.));
575 assert_eq!(state.stack_span(0, 0), Some((0., -10.)));
576 assert_eq!(state.stack_span(1, 0), Some((0., 5.)));
577 assert_eq!(state.stack_span(1, 2), Some((20., 35.)));
578 state.set_visible(0, false, window, cx);
579 assert_eq!(state.stack_span(0, 2), None);
580 assert_eq!(state.stack_span(1, 2), Some((0., 15.)));
581 assert_eq!(state.range(), (0., 15.));
582 state.set_visible(0, true, window, cx);
583 assert!(state.set_layout(ChartLayout::Pie, window, cx));
584 assert_eq!(
585 state.range(),
586 (-10., 20.),
587 "only stacking changes the range"
588 );
589 let slices = state.pie_slices();
590 assert_eq!(slices[0], (0., 0.), "a negative total has no slice");
591 assert!((slices[1].1 - 10. / 45.).abs() < 1e-6);
592 assert_eq!(slices[2].1, 1.);
593 });
594 window.draw(cx).clear(cx);
595 });
596 let inspected =
598 |cx: &mut gpui::VisualTestContext| cx.update(|_, cx| state.read(cx).inspected_index());
599 cx.simulate_mouse_move(point(px(170.), px(40.)), None, gpui::Modifiers::default());
600 assert_eq!(inspected(cx), Some(1), "an eighth turn lies in Tue's slice");
601 cx.simulate_mouse_move(point(px(120.), px(60.)), None, gpui::Modifiers::default());
602 assert_eq!(inspected(cx), Some(2), "three quarters lies in Wed's slice");
603 cx.simulate_mouse_move(point(px(290.), px(60.)), None, gpui::Modifiers::default());
604 assert_eq!(
605 inspected(cx),
606 Some(2),
607 "outside the circle keeps inspection"
608 );
609 cx.update(|window, cx| {
610 state.update(cx, |state, cx| {
611 state.set_layout(ChartLayout::Radar, window, cx);
612 assert_eq!(state.radar_turn(1), 1. / 3.);
613 })
614 });
615 cx.simulate_mouse_move(point(px(150.), px(10.)), None, gpui::Modifiers::default());
616 assert_eq!(
617 inspected(cx),
618 Some(0),
619 "the top spoke is the first category"
620 );
621 cx.simulate_mouse_move(point(px(115.), px(80.)), None, gpui::Modifiers::default());
622 assert_eq!(
623 inspected(cx),
624 Some(2),
625 "the lower-left spoke is the third category"
626 );
627 }
628}