tuile 0.3.0

Textual-grade widgets, design system, animation and app runtime on top of ratatui
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
//! Shared vocabulary every widget speaks: event outcomes, interaction state (`Look`),
//! focus rings, hit boxes for mouse handling, and small key/mouse helpers.

use crossterm::event::{
    Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
};
use ratatui_core::layout::{Position, Rect};

// outcome

/// Result of feeding an event to a widget state.
///
/// `Ignored` → the widget did nothing, let someone else handle it.
/// `Consumed` → handled, redraw is enough (hover moved, cursor blinked, scrolled).
/// `Changed` → the *value* the widget owns changed (toggle flipped, text edited, row picked).
/// `Submitted` → the value was *committed* (Enter in a field, a row activated, a dialog
/// answered). Editing widgets report `Changed` per keystroke and `Submitted` once, so a
/// screen that writes a config on commit does not write it on the first character typed.
///
/// The order is the composition order: `|` keeps the strongest outcome of a fan-out, and
/// `is_changed()` is true for `Submitted` as well, since a commit is also a value change.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Outcome {
    #[default]
    Ignored,
    Consumed,
    Changed,
    Submitted,
}

impl Outcome {
    pub fn is_ignored(self) -> bool {
        self == Outcome::Ignored
    }
    /// Anything but `Ignored`.
    pub fn is_consumed(self) -> bool {
        self != Outcome::Ignored
    }
    /// `Changed` or `Submitted`: the value the widget owns is not what it was.
    pub fn is_changed(self) -> bool {
        self >= Outcome::Changed
    }
    /// `Submitted` only: the user committed the value (Enter, activate, answer).
    pub fn is_submitted(self) -> bool {
        self == Outcome::Submitted
    }
    /// `true` → `Changed`, `false` → `Consumed`.
    pub fn changed_if(flag: bool) -> Outcome {
        if flag {
            Outcome::Changed
        } else {
            Outcome::Consumed
        }
    }
}

impl std::ops::BitOr for Outcome {
    type Output = Outcome;
    fn bitor(self, rhs: Outcome) -> Outcome {
        self.max(rhs)
    }
}

impl std::ops::BitOrAssign for Outcome {
    fn bitor_assign(&mut self, rhs: Outcome) {
        *self = (*self).max(rhs);
    }
}

// look

/// Interaction state that drives a widget's styling (Textual `:focus`, `:hover`, `:disabled`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Look {
    pub focused: bool,
    pub hover: bool,
    pub enabled: bool,
}

impl Default for Look {
    fn default() -> Self {
        Look::PLAIN
    }
}

impl Look {
    pub const PLAIN: Look = Look {
        focused: false,
        hover: false,
        enabled: true,
    };

    pub const fn new() -> Self {
        Look::PLAIN
    }
    pub const fn focused(mut self, v: bool) -> Self {
        self.focused = v;
        self
    }
    pub const fn hover(mut self, v: bool) -> Self {
        self.hover = v;
        self
    }
    pub const fn enabled(mut self, v: bool) -> Self {
        self.enabled = v;
        self
    }
    /// Hover only counts when the widget is enabled.
    pub const fn hovering(&self) -> bool {
        self.hover && self.enabled
    }
}

// focus ring

/// Tab-order over a list of ids (any `Copy + PartialEq`, typically a small enum).
///
/// ```
/// # use tuile::core::Focus;
/// #[derive(Clone, Copy, PartialEq, Debug)] enum Id { Name, Email, Save }
/// let mut f = Focus::new([Id::Name, Id::Email, Id::Save]);
/// f.next(); assert!(f.is(Id::Email));
/// f.prev(); f.prev(); assert!(f.is(Id::Save));
/// ```
#[derive(Clone, Debug)]
pub struct Focus<T> {
    order: Vec<T>,
    current: usize,
    /// Wrap around at both ends (default `true`).
    pub wrap: bool,
}

impl<T: Copy + PartialEq> Focus<T> {
    pub fn new(order: impl Into<Vec<T>>) -> Self {
        Focus {
            order: order.into(),
            current: 0,
            wrap: true,
        }
    }

    /// Replace the tab order (e.g. when a section collapses); keeps the current id if it survives.
    pub fn set_order(&mut self, order: impl Into<Vec<T>>) {
        let cur = self.current();
        self.order = order.into();
        self.current = cur
            .and_then(|c| self.order.iter().position(|&x| x == c))
            .unwrap_or(0);
    }

