1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
/// Heatmap chart component
use crate::components::svg::colorbar::ColorBar;
use crate::components::svg::heatmap_tooltip::HeatmapTooltip;
use crate::hooks::use_container_size;
use leptos::prelude::*;
use lodviz_core::core::color_map::{ColorMap, SequentialColorMap};
use lodviz_core::core::data::GridData;
use lodviz_core::core::theme::{ChartConfig, ChartTheme};
/// HeatmapChart: renders a 2-D grid as colored rectangles using a continuous ColorMap.
///
/// Features:
/// - Configurable color map (any `ColorMap` variant)
/// - Optional cell value labels
/// - Optional ColorBar legend
/// - Hover tooltip (row, col, value)
/// - Responsive via `use_container_size()`
#[component]
pub fn HeatmapChart(
/// 2-D grid data (rows × columns)
data: Signal<GridData>,
/// Color map for encoding values as colors
#[prop(default = ColorMap::Sequential(SequentialColorMap::Viridis))]
color_map: ColorMap,
/// Show numeric value labels inside each cell
#[prop(default = false)]
show_values: bool,
/// Show a vertical color bar on the right
#[prop(default = true)]
show_colorbar: bool,
/// Chart configuration
#[prop(default = Signal::derive(|| ChartConfig::default()), into)]
config: Signal<ChartConfig>,
/// Fixed width override
#[prop(optional)]
width: Option<u32>,
/// Fixed height override
#[prop(optional)]
height: Option<u32>,
) -> impl IntoView {
let ctx_theme = use_context::<Signal<ChartTheme>>();
let theme = Memo::new(move |_| {
config
.get()
.theme
.unwrap_or_else(|| ctx_theme.map(|s| s.get()).unwrap_or_default())
});
let (container_width, container_height, container_ref) = use_container_size();
let chart_width = Memo::new(move |_| {
let m = container_width.get();
if m > 0.0 {
return m as u32;
}
config.get().width.or(width).unwrap_or(600)
});
let chart_height = Memo::new(move |_| {
let m = container_height.get();
if m > 0.0 {
return m as u32;
}
config.get().height.or(height).unwrap_or(400)
});
let final_title = Memo::new(move |_| config.get().title);
// Colorbar width in margin right
let colorbar_w = if show_colorbar { 60.0 } else { 0.0 };
let margin_top = 40.0_f64;
let margin_bottom = 60.0_f64;
let margin_left = 70.0_f64;
let margin_right = colorbar_w + 20.0;
let inner_width =
Memo::new(move |_| (chart_width.get() as f64 - margin_left - margin_right).max(10.0));
let inner_height =
Memo::new(move |_| (chart_height.get() as f64 - margin_top - margin_bottom).max(10.0));
// Derived grid stats
let grid_stats = Memo::new(move |_| {
let g = data.get();
let nrows = g.values.len();
let ncols = g.values.first().map(|r| r.len()).unwrap_or(0);
let min = g.min();
let max_v = g.max();
let range = (max_v - min).max(1e-12);
(nrows, ncols, min, max_v, range)
});
// Hover state
let (hover_row, set_hover_row) = signal(None::<usize>);
let (hover_col, set_hover_col) = signal(None::<usize>);
let (hover_x, set_hover_x) = signal(0.0_f64);
let (hover_y, set_hover_y) = signal(0.0_f64);
let hover_row_label = Signal::derive(move || {
let g = data.get();
hover_row.get().and_then(|r| {
g.row_labels
.as_ref()
.and_then(|labels| labels.get(r))
.cloned()
.or_else(|| Some(format!("Row {}", r + 1)))
})
});
let hover_col_label = Signal::derive(move || {
let g = data.get();
hover_col.get().and_then(|c| {
g.col_labels
.as_ref()
.and_then(|labels| labels.get(c))
.cloned()
.or_else(|| Some(format!("Col {}", c + 1)))
})
});
let hover_value = Signal::derive(move || {
let g = data.get();
hover_row.get().and_then(|r| {
hover_col
.get()
.and_then(|c| g.values.get(r)?.get(c).copied())
})
});
let color_map_clone = color_map.clone();
let color_map_colorbar = color_map.clone();
let clip_id = format!("heatmap-clip-{}", uuid::Uuid::new_v4().simple());
let iw_signal = Signal::derive(move || inner_width.get());
let ih_signal = Signal::derive(move || inner_height.get());
let a11y_title_id = format!("chart-title-{}", uuid::Uuid::new_v4().as_simple());
let a11y_desc_id = format!("chart-desc-{}", uuid::Uuid::new_v4().as_simple());
let a11y_labelledby = format!("{} {}", a11y_title_id, a11y_desc_id);
view! {
<div
class="heatmap-chart"
style=move || {
format!(
"width: 100%; height: 100%; display: flex; flex-direction: column; background-color: {};",
theme.get().background_color,
)
}
>
{move || {
final_title
.get()
.map(|t| {
let th = theme.get();
view! {
<h3 style=format!(
"text-align: center; margin: 0; padding-top: {}px; padding-bottom: {}px; font-size: {}px; font-family: {}; color: {}; font-weight: {};",
th.title_padding_top,
th.title_padding_bottom,
th.title_font_size,
th.font_family,
th.text_color,
th.title_font_weight,
)>{t}</h3>
}
})
}}
<div node_ref=container_ref style="flex: 1; position: relative; min-height: 0;">
<svg
role="img"
aria-labelledby=a11y_labelledby
viewBox=move || format!("0 0 {} {}", chart_width.get(), chart_height.get())
style="width: 100%; height: 100%; display: block;"
>
<title id=a11y_title_id>
{move || final_title.get().unwrap_or("Heatmap".to_string())}
</title>
<desc id=a11y_desc_id>
"Heatmap showing data values encoded as a color gradient across a two-dimensional grid."
</desc>
<g transform=move || format!("translate({margin_left}, {margin_top})")>
<defs>
<clipPath id=clip_id.clone()>
<rect
x="0"
y="0"
width=move || inner_width.get()
height=move || inner_height.get()
/>
</clipPath>
</defs>
// Grid cells
{move || {
let g = data.get();
let (nrows, ncols, min, _, range) = grid_stats.get();
if nrows == 0 || ncols == 0 {
return vec![].into_iter().collect_view();
}
let iw = inner_width.get();
let ih = inner_height.get();
let cell_w = iw / ncols as f64;
let cell_h = ih / nrows as f64;
let th = theme.get();
let cm = color_map_clone.clone();
g.values
.iter()
.enumerate()
.flat_map(|(row, row_vals)| {
let cm_row = cm.clone();
let tc_row = th.text_color.clone();
row_vals
.iter()
.enumerate()
.map(move |(col, &val)| {
let t = (val - min) / range;
let fill = cm_row.map(t);
let x = col as f64 * cell_w;
let y = row as f64 * cell_h;
let label = if show_values {
Some(format!("{val:.2}"))
} else {
None
};
let font_size = (cell_h * 0.35).clamp(7.0, 12.0);
let tc = tc_row.clone();
view! {
<g
style="cursor: default;"
on:mousemove=move |ev| {
set_hover_row.set(Some(row));
set_hover_col.set(Some(col));
set_hover_x.set(ev.offset_x() as f64 - margin_left);
set_hover_y.set(ev.offset_y() as f64 - margin_top);
}
on:mouseleave=move |_| {
set_hover_row.set(None);
set_hover_col.set(None);
}
>
<rect
x=format!("{x:.2}")
y=format!("{y:.2}")
width=format!("{cell_w:.2}")
height=format!("{cell_h:.2}")
fill=fill
stroke="none"
/>
{label
.map(|lbl| {
view! {
<text
x=format!("{:.2}", x + cell_w / 2.0)
y=format!("{:.2}", y + cell_h / 2.0 + font_size * 0.35)
text-anchor="middle"
font-size=font_size
fill=tc.clone()
pointer-events="none"
>
{lbl}
</text>
}
})}
</g>
}
})
})
.collect_view()
}}
// Row axis labels (Y)
{move || {
let g = data.get();
let (nrows, _, _, _, _) = grid_stats.get();
if nrows == 0 {
return vec![].into_iter().collect_view();
}
let ih = inner_height.get();
let cell_h = ih / nrows as f64;
let th = theme.get();
(0..nrows)
.map(|row| {
let label = g
.row_labels
.as_ref()
.and_then(|l| l.get(row))
.cloned()
.unwrap_or_else(|| format!("{}", row + 1));
let y = row as f64 * cell_h + cell_h / 2.0;
view! {
<text
x="-6"
y=format!("{:.2}", y + th.axis_font_size * 0.35)
text-anchor="end"
font-size=th.axis_font_size
fill=th.text_color.clone()
>
{label}
</text>
}
})
.collect_view()
}}
// Column axis labels (X)
{move || {
let g = data.get();
let (_, ncols, _, _, _) = grid_stats.get();
if ncols == 0 {
return vec![].into_iter().collect_view();
}
let iw = inner_width.get();
let ih = inner_height.get();
let cell_w = iw / ncols as f64;
let th = theme.get();
(0..ncols)
.map(|col| {
let label = g
.col_labels
.as_ref()
.and_then(|l| l.get(col))
.cloned()
.unwrap_or_else(|| format!("{}", col + 1));
let x = col as f64 * cell_w + cell_w / 2.0;
view! {
<text
x=format!("{x:.2}")
y=format!("{:.2}", ih + 16.0)
text-anchor="middle"
font-size=th.axis_font_size
fill=th.text_color.clone()
>
{label}
</text>
}
})
.collect_view()
}}
// ColorBar
{move || {
if !show_colorbar {
return None;
}
let (_, _, min, max_v, _) = grid_stats.get();
let ih = inner_height.get();
let iw = inner_width.get();
let th = theme.get();
Some(
view! {
<g transform=format!("translate({:.2}, 0)", iw + 10.0)>
<ColorBar
color_map=color_map_colorbar.clone()
min_value=min
max_value=max_v
bar_width=14.0
height=ih
tick_count=5
text_color=th.text_color.clone()
font_size=th.axis_font_size
/>
</g>
},
)
}}
// Tooltip
<HeatmapTooltip
row_label=hover_row_label
col_label=hover_col_label
value=hover_value
x=Signal::derive(move || hover_x.get())
y=Signal::derive(move || hover_y.get())
inner_width=iw_signal
inner_height=ih_signal
tooltip_bg=Signal::derive(move || theme.get().tooltip_bg.clone())
tooltip_text=Signal::derive(move || theme.get().tooltip_text.clone())
/>
</g>
</svg>
</div>
</div>
}
}