tui-lipan 0.1.0

Opinionated, component-based TUI framework for Rust - declarative components, reconciliation, layout engine, focus, overlays, and rich widgets 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
//! Terminal output view helpers.

mod buffer;
mod events;
mod layout;
mod mod_private;
mod node;
mod pty;
mod reconcile;
mod screen;

pub use buffer::TerminalBuffer;
pub use events::{
    MouseEncoding, MouseMode, MouseModeState, TerminalInputEvent, TerminalInputKind,
    TerminalSelection, TerminalSelectionEvent, focus_sequences, key_event_to_bytes,
    mouse_event_to_bytes, paste_sequences, terminal_selection_text, wrap_bracketed_paste,
};
pub use mod_private::Terminal;
pub use pty::{TerminalPty, TerminalPtyConfig, TerminalPtyError, TerminalPtyEvent};
pub use screen::{TerminalColorPalette, TerminalRenderSnapshot, TerminalScreen, TerminalViewport};

pub(crate) use layout::{measure_terminal, terminal_content_layout, terminal_mouse_content_rect};
pub(crate) use node::TerminalNode;
pub(crate) use reconcile::reconcile_terminal;

use crate::callback::{Callback, KeyHandler};
use crate::core::element::{Element, ElementKind};
use crate::style::{
    BorderStyle, Length, Padding, ScrollbarConfig, ScrollbarVariant, Span, Style, StyleSlot,
};
use crate::widgets::ScrollEvent;
use std::sync::Arc;

impl Default for Terminal {
    fn default() -> Self {
        Self {
            content: Arc::from(""),
            cursor_row: 0,
            cursor_col: 0,
            show_cursor: true,
            color_lines: None,
            color_cache_key: 0,
            scrollback_offset: 0,
            total_scrollback_rows: 0,
            mouse_mode: MouseModeState::default(),
            selection: None,
            selection_controlled: false,
            selection_style: StyleSlot::Inherit,
            on_selection: None,
            on_resize: None,
            on_mouse_forward: None,
            scroll_wheel: true,
            on_scroll: None,
            on_scroll_to: None,
            style: Style::default(),
            hover_style: StyleSlot::Inherit,
            focus_style: StyleSlot::Inherit,
            focus_content_style: Style::default(),
            border: false,
            border_style: BorderStyle::default(),
            padding: Padding::default(),
            scrollbar: true,
            scrollbar_variant: ScrollbarVariant::default(),
            scrollbar_gap: 0,
            scrollbar_thumb: None,
            scrollbar_thumb_style: None,
            scrollbar_thumb_focus_style: None,
            scrollbar_track_style: None,
            h_scrollbar: true,
            h_scrollbar_variant: ScrollbarVariant::default(),
            width: Length::Flex(1),
            height: Length::Flex(1),
            focusable: true,
            on_key: None,
            on_input: None,
        }
    }
}

impl Terminal {
    /// Create an empty terminal view.
    pub fn new() -> Self {
        Self::default()
    }

    /// Replace visible content.
    pub fn content(mut self, content: impl Into<Arc<str>>) -> Self {
        self.content = content.into();
        self
    }

    /// Set cursor byte position in content.
    pub fn cursor(mut self, cursor: usize) -> Self {
        let (row, col) = byte_to_row_col(self.content.as_ref(), cursor);
        self.cursor_row = row;
        self.cursor_col = col;
        self
    }

    /// Set cursor row/column in the visible viewport.
    pub fn cursor_position(mut self, row: u16, col: u16) -> Self {
        self.cursor_row = row;
        self.cursor_col = col;
        self
    }

    /// Toggle cursor rendering.
    pub fn show_cursor(mut self, show_cursor: bool) -> Self {
        self.show_cursor = show_cursor;
        self
    }

    /// Set precomputed colored lines (must match `content` line lengths).
    pub fn color_lines(mut self, color_lines: Arc<[Vec<Span>]>, cache_key: u64) -> Self {
        self.color_lines = Some(color_lines);
        self.color_cache_key = cache_key;
        self
    }

    /// Apply a full terminal render snapshot.
    pub fn snapshot(mut self, snapshot: TerminalRenderSnapshot) -> Self {
        self.content = snapshot.text;
        self.cursor_row = snapshot.cursor_row;
        self.cursor_col = snapshot.cursor_col;
        self.show_cursor = snapshot.cursor_visible;
        self.color_lines = Some(snapshot.color_lines);
        self.color_cache_key = snapshot.sequence;
        self.scrollback_offset = snapshot.scrollback_offset;
        self.total_scrollback_rows = snapshot.total_scrollback_rows;
        self.mouse_mode = snapshot.mouse_mode;
        self
    }

    /// Set base style.
    pub fn style(mut self, style: Style) -> Self {
        self.style = style;
        self
    }

    /// Set hover style.
    pub fn hover_style(mut self, style: Style) -> Self {
        self.hover_style = StyleSlot::Replace(style);
        self
    }

    /// Extend the active theme's hover style with additional fields.
    pub fn extend_hover_style(mut self, style: Style) -> Self {
        self.hover_style = StyleSlot::Extend(style);
        self
    }