    pub fn order(&self) -> &[T] {
        &self.order
    }

    pub fn current(&self) -> Option<T> {
        self.order.get(self.current).copied()
    }

    pub fn is(&self, id: T) -> bool {
        self.current() == Some(id)
    }

    pub fn set(&mut self, id: T) -> bool {
        match self.order.iter().position(|&x| x == id) {
            Some(i) => {
                self.current = i;
                true
            }
            None => false,
        }
    }

    pub fn index(&self) -> usize {
        self.current
    }

    pub fn set_index(&mut self, i: usize) {
        if !self.order.is_empty() {
            self.current = i.min(self.order.len() - 1);
        }
    }

    pub fn next(&mut self) {
        self.step(1);
    }

    pub fn prev(&mut self) {
        self.step(-1);
    }

    fn step(&mut self, d: i32) {
        let n = self.order.len() as i32;
        if n == 0 {
            return;
        }
        let next = self.current as i32 + d;
        self.current = if self.wrap {
            next.rem_euclid(n)
        } else {
            next.clamp(0, n - 1)
        } as usize;
    }

    /// `Tab` / `Shift+Tab` navigation; returns `Consumed` when the key was one of those.
    pub fn handle_key(&mut self, key: KeyEvent) -> Outcome {
        match key.code {
            KeyCode::Tab => {
                self.next();
                Outcome::Consumed
            }
            KeyCode::BackTab => {
                self.prev();
                Outcome::Consumed
            }
            _ => Outcome::Ignored,
        }
    }
}

// mouse

pub fn mouse_pos(m: &MouseEvent) -> Position {
    Position {
        x: m.column,
        y: m.row,
    }
}

pub fn mouse_in(area: Rect, m: &MouseEvent) -> bool {
    area.contains(mouse_pos(m))
}

pub fn is_left_down(m: &MouseEvent) -> bool {
    m.kind == MouseEventKind::Down(MouseButton::Left)
}

pub fn is_left_up(m: &MouseEvent) -> bool {
    m.kind == MouseEventKind::Up(MouseButton::Left)
}

pub fn is_left_drag(m: &MouseEvent) -> bool {
    m.kind == MouseEventKind::Drag(MouseButton::Left)
}

pub fn is_move(m: &MouseEvent) -> bool {
    m.kind == MouseEventKind::Moved
}

/// `+1` for wheel down, `-1` for wheel up, `None` otherwise.
pub fn wheel_delta(m: &MouseEvent) -> Option<i32> {
    match m.kind {
        MouseEventKind::ScrollDown => Some(1),
        MouseEventKind::ScrollUp => Some(-1),
        _ => None,
    }
}

/// What a [`HitBox`] observed for one mouse event.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Hit {
    None,
    /// Pointer entered or left the box (hover flag flipped).
    HoverChanged,
    /// Left button pressed inside.
    Press,
    /// Left button dragged while pressed here.
    Drag,
    /// Left button released inside after a press inside: a click.
    Click,
    /// Press was cancelled (released outside).
    Cancel,
    /// Mouse wheel over the box, `+1` down / `-1` up.
    Wheel(i32),
}

/// Hover/press tracker for one rectangle. Store it in a widget state, call
/// [`HitBox::set_area`] on render and [`HitBox::mouse`] on every mouse event.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct HitBox {
    pub area: Rect,
    pub hover: bool,
    pub pressed: bool,
}

impl HitBox {
    pub fn set_area(&mut self, area: Rect) {
        self.area = area;
    }

    pub fn contains(&self, m: &MouseEvent) -> bool {
        mouse_in(self.area, m)
    }

    pub fn mouse(&mut self, m: &MouseEvent) -> Hit {
        let inside = self.contains(m);
        match m.kind {
            MouseEventKind::Moved => {
                if inside != self.hover {
                    self.hover = inside;
                    Hit::HoverChanged
                } else {
                    Hit::None
                }
            }
            MouseEventKind::Down(MouseButton::Left) => {
                let was = self.hover;
                self.hover = inside;
                if inside {
                    self.pressed = true;
                    Hit::Press
                } else if was {
                    Hit::HoverChanged
                } else {
                    Hit::None
                }
            }
            MouseEventKind::Drag(MouseButton::Left) => {
                if self.pressed {
                    Hit::Drag
                } else if inside != self.hover {
                    self.hover = inside;
                    Hit::HoverChanged
                } else {
                    Hit::None
                }
            }
            MouseEventKind::Up(MouseButton::Left) => {
                if self.pressed {
                    self.pressed = false;
                    if inside { Hit::Click } else { Hit::Cancel }
                } else {
                    Hit::None
                }
            }
            MouseEventKind::ScrollDown if inside => Hit::Wheel(1),
            MouseEventKind::ScrollUp if inside => Hit::Wheel(-1),
            _ => Hit::None,
        }
    }

