use std::cell::RefCell;
use std::collections::HashSet;
use std::f32::consts::{FRAC_PI_2, TAU};
use std::rc::Rc;
use arc_motion::{arc_spring_with_options, spring::SpringOptions};
use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, SpringSpec, Typography};
use gpui_kit::{
App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
MouseDownEvent, MouseMoveEvent, ParentElement, Pixels, RenderOnce, Role, SharedString, Styled,
Window, base::StyledExt as _, canvas, div, prelude::*, px,
};
use super::common::{
build_annular_sector_fill, chart_other_color, chart_series_color, format_grouped, format_share,
};
pub const DONUT_OTHER_KEY: &str = "__other";
pub const DONUT_LIFT_PX: f32 = 4.5;
pub const DONUT_GROW_PX: f32 = 2.0;
pub const DONUT_GAP_PX: f32 = 3.0;
pub const DONUT_MARGIN_PX: f32 = 8.0;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum DonutLegendAction {
#[default]
Toggle,
Select,
}
#[derive(Clone, Debug)]
pub struct DonutChartDatum {
pub key: SharedString,
pub label: SharedString,
pub value: f64,
pub color: Option<Hsla>,
}
impl DonutChartDatum {
pub fn new(key: impl Into<SharedString>, label: impl Into<SharedString>, value: f64) -> Self {
Self {
key: key.into(),
label: label.into(),
value,
color: None,
}
}
pub fn color(mut self, color: Hsla) -> Self {
self.color = Some(color);
self
}
}
#[derive(Clone, Debug)]
pub struct DonutSlice {
pub key: SharedString,
pub label: SharedString,
pub value: f64,
pub color: Option<Hsla>,
pub member_count: usize,
}
pub fn donut_group_slices(
data: &[DonutChartDatum],
group_below: f64,
max_segments: usize,
other_label: &str,
) -> Vec<DonutSlice> {
let parts: Vec<&DonutChartDatum> = data.iter().filter(|d| d.value > 0.0).collect();
let total: f64 = parts.iter().map(|d| d.value).sum();
if total <= 0.0 {
return Vec::new();
}
let mut ranked = parts.clone();
ranked.sort_by(|a, b| b.value.total_cmp(&a.value));
let limit = max_segments.max(2) - 1;
let keep: HashSet<SharedString> = ranked
.iter()
.enumerate()
.filter(|&(rank, d)| d.value / total >= group_below && rank < limit)
.map(|(_, d)| d.key.clone())
.collect();
let rest: Vec<&DonutChartDatum> = parts
.iter()
.copied()
.filter(|d| !keep.contains(&d.key))
.collect();
if rest.len() < 2 {
return parts
.into_iter()
.map(|d| DonutSlice {
key: d.key.clone(),
label: d.label.clone(),
value: d.value,
color: d.color,
member_count: 1,
})
.collect();
}
let mut out: Vec<DonutSlice> = parts
.into_iter()
.filter(|d| keep.contains(&d.key))
.map(|d| DonutSlice {
key: d.key.clone(),
label: d.label.clone(),
value: d.value,
color: d.color,
member_count: 1,
})
.collect();
out.push(DonutSlice {
key: SharedString::from(DONUT_OTHER_KEY),
label: SharedString::from(other_label.to_string()),
value: rest.iter().map(|d| d.value).sum(),
color: None,
member_count: rest.len(),
});
out
}
pub fn donut_layout_arcs(
slices: &[DonutSlice],
hidden: &HashSet<SharedString>,
) -> Vec<(SharedString, f32, f32)> {
let total: f64 = slices
.iter()
.filter(|s| !hidden.contains(&s.key))
.map(|s| s.value)
.sum();
let denom = if total > 0.0 { total } else { 1.0 };
let mut at = 0.0f64;
slices
.iter()
.map(|s| {
let span = if hidden.contains(&s.key) {
0.0
} else {
s.value / denom
};
let start = at as f32;
at += span;
(s.key.clone(), start, at as f32)
})
.collect()
}
pub fn donut_hit_test(
x: f32,
y: f32,
cx: f32,
cy: f32,
inner_r: f32,
outer_r: f32,
arcs: &[(SharedString, f32, f32)],
) -> Option<SharedString> {
let dx = x - cx;
let dy = y - cy;
let r = dx.hypot(dy);
if r < (inner_r - 6.0).max(0.0) || r > outer_r + DONUT_MARGIN_PX {
return None;
}
let mut turn = (dy.atan2(dx) + FRAC_PI_2) / TAU;
if turn < 0.0 {
turn += 1.0;
}
for (key, t0, t1) in arcs {
if t1 > t0 && turn >= *t0 && turn <= *t1 {
return Some(key.clone());
}
}
None
}
struct DonutState {
selected: Option<SharedString>,
preview: Option<SharedString>,
hidden: HashSet<SharedString>,
ring_bounds: Option<Bounds<Pixels>>,
focus: FocusHandle,
}
#[derive(IntoElement)]
pub struct DonutChart {
id: ElementId,
label: SharedString,
data: Vec<DonutChartDatum>,
unit: SharedString,
total_label: SharedString,
size: f32,
thickness: f32,
group_below: f64,
max_segments: usize,
other_label: SharedString,
legend_action: DonutLegendAction,
legend: bool,
empty_label: SharedString,
}
impl DonutChart {
pub fn new(
id: impl Into<ElementId>,
label: impl Into<SharedString>,
data: Vec<DonutChartDatum>,
) -> Self {
Self {
id: id.into(),
label: label.into(),
data,
unit: SharedString::default(),
total_label: SharedString::from("Total"),
size: 208.0,
thickness: 24.0,
group_below: 0.04,
max_segments: 6,
other_label: SharedString::from("Other"),
legend_action: DonutLegendAction::Toggle,
legend: true,
empty_label: SharedString::from("No data yet"),
}
}
pub fn unit(mut self, unit: impl Into<SharedString>) -> Self {
self.unit = unit.into();
self
}
pub fn total_label(mut self, label: impl Into<SharedString>) -> Self {
self.total_label = label.into();
self
}
pub fn size(mut self, px_val: f32) -> Self {
self.size = px_val.clamp(120.0, 320.0);
self
}
pub fn thickness(mut self, px_val: f32) -> Self {
self.thickness = px_val.clamp(12.0, 48.0);
self
}
pub fn group_below(mut self, share: f64) -> Self {
self.group_below = share.clamp(0.0, 0.5);
self
}
pub fn max_segments(mut self, max: usize) -> Self {
self.max_segments = max.max(2);
self
}
pub fn legend_action(mut self, action: DonutLegendAction) -> Self {
self.legend_action = action;
self
}
pub fn legend(mut self, show: bool) -> Self {
self.legend = show;
self
}
}
impl RenderOnce for DonutChart {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let slices = donut_group_slices(
&self.data,
self.group_below,
self.max_segments,
self.other_label.as_ref(),
);
let state = window.use_keyed_state(
SharedString::from(format!("arc-donut-state-{:?}", self.id)),
cx,
|_w, cx| {
Rc::new(RefCell::new(DonutState {
selected: None,
preview: None,
hidden: HashSet::new(),
ring_bounds: None,
focus: cx.focus_handle(),
}))
},
);
let st_rc = state.read(cx).clone();
let (selected_key, preview_key, hidden_set, focus_handle) = {
let st = st_rc.borrow();
(
st.selected.clone(),
st.preview.clone(),
st.hidden.clone(),
st.focus.clone(),
)
};
let visible_slices: Vec<&DonutSlice> = slices
.iter()
.filter(|s| !hidden_set.contains(&s.key))
.collect();
let visible_count = visible_slices.len();
let total: f64 = visible_slices.iter().map(|s| s.value).sum();
let active_key = preview_key
.filter(|k| !hidden_set.contains(k))
.or_else(|| selected_key.clone().filter(|k| !hidden_set.contains(k)));
let active_slice = active_key
.as_ref()
.and_then(|k| visible_slices.iter().find(|s| &s.key == k).copied());
let arcs = donut_layout_arcs(&slices, &hidden_set);
let diam = self.size;
let outer_r = diam * 0.5 - DONUT_MARGIN_PX;
let inner_r = (outer_r - self.thickness).max(16.0);
struct RenderSlice {
color: Hsla,
t0: f32,
t1: f32,
lift: f32,
}
let mut render_slices = Vec::with_capacity(slices.len());
for (idx, s) in slices.iter().enumerate() {
let (_, target_t0, target_t1) = arcs[idx];
let anim_t0 = arc_spring_with_options(
SharedString::from(format!("arc-donut-s0-{:?}-{}", self.id, s.key)),
target_t0,
SpringOptions::new(SpringSpec::visual(0.48, 0.0)),
window,
cx,
)
.value;
let anim_t1 = arc_spring_with_options(
SharedString::from(format!("arc-donut-s1-{:?}-{}", self.id, s.key)),
target_t1,
SpringOptions::new(SpringSpec::visual(0.48, 0.0)),
window,
cx,
)
.value;
let is_active = active_key.as_ref() == Some(&s.key);
let lift = arc_spring_with_options(
SharedString::from(format!("arc-donut-lift-{:?}-{}", self.id, s.key)),
if is_active { 1.0 } else { 0.0 },
SpringOptions::new(SpringSpec::visual(0.22, 0.0)),
window,
cx,
)
.value
.clamp(0.0, 1.0);
let col = s.color.unwrap_or_else(|| {
if s.key.as_ref() == DONUT_OTHER_KEY {
chart_other_color(&colors)
} else {
chart_series_color(&colors, idx)
}
});
render_slices.push(RenderSlice {
color: col,
t0: anim_t0,
t1: anim_t1,
lift,
});
}
let has_active = active_slice.is_some();
let arcs_for_hit = arcs.clone();
let arcs_for_click = arcs.clone();
let st_paint = st_rc.clone();
let st_move = st_rc.clone();
let st_click = st_rc.clone();
let st_leave = st_rc.clone();
let st_key = st_rc.clone();
let visible_keys: Vec<SharedString> =
visible_slices.iter().map(|s| s.key.clone()).collect();
let ring_canvas = canvas(
move |bounds, _w, _cx| {
st_paint.borrow_mut().ring_bounds = Some(bounds);
bounds
},
move |bounds, _, window, _cx| {
let left: f32 = bounds.origin.x.into();
let top: f32 = bounds.origin.y.into();
let w: f32 = bounds.size.width.into();
let h: f32 = bounds.size.height.into();
let cx_px = left + w * 0.5;
let cy_px = top + h * 0.5;
for rs in &render_slices {
if rs.t1 - rs.t0 <= 0.002 {
continue;
}
let mid_angle = ((rs.t0 + rs.t1) * 0.5) * TAU - FRAC_PI_2;
let dx = mid_angle.cos() * rs.lift * DONUT_LIFT_PX;
let dy = mid_angle.sin() * rs.lift * DONUT_LIFT_PX;
let r_out = outer_r + rs.lift * DONUT_GROW_PX;
let r_in = (inner_r - rs.lift * DONUT_GROW_PX * 0.5).max(8.0);
let alpha = if has_active && rs.lift < 0.2 {
0.55
} else {
1.0
};
if let Some(path) = build_annular_sector_fill(
cx_px + dx,
cy_px + dy,
r_out,
r_in,
rs.t0,
rs.t1,
DONUT_GAP_PX,
) {
window.paint_path(path, rs.color.alpha(rs.color.a * alpha));
}
}
},
)
.w(px(diam))
.h(px(diam));
let unit_suffix = if self.unit.is_empty() {
String::new()
} else {
format!(" {}", self.unit)
};
let (center_label, center_value, center_share) = match active_slice {
Some(s) => (
s.label.clone(),
format!("{}{}", format_grouped(s.value, 1), unit_suffix),
Some(format_share(if total > 0.0 {
s.value / total
} else {
0.0
})),
),
None => (
self.total_label.clone(),
format!("{}{}", format_grouped(total, 1), unit_suffix),
None,
),
};
let ring_box = div()
.id(SharedString::from(format!("arc-donut-ring-{:?}", self.id)))
.relative()
.w(px(diam))
.h(px(diam))
.flex_none()
.track_focus(&focus_handle)
.role(Role::Group)
.cursor_pointer()
.on_mouse_move(move |ev: &MouseMoveEvent, window, _cx| {
let bounds = st_move.borrow().ring_bounds;
if let Some(b) = bounds {
let cx_px: f32 = b.origin.x.into();
let cy_px: f32 = b.origin.y.into();
let w: f32 = b.size.width.into();
let h: f32 = b.size.height.into();
let hit = donut_hit_test(
ev.position.x.into(),
ev.position.y.into(),
cx_px + w * 0.5,
cy_px + h * 0.5,
inner_r,
outer_r,
&arcs_for_hit,
);
let mut st = st_move.borrow_mut();
if st.preview != hit {
st.preview = hit;
window.refresh();
}
}
})
.on_mouse_down(
MouseButton::Left,
move |ev: &MouseDownEvent, window, _cx| {
let bounds = st_click.borrow().ring_bounds;
if let Some(b) = bounds {
let cx_px: f32 = b.origin.x.into();
let cy_px: f32 = b.origin.y.into();
let w: f32 = b.size.width.into();
let h: f32 = b.size.height.into();
let hit = donut_hit_test(
ev.position.x.into(),
ev.position.y.into(),
cx_px + w * 0.5,
cy_px + h * 0.5,
inner_r,
outer_r,
&arcs_for_click,
);
let mut st = st_click.borrow_mut();
if let Some(k) = hit {
if st.selected.as_ref() == Some(&k) {
st.selected = None;
} else {
st.selected = Some(k);
}
window.refresh();
}
}
},
)
.on_hover(move |hovered, window, _cx| {
if !*hovered {
let mut st = st_leave.borrow_mut();
if st.preview.is_some() {
st.preview = None;
window.refresh();
}
}
})
.on_key_down(move |ev: &KeyDownEvent, window, _cx| {
if visible_keys.is_empty() {
return;
}
let mut st = st_key.borrow_mut();
let cur_pos = st
.selected
.as_ref()
.and_then(|k| visible_keys.iter().position(|vk| vk == k));
let next_key = match ev.keystroke.key.as_str() {
"escape" => {
st.selected = None;
st.preview = None;
window.refresh();
return;
}
"right" | "down" => {
let idx = cur_pos.map(|p| (p + 1) % visible_keys.len()).unwrap_or(0);
Some(visible_keys[idx].clone())
}
"left" | "up" => {
let idx = cur_pos
.map(|p| (p + visible_keys.len() - 1) % visible_keys.len())
.unwrap_or(visible_keys.len() - 1);
Some(visible_keys[idx].clone())
}
_ => return,
};
st.selected = next_key;
window.refresh();
})
.child(ring_canvas)
.child(
div()
.absolute()
.inset_0()
.flex()
.flex_col()
.items_center()
.justify_center()
.gap(px(2.0))
.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(center_label),
)
.child(
div()
.text_size(Typography::TEXT_LG)
.font_semibold()
.text_color(colors.foreground)
.child(center_value),
)
.when_some(center_share, |this, sh| {
this.child(
div()
.text_size(Typography::TEXT_XS)
.font_medium()
.text_color(colors.accent)
.child(sh),
)
}),
);
let legend_panel = if self.legend {
let mut list = div()
.flex_1()
.min_w(px(180.0))
.flex()
.flex_col()
.gap(px(4.0));
for (idx, s) in slices.iter().enumerate() {
let is_hidden = hidden_set.contains(&s.key);
let is_active = active_key.as_ref() == Some(&s.key);
let share = if !is_hidden && total > 0.0 {
format_share(s.value / total)
} else {
"—".to_string()
};
let col = s.color.unwrap_or_else(|| {
if s.key.as_ref() == DONUT_OTHER_KEY {
chart_other_color(&colors)
} else {
chart_series_color(&colors, idx)
}
});
let key_click = s.key.clone();
let key_hover = s.key.clone();
let st_row_click = st_rc.clone();
let st_row_hover = st_rc.clone();
let action = self.legend_action;
list = list.child(
div()
.id(SharedString::from(format!(
"arc-donut-leg-{:?}-{}",
self.id, idx
)))
.w_full()
.px(Spacing::S2)
.py(px(6.0))
.rounded(Radii::CONTROL)
.bg(if is_active {
colors.surface_muted
} else {
gpui_kit::Hsla::transparent_black()
})
.cursor_pointer()
.flex()
.items_center()
.justify_between()
.gap(Spacing::S2)
.on_hover(move |hovered, window, _cx| {
let mut st = st_row_hover.borrow_mut();
if *hovered {
st.preview = Some(key_hover.clone());
} else if st.preview.as_ref() == Some(&key_hover) {
st.preview = None;
}
window.refresh();
})
.on_mouse_down(MouseButton::Left, move |_, window, _cx| {
let mut st = st_row_click.borrow_mut();
match action {
DonutLegendAction::Toggle => {
if st.hidden.contains(&key_click) {
st.hidden.remove(&key_click);
} else if visible_count > 1 {
st.hidden.insert(key_click.clone());
if st.selected.as_ref() == Some(&key_click) {
st.selected = None;
}
}
}
DonutLegendAction::Select => {
if st.selected.as_ref() == Some(&key_click) {
st.selected = None;
} else {
st.selected = Some(key_click.clone());
}
}
}
window.refresh();
})
.child(
div()
.flex()
.items_center()
.gap(Spacing::S2)
.child(
div()
.w(px(9.0))
.h(px(9.0))
.rounded(Radii::PILL)
.bg(if is_hidden { colors.border_strong } else { col }),
)
.child(
div()
.text_size(Typography::TEXT_SM)
.text_color(if is_hidden {
colors.text_muted
} else {
colors.foreground
})
.child(s.label.clone()),
),
)
.child(
div()
.flex()
.items_center()
.gap(Spacing::S2)
.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(format_grouped(s.value, 1)),
)
.child(
div()
.w(px(34.0))
.flex()
.justify_end()
.text_size(Typography::TEXT_XS)
.font_semibold()
.text_color(if is_hidden {
colors.text_muted
} else {
colors.foreground
})
.child(share),
),
),
);
}
Some(list)
} else {
None
};
div()
.id(self.id)
.w_full()
.p(Spacing::S5)
.rounded(Radii::PANEL)
.border_1()
.border_color(colors.border)
.bg(colors.surface)
.flex()
.flex_col()
.gap(Spacing::S3)
.child(
div()
.text_size(Typography::TEXT_SM)
.font_semibold()
.text_color(colors.foreground)
.child(self.label),
)
.child(if slices.is_empty() {
div()
.w_full()
.h(px(diam))
.flex()
.items_center()
.justify_center()
.text_size(Typography::TEXT_SM)
.text_color(colors.text_muted)
.child(self.empty_label)
.into_any_element()
} else {
div()
.w_full()
.flex()
.flex_wrap()
.items_center()
.gap(Spacing::S5)
.child(ring_box)
.when_some(legend_panel, |this, leg| this.child(leg))
.into_any_element()
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn donut_grouping_layout_and_hit_testing() {
let data = vec![
DonutChartDatum::new("org", "Organic", 480.0),
DonutChartDatum::new("dir", "Direct", 320.0),
DonutChartDatum::new("ref", "Referral", 160.0),
DonutChartDatum::new("em", "Email", 20.0),
DonutChartDatum::new("soc", "Social", 20.0),
];
let slices = donut_group_slices(&data, 0.04, 6, "Other");
assert_eq!(slices.len(), 4);
assert_eq!(slices[3].key.as_ref(), DONUT_OTHER_KEY);
assert_eq!(slices[3].member_count, 2);
assert!((slices[3].value - 40.0).abs() < 1e-6);
let hidden = HashSet::new();
let arcs = donut_layout_arcs(&slices, &hidden);
assert!((arcs.last().unwrap().2 - 1.0).abs() < 1e-5);
let hit = donut_hit_test(140.0, 60.0, 100.0, 100.0, 40.0, 90.0, &arcs);
assert_eq!(hit.as_deref(), Some("org"));
assert_eq!(
donut_hit_test(100.0, 100.0, 100.0, 100.0, 40.0, 90.0, &arcs),
None
);
}
}