    /// Inherit hover style from the active theme.
    pub fn inherit_hover_style(mut self) -> Self {
        self.hover_style = StyleSlot::Inherit;
        self
    }

    /// Set hover style slot directly for composite forwarding.
    pub fn hover_style_slot(mut self, slot: StyleSlot) -> Self {
        self.hover_style = slot;
        self
    }

    /// Set focus chrome style.
    pub fn focus_style(mut self, style: Style) -> Self {
        self.focus_style = StyleSlot::Replace(style);
        self
    }

    /// Extend the active theme's focus style with additional fields.
    pub fn extend_focus_style(mut self, style: Style) -> Self {
        self.focus_style = StyleSlot::Extend(style);
        self
    }

    /// Inherit focus style from the active theme.
    pub fn inherit_focus_style(mut self) -> Self {
        self.focus_style = StyleSlot::Inherit;
        self
    }

    /// Set focus style slot directly for composite forwarding.
    pub fn focus_style_slot(mut self, slot: StyleSlot) -> Self {
        self.focus_style = slot;
        self
    }

    /// Set focused content text style.
    pub fn focus_content_style(mut self, style: Style) -> Self {
        self.focus_content_style = style;
        self
    }

    /// Toggle border.
    pub fn border(mut self, border: bool) -> Self {
        self.border = border;
        self
    }

    /// Set border style.
    pub fn border_style(mut self, border_style: BorderStyle) -> Self {
        self.border_style = border_style;
        self
    }

    /// Set inner padding.
    pub fn padding(mut self, padding: impl Into<Padding>) -> Self {
        self.padding = padding.into();
        self
    }

    /// Toggle vertical scrollbar.
    pub fn scrollbar(mut self, scrollbar: bool) -> Self {
        self.scrollbar = scrollbar;
        self
    }

    /// Set scrollbar configuration.
    pub fn scrollbar_config(mut self, config: ScrollbarConfig) -> Self {
        self.scrollbar_variant = config.variant;
        self.scrollbar_gap = config.gap;
        self.scrollbar_thumb = config.thumb;
        self.scrollbar_thumb_style = config.thumb_style;
        self.scrollbar_thumb_focus_style = config.thumb_focus_style;
        self.scrollbar_track_style = config.track_style;
        self
    }

    /// Toggle horizontal scrollbar.
    pub fn h_scrollbar(mut self, h_scrollbar: bool) -> Self {
        self.h_scrollbar = h_scrollbar;
        self
    }

    /// Set horizontal scrollbar style.
    pub fn h_scrollbar_variant(mut self, style: ScrollbarVariant) -> Self {
        self.h_scrollbar_variant = style;
        self
    }

    /// Toggle mouse wheel scrolling through scrollback history.
    pub fn scroll_wheel(mut self, scroll_wheel: bool) -> Self {
        self.scroll_wheel = scroll_wheel;
        self
    }

    /// Set callback for scroll events with full metrics.
    pub fn on_scroll(mut self, cb: Callback<ScrollEvent>) -> Self {
        self.on_scroll = Some(cb);
        self
    }

    /// Set callback emitting the new scrollback offset on scroll.
    ///
    /// The offset is in scrollback rows: 0 = live (bottom), positive
    /// values = scrolled into history. Use this to call
    /// `TerminalScreen::set_scrollback(offset)` in your component.
    pub fn on_scroll_to(mut self, cb: Callback<usize>) -> Self {
        self.on_scroll_to = Some(cb);
        self
    }

    /// Set selection highlight style.
    pub fn selection_style(mut self, style: Style) -> Self {
        self.selection_style = StyleSlot::Replace(style);
        self
    }

    /// Extend the active theme's selection style with additional fields.
    pub fn extend_selection_style(mut self, style: Style) -> Self {
        self.selection_style = StyleSlot::Extend(style);
        self
    }

    /// Inherit selection style from the active theme.
    pub fn inherit_selection_style(mut self) -> Self {
        self.selection_style = StyleSlot::Inherit;
        self
    }

    /// Set selection style slot directly for composite forwarding.
    pub fn selection_style_slot(mut self, slot: StyleSlot) -> Self {
        self.selection_style = slot;
        self
    }

    /// Set current selection.
    pub fn selection(mut self, selection: Option<TerminalSelection>) -> Self {
        self.selection = selection;
        self.selection_controlled = true;
        self
    }

    /// Set selection change callback.
    pub fn on_selection(mut self, cb: Callback<TerminalSelectionEvent>) -> Self {
        self.on_selection = Some(cb);
        self
    }

    /// Set callback fired when the terminal viewport size changes.
    pub fn on_resize(mut self, cb: Callback<TerminalViewport>) -> Self {
        self.on_resize = Some(cb);
        self
    }

    /// Set callback to forward mouse bytes to PTY.
    pub fn on_mouse_forward(mut self, cb: Callback<Vec<u8>>) -> Self {
        self.on_mouse_forward = Some(cb);
        self
    }

    /// Set width.
    pub fn width(mut self, width: Length) -> Self {
        self.width = width;
        self
    }