    /// Current interaction look, combined with an externally-owned focus flag.
    pub fn look(&self, focused: bool, enabled: bool) -> Look {
        Look {
            focused,
            hover: self.hover,
            enabled,
        }
    }
}

// keys

/// Key presses only (crossterm may also report repeats/releases with the kitty protocol).
pub fn is_press(k: &KeyEvent) -> bool {
    k.kind != KeyEventKind::Release
}

pub fn ctrl(k: &KeyEvent, c: char) -> bool {
    k.modifiers.contains(KeyModifiers::CONTROL) && k.code == KeyCode::Char(c)
}

pub fn alt(k: &KeyEvent, c: char) -> bool {
    k.modifiers.contains(KeyModifiers::ALT) && k.code == KeyCode::Char(c)
}

pub fn plain_char(k: &KeyEvent) -> Option<char> {
    match k.code {
        KeyCode::Char(c)
            if !k
                .modifiers
                .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) =>
        {
            Some(c)
        }
        _ => None,
    }
}

/// `Enter` or `Space`, the universal "activate" keys.
pub fn is_activate(k: &KeyEvent) -> bool {
    matches!(k.code, KeyCode::Enter | KeyCode::Char(' '))
}

/// Human-readable key label for footers/help (`^S`, `⇧Tab`, `F5`, `Esc`).
pub fn key_label(k: &KeyEvent) -> String {
    let mut s = String::new();
    if k.modifiers.contains(KeyModifiers::CONTROL) {
        s.push('^');
    }
    if k.modifiers.contains(KeyModifiers::ALT) {
        s.push_str("Alt+");
    }
    if k.modifiers.contains(KeyModifiers::SHIFT)
        && !matches!(k.code, KeyCode::Char(_) | KeyCode::BackTab)
    {
        s.push('⇧');
    }
    match k.code {
        KeyCode::Char(' ') => s.push_str("Space"),
        KeyCode::Char(c) => s.push(c),
        KeyCode::F(n) => s.push_str(&format!("F{n}")),
        KeyCode::Esc => s.push_str("Esc"),
        KeyCode::Enter => s.push_str("Enter"),
        KeyCode::BackTab => s.push_str("⇧Tab"),
        KeyCode::Tab => s.push_str("Tab"),
        KeyCode::Backspace => s.push_str("Bksp"),
        KeyCode::Up => s.push('↑'),
        KeyCode::Down => s.push('↓'),
        KeyCode::Left => s.push('←'),
        KeyCode::Right => s.push('→'),
        KeyCode::PageUp => s.push_str("PgUp"),
        KeyCode::PageDown => s.push_str("PgDn"),
        other => s.push_str(&format!("{other:?}")),
    }
    s
}

/// Widgets with state implement this so apps can forward raw events with one call.
pub trait Interactive {
    fn handle_key(&mut self, _key: KeyEvent) -> Outcome {
        Outcome::Ignored
    }
    fn handle_mouse(&mut self, _m: MouseEvent) -> Outcome {
        Outcome::Ignored
    }
    fn handle(&mut self, ev: &Event) -> Outcome {
        match ev {
            Event::Key(k) if is_press(k) => self.handle_key(*k),
            Event::Mouse(m) => self.handle_mouse(*m),
            _ => Outcome::Ignored,
        }
    }
}

// minimum size

/// The smallest area a widget draws in. Layout code can allocate from it, and `render` uses
/// [`crate::draw::refuse`] to guard and visibly mark when the area is too small.
///
/// ```
/// # use tuile::prelude::*;
/// struct MyWidget { /* config */ }
/// impl MinSize for MyWidget {
///     fn min_size(&self) -> (u16, u16) { (10, 2) }
/// }
/// ```
pub trait MinSize {
    /// `(width, height)` in cells, for this builder's current configuration.
    fn min_size(&self) -> (u16, u16);
}
// text navigation

