1use ratatui::{
31 buffer::Buffer,
32 layout::Rect,
33 style::{Color, Modifier, Style},
34 widgets::Widget,
35};
36use std::cell::RefCell;
37use std::collections::BTreeSet;
38use unicode_width::UnicodeWidthStr;
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum HitKind {
43 Point,
45 Legend,
47}
48
49#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct Hit {
52 pub rect: Rect,
54 pub shape: Vec<Rect>,
57 pub kind: HitKind,
59 pub series: usize,
61 pub index: usize,
63 pub title: String,
65 pub lines: Vec<String>,
67}
68
69thread_local! {
70 static RECORDER: RefCell<Option<Vec<Hit>>> = const { RefCell::new(None) };
71}
72
73pub(crate) fn recording() -> bool {
75 RECORDER.with(|r| r.borrow().is_some())
76}
77
78pub(crate) fn record_point(
80 rect: Rect,
81 series: usize,
82 index: usize,
83 text: impl FnOnce() -> (String, Vec<String>),
84) {
85 RECORDER.with(|r| {
86 if let Some(v) = r.borrow_mut().as_mut() {
87 if rect.is_empty() {
88 return;
89 }
90 let (title, lines) = text();
91 v.push(Hit {
92 rect,
93 shape: Vec::new(),
94 kind: HitKind::Point,
95 series,
96 index,
97 title,
98 lines,
99 });
100 }
101 });
102}
103
104pub(crate) fn record_shape(
106 shape: Vec<Rect>,
107 series: usize,
108 index: usize,
109 text: impl FnOnce() -> (String, Vec<String>),
110) {
111 RECORDER.with(|r| {
112 if let Some(v) = r.borrow_mut().as_mut() {
113 let Some(first) = shape.first().copied() else {
114 return;
115 };
116 let rect = shape.iter().fold(first, |a, b| a.union(*b));
117 let (title, lines) = text();
118 v.push(Hit {
119 rect,
120 shape,
121 kind: HitKind::Point,
122 series,
123 index,
124 title,
125 lines,
126 });
127 }
128 });
129}
130
131pub(crate) fn record_grid(
135 plot: Rect,
136 grid: &[Option<usize>],
137 series_of: impl Fn(usize) -> usize,
138 text: impl Fn(usize) -> (String, Vec<String>),
139) {
140 if !recording() || plot.is_empty() {
141 return;
142 }
143 let w = usize::from(plot.width);
144 let mut shapes: std::collections::BTreeMap<usize, Vec<Rect>> =
145 std::collections::BTreeMap::new();
146 for (row, cells) in grid.chunks(w).enumerate() {
147 let mut x = 0;
148 while x < cells.len() {
149 let Some(k) = cells[x] else {
150 x += 1;
151 continue;
152 };
153 let start = x;
154 while x < cells.len() && cells[x] == Some(k) {
155 x += 1;
156 }
157 shapes.entry(k).or_default().push(Rect::new(
158 plot.x + start as u16,
159 plot.y + row as u16,
160 (x - start) as u16,
161 1,
162 ));
163 }
164 }
165 for (k, shape) in shapes {
166 record_shape(shape, series_of(k), k, || text(k));
167 }
168}
169
170pub(crate) fn record_legend(rect: Rect, series: usize, name: &str) {
172 RECORDER.with(|r| {
173 if let Some(v) = r.borrow_mut().as_mut() {
174 if rect.is_empty() {
175 return;
176 }
177 v.push(Hit {
178 rect,
179 shape: Vec::new(),
180 kind: HitKind::Legend,
181 series,
182 index: 0,
183 title: name.to_string(),
184 lines: Vec::new(),
185 });
186 }
187 });
188}
189
190#[derive(Debug, Clone, Default, PartialEq, Eq)]
192pub struct HitMap {
193 hits: Vec<Hit>,
194}
195
196impl HitMap {
197 pub fn capture(widget: impl Widget, area: Rect, buf: &mut Buffer) -> Self {
199 let prev = RECORDER.with(|r| r.borrow_mut().replace(Vec::new()));
200 widget.render(area, buf);
201 let hits = RECORDER.with(|r| std::mem::replace(&mut *r.borrow_mut(), prev));
202 Self {
203 hits: hits.unwrap_or_default(),
204 }
205 }
206
207 pub fn hits(&self) -> &[Hit] {
209 &self.hits
210 }
211
212 pub fn is_empty(&self) -> bool {
214 self.hits.is_empty()
215 }
216
217 pub fn at(&self, x: u16, y: u16) -> Option<&Hit> {
219 self.hits
220 .iter()
221 .filter(|h| h.kind == HitKind::Point && h.contains(x, y))
222 .min_by_key(|h| h.area())
223 }
224
225 pub fn legend_at(&self, x: u16, y: u16) -> Option<&Hit> {
227 self.hits
228 .iter()
229 .find(|h| h.kind == HitKind::Legend && contains(h.rect, x, y))
230 }
231
232 pub fn nearest(&self, x: u16, y: u16, reach: u16) -> Option<&Hit> {
235 let limit = u32::from(reach) * u32::from(reach);
236 self.hits
237 .iter()
238 .filter(|h| h.kind == HitKind::Point)
239 .map(|h| (h.dist2(x, y), h))
240 .filter(|(d, _)| *d <= limit)
241 .min_by_key(|(d, _)| *d)
242 .map(|(_, h)| h)
243 }
244
245 pub fn pick(&self, x: u16, y: u16) -> Option<&Hit> {
248 self.at(x, y).or_else(|| self.nearest(x, y, 2))
249 }
250}
251
252impl Hit {
253 fn rects(&self) -> &[Rect] {
254 if self.shape.is_empty() {
255 std::slice::from_ref(&self.rect)
256 } else {
257 &self.shape
258 }
259 }
260
261 fn contains(&self, x: u16, y: u16) -> bool {
262 self.rects().iter().any(|r| contains(*r, x, y))
263 }
264
265 fn area(&self) -> u32 {
266 self.rects()
267 .iter()
268 .map(|r| u32::from(r.width) * u32::from(r.height))
269 .sum()
270 }
271
272 fn dist2(&self, x: u16, y: u16) -> u32 {
273 self.rects()
274 .iter()
275 .map(|r| dist2(*r, x, y))
276 .min()
277 .unwrap_or(u32::MAX)
278 }
279}
280
281fn contains(r: Rect, x: u16, y: u16) -> bool {
282 x >= r.x && x < r.right() && y >= r.y && y < r.bottom()
283}
284
285fn dist2(r: Rect, x: u16, y: u16) -> u32 {
286 let dx = if x < r.x {
287 r.x - x
288 } else if x >= r.right() {
289 x - (r.right() - 1)
290 } else {
291 0
292 };
293 let dy = if y < r.y {
294 r.y - y
295 } else if y >= r.bottom() {
296 y - (r.bottom() - 1)
297 } else {
298 0
299 };
300 u32::from(dx) * u32::from(dx) + 4 * u32::from(dy) * u32::from(dy)
301}
302
303#[derive(Debug, Clone, Copy, PartialEq, Eq)]
305pub enum Click {
306 Toggled {
308 series: usize,
310 hidden: bool,
312 },
313 Selected {
315 series: usize,
317 index: usize,
319 },
320 Cleared,
322 Nothing,
324}
325
326#[derive(Debug, Clone, Default, PartialEq, Eq)]
328pub struct Interaction {
329 pos: Option<(u16, u16)>,
330 hidden: BTreeSet<usize>,
331 selected: Option<(usize, usize)>,
332 style: Option<Style>,
333}
334
335impl Interaction {
336 pub fn on_move(&mut self, x: u16, y: u16) {
338 self.pos = Some((x, y));
339 }
340
341 pub fn on_leave(&mut self) {
343 self.pos = None;
344 }
345
346 pub fn position(&self) -> Option<(u16, u16)> {
348 self.pos
349 }
350
351 pub fn on_click(&mut self, x: u16, y: u16, hits: &HitMap) -> Click {
353 self.pos = Some((x, y));
354 if let Some(h) = hits.legend_at(x, y) {
355 let hidden = self.toggle(h.series);
356 return Click::Toggled {
357 series: h.series,
358 hidden,
359 };
360 }
361 match hits.pick(x, y) {
362 Some(h) if self.selected == Some((h.series, h.index)) => {
363 self.selected = None;
364 Click::Cleared
365 }
366 Some(h) => {
367 self.selected = Some((h.series, h.index));
368 Click::Selected {
369 series: h.series,
370 index: h.index,
371 }
372 }
373 None if self.selected.take().is_some() => Click::Cleared,
374 None => Click::Nothing,
375 }
376 }
377
378 pub fn toggle(&mut self, series: usize) -> bool {
380 if !self.hidden.remove(&series) {
381 self.hidden.insert(series);
382 return true;
383 }
384 false
385 }
386
387 pub fn hidden(&self) -> Vec<usize> {
389 self.hidden.iter().copied().collect()
390 }
391
392 pub fn is_hidden(&self, series: usize) -> bool {
394 self.hidden.contains(&series)
395 }
396
397 pub fn reset(&mut self) {
399 self.hidden.clear();
400 self.selected = None;
401 }
402
403 pub fn selected(&self) -> Option<(usize, usize)> {
405 self.selected
406 }
407
408 #[must_use]
410 pub fn tooltip_style(mut self, style: Style) -> Self {
411 self.style = Some(style);
412 self
413 }
414
415 pub fn hovered<'a>(&self, hits: &'a HitMap) -> Option<&'a Hit> {
417 let (x, y) = self.pos?;
418 hits.pick(x, y)
419 }
420
421 pub fn render_tooltip(&self, hits: &HitMap, buf: &mut Buffer, bounds: Rect) {
424 let bounds = bounds.intersection(buf.area);
425 let selected = self.selected.and_then(|(s, i)| {
426 hits.hits
427 .iter()
428 .find(|h| h.kind == HitKind::Point && h.series == s && h.index == i)
429 });
430 for h in selected.into_iter().chain(self.hovered(hits)) {
431 for r in h.rects() {
432 highlight(buf, r.intersection(bounds));
433 }
434 }
435 let Some(h) = self.hovered(hits).or(selected) else {
436 return;
437 };
438 let (px, py) = self.pos.unwrap_or((h.rect.x, h.rect.y));
439 let mut lines: Vec<&str> = Vec::new();
440 if !h.title.is_empty() {
441 lines.push(&h.title);
442 }
443 lines.extend(h.lines.iter().map(String::as_str));
444 if lines.is_empty() || bounds.is_empty() {
445 return;
446 }
447 let w = lines
448 .iter()
449 .map(|l| UnicodeWidthStr::width(*l))
450 .max()
451 .unwrap_or(0) as u16
452 + 2;
453 let hgt = lines.len() as u16;
454 let (w, hgt) = (w.min(bounds.width), hgt.min(bounds.height));
455 let mut x = px.saturating_add(2);
456 if x + w > bounds.right() {
457 x = px.saturating_sub(w + 1).max(bounds.x);
458 }
459 let mut y = py.saturating_add(1);
460 if y + hgt > bounds.bottom() {
461 y = py.saturating_sub(hgt).max(bounds.y);
462 }
463 let x = x.clamp(bounds.x, bounds.right().saturating_sub(w));
464 let y = y.clamp(bounds.y, bounds.bottom().saturating_sub(hgt));
465 let style = self
466 .style
467 .unwrap_or_else(|| Style::default().fg(Color::White).bg(Color::DarkGray));
468 for (i, l) in lines.iter().take(usize::from(hgt)).enumerate() {
469 let row = y + i as u16;
470 for cx in x..x + w {
471 buf[(cx, row)].set_char(' ').set_style(style);
472 }
473 let st = if i == 0 && !h.title.is_empty() {
474 style.add_modifier(Modifier::BOLD)
475 } else {
476 style
477 };
478 buf.set_stringn(x + 1, row, l, usize::from(w.saturating_sub(2)), st);
479 }
480 }
481}
482
483fn highlight(buf: &mut Buffer, r: Rect) {
484 for y in r.top()..r.bottom() {
485 for x in r.left()..r.right() {
486 let c = &mut buf[(x, y)];
487 c.modifier.insert(Modifier::REVERSED);
488 }
489 }
490}
491
492#[cfg(test)]
493mod tests {
494 use super::*;
495
496 fn hm() -> HitMap {
497 let area = Rect::new(0, 0, 20, 8);
498 let mut buf = Buffer::empty(area);
499 struct W;
500 impl Widget for W {
501 fn render(self, _: Rect, _: &mut Buffer) {
502 record_point(Rect::new(2, 2, 3, 3), 0, 0, || {
503 ("a".into(), vec!["v 1".into()])
504 });
505 record_point(Rect::new(10, 2, 1, 1), 1, 4, || ("b".into(), vec![]));
506 record_legend(Rect::new(0, 7, 6, 1), 1, "b");
507 }
508 }
509 HitMap::capture(W, area, &mut buf)
510 }
511
512 #[test]
513 fn capture_collects_and_is_scoped() {
514 let h = hm();
515 assert_eq!(h.hits().len(), 3);
516 assert!(!recording());
517 assert!(!h.is_empty());
518 }
519
520 #[test]
521 fn at_nearest_pick_legend() {
522 let h = hm();
523 assert_eq!(h.at(3, 3).unwrap().series, 0);
524 assert!(h.at(8, 3).is_none());
525 assert_eq!(h.nearest(9, 2, 2).unwrap().series, 1);
526 assert!(h.nearest(15, 2, 2).is_none());
527 assert_eq!(h.pick(8, 2).unwrap().index, 4);
528 assert_eq!(h.legend_at(1, 7).unwrap().series, 1);
529 assert!(h.legend_at(1, 5).is_none());
530 }
531
532 #[test]
533 fn shapes_hit_only_their_cells() {
534 let area = Rect::new(0, 0, 10, 4);
535 let grid: Vec<Option<usize>> = (0..40)
536 .map(|i| match (i / 10, i % 10) {
537 (0, 0..=2) => Some(0),
538 (1, 1..=2) => Some(0),
539 (_, 8..=9) => Some(1),
540 _ => None,
541 })
542 .collect();
543 struct W(Vec<Option<usize>>);
544 impl Widget for W {
545 fn render(self, a: Rect, _: &mut Buffer) {
546 record_grid(a, &self.0, |k| k, |k| (format!("k{k}"), vec![]));
547 }
548 }
549 let mut buf = Buffer::empty(area);
550 let h = HitMap::capture(W(grid), area, &mut buf);
551 assert_eq!(h.hits().len(), 2);
552 assert_eq!(h.at(1, 0).unwrap().title, "k0");
553 assert!(h.at(5, 3).is_none(), "bbox corner outside the wedge");
554 assert_eq!(h.at(9, 3).unwrap().title, "k1");
555 assert_eq!(h.at(2, 1).unwrap().index, 0);
556 assert!(h.at(0, 1).is_none());
557 }
558
559 #[test]
560 fn click_selects_clears_and_toggles_legend() {
561 let h = hm();
562 let mut ui = Interaction::default();
563 assert_eq!(
564 ui.on_click(3, 3, &h),
565 Click::Selected {
566 series: 0,
567 index: 0
568 }
569 );
570 assert_eq!(ui.selected(), Some((0, 0)));
571 assert_eq!(ui.on_click(3, 3, &h), Click::Cleared);
572 assert_eq!(ui.on_click(18, 0, &h), Click::Nothing);
573 assert_eq!(
574 ui.on_click(1, 7, &h),
575 Click::Toggled {
576 series: 1,
577 hidden: true
578 }
579 );
580 assert_eq!(ui.hidden(), vec![1]);
581 assert!(ui.is_hidden(1));
582 assert_eq!(
583 ui.on_click(1, 7, &h),
584 Click::Toggled {
585 series: 1,
586 hidden: false
587 }
588 );
589 ui.on_click(3, 3, &h);
590 assert_eq!(ui.on_click(18, 0, &h), Click::Cleared);
591 ui.toggle(2);
592 ui.reset();
593 assert!(ui.hidden().is_empty() && ui.selected().is_none());
594 }
595
596 #[test]
597 fn tooltip_draws_clamped_and_highlights() {
598 let h = hm();
599 let mut buf = Buffer::empty(Rect::new(0, 0, 20, 8));
600 let mut ui = Interaction::default();
601 ui.on_move(3, 3);
602 ui.render_tooltip(&h, &mut buf, Rect::new(0, 0, 20, 8));
603 assert!(
604 buf[(3, 3)].modifier.contains(Modifier::REVERSED) || buf[(3, 4)].bg == Color::DarkGray
605 );
606 let text: String = buf.content().iter().map(|c| c.symbol()).collect();
607 assert!(text.contains('a') && text.contains("v 1"));
608 ui.on_move(19, 7);
610 let h2 = HitMap {
611 hits: vec![Hit {
612 rect: Rect::new(19, 7, 1, 1),
613 shape: vec![],
614 kind: HitKind::Point,
615 series: 0,
616 index: 0,
617 title: "wide tooltip title".into(),
618 lines: vec!["line".into()],
619 }],
620 };
621 ui.render_tooltip(&h2, &mut buf, Rect::new(0, 0, 20, 8));
622 ui.on_leave();
623 assert!(ui.position().is_none());
624 ui.render_tooltip(&h2, &mut buf, Rect::new(0, 0, 0, 0));
625 }
626}