tuika 0.4.0

A composable terminal UI toolkit — flexbox layout, overlays, focus, and safe ratatui interoperability.
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
//! 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::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 [`highlight`] paints the selection into it. Pair with
//!   [`crate::clipboard::write_clipboard`] 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};

/// 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 {
        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 = Instant::now();
                    let is_double = self.last_click.is_some_and(|(previous, at)| {
                        previous == position && now.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 highlight(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,
        }
    }
}

#[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));
        highlight(
            &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"));
    }

    #[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());
    }
}