/// Index of the next word boundary from `pos`, the rule behind Ctrl+Left / Ctrl+Right.
///
/// Forward: skip any run of non-alphanumerics, then the word itself, landing after it.
/// Backward: the mirror, landing on the word's first grapheme. Both saturate at the ends.
/// Shared by `Input` and `TextArea` so the two widgets cannot drift apart.
pub fn word_boundary(graphemes: &[&str], pos: usize, forward: bool) -> usize {
    let alnum = |g: &str| g.chars().all(char::is_alphanumeric);
    let len = graphemes.len();
    if forward {
        let mut i = pos;
        while i < len && !alnum(graphemes[i]) {
            i += 1;
        }
        while i < len && alnum(graphemes[i]) {
            i += 1;
        }
        i
    } else {
        let mut i = pos.saturating_sub(1);
        while i > 0 && !alnum(graphemes[i]) {
            i = i.saturating_sub(1);
        }
        while i > 0 && alnum(graphemes[i.saturating_sub(1)]) {
            i = i.saturating_sub(1);
        }
        i
    }
}
// highlighting

/// Syntax highlighting function: returns styled ranges as half-open grapheme offsets.
///
/// Each `(start, end, Style)` tuple marks a range `[start..end)` of grapheme cluster indices
/// (as walked by `line.graphemes(true)`). Ranges must be ascending and non-overlapping.
/// Text not covered by any range keeps the caller's base style. Out-of-bounds, overlapping,
/// or descending ranges are ignored (the helper never panics).
pub type Highlighter = fn(&str) -> Vec<(usize, usize, ratatui_core::style::Style)>;

#[cfg(test)]
mod tests {
    use super::*;

    fn me(kind: MouseEventKind, x: u16, y: u16) -> MouseEvent {
        MouseEvent {
            kind,
            column: x,
            row: y,
            modifiers: KeyModifiers::NONE,
        }
    }

    #[test]
    fn hitbox_click_requires_press_and_release_inside() {
        let mut h = HitBox {
            area: Rect::new(5, 5, 10, 3),
            ..Default::default()
        };
        assert_eq!(h.mouse(&me(MouseEventKind::Moved, 6, 6)), Hit::HoverChanged);
        assert_eq!(h.mouse(&me(MouseEventKind::Moved, 7, 6)), Hit::None);
        assert_eq!(
            h.mouse(&me(MouseEventKind::Down(MouseButton::Left), 7, 6)),
            Hit::Press
        );
        assert_eq!(
            h.mouse(&me(MouseEventKind::Up(MouseButton::Left), 40, 40)),
            Hit::Cancel
        );
        h.mouse(&me(MouseEventKind::Down(MouseButton::Left), 7, 6));
        assert_eq!(
            h.mouse(&me(MouseEventKind::Up(MouseButton::Left), 8, 7)),
            Hit::Click
        );
        assert_eq!(h.mouse(&me(MouseEventKind::Moved, 0, 0)), Hit::HoverChanged);
        assert!(!h.hover);
    }

    #[test]
    fn outcome_combines_upwards() {
        assert_eq!(Outcome::Ignored | Outcome::Consumed, Outcome::Consumed);
        assert_eq!(Outcome::Changed | Outcome::Consumed, Outcome::Changed);
        let mut o = Outcome::Ignored;
        o |= Outcome::Changed;
        assert!(o.is_changed());
    }

    #[test]
    fn focus_wraps_and_survives_reorder() {
        let mut f = Focus::new(['a', 'b', 'c']);
        f.prev();
        assert!(f.is('c'));
        f.set_order(['c', 'd']);
        assert!(f.is('c'));
        f.wrap = false;
        f.next();
        f.next();
        assert!(f.is('d'));
    }

    #[test]
    fn word_boundary_crosses_punctuation_and_stops_at_the_ends() {
        // graphemes of "one, two"
        let g = ["o", "n", "e", ",", " ", "t", "w", "o"];
        // forward from inside the first word lands past it, then past the second
        assert_eq!(word_boundary(&g, 0, true), 3);
        assert_eq!(word_boundary(&g, 3, true), 8);
        // backward from the end lands on the second word's first grapheme, then the first's
        assert_eq!(word_boundary(&g, 8, false), 5);
        assert_eq!(word_boundary(&g, 5, false), 0);
        // both directions saturate rather than run off the ends
        assert_eq!(word_boundary(&g, 8, true), 8);
        assert_eq!(word_boundary(&g, 0, false), 0);
        assert_eq!(word_boundary(&[], 0, true), 0);
    }
}