use std::collections::{HashMap, HashSet};
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 GAP: f32 = 2.0;
const PAD: f32 = 3.0;
const HEADER: f32 = 22.0;
const TIP_OFFSET: f32 = 14.0;
const COLOR_STEPS: usize = 5;
#[derive(Clone, Debug)]
pub struct TreemapNode {
pub id: SharedString,
pub label: SharedString,
pub value: Option<f64>,
pub color: Option<f64>,
pub children: Vec<TreemapNode>,
}
impl TreemapNode {
pub fn leaf(id: impl Into<SharedString>, label: impl Into<SharedString>, value: f64) -> Self {
Self {
id: id.into(),
label: label.into(),
value: Some(value),
color: None,
children: Vec::new(),
}
}
pub fn branch(
id: impl Into<SharedString>,
label: impl Into<SharedString>,
children: Vec<TreemapNode>,
) -> Self {
Self {
id: id.into(),
label: label.into(),
value: None,
color: None,
children,
}
}
pub fn with_color(mut self, color: f64) -> Self {
self.color = Some(color);
self
}
pub fn with_value(mut self, value: f64) -> Self {
self.value = Some(value);
self
}
pub fn with_children(mut self, children: Vec<TreemapNode>) -> Self {
self.children = children;
self
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct TreemapRect {
pub x: f32,
pub y: f32,
pub w: f32,
pub h: f32,
}
impl TreemapRect {
pub fn new(x: f32, y: f32, w: f32, h: f32) -> Self {
Self { x, y, w, h }
}
pub fn inset(self, top: f32, side: f32) -> Self {
Self {
x: self.x + side,
y: self.y + top,
w: (self.w - side * 2.0).max(0.0),
h: (self.h - top - side).max(0.0),
}
}
pub fn contains(self, px_x: f32, px_y: f32) -> bool {
px_x >= self.x && px_x <= self.x + self.w && px_y >= self.y && px_y <= self.y + self.h
}
}
#[derive(Clone, Debug)]
pub struct TreemapFlatNode {
pub id: String,
pub label: String,
pub value: f64,
pub color: Option<f64>,
pub depth: usize,
pub parent: Option<String>,
pub children: Vec<String>,
pub path: Vec<String>,
}
pub fn treemap_flatten(root: &TreemapNode) -> (HashMap<String, TreemapFlatNode>, Vec<String>) {
fn visit(
node: &TreemapNode,
depth: usize,
parent: Option<String>,
path_prefix: &[String],
flat: &mut HashMap<String, TreemapFlatNode>,
order: &mut Vec<String>,
) -> (f64, f64, f64) {
let id = node.id.to_string();
let label = node.label.to_string();
let mut child_prefix = path_prefix.to_vec();
if depth > 0 {
child_prefix.push(label.clone());
}
let own_path = if depth == 0 {
vec![label.clone()]
} else {
let mut p = path_prefix.to_vec();
p.push(label.clone());
p
};
order.push(id.clone());
let mut value = 0.0;
let mut weighted = 0.0;
let mut colored = 0.0;
if !node.children.is_empty() {
for kid in &node.children {
let (v, w, c) = visit(kid, depth + 1, Some(id.clone()), &child_prefix, flat, order);
value += v;
weighted += w;
colored += c;
}
} else {
value = node.value.unwrap_or(0.0).max(0.0);
if let Some(c) = node.color
&& c.is_finite()
{
weighted = c * value;
colored = value;
}
}
flat.insert(
id.clone(),
TreemapFlatNode {
id,
label,
value,
color: if colored > 0.0 {
Some(weighted / colored)
} else {
None
},
depth,
parent,
children: node.children.iter().map(|k| k.id.to_string()).collect(),
path: own_path,
},
);
(value, weighted, colored)
}
let mut flat = HashMap::new();
let mut order = Vec::new();
visit(root, 0, None, &[], &mut flat, &mut order);
(flat, order)
}
pub fn treemap_squarify(
items: &[(String, f64)],
rect: TreemapRect,
) -> HashMap<String, TreemapRect> {
let mut out = HashMap::new();
let mut list: Vec<(String, f64)> = items
.iter()
.filter(|(_, v)| v.is_finite() && *v > 0.0)
.cloned()
.collect();
list.sort_by(|a, b| b.1.total_cmp(&a.1));
let total: f64 = list.iter().map(|(_, v)| *v).sum();
if total <= 0.0 || rect.w <= 0.0 || rect.h <= 0.0 {
for (id, _) in items {
out.insert(id.clone(), TreemapRect::new(rect.x, rect.y, 0.0, 0.0));
}
return out;
}
let scale = (rect.w as f64 * rect.h as f64) / total;
let mut x = rect.x as f64;
let mut y = rect.y as f64;
let mut w = rect.w as f64;
let mut h = rect.h as f64;
let worst = |row: &[f64], side: f64| -> f64 {
let sum: f64 = row.iter().sum();
if sum <= 0.0 || side <= 0.0 {
return f64::INFINITY;
}
let mut max_v = f64::NEG_INFINITY;
let mut min_v = f64::INFINITY;
for &v in row {
max_v = max_v.max(v);
min_v = min_v.min(v);
}
if min_v <= 0.0 {
return f64::INFINITY;
}
let s2 = side * side;
let sum2 = sum * sum;
((s2 * max_v) / sum2).max(sum2 / (s2 * min_v))
};
let mut i = 0usize;
while i < list.len() {
let side = w.min(h).max(1e-6);
let mut row = vec![list[i].1 * scale];
let mut j = i + 1;
while j < list.len() {
let mut next = row.clone();
next.push(list[j].1 * scale);
if worst(&next, side) > worst(&row, side) {
break;
}
row.push(list[j].1 * scale);
j += 1;
}
let sum: f64 = row.iter().sum();
if w >= h {
let cw = if h > 1e-6 { sum / h } else { 0.0 };
let mut cy = y;
for (id, value) in &list[i..j] {
let th = if cw > 1e-6 { (value * scale) / cw } else { 0.0 };
out.insert(
id.clone(),
TreemapRect::new(x as f32, cy as f32, cw as f32, th as f32),
);
cy += th;
}
x += cw;
w = (w - cw).max(0.0);
} else {
let rh = if w > 1e-6 { sum / w } else { 0.0 };
let mut cx = x;
for (id, value) in &list[i..j] {
let tw = if rh > 1e-6 { (value * scale) / rh } else { 0.0 };
out.insert(
id.clone(),
TreemapRect::new(cx as f32, y as f32, tw as f32, rh as f32),
);
cx += tw;
}
y += rh;
h = (h - rh).max(0.0);
}
i = j;
}
for (id, _) in items {
out.entry(id.clone())
.or_insert_with(|| TreemapRect::new(rect.x, rect.y, 0.0, 0.0));
}
out
}
pub fn treemap_layout_from(
flat: &HashMap<String, TreemapFlatNode>,
focus_id: &str,
view: TreemapRect,
) -> HashMap<String, TreemapRect> {
fn nest(
flat: &HashMap<String, TreemapFlatNode>,
id: &str,
rect: TreemapRect,
top: bool,
out: &mut HashMap<String, TreemapRect>,
) {
let Some(node) = flat.get(id) else {
return;
};
if node.children.is_empty() {
return;
}
let room = if top {
rect
} else {
let header = if rect.h > 48.0 && rect.w > 64.0 {
HEADER
} else {
PAD
};
rect.inset(header, PAD)
};
let items: Vec<(String, f64)> = node
.children
.iter()
.filter_map(|cid| flat.get(cid).map(|c| (cid.clone(), c.value)))
.collect();
let placed = treemap_squarify(&items, room);
for cid in &node.children {
if let Some(&r) = placed.get(cid) {
let gapped = TreemapRect::new(
r.x + GAP * 0.5,
r.y + GAP * 0.5,
(r.w - GAP).max(0.0),
(r.h - GAP).max(0.0),
);
out.insert(cid.clone(), gapped);
nest(flat, cid, gapped, false, out);
}
}
}
let mut out = HashMap::new();
nest(flat, focus_id, view, true, &mut out);
out
}
pub fn treemap_carry(r: TreemapRect, from: TreemapRect, to: TreemapRect) -> TreemapRect {
let sx = if from.w.abs() > 1e-4 {
to.w / from.w
} else {
1.0
};
let sy = if from.h.abs() > 1e-4 {
to.h / from.h
} else {
1.0
};
TreemapRect::new(
to.x + (r.x - from.x) * sx,
to.y + (r.y - from.y) * sy,
r.w * sx,
r.h * sy,
)
}
pub fn treemap_nearest_neighbor(
current_id: &str,
candidates: &[String],
rects: &HashMap<String, TreemapRect>,
dx: f32,
dy: f32,
) -> Option<String> {
let cur = rects.get(current_id)?;
let ox = cur.x + cur.w * 0.5;
let oy = cur.y + cur.h * 0.5;
let mut best: Option<String> = None;
let mut best_score = f32::INFINITY;
for cid in candidates {
if cid == current_id {
continue;
}
let Some(r) = rects.get(cid) else {
continue;
};
let vx = r.x + r.w * 0.5 - ox;
let vy = r.y + r.h * 0.5 - oy;
let along = vx * dx + vy * dy;
let across = (vx * dy - vy * dx).abs();
if along <= 1.0 {
continue;
}
let score = along + across * 1.5;
if score < best_score {
best_score = score;
best = Some(cid.clone());
}
}
best
}
fn is_under(flat: &HashMap<String, TreemapFlatNode>, id: &str, ancestor: &str) -> bool {
let mut cur = flat.get(id);
while let Some(node) = cur {
if node.id == ancestor {
return true;
}
cur = node.parent.as_deref().and_then(|p| flat.get(p));
}
false
}
#[derive(Clone, Copy, Debug)]
struct DrawnTile {
rect: TreemapRect,
opacity: f32,
}
#[derive(Clone)]
struct TreemapState {
focus_handle: FocusHandle,
own_focus: String,
active_id: Option<String>,
pointer_xy: Option<(f32, f32)>,
stage_bounds: Bounds<Pixels>,
drawn: HashMap<String, DrawnTile>,
from_tiles: HashMap<String, DrawnTile>,
to_tiles: HashMap<String, DrawnTile>,
last_focus_id: Option<String>,
last_layout: HashMap<String, TreemapRect>,
last_size: (u32, u32),
transition_spring: ChartSpring,
first_reveal: bool,
last_tick: f64,
}
type FocusChangeHandler = Rc<dyn Fn(SharedString, &mut Window, &mut App)>;
#[derive(IntoElement)]
pub struct Treemap {
id: ElementId,
data: TreemapNode,
label: SharedString,
color_label: Option<SharedString>,
color_domain: Option<(f64, f64)>,
focus: Option<SharedString>,
default_focus: Option<SharedString>,
on_focus_change: Option<FocusChangeHandler>,
format_value: Option<Rc<dyn Fn(f64) -> String>>,
format_color: Option<Rc<dyn Fn(f64) -> String>>,
height: f32,
empty_label: SharedString,
}
impl Treemap {
pub fn new(
id: impl Into<ElementId>,
data: TreemapNode,
label: impl Into<SharedString>,
) -> Self {
Self {
id: id.into(),
data,
label: label.into(),
color_label: None,
color_domain: None,
focus: None,
default_focus: None,
on_focus_change: None,
format_value: None,
format_color: None,
height: 400.0,
empty_label: "No data yet".into(),
}
}
pub fn color_label(mut self, label: impl Into<SharedString>) -> Self {
self.color_label = Some(label.into());
self
}
pub fn color_domain(mut self, min: f64, max: f64) -> Self {
self.color_domain = Some((min, max));
self
}
pub fn focus(mut self, id: impl Into<SharedString>) -> Self {
self.focus = Some(id.into());
self
}
pub fn default_focus(mut self, id: impl Into<SharedString>) -> Self {
self.default_focus = Some(id.into());
self
}
pub fn on_focus_change(
mut self,
f: impl Fn(SharedString, &mut Window, &mut App) + 'static,
) -> Self {
self.on_focus_change = Some(Rc::new(f));
self
}
pub fn format_value(mut self, f: impl Fn(f64) -> String + 'static) -> Self {
self.format_value = Some(Rc::new(f));
self
}
pub fn format_color(mut self, f: impl Fn(f64) -> String + 'static) -> Self {
self.format_color = Some(Rc::new(f));
self
}
pub fn height(mut self, height: f32) -> Self {
self.height = height.max(160.0);
self
}
pub fn empty_label(mut self, label: impl Into<SharedString>) -> Self {
self.empty_label = label.into();
self
}
fn fmt_val(&self, v: f64) -> String {
if let Some(f) = &self.format_value {
f(v)
} else {
format_grouped(v, 1)
}
}
fn fmt_color(&self, v: f64) -> String {
if let Some(f) = &self.format_color {
f(v)
} else {
format_grouped(v, 1)
}
}
}
impl RenderOnce for Treemap {
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 (flat, order) = treemap_flatten(&self.data);
let root_id = self.data.id.to_string();
let root = flat.get(&root_id).cloned().expect("treemap root exists");
let default_focus_id = self
.default_focus
.as_ref()
.map(|s| s.to_string())
.unwrap_or_else(|| root_id.clone());
let state = window.use_keyed_state(
ElementId::NamedChild(self.id.clone().into(), "__treemap-state".into()),
cx,
|_w, cx| TreemapState {
focus_handle: cx.focus_handle(),
own_focus: default_focus_id.clone(),
active_id: None,
pointer_xy: None,
stage_bounds: Bounds::default(),
drawn: HashMap::new(),
from_tiles: HashMap::new(),
to_tiles: HashMap::new(),
last_focus_id: None,
last_layout: HashMap::new(),
last_size: (0, 0),
transition_spring: ChartSpring::new(if reduced { 1.0 } else { 0.0 }),
first_reveal: true,
last_tick: now,
},
);
let snap = state.read(cx).clone();
let wanted_focus = self
.focus
.as_ref()
.map(|s| s.to_string())
.unwrap_or_else(|| snap.own_focus.clone());
let center = flat
.get(&wanted_focus)
.filter(|n| !n.children.is_empty())
.cloned()
.unwrap_or_else(|| root.clone());
let width_px: f32 = snap.stage_bounds.size.width.into();
let view_w = if width_px > 20.0 { width_px } else { 560.0 };
let view = TreemapRect::new(0.0, 0.0, view_w, self.height);
let target_layout = treemap_layout_from(&flat, ¢er.id, view);
let size_key = (view_w.round() as u32, self.height.round() as u32);
let mut branch_of: HashMap<String, usize> = HashMap::new();
for (idx, top_cid) in root.children.iter().enumerate() {
let mut stack = vec![top_cid.clone()];
while let Some(cur) = stack.pop() {
branch_of.insert(cur.clone(), idx);
if let Some(n) = flat.get(&cur) {
for ch in &n.children {
stack.push(ch.clone());
}
}
}
}
let colored_leaves: Vec<f64> = order
.iter()
.filter_map(|id| flat.get(id))
.filter(|n| n.depth > 0 && n.children.is_empty())
.filter_map(|n| n.color)
.collect();
let colored = self.color_label.is_some() && !colored_leaves.is_empty();
let (color_lo, color_hi) = self.color_domain.unwrap_or_else(|| {
if colored_leaves.is_empty() {
(0.0, 1.0)
} else {
let lo = colored_leaves.iter().copied().fold(f64::INFINITY, f64::min);
let hi = colored_leaves
.iter()
.copied()
.fold(f64::NEG_INFINITY, f64::max);
(lo, hi)
}
});
let shade_weight = |val: Option<f64>| -> f32 {
if !colored {
return 0.34;
}
let Some(v) = val else {
return 0.34;
};
let span = (color_hi - color_lo).abs().max(1e-9);
let t = ((v - color_lo) / span).clamp(0.0, 1.0);
let step = (t * (COLOR_STEPS - 1) as f64).round() / (COLOR_STEPS - 1) as f64;
(0.14 + step * 0.44) as f32
};
let hue_of = |branch_idx: Option<usize>| -> Hsla {
match branch_idx {
Some(i) if i < 4 => chart_series_color(&colors, i),
None => colors.series.series_1,
_ => colors.foreground,
}
};
let needs_retarget =
snap.last_focus_id.as_deref() != Some(center.id.as_str()) || snap.last_size != size_key;
if needs_retarget {
let next_visible: HashSet<String> = order
.iter()
.filter_map(|id| flat.get(id))
.filter(|n| {
let level = n.depth.saturating_sub(center.depth);
n.depth > center.depth
&& (1..=2).contains(&level)
&& is_under(&flat, &n.id, ¢er.id)
})
.map(|n| n.id.clone())
.collect();
let flat_ref = ♭
let target_ref = &target_layout;
let center_id_clone = center.id.clone();
state.update(cx, |s, _cx| {
let first = s.drawn.is_empty();
let was_visible: HashSet<String> = s
.drawn
.iter()
.filter(|(_, d)| d.opacity > 0.5)
.map(|(k, _)| k.clone())
.collect();
let mut to_old: Option<(TreemapRect, TreemapRect)> = None;
let mut to_new: Option<(TreemapRect, TreemapRect)> = None;
if let Some(prev_id) = s.last_focus_id.as_deref()
&& prev_id != center_id_clone
&& !first
{
if is_under(flat_ref, ¢er_id_clone, prev_id) {
if let Some(&in_old) = s.last_layout.get(¢er_id_clone) {
to_old = Some((view, in_old));
to_new = Some((in_old, view));
}
} else if is_under(flat_ref, prev_id, ¢er_id_clone)
&& let Some(&in_new) = target_ref.get(prev_id)
{
to_old = Some((in_new, view));
to_new = Some((view, in_new));
}
}
let mut from_map = HashMap::new();
let mut to_map = HashMap::new();
for id in &order {
let Some(node) = flat_ref.get(id) else {
continue;
};
if node.depth == 0 {
continue;
}
let goal = target_ref.get(id).copied();
let now_drawn = s.drawn.get(id).copied();
let in_next = next_visible.contains(id);
let in_prev = was_visible.contains(id);
if in_next {
if let Some(g) = goal {
to_map.insert(
id.clone(),
DrawnTile {
rect: g,
opacity: 1.0,
},
);
if in_prev {
if let Some(d) = now_drawn {
from_map.insert(id.clone(), d);
}
} else if first {
from_map.insert(
id.clone(),
DrawnTile {
rect: TreemapRect::new(
g.x + g.w * 0.5,
g.y + g.h * 0.5,
0.0,
0.0,
),
opacity: 0.0,
},
);
} else {
let mapped = match to_old {
Some((f, t)) => treemap_carry(g, f, t),
None => g,
};
from_map.insert(
id.clone(),
DrawnTile {
rect: mapped,
opacity: 0.0,
},
);
}
}
} else if in_prev && let Some(d) = now_drawn {
from_map.insert(id.clone(), d);
let mapped = match to_new {
Some((f, t)) => treemap_carry(d.rect, f, t),
None => d.rect,
};
to_map.insert(
id.clone(),
DrawnTile {
rect: mapped,
opacity: 0.0,
},
);
}
}
s.from_tiles = from_map;
s.to_tiles = to_map;
s.last_focus_id = Some(center_id_clone.clone());
s.last_layout = target_ref.clone();
s.last_size = size_key;
s.first_reveal = first;
if reduced {
s.transition_spring.snap(1.0);
s.drawn = s.to_tiles.clone();
} else {
s.transition_spring.snap(0.0);
s.transition_spring.set_target(1.0);
}
s.last_tick = now;
});
}
let mut anim_running = false;
let view_area = (view.w * view.h).max(1.0);
state.update(cx, |s, _cx| {
let dt = (now - s.last_tick).clamp(0.0, 0.05);
s.last_tick = now;
if reduced {
s.transition_spring.snap(1.0);
} else {
let (dur, bounce) = if s.first_reveal {
(0.78, 0.0)
} else {
(0.54, 0.06)
};
if dt > 0.0 && !s.transition_spring.is_settled() {
s.transition_spring.step(dur, bounce, dt as f32);
}
}
let t = s.transition_spring.position().clamp(0.0, 1.0);
anim_running = !s.transition_spring.is_settled();
let mut next_drawn = HashMap::new();
for (id, &a) in &s.from_tiles {
if let Some(&b) = s.to_tiles.get(id) {
let local = if s.first_reveal {
let area_ratio = (b.rect.w * b.rect.h / view_area).clamp(0.0, 1.0);
let delay = ((1.0 - area_ratio) * 0.28).min(0.28);
((t - delay) / (1.0 - delay).max(0.01)).clamp(0.0, 1.0)
} else {
t
};
let mix = |u: f32, v: f32| u + (v - u) * local;
next_drawn.insert(
id.clone(),
DrawnTile {
rect: TreemapRect::new(
mix(a.rect.x, b.rect.x),
mix(a.rect.y, b.rect.y),
mix(a.rect.w, b.rect.w),
mix(a.rect.h, b.rect.h),
),
opacity: mix(a.opacity, b.opacity),
},
);
}
}
if !next_drawn.is_empty() {
s.drawn = next_drawn;
}
});
if anim_running {
window.request_animation_frame();
}
let snap = state.read(cx).clone();
let active_node = snap.active_id.as_deref().and_then(|id| flat.get(id));
let top_of = |node: &TreemapFlatNode| -> Option<String> {
let mut cur = Some(node);
while let Some(n) = cur {
if n.parent.as_deref() == Some(center.id.as_str()) {
return Some(n.id.clone());
}
cur = n.parent.as_deref().and_then(|p| flat.get(p));
}
None
};
let focus_top = active_node.and_then(&top_of);
let mut trail = Vec::new();
let mut cursor = Some(center.clone());
while let Some(n) = cursor {
trail.push(n.clone());
cursor = n.parent.as_deref().and_then(|p| flat.get(p).cloned());
}
trail.reverse();
let empty = root.value <= 0.0;
let is_controlled = self.focus.is_some();
let on_focus_change = self.on_focus_change.clone();
let top_tiles: Vec<String> = center
.children
.iter()
.filter(|cid| flat.get(*cid).map(|n| n.value > 0.0).unwrap_or(false))
.cloned()
.collect();
let mut crumbs_row = div().flex().items_center().flex_wrap().gap(px(4.0));
let trail_len = trail.len();
for (idx, crumb) in trail.iter().enumerate() {
if idx > 0 {
crumbs_row = crumbs_row.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted.opacity(0.6))
.child("/"),
);
}
if idx + 1 < trail_len {
let target_id = crumb.id.clone();
let st = state.clone();
let cb = on_focus_change.clone();
crumbs_row = crumbs_row.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("treemap-crumb-{idx}-{target_id}")),
))
.px(px(6.0))
.py(px(2.0))
.rounded(px(6.0))
.cursor_pointer()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.hover(|s| s.text_color(colors.foreground).bg(colors.surface_muted))
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
if !is_controlled {
st.update(cx, |s, cx| {
s.own_focus = target_id.clone();
s.active_id = None;
cx.notify();
});
}
if let Some(cb) = &cb {
cb(SharedString::from(target_id.clone()), window, cx);
}
})
.child(crumb.label.clone()),
);
} else {
crumbs_row = crumbs_row.child(
div()
.px(px(4.0))
.py(px(2.0))
.text_size(Typography::TEXT_XS)
.font_medium()
.text_color(colors.foreground)
.child(crumb.label.clone()),
);
}
}
let bar = div()
.flex()
.items_center()
.justify_between()
.gap(Spacing::S3)
.mb(Spacing::S2)
.child(crumbs_row)
.child(
div()
.text_size(Typography::TEXT_SM)
.font_semibold()
.text_color(colors.foreground)
.child(self.fmt_val(center.value)),
);
let mut render_tiles: Vec<(String, DrawnTile, usize)> = snap
.drawn
.iter()
.filter_map(|(id, &d)| {
if d.opacity < 0.02 || d.rect.w < 1.0 || d.rect.h < 1.0 {
return None;
}
let node = flat.get(id)?;
Some((id.clone(), d, node.depth))
})
.collect();
render_tiles.sort_by_key(|(_, _, depth)| *depth);
let bounds_state = state.clone();
let bounds_tracker = canvas(
move |bounds, _window, cx| {
bounds_state.update(cx, |s, _cx| {
s.stage_bounds = bounds;
});
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
let hit_order: Vec<(String, TreemapRect, usize)> = render_tiles
.iter()
.map(|(id, d, depth)| (id.clone(), d.rect, *depth))
.collect();
let move_state = state.clone();
let move_hits = hit_order.clone();
let click_state = state.clone();
let click_hits = hit_order;
let click_flat = flat.clone();
let click_center_id = center.id.clone();
let click_cb = on_focus_change.clone();
let key_state = state.clone();
let key_flat = flat.clone();
let key_center = center.clone();
let key_target = target_layout.clone();
let key_cb = on_focus_change.clone();
let mut stage = div()
.id(self.id.clone())
.role(Role::Group)
.aria_label(self.label.clone())
.track_focus(&snap.focus_handle)
.relative()
.w_full()
.h(px(self.height))
.rounded(Radii::CONTROL)
.bg(colors.surface_muted)
.overflow_hidden()
.on_mouse_move(move |ev: &MouseMoveEvent, _w, cx| {
move_state.update(cx, |s, cx| {
let b = s.stage_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.active_id.is_some() || s.pointer_xy.is_some() {
s.active_id = None;
s.pointer_xy = None;
cx.notify();
}
return;
}
let hit = move_hits
.iter()
.rev()
.find(|(_, r, _)| r.contains(lx, ly))
.map(|(id, _, _)| id.clone());
s.pointer_xy = Some((lx, ly));
if s.active_id != hit {
s.active_id = hit;
}
cx.notify();
});
})
.on_mouse_down(MouseButton::Left, move |ev: &MouseDownEvent, window, cx| {
let (focus_handle, hit_id) = {
let s = click_state.read(cx);
let b = s.stage_bounds;
let lx: f32 = (ev.position.x - b.origin.x).into();
let ly: f32 = (ev.position.y - b.origin.y).into();
let hit = click_hits
.iter()
.rev()
.find(|(_, r, _)| r.contains(lx, ly))
.map(|(id, _, _)| id.clone());
(s.focus_handle.clone(), hit)
};
window.focus(&focus_handle, cx);
if let Some(id) = hit_id {
let mut top_child_id = None;
let mut cur = click_flat.get(&id);
while let Some(n) = cur {
if n.parent.as_deref() == Some(click_center_id.as_str()) {
top_child_id = Some(n.id.clone());
break;
}
cur = n.parent.as_deref().and_then(|p| click_flat.get(p));
}
if let Some(tid) = top_child_id
&& click_flat
.get(&tid)
.map(|n| !n.children.is_empty())
.unwrap_or(false)
{
if !is_controlled {
click_state.update(cx, |s, cx| {
s.own_focus = tid.clone();
s.active_id = None;
cx.notify();
});
}
if let Some(cb) = &click_cb {
cb(SharedString::from(tid), window, cx);
}
return;
}
click_state.update(cx, |s, cx| {
s.active_id = Some(id);
cx.notify();
});
}
})
.on_key_down(move |ev: &KeyDownEvent, window, cx| {
let key = ev.keystroke.key.as_str();
let current_active = key_state.read(cx).active_id.clone();
let current_top = current_active.as_deref().and_then(|aid| {
let mut cur = key_flat.get(aid);
while let Some(n) = cur {
if n.parent.as_deref() == Some(key_center.id.as_str()) {
return Some(n.id.clone());
}
cur = n.parent.as_deref().and_then(|p| key_flat.get(p));
}
None
});
let dir = match key {
"right" => Some((1.0f32, 0.0f32)),
"left" => Some((-1.0, 0.0)),
"down" => Some((0.0, 1.0)),
"up" => Some((0.0, -1.0)),
_ => None,
};
if let Some((dx, dy)) = dir {
cx.stop_propagation();
let next = match current_top {
None => top_tiles.first().cloned(),
Some(ref cid) => {
treemap_nearest_neighbor(cid, &top_tiles, &key_target, dx, dy)
}
};
if let Some(nid) = next {
key_state.update(cx, |s, cx| {
s.pointer_xy = None;
s.active_id = Some(nid);
cx.notify();
});
}
} else if key == "home" || key == "end" {
cx.stop_propagation();
let pick = if key == "home" {
top_tiles.first().cloned()
} else {
top_tiles.last().cloned()
};
key_state.update(cx, |s, cx| {
s.pointer_xy = None;
s.active_id = pick;
cx.notify();
});
} else if key == "enter" || key == "space" {
if let Some(cid) = current_top
&& let Some(node) = key_flat.get(&cid)
&& !node.children.is_empty()
{
cx.stop_propagation();
let first_kid = node.children.first().cloned();
if !is_controlled {
key_state.update(cx, |s, cx| {
s.own_focus = cid.clone();
s.active_id = first_kid;
s.pointer_xy = None;
cx.notify();
});
}
if let Some(cb) = &key_cb {
cb(SharedString::from(cid), window, cx);
}
}
} else if key == "escape" || key == "backspace" {
if let Some(parent_id) = key_center.parent.clone() {
cx.stop_propagation();
if !is_controlled {
key_state.update(cx, |s, cx| {
s.own_focus = parent_id.clone();
s.active_id = Some(key_center.id.clone());
s.pointer_xy = None;
cx.notify();
});
}
if let Some(cb) = &key_cb {
cb(SharedString::from(parent_id), window, cx);
}
} else if current_active.is_some() {
cx.stop_propagation();
key_state.update(cx, |s, cx| {
s.active_id = None;
cx.notify();
});
}
}
})
.child(bounds_tracker);
for (id, drawn, _depth) in &render_tiles {
let Some(node) = flat.get(id) else {
continue;
};
let is_branch = !node.children.is_empty();
let is_active = snap.active_id.as_deref() == Some(id.as_str());
let tile_top = top_of(node);
let is_dim = focus_top.is_some() && tile_top.is_some() && focus_top != tile_top;
let hue = hue_of(branch_of.get(id).copied());
let base_weight = if is_branch && node.depth == center.depth + 1 {
0.18
} else {
shade_weight(node.color)
};
let fill = oklab_mix(hue, colors.surface, base_weight);
let border = if is_active {
colors.foreground
} else if is_branch {
oklab_mix(hue, colors.border, 0.35)
} else {
oklab_mix(colors.surface, colors.border, 0.5)
};
let alpha = drawn.opacity * if is_dim { 0.42 } else { 1.0 };
let r = drawn.rect;
let show_name = r.w > 56.0 && r.h > 22.0;
let show_value = !is_branch && r.w > 64.0 && r.h > 46.0;
let mut tile = div()
.absolute()
.left(px(r.x))
.top(px(r.y))
.w(px(r.w))
.h(px(r.h))
.rounded(px(4.0))
.bg(fill.opacity(alpha))
.border_1()
.border_color(border.opacity(if is_active { 0.95 } else { alpha * 0.75 }))
.overflow_hidden()
.px(px(6.0))
.py(px(3.0))
.flex()
.flex_col()
.justify_start();
if is_branch && node.depth == center.depth + 1 {
tile = tile.cursor_pointer();
}
if show_name {
let mut name_el = div()
.text_size(if is_branch {
px(11.0)
} else {
Typography::TEXT_XS
})
.text_color(colors.foreground.opacity(alpha))
.truncate()
.child(node.label.clone());
name_el = if is_branch {
name_el.font_semibold()
} else {
name_el.font_medium()
};
tile = tile.child(name_el);
}
if show_value {
tile = tile.child(
div()
.text_size(px(11.0))
.text_color(colors.text_muted.opacity(alpha))
.truncate()
.child(self.fmt_val(node.value)),
);
}
stage = stage.child(tile);
}
if empty {
stage = stage.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()),
);
}
if let Some(node) = active_node {
let parent = node
.parent
.as_deref()
.and_then(|pid| flat.get(pid))
.unwrap_or(node);
let share_pct = if parent.value > 0.0 {
(node.value / parent.value) * 100.0
} else {
0.0
};
let tile_rect = target_layout.get(&node.id).copied();
let (ax, ay) = snap.pointer_xy.unwrap_or_else(|| {
tile_rect
.map(|r| (r.x + r.w * 0.5, r.y + (r.h * 0.5).min(28.0)))
.unwrap_or((view_w * 0.5, self.height * 0.5))
});
let tip_w = 196.0f32;
let tip_h = if colored && node.color.is_some() {
86.0f32
} else {
68.0f32
};
let mut left = ax + TIP_OFFSET;
if left + tip_w > view_w - 4.0 {
left = (ax - TIP_OFFSET - tip_w).max(4.0);
}
let mut top = ay + TIP_OFFSET;
if top + tip_h > self.height - 4.0 {
top = (ay - TIP_OFFSET - tip_h).max(4.0);
}
let path_header = if node.path.len() > 1 {
node.path[..node.path.len() - 1].join(" / ")
} else {
root.label.clone()
};
let mut tip_box = 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()
.text_size(px(11.0))
.text_color(colors.text_muted)
.truncate()
.child(path_header),
)
.child(
div()
.flex()
.items_center()
.justify_between()
.gap(Spacing::S2)
.child(
div()
.text_size(Typography::TEXT_XS)
.font_semibold()
.text_color(colors.foreground)
.truncate()
.child(node.label.clone()),
)
.child(
div()
.text_size(Typography::TEXT_XS)
.font_semibold()
.text_color(colors.foreground)
.child(self.fmt_val(node.value)),
),
)
.child(
div()
.text_size(px(11.0))
.text_color(colors.text_muted)
.child(format!("{:.1}% of {}", share_pct, parent.label)),
);
if colored && let (Some(clabel), Some(cval)) = (&self.color_label, node.color) {
tip_box = tip_box.child(
div()
.text_size(px(11.0))
.text_color(colors.text_muted)
.child(format!("{} {}", clabel, self.fmt_color(cval))),
);
}
stage = stage.child(tip_box);
}
let mut root_el = div().w_full().flex().flex_col().child(bar).child(stage);
if colored {
let scale_hue = if center.depth == 0 {
colors.foreground
} else {
hue_of(branch_of.get(¢er.id).copied())
};
let mut swatches = div().flex().items_center().gap(px(3.0));
for i in 0..COLOR_STEPS {
let weight = 0.14 + (i as f32 / (COLOR_STEPS - 1) as f32) * 0.44;
swatches =
swatches.child(div().w(px(16.0)).h(px(10.0)).rounded(px(2.0)).bg(oklab_mix(
scale_hue,
colors.surface,
weight,
)));
}
root_el = root_el.child(
div()
.mt(Spacing::S2)
.flex()
.items_center()
.gap(Spacing::S2)
.text_size(px(11.0))
.text_color(colors.text_muted)
.child(self.color_label.clone().unwrap_or_default())
.child(self.fmt_color(color_lo))
.child(swatches)
.child(self.fmt_color(color_hi)),
);
}
root_el
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn treemap_flatten_squarify_and_neighbor_navigation() {
let tree = TreemapNode::branch(
"root",
"Revenue",
vec![
TreemapNode::branch(
"na",
"North America",
vec![
TreemapNode::leaf("us", "United States", 60.0).with_color(18.0),
TreemapNode::leaf("ca", "Canada", 20.0).with_color(10.0),
],
),
TreemapNode::leaf("eu", "Europe", 40.0).with_color(12.0),
],
);
let (flat, _) = treemap_flatten(&tree);
assert_eq!(flat["root"].value, 120.0);
assert_eq!(flat["na"].value, 80.0);
assert!((flat["na"].color.unwrap() - 16.0).abs() < 1e-6);
let view = TreemapRect::new(0.0, 0.0, 600.0, 300.0);
let rects = treemap_layout_from(&flat, "root", view);
let na = rects["na"];
let eu = rects["eu"];
let ratio = (na.w * na.h) / (eu.w * eu.h);
assert!(ratio > 1.8 && ratio < 2.2, "unexpected ratio: {ratio}");
let next = treemap_nearest_neighbor(
"na",
&["na".to_string(), "eu".to_string()],
&rects,
1.0,
0.0,
);
assert_eq!(next.as_deref(), Some("eu"));
}
}