Skip to main content

arc_ui/chart/
waffle_chart.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/waffle-chart/waffle-chart.tsx`
3//!
4//! `WaffleChart` — unit grid chart (default 10×10 = 100 cells, 1 cell = 1%),
5//! using Hamilton's largest-remainder allocation, minimal-movement persistent cell
6//! reassignment across dataset updates, color-free secondary shape encoding
7//! (`square` / `round` / `framed`), interactive legend with hover preview + pin toggle,
8//! cell-by-cell & category-jumping keyboard navigation, and floating tooltip.
9
10use std::collections::HashMap;
11use std::rc::Rc;
12
13use arc_motion::{is_reduced_motion, motion_now};
14use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, Typography, oklab_mix};
15use gpui_kit::{
16    App, Bounds, ElementId, FocusHandle, Hsla, InteractiveElement as _, IntoElement, KeyDownEvent,
17    MouseButton, MouseDownEvent, MouseMoveEvent, ParentElement, Pixels, RenderOnce, Role,
18    SharedString, Styled, Window, base::StyledExt as _, canvas, div, prelude::*, px,
19};
20
21use super::common::{ChartSpring, chart_series_color, format_grouped};
22
23const CELL_GAP: f32 = 3.0;
24const NEUTRAL_SHADES: [f32; 4] = [0.40, 0.20, 0.30, 0.14];
25
26/// Secondary color-free cell shape channel for neutral categories.
27#[derive(Clone, Copy, Debug, Eq, PartialEq)]
28pub enum WaffleCellShape {
29    Square,
30    Round,
31    Framed,
32}
33
34/// One category in `WaffleChart`.
35#[derive(Clone, Debug)]
36pub struct WaffleCategory {
37    pub key: SharedString,
38    pub label: SharedString,
39    pub value: f64,
40    pub color: Option<Hsla>,
41}
42
43impl WaffleCategory {
44    pub fn new(key: impl Into<SharedString>, label: impl Into<SharedString>, value: f64) -> Self {
45        Self {
46            key: key.into(),
47            label: label.into(),
48            value,
49            color: None,
50        }
51    }
52
53    pub fn with_color(mut self, color: Hsla) -> Self {
54        self.color = Some(color);
55        self
56    }
57}
58
59/// Persistent cell object tracked across dataset changes.
60#[derive(Clone, Debug, Eq, PartialEq)]
61pub struct WaffleCell {
62    pub id: usize,
63    pub key: Option<String>,
64    pub slot: usize,
65}
66
67/// Allocate integer cell counts per category using the largest-remainder method so
68/// total assigned cells always equal `total_cells` (when total > 0).
69pub fn waffle_allocate(values: &[f64], total_cells: usize) -> Vec<usize> {
70    let total: f64 = values.iter().map(|v| v.max(0.0)).sum();
71    if total <= 0.0 || total_cells == 0 {
72        return vec![0; values.len()];
73    }
74    let exact: Vec<f64> = values
75        .iter()
76        .map(|v| (v.max(0.0) / total) * total_cells as f64)
77        .collect();
78    let mut counts: Vec<usize> = exact.iter().map(|v| v.floor() as usize).collect();
79    let assigned: usize = counts.iter().sum();
80    let mut left = total_cells.saturating_sub(assigned);
81    let mut order: Vec<(usize, f64)> = exact
82        .iter()
83        .enumerate()
84        .map(|(i, &v)| (i, v - v.floor()))
85        .collect();
86    order.sort_by(|a, b| b.1.total_cmp(&a.1));
87    for (idx, _) in order {
88        if left == 0 {
89            break;
90        }
91        counts[idx] += 1;
92        left -= 1;
93    }
94    counts
95}
96
97/// Reassign persistent cells with minimal movement: categories keep existing cells first,
98/// surplus cells join growing categories, and slot order stays monotonic so paths never cross.
99pub fn waffle_reassign(
100    previous: &[WaffleCell],
101    keys: &[String],
102    counts: &[usize],
103) -> Vec<WaffleCell> {
104    let mut by_slot = previous.to_vec();
105    by_slot.sort_by_key(|c| c.slot);
106
107    let want: HashMap<&str, usize> = keys
108        .iter()
109        .enumerate()
110        .map(|(i, k)| (k.as_str(), counts.get(i).copied().unwrap_or(0)))
111        .collect();
112
113    let mut kept: HashMap<String, Vec<WaffleCell>> = HashMap::new();
114    let mut pool: Vec<WaffleCell> = Vec::new();
115    for cell in by_slot {
116        if let Some(ref k) = cell.key {
117            let cap = want.get(k.as_str()).copied().unwrap_or(0);
118            let entry = kept.entry(k.clone()).or_default();
119            if entry.len() < cap {
120                entry.push(cell);
121                continue;
122            }
123        }
124        pool.push(cell);
125    }
126
127    let mut pool_idx = 0usize;
128    let mut next = Vec::with_capacity(previous.len());
129    let mut slot = 0usize;
130    for (idx, k) in keys.iter().enumerate() {
131        let target = counts.get(idx).copied().unwrap_or(0);
132        let mut own = kept.remove(k).unwrap_or_default();
133        while own.len() < target && pool_idx < pool.len() {
134            own.push(pool[pool_idx].clone());
135            pool_idx += 1;
136        }
137        own.sort_by_key(|c| c.slot);
138        for cell in own {
139            next.push(WaffleCell {
140                id: cell.id,
141                key: Some(k.clone()),
142                slot,
143            });
144            slot += 1;
145        }
146    }
147    while pool_idx < pool.len() {
148        let cell = &pool[pool_idx];
149        next.push(WaffleCell {
150            id: cell.id,
151            key: None,
152            slot,
153        });
154        slot += 1;
155        pool_idx += 1;
156    }
157    next.sort_by_key(|c| c.id);
158    next
159}
160
161#[derive(Clone)]
162struct WaffleState {
163    focus_handle: FocusHandle,
164    signature: String,
165    cells: Vec<WaffleCell>,
166    prev_slots: Vec<usize>,
167    own_pinned: Option<String>,
168    preview_key: Option<String>,
169    pointer: Option<(String, usize)>,
170    grid_bounds: Bounds<Pixels>,
171    reveal_spring: ChartSpring,
172    morph_spring: ChartSpring,
173    last_tick: f64,
174}
175
176type ValueFormatter = Rc<dyn Fn(f64, &WaffleCategory) -> String>;
177type ActiveChangeHandler = Rc<dyn Fn(Option<SharedString>, &mut Window, &mut App)>;
178
179/// Interactive unit grid `WaffleChart`.
180#[derive(IntoElement)]
181pub struct WaffleChart {
182    id: ElementId,
183    data: Vec<WaffleCategory>,
184    label: SharedString,
185    unit: SharedString,
186    format_value: Option<ValueFormatter>,
187    rows: usize,
188    columns: usize,
189    accent_key: Option<Option<SharedString>>,
190    active_key: Option<Option<SharedString>>,
191    default_active_key: Option<SharedString>,
192    on_active_change: Option<ActiveChangeHandler>,
193    legend: bool,
194    decimals: usize,
195    empty_label: SharedString,
196}
197
198impl WaffleChart {
199    pub fn new(
200        id: impl Into<ElementId>,
201        data: Vec<WaffleCategory>,
202        label: impl Into<SharedString>,
203    ) -> Self {
204        Self {
205            id: id.into(),
206            data,
207            label: label.into(),
208            unit: SharedString::default(),
209            format_value: None,
210            rows: 10,
211            columns: 10,
212            accent_key: None,
213            active_key: None,
214            default_active_key: None,
215            on_active_change: None,
216            legend: true,
217            decimals: 0,
218            empty_label: "No data".into(),
219        }
220    }
221
222    pub fn unit(mut self, unit: impl Into<SharedString>) -> Self {
223        self.unit = unit.into();
224        self
225    }
226
227    pub fn format_value(mut self, f: impl Fn(f64, &WaffleCategory) -> String + 'static) -> Self {
228        self.format_value = Some(Rc::new(f));
229        self
230    }
231
232    pub fn grid(mut self, rows: usize, columns: usize) -> Self {
233        self.rows = rows.max(1);
234        self.columns = columns.max(1);
235        self
236    }
237
238    pub fn accent_key(mut self, key: Option<impl Into<SharedString>>) -> Self {
239        self.accent_key = Some(key.map(Into::into));
240        self
241    }
242
243    pub fn active_key(mut self, key: Option<impl Into<SharedString>>) -> Self {
244        self.active_key = Some(key.map(Into::into));
245        self
246    }
247
248    pub fn default_active_key(mut self, key: impl Into<SharedString>) -> Self {
249        self.default_active_key = Some(key.into());
250        self
251    }
252
253    pub fn on_active_change(
254        mut self,
255        f: impl Fn(Option<SharedString>, &mut Window, &mut App) + 'static,
256    ) -> Self {
257        self.on_active_change = Some(Rc::new(f));
258        self
259    }
260
261    pub fn legend(mut self, show: bool) -> Self {
262        self.legend = show;
263        self
264    }
265
266    pub fn decimals(mut self, decimals: usize) -> Self {
267        self.decimals = decimals.min(3);
268        self
269    }
270
271    pub fn empty_label(mut self, label: impl Into<SharedString>) -> Self {
272        self.empty_label = label.into();
273        self
274    }
275
276    fn fmt_val(&self, item: &WaffleCategory) -> String {
277        let base = if let Some(f) = &self.format_value {
278            f(item.value, item)
279        } else {
280            format_grouped(item.value, 1)
281        };
282        if self.unit.is_empty() {
283            base
284        } else {
285            format!("{base} {}", self.unit)
286        }
287    }
288}
289
290impl RenderOnce for WaffleChart {
291    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
292        let theme = cx.arc_theme().clone();
293        let colors = theme.colors;
294        let reduced = is_reduced_motion(cx);
295        let now = motion_now(cx);
296
297        let rows = self.rows;
298        let columns = self.columns;
299        let cell_count = (rows * columns).max(1);
300        let total: f64 = self.data.iter().map(|d| d.value.max(0.0)).sum();
301        let empty = self.data.is_empty() || total <= 0.0;
302
303        let accent: Option<String> = match &self.accent_key {
304            Some(opt) => opt.as_ref().map(|s| s.to_string()),
305            None => self.data.first().map(|d| d.key.to_string()),
306        };
307
308        let keys: Vec<String> = self.data.iter().map(|d| d.key.to_string()).collect();
309        let values: Vec<f64> = self.data.iter().map(|d| d.value).collect();
310        let counts = waffle_allocate(&values, cell_count);
311        let signature = format!(
312            "{cell_count}|{}",
313            self.data
314                .iter()
315                .map(|d| format!("{}:{:.4}", d.key, d.value))
316                .collect::<Vec<_>>()
317                .join(",")
318        );
319
320        let default_pinned = self.default_active_key.as_ref().map(|s| s.to_string());
321        let state = window.use_keyed_state(
322            ElementId::NamedChild(self.id.clone().into(), "__waffle-state".into()),
323            cx,
324            |_w, cx| {
325                let init_base: Vec<WaffleCell> = (0..cell_count)
326                    .map(|id| WaffleCell {
327                        id,
328                        key: None,
329                        slot: id,
330                    })
331                    .collect();
332                let cells = waffle_reassign(&init_base, &keys, &counts);
333                let prev_slots = cells.iter().map(|c| c.slot).collect();
334                WaffleState {
335                    focus_handle: cx.focus_handle(),
336                    signature: signature.clone(),
337                    cells,
338                    prev_slots,
339                    own_pinned: default_pinned.clone(),
340                    preview_key: None,
341                    pointer: None,
342                    grid_bounds: Bounds::default(),
343                    reveal_spring: {
344                        let mut sp = ChartSpring::new(if reduced { 1.0 } else { 0.0 });
345                        sp.set_target(1.0);
346                        sp
347                    },
348                    morph_spring: ChartSpring::new(1.0),
349                    last_tick: now,
350                }
351            },
352        );
353
354        // Reconcile dataset updates with minimal cell travel
355        if state.read(cx).signature != signature {
356            state.update(cx, |s, _cx| {
357                let mut base = Vec::with_capacity(cell_count);
358                for id in 0..cell_count {
359                    base.push(s.cells.get(id).cloned().unwrap_or(WaffleCell {
360                        id,
361                        key: None,
362                        slot: id,
363                    }));
364                }
365                s.prev_slots = base.iter().map(|c| c.slot).collect();
366                s.cells = waffle_reassign(&base, &keys, &counts);
367                s.signature = signature.clone();
368                if reduced {
369                    s.morph_spring.snap(1.0);
370                } else {
371                    s.morph_spring.snap(0.0);
372                    s.morph_spring.set_target(1.0);
373                }
374            });
375        }
376
377        // Advance animations
378        let mut running = false;
379        state.update(cx, |s, _cx| {
380            let dt = (now - s.last_tick).clamp(0.0, 0.05);
381            s.last_tick = now;
382            if reduced {
383                s.reveal_spring.snap(1.0);
384                s.morph_spring.snap(1.0);
385            } else if dt > 0.0 {
386                if !s.reveal_spring.is_settled() {
387                    s.reveal_spring.step(0.68, 0.04, dt as f32);
388                }
389                if !s.morph_spring.is_settled() {
390                    s.morph_spring.step(0.52, 0.06, dt as f32);
391                }
392            }
393            running = !s.reveal_spring.is_settled() || !s.morph_spring.is_settled();
394        });
395        if running {
396            window.request_animation_frame();
397        }
398
399        let snap = state.read(cx).clone();
400        let is_controlled = self.active_key.is_some();
401        let pinned = match &self.active_key {
402            Some(opt) => opt.as_ref().map(|s| s.to_string()),
403            None => snap.own_pinned.clone(),
404        };
405        let focus_key = snap
406            .pointer
407            .as_ref()
408            .map(|(k, _)| k.clone())
409            .or_else(|| snap.preview_key.clone())
410            .or_else(|| pinned.clone());
411        let active_key = focus_key.filter(|k| self.data.iter().any(|d| d.key.as_ref() == k));
412
413        // Color & shape maps
414        let non_accent_order: Vec<String> = self
415            .data
416            .iter()
417            .filter(|d| accent.as_deref() != Some(d.key.as_ref()))
418            .map(|d| d.key.to_string())
419            .collect();
420
421        let color_of = |key: Option<&str>| -> Hsla {
422            let Some(k) = key else {
423                return colors.surface_muted;
424            };
425            let Some(item) = self.data.iter().find(|d| d.key.as_ref() == k) else {
426                return colors.surface_muted;
427            };
428            if let Some(c) = item.color {
429                return c;
430            }
431            if accent.as_deref() == Some(k) {
432                return colors.series.series_1;
433            }
434            let rank = non_accent_order.iter().position(|x| x == k).unwrap_or(0);
435            if rank < 3 {
436                chart_series_color(&colors, rank + 1)
437            } else {
438                let shade = NEUTRAL_SHADES[(rank - 3) % NEUTRAL_SHADES.len()];
439                oklab_mix(colors.foreground, colors.surface, shade)
440            }
441        };
442
443        let shape_of = |key: Option<&str>| -> WaffleCellShape {
444            let Some(k) = key else {
445                return WaffleCellShape::Square;
446            };
447            if accent.as_deref() == Some(k) {
448                return WaffleCellShape::Square;
449            }
450            let rank = non_accent_order.iter().position(|x| x == k).unwrap_or(0);
451            match rank % 3 {
452                0 => WaffleCellShape::Square,
453                1 => WaffleCellShape::Round,
454                _ => WaffleCellShape::Framed,
455            }
456        };
457
458        let share_of = |item: &WaffleCategory| -> f64 {
459            if total > 0.0 {
460                (item.value.max(0.0) / total) * 100.0
461            } else {
462                0.0
463            }
464        };
465
466        // Grid sizing: square cells filling container width up to 240px side when legend sits beside it
467        let measured_w: f32 = snap.grid_bounds.size.width.into();
468        let grid_w = if measured_w > 40.0 { measured_w } else { 220.0 };
469        let cell_size =
470            ((grid_w - CELL_GAP * (columns.saturating_sub(1) as f32)) / columns as f32).max(6.0);
471        let grid_h = cell_size * rows as f32 + CELL_GAP * (rows.saturating_sub(1) as f32);
472
473        let place = |slot: usize| -> (f32, f32) {
474            let col = slot / rows;
475            let row_from_bottom = slot % rows;
476            let x = col as f32 * (cell_size + CELL_GAP);
477            let y = (rows - 1 - row_from_bottom) as f32 * (cell_size + CELL_GAP);
478            (x, y)
479        };
480
481        // Precompute category start offsets for PageUp / PageDown jumps
482        let mut blocks: Vec<(usize, usize)> = Vec::new();
483        let mut cursor_slot = 0usize;
484        for &c in &counts {
485            if c > 0 {
486                blocks.push((cursor_slot, c));
487                cursor_slot += c;
488            }
489        }
490        let filled_count = cursor_slot;
491
492        // Build cells
493        let reveal_p = snap.reveal_spring.position().clamp(0.0, 1.0);
494        let morph_p = snap.morph_spring.position().clamp(0.0, 1.0);
495
496        let bounds_state = state.clone();
497        let bounds_tracker = canvas(
498            move |bounds, _w, cx| {
499                bounds_state.update(cx, |s, _cx| {
500                    s.grid_bounds = bounds;
501                });
502            },
503            |_, _, _, _| {},
504        )
505        .absolute()
506        .inset_0();
507
508        let cells_for_move = snap.cells.clone();
509        let move_state = state.clone();
510        let cells_for_down = snap.cells.clone();
511        let down_state = state.clone();
512        let cells_for_key = snap.cells.clone();
513        let key_state = state.clone();
514
515        let slot_at = move |lx: f32, ly: f32, w: f32| -> Option<usize> {
516            let sz =
517                ((w - CELL_GAP * (columns.saturating_sub(1) as f32)) / columns as f32).max(1.0);
518            let step = sz + CELL_GAP;
519            let col = (lx / step).floor() as isize;
520            let row = (ly / step).floor() as isize;
521            if col < 0 || col >= columns as isize || row < 0 || row >= rows as isize {
522                return None;
523            }
524            Some((col as usize) * rows + (rows - 1 - row as usize))
525        };
526
527        let mut grid_el = div()
528            .id(self.id.clone())
529            .role(Role::Group)
530            .aria_label(self.label.clone())
531            .track_focus(&snap.focus_handle)
532            .relative()
533            .w(px(220.0))
534            .h(px(grid_h))
535            .on_mouse_move(move |ev: &MouseMoveEvent, _w, cx| {
536                move_state.update(cx, |s, cx| {
537                    let b = s.grid_bounds;
538                    let lx: f32 = (ev.position.x - b.origin.x).into();
539                    let ly: f32 = (ev.position.y - b.origin.y).into();
540                    let bw: f32 = b.size.width.into();
541                    let bh: f32 = b.size.height.into();
542                    if lx < 0.0 || ly < 0.0 || lx > bw || ly > bh {
543                        if s.pointer.is_some() {
544                            s.pointer = None;
545                            cx.notify();
546                        }
547                        return;
548                    }
549                    let next = slot_at(lx, ly, bw).and_then(|sl| {
550                        cells_for_move
551                            .iter()
552                            .find(|c| c.slot == sl)
553                            .and_then(|c| c.key.clone().map(|k| (k, sl)))
554                    });
555                    if s.pointer != next {
556                        s.pointer = next;
557                        cx.notify();
558                    }
559                });
560            })
561            .on_mouse_down(MouseButton::Left, move |ev: &MouseDownEvent, window, cx| {
562                let fh = down_state.read(cx).focus_handle.clone();
563                window.focus(&fh, cx);
564                down_state.update(cx, |s, cx| {
565                    let b = s.grid_bounds;
566                    let lx: f32 = (ev.position.x - b.origin.x).into();
567                    let ly: f32 = (ev.position.y - b.origin.y).into();
568                    let bw: f32 = b.size.width.into();
569                    let next = slot_at(lx, ly, bw).and_then(|sl| {
570                        cells_for_down
571                            .iter()
572                            .find(|c| c.slot == sl)
573                            .and_then(|c| c.key.clone().map(|k| (k, sl)))
574                    });
575                    s.pointer = next;
576                    cx.notify();
577                });
578            })
579            .on_key_down(move |ev: &KeyDownEvent, _w, cx| {
580                if empty || filled_count == 0 {
581                    return;
582                }
583                let key = ev.keystroke.key.as_str();
584                if key == "escape" {
585                    key_state.update(cx, |s, cx| {
586                        if s.pointer.is_some() {
587                            s.pointer = None;
588                            cx.notify();
589                        }
590                    });
591                    return;
592                }
593                let current_slot = key_state.read(cx).pointer.as_ref().map(|(_, sl)| *sl);
594                let at = current_slot.unwrap_or(0);
595                let col = at / rows;
596                let row = at % rows;
597                let block_idx = blocks
598                    .iter()
599                    .position(|&(start, sz)| at >= start && at < start + sz)
600                    .unwrap_or(0);
601
602                let next_slot = match key {
603                    "up" => Some(col * rows + (row + 1).min(rows - 1)),
604                    "down" => Some(col * rows + row.saturating_sub(1)),
605                    "right" => Some((col + 1).min(columns - 1) * rows + row),
606                    "left" => Some(col.saturating_sub(1) * rows + row),
607                    "pagedown" => blocks
608                        .get((block_idx + 1).min(blocks.len().saturating_sub(1)))
609                        .map(|b| b.0),
610                    "pageup" => {
611                        let cur_start = blocks.get(block_idx).map(|b| b.0).unwrap_or(0);
612                        if at > cur_start {
613                            Some(cur_start)
614                        } else {
615                            blocks.get(block_idx.saturating_sub(1)).map(|b| b.0)
616                        }
617                    }
618                    "home" => Some(0),
619                    "end" => Some(filled_count.saturating_sub(1)),
620                    _ => None,
621                };
622                if let Some(target) = next_slot {
623                    cx.stop_propagation();
624                    let clamped = if current_slot.is_some() {
625                        target.min(filled_count.saturating_sub(1))
626                    } else {
627                        0
628                    };
629                    let hit = cells_for_key
630                        .iter()
631                        .find(|c| c.slot == clamped)
632                        .and_then(|c| c.key.clone().map(|k| (k, clamped)));
633                    key_state.update(cx, |s, cx| {
634                        s.pointer = hit;
635                        cx.notify();
636                    });
637                }
638            })
639            .child(bounds_tracker);
640
641        for cell in &snap.cells {
642            if cell.key.is_none() {
643                continue;
644            }
645            let prev_slot = snap.prev_slots.get(cell.id).copied().unwrap_or(cell.slot);
646            let (x0, y0) = place(prev_slot);
647            let (x1, y1) = place(cell.slot);
648            let x = x0 + (x1 - x0) * morph_p;
649            let y = y0 + (y1 - y0) * morph_p;
650
651            let stagger = (cell.slot as f32 / cell_count as f32) * 0.30;
652            let local_p = ((reveal_p - stagger) / (1.0 - stagger).max(0.01)).clamp(0.0, 1.0);
653            let scale = 0.45 + 0.55 * local_p;
654            let sz = cell_size * scale;
655            let offset = (cell_size - sz) * 0.5;
656
657            let is_on = active_key.as_deref() == cell.key.as_deref();
658            let is_dim = active_key.is_some() && !is_on;
659            let is_cursor = snap
660                .pointer
661                .as_ref()
662                .map(|(_, sl)| *sl == cell.slot)
663                .unwrap_or(false);
664
665            let base_color = color_of(cell.key.as_deref());
666            let shape = shape_of(cell.key.as_deref());
667            let opacity = local_p * if is_dim { 0.24 } else { 1.0 };
668
669            let mut dot = div()
670                .absolute()
671                .left(px(x + offset))
672                .top(px(y + offset))
673                .w(px(sz))
674                .h(px(sz));
675
676            dot = match shape {
677                WaffleCellShape::Square => dot.rounded(px(3.0)).bg(base_color.opacity(opacity)),
678                WaffleCellShape::Round => dot.rounded_full().bg(base_color.opacity(opacity)),
679                WaffleCellShape::Framed => dot
680                    .rounded(px(3.0))
681                    .bg(colors.surface.opacity(opacity))
682                    .border_2()
683                    .border_color(base_color.opacity(opacity)),
684            };
685
686            if is_cursor {
687                dot = dot.border_2().border_color(colors.foreground);
688            }
689
690            grid_el = grid_el.child(dot);
691        }
692
693        // Floating tooltip anchored to hovered/keyboard-focused cell
694        let reading = snap.pointer.as_ref().and_then(|(k, sl)| {
695            self.data
696                .iter()
697                .find(|d| d.key.as_ref() == k)
698                .map(|item| (item, *sl))
699        });
700        let mut board = div().relative().child(grid_el);
701        if let Some((item, slot)) = reading {
702            let (cx_px, cy_px) = place(slot);
703            let tip_w = 176.0f32;
704            let tip_h = 52.0f32;
705            let left =
706                (cx_px + cell_size * 0.5 - tip_w * 0.5).clamp(0.0, (grid_w - tip_w).max(0.0));
707            let top = if cy_px - tip_h - 8.0 >= 0.0 {
708                cy_px - tip_h - 8.0
709            } else {
710                cy_px + cell_size + 8.0
711            };
712            let swatch_color = color_of(Some(item.key.as_ref()));
713            let swatch_shape = shape_of(Some(item.key.as_ref()));
714            let mut swatch = div().w(px(9.0)).h(px(9.0)).flex_shrink_0();
715            swatch = match swatch_shape {
716                WaffleCellShape::Square => swatch.rounded(px(2.0)).bg(swatch_color),
717                WaffleCellShape::Round => swatch.rounded_full().bg(swatch_color),
718                WaffleCellShape::Framed => swatch
719                    .rounded(px(2.0))
720                    .border_2()
721                    .border_color(swatch_color),
722            };
723
724            board = board.child(
725                div()
726                    .absolute()
727                    .left(px(left))
728                    .top(px(top))
729                    .w(px(tip_w))
730                    .px(Spacing::S3)
731                    .py(Spacing::S2)
732                    .rounded(Radii::CONTROL)
733                    .bg(colors.surface_raised)
734                    .border_1()
735                    .border_color(colors.border)
736                    .shadow_md()
737                    .flex()
738                    .flex_col()
739                    .gap(px(2.0))
740                    .child(
741                        div()
742                            .flex()
743                            .items_center()
744                            .justify_between()
745                            .gap(Spacing::S2)
746                            .child(
747                                div()
748                                    .flex()
749                                    .items_center()
750                                    .gap(px(6.0))
751                                    .child(swatch)
752                                    .child(
753                                        div()
754                                            .text_size(Typography::TEXT_XS)
755                                            .font_semibold()
756                                            .text_color(colors.foreground)
757                                            .truncate()
758                                            .child(item.label.clone()),
759                                    ),
760                            )
761                            .child(
762                                div()
763                                    .text_size(Typography::TEXT_XS)
764                                    .font_semibold()
765                                    .text_color(colors.foreground)
766                                    .child(format!(
767                                        "{:.prec$}%",
768                                        share_of(item),
769                                        prec = self.decimals
770                                    )),
771                            ),
772                    )
773                    .child(
774                        div()
775                            .text_size(px(11.0))
776                            .text_color(colors.text_muted)
777                            .child(self.fmt_val(item)),
778                    ),
779            );
780        }
781
782        if empty {
783            board = board.child(
784                div()
785                    .absolute()
786                    .inset_0()
787                    .flex()
788                    .items_center()
789                    .justify_center()
790                    .text_size(px(13.0))
791                    .text_color(colors.text_muted)
792                    .child(self.empty_label.clone()),
793            );
794        }
795
796        // Interactive legend column
797        let mut body = div()
798            .w_full()
799            .flex()
800            .flex_wrap()
801            .items_start()
802            .gap(Spacing::S5)
803            .child(board);
804
805        if self.legend && !empty {
806            let on_active = self.on_active_change.clone();
807            let mut legend_col = div()
808                .flex_1()
809                .min_w(px(160.0))
810                .flex()
811                .flex_col()
812                .gap(px(4.0));
813
814            for item in &self.data {
815                let k = item.key.to_string();
816                let is_on = active_key.as_deref() == Some(k.as_str());
817                let is_pinned = pinned.as_deref() == Some(k.as_str());
818                let is_dim = active_key.is_some() && !is_on;
819                let sw_color = color_of(Some(k.as_str()));
820                let sw_shape = shape_of(Some(k.as_str()));
821
822                let mut sw = div().w(px(10.0)).h(px(10.0)).flex_shrink_0();
823                sw = match sw_shape {
824                    WaffleCellShape::Square => sw.rounded(px(2.0)).bg(sw_color),
825                    WaffleCellShape::Round => sw.rounded_full().bg(sw_color),
826                    WaffleCellShape::Framed => {
827                        sw.rounded(px(2.0)).border_2().border_color(sw_color)
828                    }
829                };
830
831                let hover_st = state.clone();
832                let hover_key = k.clone();
833                let click_st = state.clone();
834                let click_key = k.clone();
835                let click_cb = on_active.clone();
836
837                legend_col = legend_col.child(
838                    div()
839                        .id(ElementId::NamedChild(
840                            self.id.clone().into(),
841                            SharedString::from(format!("waffle-legend-{k}")),
842                        ))
843                        .px(Spacing::S2)
844                        .py(px(5.0))
845                        .rounded(px(6.0))
846                        .cursor_pointer()
847                        .bg(if is_pinned {
848                            colors.surface_muted
849                        } else {
850                            Hsla::transparent_black()
851                        })
852                        .hover(|s| s.bg(colors.surface_muted))
853                        .flex()
854                        .items_center()
855                        .justify_between()
856                        .gap(Spacing::S3)
857                        .opacity(if is_dim { 0.45 } else { 1.0 })
858                        .on_hover(move |hovered, _w, cx| {
859                            hover_st.update(cx, |s, cx| {
860                                if *hovered {
861                                    s.preview_key = Some(hover_key.clone());
862                                } else if s.preview_key.as_deref() == Some(hover_key.as_str()) {
863                                    s.preview_key = None;
864                                }
865                                cx.notify();
866                            });
867                        })
868                        .on_mouse_down(MouseButton::Left, move |_, window, cx| {
869                            let next = if is_pinned {
870                                None
871                            } else {
872                                Some(click_key.clone())
873                            };
874                            if !is_controlled {
875                                click_st.update(cx, |s, cx| {
876                                    s.own_pinned = next.clone();
877                                    cx.notify();
878                                });
879                            }
880                            if let Some(cb) = &click_cb {
881                                cb(next.map(SharedString::from), window, cx);
882                            }
883                        })
884                        .child(
885                            div()
886                                .flex()
887                                .items_center()
888                                .gap(Spacing::S2)
889                                .child(sw)
890                                .child(
891                                    div()
892                                        .text_size(px(13.0))
893                                        .when(is_on, |this| this.font_semibold())
894                                        .text_color(colors.foreground)
895                                        .child(item.label.clone()),
896                                ),
897                        )
898                        .child(
899                            div()
900                                .text_size(px(13.0))
901                                .font_medium()
902                                .text_color(colors.text_muted)
903                                .child(format!("{:.prec$}%", share_of(item), prec = self.decimals)),
904                        ),
905                );
906            }
907
908            body = body.child(legend_col);
909        }
910
911        body
912    }
913}
914
915#[cfg(test)]
916mod tests {
917    use super::*;
918
919    #[test]
920    fn waffle_largest_remainder_and_minimal_reassignment() {
921        let counts = waffle_allocate(&[33.3, 33.3, 33.4], 100);
922        assert_eq!(counts.iter().sum::<usize>(), 100);
923        assert_eq!(counts, vec![33, 33, 34]);
924
925        let init: Vec<WaffleCell> = (0..10)
926            .map(|id| WaffleCell {
927                id,
928                key: None,
929                slot: id,
930            })
931            .collect();
932        let keys = vec!["a".to_string(), "b".to_string()];
933        let first = waffle_reassign(&init, &keys, &[6, 4]);
934        let a_ids_before: Vec<usize> = first
935            .iter()
936            .filter(|c| c.key.as_deref() == Some("a"))
937            .map(|c| c.id)
938            .collect();
939        assert_eq!(a_ids_before.len(), 6);
940
941        // Shrink "a" to 4 and grow "b" to 6: all 4 kept cells of "a" must stay from a_ids_before
942        let second = waffle_reassign(&first, &keys, &[4, 6]);
943        let a_ids_after: Vec<usize> = second
944            .iter()
945            .filter(|c| c.key.as_deref() == Some("a"))
946            .map(|c| c.id)
947            .collect();
948        assert_eq!(a_ids_after.len(), 4);
949        assert!(a_ids_after.iter().all(|id| a_ids_before.contains(id)));
950    }
951}