tuika 0.9.0

The application framework for Rust terminal UIs — flexbox layout, overlays, focus, keymap, components, and safe ratatui interoperability.
Documentation
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
//! Mouse interaction over the rendered cell grid: text selection, click
//! hit-testing, and click detection.
//!
//! Terminals don't hand you selection or clickable regions — once an app
//! enables mouse capture (see [`AltScreen`](crate::host::AltScreen)) the terminal's
//! own click-drag selection stops working, and every drag arrives as a
//! [`Mouse`] event instead. This module rebuilds those affordances *on top of*
//! the grid the app already rendered:
//!
//! - [`SelectionState`] turns a left button `Down -> Drag -> Up` gesture into a
//!   [`SelectionRange`]; [`selected_text`] reads the text back out of the
//!   [`Buffer`] and [`paint_selection`] paints the selection into it. Pair with
//!   [`crate::term::clipboard::write`] to copy.
//! - [`HitMap`] maps screen regions to values so a click resolves to whatever
//!   was drawn there (a button, a link, a list row); [`ClickTracker`] turns a
//!   `Down`/`Up` pair on the same cell into a click (and lets a drag cancel it).
//!
//! Selection is *linear* (stream) like a terminal's own: a multi-row selection
//! covers the tail of the first row, all of the middle rows, and the head of
//! the last row — not a rectangular block.
//!
//! **Touch:** terminal emulators deliver touch as mouse events (a tap is a
//! `Down`+`Up`, a swipe is `ScrollUp`/`ScrollDown` or a `Drag`), so touch input
//! flows through this same path — there is no separate touch event to model.

use ratatui_core::buffer::Buffer;
use ratatui_core::layout::Rect;
use ratatui_core::style::Style;
use std::time::{Duration, Instant};

use crate::event::{Mouse, MouseButton, MouseKind};
use crate::{Clock, SystemClock};

/// A normalized text selection in reading order: `start` is at or before `end`
/// ordered by `(row, column)`. Both endpoints are inclusive cells.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SelectionRange {
    /// `(column, row)` of the first selected cell.
    pub start: (u16, u16),
    /// `(column, row)` of the last selected cell (inclusive).
    pub end: (u16, u16),
}

impl SelectionRange {
    /// Order two cells into reading order (`(row, col)` ascending).
    fn between(a: (u16, u16), b: (u16, u16)) -> Self {
        let (start, end) = if (a.1, a.0) <= (b.1, b.0) {
            (a, b)
        } else {
            (b, a)
        };
        SelectionRange { start, end }
    }

    /// The inclusive `[left, right]` selected column span on `row`, clamped to
    /// `area`. Rows outside the selection return `None`.
    fn row_span(&self, row: u16, area: Rect) -> Option<(u16, u16)> {
        if row < self.start.1 || row > self.end.1 {
            return None;
        }
        let left = if row == self.start.1 {
            self.start.0
        } else {
            area.x
        };
        let right = if row == self.end.1 {
            self.end.0
        } else {
            area.right().saturating_sub(1)
        };
        let left = left.max(area.x);
        let right = right.min(area.right().saturating_sub(1));
        (left <= right).then_some((left, right))
    }

    /// Whether `(column, row)` falls inside the selection within `area`.
    pub fn contains(&self, column: u16, row: u16, area: Rect) -> bool {
        self.row_span(row, area)
            .is_some_and(|(l, r)| column >= l && column <= r)
    }
}

/// Tracks click-drag and double-click text selection across mouse events.
///
/// Left `Down` starts (and clears any previous selection); `Drag` extends;
/// `Up` finishes. Two plain clicks on the same cell within the double-click
/// interval queue a word selection. Call [`Self::resolve`] after rendering so
/// word boundaries can be read from the current buffer.
#[derive(Clone, Copy, Debug, Default)]
pub struct SelectionState {
    anchor: (u16, u16),
    cursor: (u16, u16),
    pressed: bool,
    selecting: bool,
    last_click: Option<((u16, u16), Instant)>,
    pending_word: Option<(u16, u16)>,
}

