use std::collections::HashMap;
use std::rc::Rc;
use arc_motion::{is_reduced_motion, motion_now};
use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, Typography, oklab_mix};
use gpui_kit::{
App, Bounds, ElementId, FocusHandle, Hsla, InteractiveElement as _, IntoElement, KeyDownEvent,
MouseButton, MouseDownEvent, MouseMoveEvent, ParentElement, Pixels, RenderOnce, Role,
SharedString, Styled, Window, base::StyledExt as _, canvas, div, prelude::*, px,
};
use super::common::{ChartSpring, chart_series_color, format_grouped};
const CELL_GAP: f32 = 3.0;
const NEUTRAL_SHADES: [f32; 4] = [0.40, 0.20, 0.30, 0.14];
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WaffleCellShape {
Square,
Round,
Framed,
}
#[derive(Clone, Debug)]
pub struct WaffleCategory {
pub key: SharedString,
pub label: SharedString,
pub value: f64,
pub color: Option<Hsla>,
}
impl WaffleCategory {
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 with_color(mut self, color: Hsla) -> Self {
self.color = Some(color);
self
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WaffleCell {
pub id: usize,
pub key: Option<String>,
pub slot: usize,
}
pub fn waffle_allocate(values: &[f64], total_cells: usize) -> Vec<usize> {
let total: f64 = values.iter().map(|v| v.max(0.0)).sum();
if total <= 0.0 || total_cells == 0 {
return vec![0; values.len()];
}
let exact: Vec<f64> = values
.iter()
.map(|v| (v.max(0.0) / total) * total_cells as f64)
.collect();
let mut counts: Vec<usize> = exact.iter().map(|v| v.floor() as usize).collect();
let assigned: usize = counts.iter().sum();
let mut left = total_cells.saturating_sub(assigned);
let mut order: Vec<(usize, f64)> = exact
.iter()
.enumerate()
.map(|(i, &v)| (i, v - v.floor()))
.collect();
order.sort_by(|a, b| b.1.total_cmp(&a.1));
for (idx, _) in order {
if left == 0 {
break;
}
counts[idx] += 1;
left -= 1;
}
counts
}
pub fn waffle_reassign(
previous: &[WaffleCell],
keys: &[String],
counts: &[usize],
) -> Vec<WaffleCell> {
let mut by_slot = previous.to_vec();
by_slot.sort_by_key(|c| c.slot);
let want: HashMap<&str, usize> = keys
.iter()
.enumerate()
.map(|(i, k)| (k.as_str(), counts.get(i).copied().unwrap_or(0)))
.collect();
let mut kept: HashMap<String, Vec<WaffleCell>> = HashMap::new();
let mut pool: Vec<WaffleCell> = Vec::new();
for cell in by_slot {
if let Some(ref k) = cell.key {
let cap = want.get(k.as_str()).copied().unwrap_or(0);
let entry = kept.entry(k.clone()).or_default();
if entry.len() < cap {
entry.push(cell);
continue;
}
}
pool.push(cell);
}
let mut pool_idx = 0usize;
let mut next = Vec::with_capacity(previous.len());
let mut slot = 0usize;
for (idx, k) in keys.iter().enumerate() {
let target = counts.get(idx).copied().unwrap_or(0);
let mut own = kept.remove(k).unwrap_or_default();
while own.len() < target && pool_idx < pool.len() {
own.push(pool[pool_idx].clone());
pool_idx += 1;
}
own.sort_by_key(|c| c.slot);
for cell in own {
next.push(WaffleCell {
id: cell.id,
key: Some(k.clone()),
slot,
});
slot += 1;
}
}
while pool_idx < pool.len() {
let cell = &pool[pool_idx];
next.push(WaffleCell {
id: cell.id,
key: None,
slot,
});
slot += 1;
pool_idx += 1;
}
next.sort_by_key(|c| c.id);
next
}
#[derive(Clone)]
struct WaffleState {
focus_handle: FocusHandle,
signature: String,
cells: Vec<WaffleCell>,
prev_slots: Vec<usize>,
own_pinned: Option<String>,
preview_key: Option<String>,
pointer: Option<(String, usize)>,
grid_bounds: Bounds<Pixels>,
reveal_spring: ChartSpring,
morph_spring: ChartSpring,
last_tick: f64,
}
type ValueFormatter = Rc<dyn Fn(f64, &WaffleCategory) -> String>;
type ActiveChangeHandler = Rc<dyn Fn(Option<SharedString>, &mut Window, &mut App)>;
#[derive(IntoElement)]
pub struct WaffleChart {
id: ElementId,
data: Vec<WaffleCategory>,
label: SharedString,
unit: SharedString,
format_value: Option<ValueFormatter>,
rows: usize,
columns: usize,
accent_key: Option<Option<SharedString>>,
active_key: Option<Option<SharedString>>,
default_active_key: Option<SharedString>,
on_active_change: Option<ActiveChangeHandler>,
legend: bool,
decimals: usize,
empty_label: SharedString,
}
impl WaffleChart {
pub fn new(
id: impl Into<ElementId>,
data: Vec<WaffleCategory>,
label: impl Into<SharedString>,
) -> Self {
Self {
id: id.into(),
data,
label: label.into(),
unit: SharedString::default(),
format_value: None,
rows: 10,
columns: 10,
accent_key: None,
active_key: None,
default_active_key: None,
on_active_change: None,
legend: true,
decimals: 0,
empty_label: "No data".into(),
}
}
pub fn unit(mut self, unit: impl Into<SharedString>) -> Self {
self.unit = unit.into();
self
}
pub fn format_value(mut self, f: impl Fn(f64, &WaffleCategory) -> String + 'static) -> Self {
self.format_value = Some(Rc::new(f));
self
}
pub fn grid(mut self, rows: usize, columns: usize) -> Self {
self.rows = rows.max(1);
self.columns = columns.max(1);
self
}
pub fn accent_key(mut self, key: Option<impl Into<SharedString>>) -> Self {
self.accent_key = Some(key.map(Into::into));
self
}
pub fn active_key(mut self, key: Option<impl Into<SharedString>>) -> Self {
self.active_key = Some(key.map(Into::into));
self
}
pub fn default_active_key(mut self, key: impl Into<SharedString>) -> Self {
self.default_active_key = Some(key.into());
self
}
pub fn on_active_change(
mut self,
f: impl Fn(Option<SharedString>, &mut Window, &mut App) + 'static,
) -> Self {
self.on_active_change = Some(Rc::new(f));
self
}
pub fn legend(mut self, show: bool) -> Self {
self.legend = show;
self
}
pub fn decimals(mut self, decimals: usize) -> Self {
self.decimals = decimals.min(3);
self
}
pub fn empty_label(mut self, label: impl Into<SharedString>) -> Self {
self.empty_label = label.into();
self
}
fn fmt_val(&self, item: &WaffleCategory) -> String {
let base = if let Some(f) = &self.format_value {
f(item.value, item)
} else {
format_grouped(item.value, 1)
};
if self.unit.is_empty() {
base
} else {
format!("{base} {}", self.unit)
}
}
}
impl RenderOnce for WaffleChart {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let reduced = is_reduced_motion(cx);
let now = motion_now(cx);
let rows = self.rows;
let columns = self.columns;
let cell_count = (rows * columns).max(1);
let total: f64 = self.data.iter().map(|d| d.value.max(0.0)).sum();
let empty = self.data.is_empty() || total <= 0.0;
let accent: Option<String> = match &self.accent_key {
Some(opt) => opt.as_ref().map(|s| s.to_string()),
None => self.data.first().map(|d| d.key.to_string()),
};
let keys: Vec<String> = self.data.iter().map(|d| d.key.to_string()).collect();
let values: Vec<f64> = self.data.iter().map(|d| d.value).collect();
let counts = waffle_allocate(&values, cell_count);
let signature = format!(
"{cell_count}|{}",
self.data
.iter()
.map(|d| format!("{}:{:.4}", d.key, d.value))
.collect::<Vec<_>>()
.join(",")
);
let default_pinned = self.default_active_key.as_ref().map(|s| s.to_string());
let state = window.use_keyed_state(
ElementId::NamedChild(self.id.clone().into(), "__waffle-state".into()),
cx,
|_w, cx| {
let init_base: Vec<WaffleCell> = (0..cell_count)
.map(|id| WaffleCell {
id,
key: None,
slot: id,
})
.collect();
let cells = waffle_reassign(&init_base, &keys, &counts);
let prev_slots = cells.iter().map(|c| c.slot).collect();
WaffleState {
focus_handle: cx.focus_handle(),
signature: signature.clone(),
cells,
prev_slots,
own_pinned: default_pinned.clone(),
preview_key: None,
pointer: None,
grid_bounds: Bounds::default(),
reveal_spring: {
let mut sp = ChartSpring::new(if reduced { 1.0 } else { 0.0 });
sp.set_target(1.0);
sp
},
morph_spring: ChartSpring::new(1.0),
last_tick: now,
}
},
);
if state.read(cx).signature != signature {
state.update(cx, |s, _cx| {
let mut base = Vec::with_capacity(cell_count);
for id in 0..cell_count {
base.push(s.cells.get(id).cloned().unwrap_or(WaffleCell {
id,
key: None,
slot: id,
}));
}
s.prev_slots = base.iter().map(|c| c.slot).collect();
s.cells = waffle_reassign(&base, &keys, &counts);
s.signature = signature.clone();
if reduced {
s.morph_spring.snap(1.0);
} else {
s.morph_spring.snap(0.0);
s.morph_spring.set_target(1.0);
}
});
}
let mut running = false;
state.update(cx, |s, _cx| {
let dt = (now - s.last_tick).clamp(0.0, 0.05);
s.last_tick = now;
if reduced {
s.reveal_spring.snap(1.0);
s.morph_spring.snap(1.0);
} else if dt > 0.0 {
if !s.reveal_spring.is_settled() {
s.reveal_spring.step(0.68, 0.04, dt as f32);
}
if !s.morph_spring.is_settled() {
s.morph_spring.step(0.52, 0.06, dt as f32);
}
}
running = !s.reveal_spring.is_settled() || !s.morph_spring.is_settled();
});
if running {
window.request_animation_frame();
}
let snap = state.read(cx).clone();
let is_controlled = self.active_key.is_some();
let pinned = match &self.active_key {
Some(opt) => opt.as_ref().map(|s| s.to_string()),
None => snap.own_pinned.clone(),
};
let focus_key = snap
.pointer
.as_ref()
.map(|(k, _)| k.clone())
.or_else(|| snap.preview_key.clone())
.or_else(|| pinned.clone());
let active_key = focus_key.filter(|k| self.data.iter().any(|d| d.key.as_ref() == k));
let non_accent_order: Vec<String> = self
.data
.iter()
.filter(|d| accent.as_deref() != Some(d.key.as_ref()))
.map(|d| d.key.to_string())
.collect();
let color_of = |key: Option<&str>| -> Hsla {
let Some(k) = key else {
return colors.surface_muted;
};
let Some(item) = self.data.iter().find(|d| d.key.as_ref() == k) else {
return colors.surface_muted;
};
if let Some(c) = item.color {
return c;
}
if accent.as_deref() == Some(k) {
return colors.series.series_1;
}
let rank = non_accent_order.iter().position(|x| x == k).unwrap_or(0);
if rank < 3 {
chart_series_color(&colors, rank + 1)
} else {
let shade = NEUTRAL_SHADES[(rank - 3) % NEUTRAL_SHADES.len()];
oklab_mix(colors.foreground, colors.surface, shade)
}
};
let shape_of = |key: Option<&str>| -> WaffleCellShape {
let Some(k) = key else {
return WaffleCellShape::Square;
};
if accent.as_deref() == Some(k) {
return WaffleCellShape::Square;
}
let rank = non_accent_order.iter().position(|x| x == k).unwrap_or(0);
match rank % 3 {
0 => WaffleCellShape::Square,
1 => WaffleCellShape::Round,
_ => WaffleCellShape::Framed,
}
};
let share_of = |item: &WaffleCategory| -> f64 {
if total > 0.0 {
(item.value.max(0.0) / total) * 100.0
} else {
0.0
}
};
let measured_w: f32 = snap.grid_bounds.size.width.into();
let grid_w = if measured_w > 40.0 { measured_w } else { 220.0 };
let cell_size =
((grid_w - CELL_GAP * (columns.saturating_sub(1) as f32)) / columns as f32).max(6.0);
let grid_h = cell_size * rows as f32 + CELL_GAP * (rows.saturating_sub(1) as f32);
let place = |slot: usize| -> (f32, f32) {
let col = slot / rows;
let row_from_bottom = slot % rows;
let x = col as f32 * (cell_size + CELL_GAP);
let y = (rows - 1 - row_from_bottom) as f32 * (cell_size + CELL_GAP);
(x, y)
};
let mut blocks: Vec<(usize, usize)> = Vec::new();
let mut cursor_slot = 0usize;
for &c in &counts {
if c > 0 {
blocks.push((cursor_slot, c));
cursor_slot += c;
}
}
let filled_count = cursor_slot;
let reveal_p = snap.reveal_spring.position().clamp(0.0, 1.0);
let morph_p = snap.morph_spring.position().clamp(0.0, 1.0);
let bounds_state = state.clone();
let bounds_tracker = canvas(
move |bounds, _w, cx| {
bounds_state.update(cx, |s, _cx| {
s.grid_bounds = bounds;
});
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
let cells_for_move = snap.cells.clone();
let move_state = state.clone();
let cells_for_down = snap.cells.clone();
let down_state = state.clone();
let cells_for_key = snap.cells.clone();
let key_state = state.clone();
let slot_at = move |lx: f32, ly: f32, w: f32| -> Option<usize> {
let sz =
((w - CELL_GAP * (columns.saturating_sub(1) as f32)) / columns as f32).max(1.0);
let step = sz + CELL_GAP;
let col = (lx / step).floor() as isize;
let row = (ly / step).floor() as isize;
if col < 0 || col >= columns as isize || row < 0 || row >= rows as isize {
return None;
}
Some((col as usize) * rows + (rows - 1 - row as usize))
};
let mut grid_el = div()
.id(self.id.clone())
.role(Role::Group)
.aria_label(self.label.clone())
.track_focus(&snap.focus_handle)
.relative()
.w(px(220.0))
.h(px(grid_h))
.on_mouse_move(move |ev: &MouseMoveEvent, _w, cx| {
move_state.update(cx, |s, cx| {
let b = s.grid_bounds;
let lx: f32 = (ev.position.x - b.origin.x).into();
let ly: f32 = (ev.position.y - b.origin.y).into();
let bw: f32 = b.size.width.into();
let bh: f32 = b.size.height.into();
if lx < 0.0 || ly < 0.0 || lx > bw || ly > bh {
if s.pointer.is_some() {
s.pointer = None;
cx.notify();
}
return;
}
let next = slot_at(lx, ly, bw).and_then(|sl| {
cells_for_move
.iter()
.find(|c| c.slot == sl)
.and_then(|c| c.key.clone().map(|k| (k, sl)))
});
if s.pointer != next {
s.pointer = next;
cx.notify();
}
});
})
.on_mouse_down(MouseButton::Left, move |ev: &MouseDownEvent, window, cx| {
let fh = down_state.read(cx).focus_handle.clone();
window.focus(&fh, cx);
down_state.update(cx, |s, cx| {
let b = s.grid_bounds;
let lx: f32 = (ev.position.x - b.origin.x).into();
let ly: f32 = (ev.position.y - b.origin.y).into();
let bw: f32 = b.size.width.into();
let next = slot_at(lx, ly, bw).and_then(|sl| {
cells_for_down
.iter()
.find(|c| c.slot == sl)
.and_then(|c| c.key.clone().map(|k| (k, sl)))
});
s.pointer = next;
cx.notify();
});
})
.on_key_down(move |ev: &KeyDownEvent, _w, cx| {
if empty || filled_count == 0 {
return;
}
let key = ev.keystroke.key.as_str();
if key == "escape" {
key_state.update(cx, |s, cx| {
if s.pointer.is_some() {
s.pointer = None;
cx.notify();
}
});
return;
}
let current_slot = key_state.read(cx).pointer.as_ref().map(|(_, sl)| *sl);
let at = current_slot.unwrap_or(0);
let col = at / rows;
let row = at % rows;
let block_idx = blocks
.iter()
.position(|&(start, sz)| at >= start && at < start + sz)
.unwrap_or(0);
let next_slot = match key {
"up" => Some(col * rows + (row + 1).min(rows - 1)),
"down" => Some(col * rows + row.saturating_sub(1)),
"right" => Some((col + 1).min(columns - 1) * rows + row),
"left" => Some(col.saturating_sub(1) * rows + row),
"pagedown" => blocks
.get((block_idx + 1).min(blocks.len().saturating_sub(1)))
.map(|b| b.0),
"pageup" => {
let cur_start = blocks.get(block_idx).map(|b| b.0).unwrap_or(0);
if at > cur_start {
Some(cur_start)
} else {
blocks.get(block_idx.saturating_sub(1)).map(|b| b.0)
}
}
"home" => Some(0),
"end" => Some(filled_count.saturating_sub(1)),
_ => None,
};
if let Some(target) = next_slot {
cx.stop_propagation();
let clamped = if current_slot.is_some() {
target.min(filled_count.saturating_sub(1))
} else {
0
};
let hit = cells_for_key
.iter()
.find(|c| c.slot == clamped)
.and_then(|c| c.key.clone().map(|k| (k, clamped)));
key_state.update(cx, |s, cx| {
s.pointer = hit;
cx.notify();
});
}
})
.child(bounds_tracker);
for cell in &snap.cells {
if cell.key.is_none() {
continue;
}
let prev_slot = snap.prev_slots.get(cell.id).copied().unwrap_or(cell.slot);
let (x0, y0) = place(prev_slot);
let (x1, y1) = place(cell.slot);
let x = x0 + (x1 - x0) * morph_p;
let y = y0 + (y1 - y0) * morph_p;
let stagger = (cell.slot as f32 / cell_count as f32) * 0.30;
let local_p = ((reveal_p - stagger) / (1.0 - stagger).max(0.01)).clamp(0.0, 1.0);
let scale = 0.45 + 0.55 * local_p;
let sz = cell_size * scale;
let offset = (cell_size - sz) * 0.5;
let is_on = active_key.as_deref() == cell.key.as_deref();
let is_dim = active_key.is_some() && !is_on;
let is_cursor = snap
.pointer
.as_ref()
.map(|(_, sl)| *sl == cell.slot)
.unwrap_or(false);
let base_color = color_of(cell.key.as_deref());
let shape = shape_of(cell.key.as_deref());
let opacity = local_p * if is_dim { 0.24 } else { 1.0 };
let mut dot = div()
.absolute()
.left(px(x + offset))
.top(px(y + offset))
.w(px(sz))
.h(px(sz));
dot = match shape {
WaffleCellShape::Square => dot.rounded(px(3.0)).bg(base_color.opacity(opacity)),
WaffleCellShape::Round => dot.rounded_full().bg(base_color.opacity(opacity)),
WaffleCellShape::Framed => dot
.rounded(px(3.0))
.bg(colors.surface.opacity(opacity))
.border_2()
.border_color(base_color.opacity(opacity)),
};
if is_cursor {
dot = dot.border_2().border_color(colors.foreground);
}
grid_el = grid_el.child(dot);
}
let reading = snap.pointer.as_ref().and_then(|(k, sl)| {
self.data
.iter()
.find(|d| d.key.as_ref() == k)
.map(|item| (item, *sl))
});
let mut board = div().relative().child(grid_el);
if let Some((item, slot)) = reading {
let (cx_px, cy_px) = place(slot);
let tip_w = 176.0f32;
let tip_h = 52.0f32;
let left =
(cx_px + cell_size * 0.5 - tip_w * 0.5).clamp(0.0, (grid_w - tip_w).max(0.0));
let top = if cy_px - tip_h - 8.0 >= 0.0 {
cy_px - tip_h - 8.0
} else {
cy_px + cell_size + 8.0
};
let swatch_color = color_of(Some(item.key.as_ref()));
let swatch_shape = shape_of(Some(item.key.as_ref()));
let mut swatch = div().w(px(9.0)).h(px(9.0)).flex_shrink_0();
swatch = match swatch_shape {
WaffleCellShape::Square => swatch.rounded(px(2.0)).bg(swatch_color),
WaffleCellShape::Round => swatch.rounded_full().bg(swatch_color),
WaffleCellShape::Framed => swatch
.rounded(px(2.0))
.border_2()
.border_color(swatch_color),
};
board = board.child(
div()
.absolute()
.left(px(left))
.top(px(top))
.w(px(tip_w))
.px(Spacing::S3)
.py(Spacing::S2)
.rounded(Radii::CONTROL)
.bg(colors.surface_raised)
.border_1()
.border_color(colors.border)
.shadow_md()
.flex()
.flex_col()
.gap(px(2.0))
.child(
div()
.flex()
.items_center()
.justify_between()
.gap(Spacing::S2)
.child(
div()
.flex()
.items_center()
.gap(px(6.0))
.child(swatch)
.child(
div()
.text_size(Typography::TEXT_XS)
.font_semibold()
.text_color(colors.foreground)
.truncate()
.child(item.label.clone()),
),
)
.child(
div()
.text_size(Typography::TEXT_XS)
.font_semibold()
.text_color(colors.foreground)
.child(format!(
"{:.prec$}%",
share_of(item),
prec = self.decimals
)),
),
)
.child(
div()
.text_size(px(11.0))
.text_color(colors.text_muted)
.child(self.fmt_val(item)),
),
);
}
if empty {
board = board.child(
div()
.absolute()
.inset_0()
.flex()
.items_center()
.justify_center()
.text_size(px(13.0))
.text_color(colors.text_muted)
.child(self.empty_label.clone()),
);
}
let mut body = div()
.w_full()
.flex()
.flex_wrap()
.items_start()
.gap(Spacing::S5)
.child(board);
if self.legend && !empty {
let on_active = self.on_active_change.clone();
let mut legend_col = div()
.flex_1()
.min_w(px(160.0))
.flex()
.flex_col()
.gap(px(4.0));
for item in &self.data {
let k = item.key.to_string();
let is_on = active_key.as_deref() == Some(k.as_str());
let is_pinned = pinned.as_deref() == Some(k.as_str());
let is_dim = active_key.is_some() && !is_on;
let sw_color = color_of(Some(k.as_str()));
let sw_shape = shape_of(Some(k.as_str()));
let mut sw = div().w(px(10.0)).h(px(10.0)).flex_shrink_0();
sw = match sw_shape {
WaffleCellShape::Square => sw.rounded(px(2.0)).bg(sw_color),
WaffleCellShape::Round => sw.rounded_full().bg(sw_color),
WaffleCellShape::Framed => {
sw.rounded(px(2.0)).border_2().border_color(sw_color)
}
};
let hover_st = state.clone();
let hover_key = k.clone();
let click_st = state.clone();
let click_key = k.clone();
let click_cb = on_active.clone();
legend_col = legend_col.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("waffle-legend-{k}")),
))
.px(Spacing::S2)
.py(px(5.0))
.rounded(px(6.0))
.cursor_pointer()
.bg(if is_pinned {
colors.surface_muted
} else {
Hsla::transparent_black()
})
.hover(|s| s.bg(colors.surface_muted))
.flex()
.items_center()
.justify_between()
.gap(Spacing::S3)
.opacity(if is_dim { 0.45 } else { 1.0 })
.on_hover(move |hovered, _w, cx| {
hover_st.update(cx, |s, cx| {
if *hovered {
s.preview_key = Some(hover_key.clone());
} else if s.preview_key.as_deref() == Some(hover_key.as_str()) {
s.preview_key = None;
}
cx.notify();
});
})
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
let next = if is_pinned {
None
} else {
Some(click_key.clone())
};
if !is_controlled {
click_st.update(cx, |s, cx| {
s.own_pinned = next.clone();
cx.notify();
});
}
if let Some(cb) = &click_cb {
cb(next.map(SharedString::from), window, cx);
}
})
.child(
div()
.flex()
.items_center()
.gap(Spacing::S2)
.child(sw)
.child(
div()
.text_size(px(13.0))
.when(is_on, |this| this.font_semibold())
.text_color(colors.foreground)
.child(item.label.clone()),
),
)
.child(
div()
.text_size(px(13.0))
.font_medium()
.text_color(colors.text_muted)
.child(format!("{:.prec$}%", share_of(item), prec = self.decimals)),
),
);
}
body = body.child(legend_col);
}
body
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn waffle_largest_remainder_and_minimal_reassignment() {
let counts = waffle_allocate(&[33.3, 33.3, 33.4], 100);
assert_eq!(counts.iter().sum::<usize>(), 100);
assert_eq!(counts, vec![33, 33, 34]);
let init: Vec<WaffleCell> = (0..10)
.map(|id| WaffleCell {
id,
key: None,
slot: id,
})
.collect();
let keys = vec!["a".to_string(), "b".to_string()];
let first = waffle_reassign(&init, &keys, &[6, 4]);
let a_ids_before: Vec<usize> = first
.iter()
.filter(|c| c.key.as_deref() == Some("a"))
.map(|c| c.id)
.collect();
assert_eq!(a_ids_before.len(), 6);
let second = waffle_reassign(&first, &keys, &[4, 6]);
let a_ids_after: Vec<usize> = second
.iter()
.filter(|c| c.key.as_deref() == Some("a"))
.map(|c| c.id)
.collect();
assert_eq!(a_ids_after.len(), 4);
assert!(a_ids_after.iter().all(|id| a_ids_before.contains(id)));
}
}