    /// Set height.
    pub fn height(mut self, height: Length) -> Self {
        self.height = height;
        self
    }

    /// Control focusability.
    pub fn focusable(mut self, focusable: bool) -> Self {
        self.focusable = focusable;
        self
    }

    /// Set raw key handler.
    pub fn on_key(mut self, handler: KeyHandler) -> Self {
        self.on_key = Some(handler);
        self
    }

    /// Set callback for terminal-encoded key input.
    pub fn on_input(mut self, cb: Callback<TerminalInputEvent>) -> Self {
        self.on_input = Some(cb);
        self
    }
}

impl From<Terminal> for Element {
    fn from(mut terminal: Terminal) -> Self {
        let on_input = terminal.on_input.clone();
        let fallback_on_key = terminal.on_key.clone();
        terminal.on_key = if on_input.is_some() || fallback_on_key.is_some() {
            Some(KeyHandler::new(move |key| {
                let mut handled = false;

                if let Some(on_input) = on_input.as_ref()
                    && let Some(bytes) = key_event_to_bytes(key)
                {
                    on_input.emit(TerminalInputEvent {
                        kind: TerminalInputKind::Key,
                        key: Some(key),
                        bytes: bytes.into(),
                    });
                    handled = true;
                }

                if let Some(handler) = fallback_on_key.as_ref() {
                    handled = handler.handle(key) || handled;
                }

                handled
            }))
        } else {
            None
        };

        Element::new(ElementKind::Terminal(terminal))
    }
}

fn byte_to_row_col(value: &str, cursor: usize) -> (u16, u16) {
    let cursor = cursor.min(value.len());
    let mut row = 0u16;
    let mut col = 0u16;
    let mut seen = 0usize;

    for ch in value.chars() {
        if seen >= cursor {
            break;
        }
        seen = seen.saturating_add(ch.len_utf8());
        if ch == '\n' {
            row = row.saturating_add(1);
            col = 0;
        } else {
            col = col.saturating_add(1);
        }
    }

    (row, col)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::event::{KeyCode, KeyEvent, KeyMods, MouseButton, MouseEvent, MouseKind};

    #[test]
    fn ctrl_mapping_works() {
        let key = KeyEvent {
            code: KeyCode::Char('c'),
            mods: KeyMods {
                ctrl: true,
                ..KeyMods::default()
            },
        };
        assert_eq!(key_event_to_bytes(key), Some(vec![3]));
    }

    #[test]
    fn alt_prefixes_escape() {
        let key = KeyEvent {
            code: KeyCode::Char('x'),
            mods: KeyMods {
                alt: true,
                ..KeyMods::default()
            },
        };
        assert_eq!(key_event_to_bytes(key), Some(vec![0x1b, b'x']));
    }

    #[test]
    fn terminal_buffer_trims_lines() {
        let mut buffer = TerminalBuffer::new(2);
        buffer.push_text("a\nb\nc\n");
        let snapshot = buffer.snapshot();
        assert_eq!(snapshot.as_ref(), "b\nc");
    }

    #[test]
    fn terminal_screen_applies_vt_sequences() {
        let mut screen = TerminalScreen::new(4, 20, 128);
        screen.process_bytes(b"\x1b[31mhello\x1b[0m\nworld");
        let snapshot = screen.snapshot();
        let mut lines = snapshot.lines().map(str::trim);
        assert_eq!(lines.next(), Some("hello"));
        assert_eq!(lines.next(), Some("world"));
    }

    #[test]
    fn mouse_event_to_bytes_sgr_encodes_coordinates() {
        let event = MouseEvent {
            x: 2,
            y: 3,
            kind: MouseKind::Down(MouseButton::Left),
            mods: KeyMods::default(),
        };
        use super::events::MouseEncoding;

        let bytes = mouse_event_to_bytes(event, MouseEncoding::Sgr, (0, 0)).expect("mouse bytes");
        assert_eq!(String::from_utf8(bytes).unwrap(), "\u{1b}[<0;3;4M");
    }

    #[test]
    fn mouse_event_to_bytes_sgr_encodes_plain_motion() {
        // Any-event tracking (1003) reports motion without a pressed button as
        // code 35 (3 "no button" + 32 motion flag). Dropping these leaves apps
        // in the pane without hover positions.
        let event = MouseEvent {
            x: 26,
            y: 5,
            kind: MouseKind::Moved,
            mods: KeyMods::default(),
        };
        use super::events::MouseEncoding;

        let bytes = mouse_event_to_bytes(event, MouseEncoding::Sgr, (0, 0)).expect("mouse bytes");
        assert_eq!(String::from_utf8(bytes).unwrap(), "\u{1b}[<35;27;6M");
    }

    #[test]
    fn grid_selection_extracts_text() {
        use crate::utils::{GridPos, GridSelection};
        let selection = GridSelection {
            anchor: GridPos { row: 0, col: 1 },
            cursor: GridPos { row: 1, col: 2 },
        };
        let lines = vec!["abcd", "efgh", "ijkl"];
        assert_eq!(selection.extract_text(&lines), "bcd\nef");
    }
}