impl SelectionState {
    /// A state with no selection in progress.
    pub fn new() -> Self {
        Self::default()
    }

    /// Feed a mouse event; returns `true` when the selection changed and a
    /// redraw is warranted.
    pub fn handle(&mut self, m: &Mouse) -> bool {
        self.handle_with_clock(m, &SystemClock)
    }

    /// Feed a mouse event using an explicit monotonic `clock`.
    ///
    /// This is behaviorally identical to [`handle`](Self::handle), but makes
    /// double-click timing deterministic in tests, replay systems, and hosts
    /// with a virtual clock.
    pub fn handle_with_clock(&mut self, m: &Mouse, clock: &dyn Clock) -> bool {
        match m.kind {
            MouseKind::Down(MouseButton::Left) => {
                self.anchor = (m.column, m.row);
                self.cursor = (m.column, m.row);
                self.pressed = true;
                let had = self.selecting;
                self.selecting = false;
                // Redraw if we cleared an existing selection.
                had
            }
            MouseKind::Drag(MouseButton::Left) if self.pressed => {
                self.cursor = (m.column, m.row);
                self.selecting = self.cursor != self.anchor;
                self.last_click = None;
                self.pending_word = None;
                true
            }
            MouseKind::Up(MouseButton::Left) if self.pressed => {
                self.cursor = (m.column, m.row);
                self.pressed = false;
                self.selecting = self.cursor != self.anchor;
                if self.selecting {
                    self.last_click = None;
                } else {
                    let position = self.cursor;
                    let now = clock.now();
                    let is_double = self.last_click.is_some_and(|(previous, at)| {
                        previous == position
                            && now.saturating_duration_since(at) <= DOUBLE_CLICK_INTERVAL
                    });
                    self.last_click = Some((position, now));
                    self.pending_word = is_double.then_some(position);
                }
                true
            }
            _ => false,
        }
    }

    /// Resolve a pending double-click against the freshly rendered buffer.
    ///
    /// Returns `true` when a word was selected. Word characters are Unicode
    /// alphanumerics plus `_`; punctuation is selected as a contiguous run.
    pub fn resolve(&mut self, buffer: &Buffer, area: Rect) -> bool {
        let Some((column, row)) = self.pending_word.take() else {
            return false;
        };
        let Some(range) = word_at(buffer, area, column, row) else {
            return false;
        };
        self.anchor = range.start;
        self.cursor = range.end;
        self.selecting = true;
        true
    }

    /// Clear the selection (e.g. on Esc or a new turn).
    pub fn clear(&mut self) {
        *self = Self::default();
    }

    /// The current selection, or `None` when nothing is selected.
    pub fn range(&self) -> Option<SelectionRange> {
        self.selecting
            .then(|| SelectionRange::between(self.anchor, self.cursor))
    }

    /// Whether a non-empty selection currently exists.
    pub fn is_active(&self) -> bool {
        self.selecting
    }
}

const DOUBLE_CLICK_INTERVAL: Duration = Duration::from_millis(500);

#[derive(Clone, Copy, PartialEq, Eq)]
enum CellClass {
    Word,
    Punctuation,
    Blank,
}

fn cell_class(buffer: &Buffer, column: u16, row: u16) -> CellClass {
    let symbol = buffer[(column, row)].symbol();
    let Some(ch) = symbol.chars().next() else {
        return CellClass::Blank;
    };
    if ch.is_whitespace() {
        CellClass::Blank
    } else if ch.is_alphanumeric() || ch == '_' {
        CellClass::Word
    } else {
        CellClass::Punctuation
    }
}

