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, Copy, PartialEq)]
345pub struct View {
346 lo: f64,
347 hi: f64,
348 min_span: f64,
349}
350
351impl Default for View {
352 fn default() -> Self {
353 Self {
354 lo: 0.0,
355 hi: 1.0,
356 min_span: 0.02,
357 }
358 }
359}
360
361impl View {
362 #[must_use]
364 pub fn min_span(mut self, span: f64) -> Self {
365 self.min_span = span.clamp(1e-6, 1.0);
366 self
367 }
368
369 pub fn window(&self) -> (f64, f64) {
371 (self.lo, self.hi)
372 }
373
374 pub fn is_zoomed(&self) -> bool {
376 self.hi - self.lo < 1.0 - 1e-9
377 }
378
379 pub fn reset(&mut self) {
381 self.lo = 0.0;
382 self.hi = 1.0;
383 }
384
385 pub fn zoom(&mut self, anchor: f64, steps: i32) {
388 let span = self.hi - self.lo;
389 let anchor = if anchor.is_finite() {
390 anchor.clamp(0.0, 1.0)
391 } else {
392 0.5
393 };
394 let new = (span * 0.8f64.powi(steps.clamp(-50, 50))).clamp(self.min_span, 1.0);
395 let rel = ((anchor - self.lo) / span).clamp(0.0, 1.0);
397 self.lo = anchor - rel * new;
398 self.hi = self.lo + new;
399 self.clamp();
400 }
401
402 pub fn on_scroll(&mut self, x: u16, area: Rect, steps: i32) {
404 let w = f64::from(area.width.max(1));
405 let rel = (f64::from(x.saturating_sub(area.x)) + 0.5) / w;
406 let anchor = self.lo + rel.clamp(0.0, 1.0) * (self.hi - self.lo);
407 self.zoom(anchor, steps);
408 }
409
410 pub fn pan(&mut self, frac: f64) {
412 if frac.is_finite() {
413 let d = frac * (self.hi - self.lo);
414 self.lo += d;
415 self.hi += d;
416 self.clamp();
417 }
418 }
419
420 fn clamp(&mut self) {
421 let span = (self.hi - self.lo).clamp(self.min_span, 1.0);
422 self.lo = self.lo.clamp(0.0, 1.0 - span);
423 self.hi = self.lo + span;
424 }
425
426 pub fn range(&self, min: f64, max: f64) -> (f64, f64) {
428 let span = max - min;
429 (min + self.lo * span, min + self.hi * span)
430 }
431
432 pub fn indices(&self, len: usize) -> std::ops::Range<usize> {
434 if len == 0 {
435 return 0..0;
436 }
437 let a = ((self.lo * len as f64).floor() as usize).min(len - 1);
438 let b = ((self.hi * len as f64).ceil() as usize).clamp(a + 1, len);
439 a..b
440 }
441
442 pub fn slice<'a, T>(&self, data: &'a [T]) -> &'a [T] {
444 &data[self.indices(data.len())]
445 }
446}
447
448#[derive(Debug, Clone, Default, PartialEq, Eq)]
450pub struct Interaction {
451 pos: Option<(u16, u16)>,
452 hidden: BTreeSet<usize>,
453 selected: Option<(usize, usize)>,
454 style: Option<Style>,
455}
456
457impl Interaction {
458 pub fn on_move(&mut self, x: u16, y: u16) {
460 self.pos = Some((x, y));
461 }
462
463 pub fn on_leave(&mut self) {
465 self.pos = None;
466 }
467
468 pub fn position(&self) -> Option<(u16, u16)> {
470 self.pos
471 }
472
473 pub fn on_click(&mut self, x: u16, y: u16, hits: &HitMap) -> Click {
475 self.pos = Some((x, y));
476 if let Some(h) = hits.legend_at(x, y) {
477 let hidden = self.toggle(h.series);
478 return Click::Toggled {
479 series: h.series,
480 hidden,
481 };
482 }
483 match hits.pick(x, y) {
484 Some(h) if self.selected == Some((h.series, h.index)) => {
485 self.selected = None;
486 Click::Cleared
487 }
488 Some(h) => {
489 self.selected = Some((h.series, h.index));
490 Click::Selected {
491 series: h.series,
492 index: h.index,
493 }
494 }
495 None if self.selected.take().is_some() => Click::Cleared,
496 None => Click::Nothing,
497 }
498 }
499
500 pub fn toggle(&mut self, series: usize) -> bool {
502 if !self.hidden.remove(&series) {
503 self.hidden.insert(series);
504 return true;
505 }
506 false
507 }
508
509 pub fn hidden(&self) -> Vec<usize> {
511 self.hidden.iter().copied().collect()
512 }
513
514 pub fn is_hidden(&self, series: usize) -> bool {
516 self.hidden.contains(&series)
517 }
518
519 pub fn reset(&mut self) {
521 self.hidden.clear();
522 self.selected = None;
523 }
524
525 pub fn selected(&self) -> Option<(usize, usize)> {
527 self.selected
528 }
529
530 #[must_use]
532 pub fn tooltip_style(mut self, style: Style) -> Self {
533 self.style = Some(style);
534 self
535 }
536
537 pub fn hovered<'a>(&self, hits: &'a HitMap) -> Option<&'a Hit> {
539 let (x, y) = self.pos?;
540 hits.pick(x, y)
541 }
542
543 pub fn render_tooltip(&self, hits: &HitMap, buf: &mut Buffer, bounds: Rect) {
546 let bounds = bounds.intersection(buf.area);
547 let selected = self.selected.and_then(|(s, i)| {
548 hits.hits
549 .iter()
550 .find(|h| h.kind == HitKind::Point && h.series == s && h.index == i)
551 });
552 for h in selected.into_iter().chain(self.hovered(hits)) {
553 for r in h.rects() {
554 highlight(buf, r.intersection(bounds));
555 }
556 }
557 let Some(h) = self.hovered(hits).or(selected) else {
558 return;
559 };
560 let (px, py) = self.pos.unwrap_or((h.rect.x, h.rect.y));
561 let mut lines: Vec<&str> = Vec::new();
562 if !h.title.is_empty() {
563 lines.push(&h.title);
564 }
565 lines.extend(h.lines.iter().map(String::as_str));
566 if lines.is_empty() || bounds.is_empty() {
567 return;
568 }
569 let w = lines
570 .iter()
571 .map(|l| UnicodeWidthStr::width(*l))
572 .max()
573 .unwrap_or(0) as u16
574 + 2;
575 let hgt = lines.len() as u16;
576 let (w, hgt) = (w.min(bounds.width), hgt.min(bounds.height));
577 let mut x = px.saturating_add(2);
578 if x + w > bounds.right() {
579 x = px.saturating_sub(w + 1).max(bounds.x);
580 }
581 let mut y = py.saturating_add(1);
582 if y + hgt > bounds.bottom() {
583 y = py.saturating_sub(hgt).max(bounds.y);
584 }
585 let x = x.clamp(bounds.x, bounds.right().saturating_sub(w));
586 let y = y.clamp(bounds.y, bounds.bottom().saturating_sub(hgt));
587 let style = self
588 .style
589 .unwrap_or_else(|| Style::default().fg(Color::White).bg(Color::DarkGray));
590 for (i, l) in lines.iter().take(usize::from(hgt)).enumerate() {
591 let row = y + i as u16;
592 for cx in x..x + w {
593 buf[(cx, row)].set_char(' ').set_style(style);
594 }
595 let st = if i == 0 && !h.title.is_empty() {
596 style.add_modifier(Modifier::BOLD)
597 } else {
598 style
599 };
600 buf.set_stringn(x + 1, row, l, usize::from(w.saturating_sub(2)), st);
601 }
602 }
603}
604
605fn highlight(buf: &mut Buffer, r: Rect) {
606 for y in r.top()..r.bottom() {
607 for x in r.left()..r.right() {
608 let c = &mut buf[(x, y)];
609 c.modifier.insert(Modifier::REVERSED);
610 }
611 }
612}
613
614#[cfg(test)]
615mod tests {
616 use super::*;
617
618 fn hm() -> HitMap {
619 let area = Rect::new(0, 0, 20, 8);
620 let mut buf = Buffer::empty(area);
621 struct W;
622 impl Widget for W {
623 fn render(self, _: Rect, _: &mut Buffer) {
624 record_point(Rect::new(2, 2, 3, 3), 0, 0, || {
625 ("a".into(), vec!["v 1".into()])
626 });
627 record_point(Rect::new(10, 2, 1, 1), 1, 4, || ("b".into(), vec![]));
628 record_legend(Rect::new(0, 7, 6, 1), 1, "b");
629 }
630 }
631 HitMap::capture(W, area, &mut buf)
632 }
633
634 #[test]
635 fn capture_collects_and_is_scoped() {
636 let h = hm();
637 assert_eq!(h.hits().len(), 3);
638 assert!(!recording());
639 assert!(!h.is_empty());
640 }
641
642 #[test]
643 fn at_nearest_pick_legend() {
644 let h = hm();
645 assert_eq!(h.at(3, 3).unwrap().series, 0);
646 assert!(h.at(8, 3).is_none());
647 assert_eq!(h.nearest(9, 2, 2).unwrap().series, 1);
648 assert!(h.nearest(15, 2, 2).is_none());
649 assert_eq!(h.pick(8, 2).unwrap().index, 4);
650 assert_eq!(h.legend_at(1, 7).unwrap().series, 1);
651 assert!(h.legend_at(1, 5).is_none());
652 }
653
654 #[test]
655 fn shapes_hit_only_their_cells() {
656 let area = Rect::new(0, 0, 10, 4);
657 let grid: Vec<Option<usize>> = (0..40)
658 .map(|i| match (i / 10, i % 10) {
659 (0, 0..=2) => Some(0),
660 (1, 1..=2) => Some(0),
661 (_, 8..=9) => Some(1),
662 _ => None,
663 })
664 .collect();
665 struct W(Vec<Option<usize>>);
666 impl Widget for W {
667 fn render(self, a: Rect, _: &mut Buffer) {
668 record_grid(a, &self.0, |k| k, |k| (format!("k{k}"), vec![]));
669 }
670 }
671 let mut buf = Buffer::empty(area);
672 let h = HitMap::capture(W(grid), area, &mut buf);
673 assert_eq!(h.hits().len(), 2);
674 assert_eq!(h.at(1, 0).unwrap().title, "k0");
675 assert!(h.at(5, 3).is_none(), "bbox corner outside the wedge");
676 assert_eq!(h.at(9, 3).unwrap().title, "k1");
677 assert_eq!(h.at(2, 1).unwrap().index, 0);
678 assert!(h.at(0, 1).is_none());
679 }
680
681 #[test]
682 fn click_selects_clears_and_toggles_legend() {
683 let h = hm();
684 let mut ui = Interaction::default();
685 assert_eq!(
686 ui.on_click(3, 3, &h),
687 Click::Selected {
688 series: 0,
689 index: 0
690 }
691 );
692 assert_eq!(ui.selected(), Some((0, 0)));
693 assert_eq!(ui.on_click(3, 3, &h), Click::Cleared);
694 assert_eq!(ui.on_click(18, 0, &h), Click::Nothing);
695 assert_eq!(
696 ui.on_click(1, 7, &h),
697 Click::Toggled {
698 series: 1,
699 hidden: true
700 }
701 );
702 assert_eq!(ui.hidden(), vec![1]);
703 assert!(ui.is_hidden(1));
704 assert_eq!(
705 ui.on_click(1, 7, &h),
706 Click::Toggled {
707 series: 1,
708 hidden: false
709 }
710 );
711 ui.on_click(3, 3, &h);
712 assert_eq!(ui.on_click(18, 0, &h), Click::Cleared);
713 ui.toggle(2);
714 ui.reset();
715 assert!(ui.hidden().is_empty() && ui.selected().is_none());
716 }
717
718 #[test]
719 fn tooltip_draws_clamped_and_highlights() {
720 let h = hm();
721 let mut buf = Buffer::empty(Rect::new(0, 0, 20, 8));
722 let mut ui = Interaction::default();
723 ui.on_move(3, 3);
724 ui.render_tooltip(&h, &mut buf, Rect::new(0, 0, 20, 8));
725 assert!(
726 buf[(3, 3)].modifier.contains(Modifier::REVERSED) || buf[(3, 4)].bg == Color::DarkGray
727 );
728 let text: String = buf.content().iter().map(|c| c.symbol()).collect();
729 assert!(text.contains('a') && text.contains("v 1"));
730 ui.on_move(19, 7);
732 let h2 = HitMap {
733 hits: vec![Hit {
734 rect: Rect::new(19, 7, 1, 1),
735 shape: vec![],
736 kind: HitKind::Point,
737 series: 0,
738 index: 0,
739 title: "wide tooltip title".into(),
740 lines: vec!["line".into()],
741 }],
742 };
743 ui.render_tooltip(&h2, &mut buf, Rect::new(0, 0, 20, 8));
744 ui.on_leave();
745 assert!(ui.position().is_none());
746 ui.render_tooltip(&h2, &mut buf, Rect::new(0, 0, 0, 0));
747 }
748
749 #[test]
750 fn view_zoom_pan_and_slice() {
751 let mut v = View::default();
752 assert!(!v.is_zoomed());
753 v.zoom(0.5, 2);
754 let (lo, hi) = v.window();
755 assert!((hi - lo - 0.64).abs() < 1e-9 && (lo + hi - 1.0).abs() < 1e-9);
756 let mut v = View::default();
758 v.zoom(0.25, 3);
759 let (lo, hi) = v.window();
760 assert!(lo <= 0.25 && 0.25 <= hi);
761 v.pan(100.0);
762 assert_eq!(v.window().1, 1.0);
763 v.pan(f64::NAN);
764 v.zoom(f64::NAN, 1000);
765 assert!(v.window().1 - v.window().0 >= 0.02 - 1e-9);
766 v.zoom(0.5, -1000);
767 assert_eq!(v.window(), (0.0, 1.0));
768 assert_eq!(v.slice::<u8>(&[]).len(), 0);
769 assert_eq!(View::default().indices(7), 0..7);
770 let mut v = View::default().min_span(0.5);
771 v.zoom(0.5, 50);
772 assert!((5..=6).contains(&v.indices(10).len()));
773 }
774}