/// The word (or contiguous punctuation run) under `(column, row)` in `buffer`,
/// as an inclusive [`SelectionRange`] on that row. Word characters are Unicode
/// alphanumerics plus `_`. Returns `None` over blank cells or outside `area`.
pub fn word_at(buffer: &Buffer, area: Rect, column: u16, row: u16) -> Option<SelectionRange> {
    if !in_rect(area, column, row) {
        return None;
    }
    let class = cell_class(buffer, column, row);
    if class == CellClass::Blank {
        return None;
    }
    let mut left = column;
    while left > area.x && cell_class(buffer, left - 1, row) == class {
        left -= 1;
    }
    let mut right = column;
    while right + 1 < area.right() && cell_class(buffer, right + 1, row) == class {
        right += 1;
    }
    Some(SelectionRange::between((left, row), (right, row)))
}

/// Extract the selected text from `buffer`, reading the grid the way a terminal
/// does: the tail of the first row, whole middle rows, and the head of the last
/// row, joined with `\n`. Trailing blanks on each row are trimmed. Wide glyphs
/// come back once (their trailing spacer cell is empty in the buffer).
pub fn selected_text(buffer: &Buffer, area: Rect, sel: SelectionRange) -> String {
    let mut out = String::new();
    let mut first = true;
    for row in sel.start.1..=sel.end.1 {
        let Some((left, right)) = sel.row_span(row, area) else {
            continue;
        };
        if !first {
            out.push('\n');
        }
        first = false;
        let mut line = String::new();
        for col in left..=right {
            line.push_str(buffer[(col, row)].symbol());
        }
        out.push_str(line.trim_end_matches(' '));
    }
    out
}

/// Paint `style` over the selected cells of `buffer` (patching, so glyphs and
/// foreground survive; typically a reversed or selection-background style).
pub fn paint_selection(buffer: &mut Buffer, area: Rect, sel: SelectionRange, style: Style) {
    for row in sel.start.1..=sel.end.1 {
        let Some((left, right)) = sel.row_span(row, area) else {
            continue;
        };
        for col in left..=right {
            buffer[(col, row)].set_style(style);
        }
    }
}

/// Maps screen regions to values for click hit-testing.
///
/// Push a region per clickable thing while laying out a frame, then resolve a
/// click position to the value drawn there. Later pushes win, so registering
/// children/overlays after their parents gives the innermost/topmost region
/// precedence.
#[derive(Clone, Debug)]
pub struct HitMap<T> {
    regions: Vec<(Rect, T)>,
}

impl<T> Default for HitMap<T> {
    fn default() -> Self {
        Self {
            regions: Vec::new(),
        }
    }
}

impl<T> HitMap<T> {
    /// An empty map with no registered regions.
    pub fn new() -> Self {
        Self::default()
    }

    /// Register `value` at `area`. A zero-area rect never matches.
    pub fn push(&mut self, area: Rect, value: T) {
        self.regions.push((area, value));
    }

    /// Drop all registered regions, ready for the next frame.
    pub fn clear(&mut self) {
        self.regions.clear();
    }

    /// The value of the last-pushed region containing `(column, row)`.
    pub fn hit(&self, column: u16, row: u16) -> Option<&T> {
        self.regions
            .iter()
            .rev()
            .find(|(r, _)| in_rect(*r, column, row))
            .map(|(_, v)| v)
    }

    /// Resolve a mouse event's position through the map.
    pub fn hit_event(&self, m: &Mouse) -> Option<&T> {
        self.hit(m.column, m.row)
    }
}

fn in_rect(r: Rect, col: u16, row: u16) -> bool {
    r.width > 0 && r.height > 0 && col >= r.x && col < r.right() && row >= r.y && row < r.bottom()
}

/// A completed click: the cell and button of a `Down`/`Up` pair on one cell.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Click {
    /// Clicked cell column (0-based).
    pub column: u16,
    /// Clicked cell row (0-based).
    pub row: u16,
    /// The mouse button that was pressed and released.
    pub button: MouseButton,
}

/// Turns `Down`/`Up` mouse pairs into [`Click`]s. A press then release on the
/// *same* cell with the *same* button is a click; a drag in between cancels it
/// (that gesture is a selection, not a click). Feed every mouse event; `handle`
/// returns `Some(Click)` only on the completing `Up`.
#[derive(Clone, Copy, Debug, Default)]
pub struct ClickTracker {
    down: Option<(u16, u16, MouseButton)>,
}

impl ClickTracker {
    /// A tracker with no press pending.
    pub fn new() -> Self {
        Self::default()
    }

    /// Feed a mouse event; returns `Some(Click)` on the `Up` that completes a
    /// press/release on the same cell with the same button.
    pub fn handle(&mut self, m: &Mouse) -> Option<Click> {
        match m.kind {
            MouseKind::Down(button) => {
                self.down = Some((m.column, m.row, button));
                None
            }
            MouseKind::Drag(_) | MouseKind::Moved => {
                // Movement disqualifies the pending press from being a click.
                self.down = None;
                None
            }
            MouseKind::Up(button) => match self.down.take() {
                Some((col, row, pressed))
                    if pressed == button && col == m.column && row == m.row =>
                {
                    Some(Click {
                        column: m.column,
                        row: m.row,
                        button,
                    })
                }
                _ => None,
            },
            _ => None,
        }
    }
}

/// Tracks which [`HitMap`] region the pointer is resting on, for hover styling.
///
/// Terminals report pointer motion as [`MouseKind::Moved`] events once mouse
/// capture is on; this pairs that stream with the hit-testing the app already
/// does for clicks. Feed every mouse event to [`handle`](Self::handle) (all of
/// them carry a cell, so drags and scrolls keep the position fresh too), then
/// after pushing the frame's regions call [`resolve`](Self::resolve) — it
/// returns `true` when the hovered value changed, which is the host's cue to
/// request a redraw. During rendering, style the hot region via
/// [`hovered`](Self::hovered) or [`is`](Self::is); to *animate* the change,
/// drive an [`anim::Transition`](crate::anim::Transition) from the resolved
/// state instead of switching styles directly.
///
/// ```
/// use tuika::mouse::{HitMap, HoverTracker};
/// use tuika::{Mouse, MouseKind};
/// use tuika::ui::Rect;
///
/// let mut hits: HitMap<u8> = HitMap::new();
/// hits.push(Rect::new(0, 0, 4, 1), 1);
/// hits.push(Rect::new(4, 0, 4, 1), 2);
///
/// let mut hover = HoverTracker::new();
/// hover.handle(&Mouse::at(MouseKind::Moved, 5, 0));
/// assert!(hover.resolve(&hits));      // entered region 2 → redraw
/// assert!(hover.is(&2));
/// assert!(!hover.resolve(&hits));     // still there → nothing to do
/// ```
#[derive(Clone, Debug)]
pub struct HoverTracker<T> {
    position: Option<(u16, u16)>,
    hovered: Option<T>,
}

impl<T> Default for HoverTracker<T> {
    fn default() -> Self {
        Self {
            position: None,
            hovered: None,
        }
    }
}

impl<T: Clone + PartialEq> HoverTracker<T> {
    /// A tracker that has not seen the pointer yet.
    pub fn new() -> Self {
        Self::default()
    }

    /// Record the pointer cell from a mouse event. Returns `true` when the
    /// pointer moved to a different cell — a hint that the hover may need
    /// re-resolving, not yet a style change.
    pub fn handle(&mut self, m: &Mouse) -> bool {
        let position = Some((m.column, m.row));
        let moved = position != self.position;
        self.position = position;
        moved
    }

    /// Re-resolve the pointer against `map` (typically right after the frame's
    /// regions were pushed — regions can move under a still pointer, so this
    /// matters even without a `Moved` event). Returns `true` when the hovered
    /// value changed and a redraw is warranted.
    pub fn resolve(&mut self, map: &HitMap<T>) -> bool {
        let hovered = self
            .position
            .and_then(|(col, row)| map.hit(col, row))
            .cloned();
        let changed = hovered != self.hovered;
        self.hovered = hovered;
        changed
    }

    /// The value of the region under the pointer, per the last
    /// [`resolve`](Self::resolve).
    pub fn hovered(&self) -> Option<&T> {
        self.hovered.as_ref()
    }

    /// Whether `value`'s region is the hovered one — the per-region question a
    /// renderer asks while styling.
    pub fn is(&self, value: &T) -> bool {
        self.hovered.as_ref() == Some(value)
    }

    /// The last pointer cell, if any event has been seen.
    pub fn position(&self) -> Option<(u16, u16)> {
        self.position
    }

    /// Forget the pointer (capture disabled, focus lost, pointer left the
    /// pane). Returns `true` when that cleared an active hover.
    pub fn clear(&mut self) -> bool {
        self.position = None;
        self.hovered.take().is_some()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::components::Text;
    use crate::event::{Mouse, MouseButton, MouseKind};
    use crate::style::Theme;
    use ratatui_core::layout::Rect;
    use ratatui_core::style::{Color, Style};

    fn down(col: u16, row: u16) -> Mouse {
        Mouse::at(MouseKind::Down(MouseButton::Left), col, row)
    }
    fn drag(col: u16, row: u16) -> Mouse {
        Mouse::at(MouseKind::Drag(MouseButton::Left), col, row)
    }
    fn up(col: u16, row: u16) -> Mouse {
        Mouse::at(MouseKind::Up(MouseButton::Left), col, row)
    }

    #[test]
    fn selection_tracks_a_left_drag() {
        let mut sel = SelectionState::new();
        assert!(!sel.handle(&down(1, 0))); // fresh press: nothing to redraw yet
        assert!(sel.handle(&drag(4, 0)));
        assert!(sel.handle(&up(4, 0)));
        let range = sel.range().expect("a drag selects");
        assert_eq!(range.start, (1, 0));
        assert_eq!(range.end, (4, 0));
        assert!(sel.is_active());
    }

    #[test]
    fn selection_normalizes_a_backwards_drag() {
        let mut sel = SelectionState::new();
        sel.handle(&down(5, 1));
        sel.handle(&drag(2, 0));
        sel.handle(&up(2, 0));
        let range = sel.range().expect("selection");
        // Reading order: (col=2,row=0) comes before (col=5,row=1).
        assert_eq!(range.start, (2, 0));
        assert_eq!(range.end, (5, 1));
    }

    #[test]
    fn a_plain_click_leaves_no_selection() {
        let mut sel = SelectionState::new();
        sel.handle(&down(3, 0));
        sel.handle(&up(3, 0)); // released on the same cell, no drag
        assert!(sel.range().is_none());
        assert!(!sel.is_active());
    }

    #[test]
    fn a_new_press_clears_the_previous_selection() {
        let mut sel = SelectionState::new();
        sel.handle(&down(0, 0));
        sel.handle(&drag(3, 0));
        sel.handle(&up(3, 0));
        assert!(sel.range().is_some());
        // Pressing again to start a new gesture must drop the old selection.
        assert!(sel.handle(&down(1, 1)));
        assert!(sel.range().is_none());
    }

    #[test]
    fn double_click_selects_the_word_under_the_pointer() {
        let theme = Theme::default();
        let buf = crate::testing::render(&Text::raw("hello, brave_world!"), 19, 1, &theme);
        let mut sel = SelectionState::new();
        sel.handle(&down(9, 0));
        sel.handle(&up(9, 0));
        sel.handle(&down(9, 0));
        sel.handle(&up(9, 0));

        assert!(sel.resolve(&buf, buf.area));
        let range = sel.range().expect("double click selects a word");
        assert_eq!(range.start, (7, 0));
        assert_eq!(range.end, (17, 0));
        assert_eq!(selected_text(&buf, buf.area, range), "brave_world");
    }

    #[test]
    fn double_click_on_blank_space_does_not_select() {
        let theme = Theme::default();
        let buf = crate::testing::render(&Text::raw("hi"), 5, 1, &theme);
        let mut sel = SelectionState::new();
        sel.handle(&down(4, 0));
        sel.handle(&up(4, 0));
        sel.handle(&down(4, 0));
        sel.handle(&up(4, 0));

        assert!(!sel.resolve(&buf, buf.area));
        assert!(sel.range().is_none());
    }

    #[test]
    fn selected_text_reads_one_row() {
        let theme = Theme::default();
        let buf = crate::testing::render(&Text::raw("hello world"), 11, 1, &theme);
        let mut sel = SelectionState::new();
        sel.handle(&down(0, 0));
        sel.handle(&drag(4, 0));
        sel.handle(&up(4, 0));
        let text = selected_text(&buf, buf.area, sel.range().unwrap());
        assert_eq!(text, "hello");
    }

    #[test]
    fn selected_text_spans_rows_linearly() {
        use ratatui_core::text::Line;
        let theme = Theme::default();
        let lines = vec![Line::from("hello"), Line::from("world")];
        let buf = crate::testing::render(&Text::new(lines), 5, 2, &theme);
        let mut sel = SelectionState::new();
        // From the "llo" of row 0 through the "wo" of row 1.
        sel.handle(&down(2, 0));
        sel.handle(&drag(1, 1));
        sel.handle(&up(1, 1));
        let text = selected_text(&buf, buf.area, sel.range().unwrap());
        assert_eq!(text, "llo\nwo");
    }

    #[test]
    fn selected_text_trims_trailing_blanks() {
        let theme = Theme::default();
        let buf = crate::testing::render(&Text::raw("hi"), 10, 1, &theme);
        let mut sel = SelectionState::new();
        sel.handle(&down(0, 0));
        sel.handle(&drag(9, 0)); // drag well past the text into blank cells
        sel.handle(&up(9, 0));
        let text = selected_text(&buf, buf.area, sel.range().unwrap());
        assert_eq!(text, "hi");
    }

    #[test]
    fn highlight_patches_selected_cells_only() {
        let theme = Theme::default();
        let mut buf = crate::testing::render(&Text::raw("hello"), 5, 1, &theme);
        let area = buf.area;
        let mut sel = SelectionState::new();
        sel.handle(&down(0, 0));
        sel.handle(&drag(2, 0));
        sel.handle(&up(2, 0));
        paint_selection(
            &mut buf,
            area,
            sel.range().unwrap(),
            Style::default().bg(Color::Blue),
        );
        // Selected cells (0..=2) get the highlight bg; the glyph survives.
        for col in 0..=2 {
            assert_eq!(
                buf[(col, 0)].bg,
                Color::Blue,
                "cell {col} should be highlighted"
            );
        }
        assert_eq!(
            buf[(0, 0)].symbol(),
            "h",
            "highlight must not clobber the glyph"
        );
        // An unselected cell is untouched.
        assert_ne!(buf[(4, 0)].bg, Color::Blue);
    }

    #[test]
    fn hit_map_last_region_wins_and_misses_return_none() {
        let mut hits: HitMap<&str> = HitMap::new();
        hits.push(Rect::new(0, 0, 10, 10), "background");
        hits.push(Rect::new(2, 2, 3, 3), "panel"); // pushed later -> wins on overlap
        hits.push(Rect::new(0, 0, 0, 0), "zero"); // zero-area never matches
        assert_eq!(hits.hit(3, 3), Some(&"panel"));
        assert_eq!(hits.hit(8, 8), Some(&"background"));
        assert_eq!(hits.hit(50, 50), None);
        // hit_event resolves an event's coordinates.
        assert_eq!(hits.hit_event(&down(3, 3)), Some(&"panel"));
    }

    fn moved(col: u16, row: u16) -> Mouse {
        Mouse::at(MouseKind::Moved, col, row)
    }

    #[test]
    fn hover_tracks_enter_move_and_leave() {
        let mut hits: HitMap<&str> = HitMap::new();
        hits.push(Rect::new(0, 0, 4, 1), "left");
        hits.push(Rect::new(4, 0, 4, 1), "right");
        let mut hover: HoverTracker<&str> = HoverTracker::new();

        // Nothing seen yet: no hover, resolving changes nothing.
        assert_eq!(hover.hovered(), None);
        assert!(!hover.resolve(&hits));

        assert!(hover.handle(&moved(1, 0)));
        assert!(hover.resolve(&hits), "entering a region is a change");
        assert!(hover.is(&"left"));

        // Moving within the same region is not a style change.
        assert!(hover.handle(&moved(2, 0)));
        assert!(!hover.resolve(&hits));

        // Crossing into the neighbor is.
        hover.handle(&moved(5, 0));
        assert!(hover.resolve(&hits));
        assert!(hover.is(&"right"));
        assert!(!hover.is(&"left"));

        // Off every region: hover ends.
        hover.handle(&moved(20, 5));
        assert!(hover.resolve(&hits));
        assert_eq!(hover.hovered(), None);
    }

    #[test]
    fn hover_position_updates_from_any_event_kind() {
        let mut hover: HoverTracker<u8> = HoverTracker::new();
        assert!(hover.handle(&down(3, 1)), "a press carries the pointer too");
        assert_eq!(hover.position(), Some((3, 1)));
        assert!(!hover.handle(&up(3, 1)), "same cell: nothing moved");
        assert!(hover.handle(&drag(4, 1)));
        assert_eq!(hover.position(), Some((4, 1)));
    }

    #[test]
    fn hover_follows_regions_that_move_under_a_still_pointer() {
        let mut hover: HoverTracker<&str> = HoverTracker::new();
        hover.handle(&moved(2, 2));
        let mut hits: HitMap<&str> = HitMap::new();
        hits.push(Rect::new(0, 0, 8, 8), "panel");
        assert!(hover.resolve(&hits));
        // Next frame the layout shifted and the panel is elsewhere.
        hits.clear();
        hits.push(Rect::new(10, 10, 4, 4), "panel");
        assert!(hover.resolve(&hits), "region left the pointer");
        assert_eq!(hover.hovered(), None);
    }

    #[test]
    fn hover_clear_forgets_pointer_and_reports_the_drop() {
        let mut hits: HitMap<u8> = HitMap::new();
        hits.push(Rect::new(0, 0, 4, 1), 7);
        let mut hover: HoverTracker<u8> = HoverTracker::new();
        hover.handle(&moved(1, 0));
        hover.resolve(&hits);
        assert!(hover.clear(), "an active hover was dropped");
        assert_eq!(hover.position(), None);
        assert!(!hover.clear(), "already cleared");
    }

    #[test]
    fn click_tracker_detects_a_click() {
        let mut clicks = ClickTracker::new();
        assert!(clicks.handle(&down(4, 2)).is_none()); // press alone is not a click
        let click = clicks
            .handle(&up(4, 2))
            .expect("down+up on one cell is a click");
        assert_eq!(
            (click.column, click.row, click.button),
            (4, 2, MouseButton::Left)
        );
    }

    #[test]
    fn click_tracker_drag_cancels_the_click() {
        let mut clicks = ClickTracker::new();
        clicks.handle(&down(4, 2));
        clicks.handle(&drag(6, 2)); // moved -> this is a selection, not a click
        assert!(clicks.handle(&up(6, 2)).is_none());
    }

    #[test]
    fn click_tracker_release_on_another_cell_is_not_a_click() {
        let mut clicks = ClickTracker::new();
        clicks.handle(&down(4, 2));
        assert!(clicks.handle(&up(9, 9)).is_none());
    }
}