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
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
#[cfg(not(target_arch = "wasm32"))]
use crate::app::runner::AppRunner;
use crate::clipboard::{ClipboardConfig, ClipboardError, ClipboardProvider, ClipboardReporter};
#[cfg(not(target_arch = "wasm32"))]
use crate::core::component::Component;
use crate::overlay::ToastPlacement;
use crate::style::Padding;
use crate::style::{Color, Paint, Style, Theme};
use std::path::PathBuf;

/// How the app occupies terminal space.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) enum ViewportMode {
    /// Take over the full terminal using the alternate screen.
    #[default]
    Fullscreen,
    /// Render inline at the current cursor position with a fixed viewport height.
    Inline { height: u16 },
}

/// Startup behavior for transcript inline mode.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum InlineStartupPolicy {
    /// Preserve host terminal content above the inline viewport.
    #[default]
    PreserveHost,
    /// Clear the host terminal before the first inline render.
    ClearHost,
}

/// Public surface mode taxonomy for app rendering.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SurfaceMode {
    /// Take over the full terminal using the alternate screen.
    #[default]
    Fullscreen,
    /// Inline viewport intended for ephemeral UI sessions.
    InlineEphemeral {
        /// Requested inline viewport height.
        height: u16,
    },
    /// Inline viewport intended for transcript-friendly sessions.
    InlineTranscript {
        /// Requested inline viewport height.
        height: u16,
        /// Startup behavior for the host terminal.
        startup: InlineStartupPolicy,
    },
}

impl SurfaceMode {
    pub(crate) fn is_inline(&self) -> bool {
        !matches!(self, Self::Fullscreen)
    }

    pub(crate) fn normalized(self) -> Self {
        match self {
            Self::Fullscreen => Self::Fullscreen,
            Self::InlineEphemeral { height } => Self::InlineEphemeral {
                height: height.max(1),
            },
            Self::InlineTranscript { height, startup } => Self::InlineTranscript {
                height: height.max(1),
                startup,
            },
        }
    }

    pub(crate) fn viewport_mode(self) -> ViewportMode {
        match self.normalized() {
            Self::Fullscreen => ViewportMode::Fullscreen,
            Self::InlineEphemeral { height } | Self::InlineTranscript { height, .. } => {
                ViewportMode::Inline { height }
            }
        }
    }

    pub(crate) fn clear_on_start(self) -> bool {
        matches!(
            self,
            Self::InlineTranscript {
                startup: InlineStartupPolicy::ClearHost,
                ..
            }
        )
    }
}

/// Controls which Enter key combinations insert new lines in `TextArea`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TextAreaNewlineBinding {
    /// Use plain Enter.
    #[default]
    Enter,
    /// Use Shift+Enter only.
    ShiftEnter,
    /// Accept both Enter and Shift+Enter.
    EnterOrShiftEnter,
}

/// Controls automatic foreground contrast adjustments for widget text.
#[cfg_attr(
    feature = "terminal-serde",
    derive(serde::Serialize, serde::Deserialize)
)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ContrastPolicy {
    /// Keep user-provided foreground colors unchanged.
    Off,
    /// Auto-adjust foreground on colored backgrounds when contrast is too low
    /// using WCAG 2.1 contrast ratio (AA normal text: >= 4.5:1).
    #[default]
    Wcag,
    /// Keep the current foreground when it is readable under WCAG 2.1;
    /// otherwise snap to black or white, whichever has higher contrast.
    BlackOrWhite,
    /// Auto-adjust using APCA perceptual contrast (WCAG 3.0 draft).
    ///
    /// Better for dark themes and polarity-aware readability. Uses `|Lc|` >= 60
    /// as the minimum body-text threshold.
    Apca,
}

#[cfg(all(test, feature = "terminal-serde"))]
mod terminal_serde_tests {
    use super::*;

    #[test]
    fn contrast_policy_round_trips() {
        let policy = ContrastPolicy::BlackOrWhite;
        let json = serde_json::to_string(&policy).unwrap();
        assert_eq!(
            serde_json::from_str::<ContrastPolicy>(&json).unwrap(),
            policy
        );
    }
}

/// Runtime devtools subsystem configuration.
#[cfg(feature = "devtools")]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DevToolsConfig {
    /// Enable devtools log ingestion and sink wiring.
    pub logs: bool,
    /// Enable runtime frame metrics collection.
    pub metrics: bool,
    /// Show tui-lipan's own framework-internal logs in the log view.
    ///
    /// Set to `false` so the devtools log view starts with framework noise
    /// (key events, dirty tracking, etc.) hidden, showing only the host
    /// application's own `debug_log!` lines. Can still be toggled at runtime
    /// from the "tui-lipan" button in the Logs tab.
    pub show_framework_logs: bool,
}

#[cfg(feature = "devtools")]
impl Default for DevToolsConfig {
    fn default() -> Self {
        Self {
            logs: true,
            metrics: true,
            show_framework_logs: true,
        }
    }
}

/// How the root viewport background is painted before the UI tree renders.
///
/// By default the framework paints nothing behind the tree, so the host
/// terminal background shows through ([`Transparent`](Self::Transparent)). Opt
/// into a filled background when you want a fully "designed" surface rather than
/// text floating on the terminal color — useful for kiosk-style apps, themes
/// with a strong identity, or matching a brand backdrop.
///
/// ```no_run
/// use tui_lipan::prelude::*;
///
/// // Fill with the active theme's backdrop surface:
/// let app = App::new().theme(Theme::lipan()).fill_background();
///
/// // Or an explicit color:
/// let app = App::new().screen_background(Color::hex_u24(0x04090D));
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum ScreenBackground {
    /// Leave the host terminal background untouched. (default)
    #[default]
    Transparent,
    /// Fill the viewport with the active root theme's backdrop surface
    /// ([`Theme::surface`]`.backdrop`).
    ///
    /// This tracks the theme of the realized root node, so apps that swap themes
    /// at runtime via a root `ThemeProvider` (rather than rebuilding the `App`)
    /// keep the backdrop in sync without any extra wiring.
    Theme,
    /// Fill the viewport with an explicit style (typically just a background color).
    Custom(Style),
}

impl ScreenBackground {
    /// Resolve to the concrete fill style for `theme`, or `None` when nothing
    /// should be painted.
    pub(crate) fn resolve(self, theme: &Theme) -> Option<Style> {
        match self {
            Self::Transparent => None,
            Self::Theme => Some(Style::new().bg(theme.surface.backdrop)),
            Self::Custom(style) => (!style.is_empty()).then_some(style),
        }
    }
}

impl From<Style> for ScreenBackground {
    fn from(style: Style) -> Self {
        Self::Custom(style)
    }
}

impl From<Color> for ScreenBackground {
    fn from(color: Color) -> Self {
        Self::Custom(Style::new().bg(color))
    }
}

impl From<Paint> for ScreenBackground {
    fn from(paint: Paint) -> Self {
        Self::Custom(Style::new().bg(paint))
    }
}

/// Application builder.
pub struct App {
    pub(crate) title: Option<String>,
    pub(crate) surface_mode: SurfaceMode,
    pub(crate) mouse_enabled: Option<bool>,
    pub(crate) scroll_wheel_multiplier: u16,
    pub(crate) theme: Theme,
    pub(crate) toast_placement: ToastPlacement,
    pub(crate) toast_gap: u16,
    pub(crate) toast_margin: Padding,
    pub(crate) clipboard_config: ClipboardConfig,
    pub(crate) keymap_path: Option<PathBuf>,
    pub(crate) text_area_newline_binding: TextAreaNewlineBinding,
    pub(crate) contrast_policy: ContrastPolicy,
    pub(crate) clipboard_provider: Option<Box<dyn ClipboardProvider>>,
    pub(crate) clipboard_reporter: ClipboardReporter,
    pub(crate) terminal_bg: Option<Color>,
    pub(crate) live_host_terminal_colors: bool,
    pub(crate) system_theme: bool,
    pub(crate) screen_background: ScreenBackground,
    #[cfg(feature = "devtools")]
    pub(crate) devtools_config: DevToolsConfig,
}

impl Default for App {
    fn default() -> Self {
        let theme = Theme::default();
        Self {
            title: None,
            surface_mode: SurfaceMode::default(),
            mouse_enabled: None,
            scroll_wheel_multiplier: 1,
            theme,
            toast_placement: ToastPlacement::default(),
            toast_gap: 1,
            toast_margin: Padding::BORDER,
            clipboard_config: ClipboardConfig::default(),
            keymap_path: None,
            text_area_newline_binding: TextAreaNewlineBinding::default(),
            contrast_policy: ContrastPolicy::default(),
            clipboard_provider: None,
            clipboard_reporter: crate::clipboard::default_clipboard_reporter(),
            terminal_bg: None,
            live_host_terminal_colors: false,
            system_theme: false,
            screen_background: ScreenBackground::default(),
            #[cfg(feature = "devtools")]
            devtools_config: DevToolsConfig::default(),
        }
    }
}

impl App {
    /// Create a new app.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the terminal window title (via OSC 2 escape sequence).
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Set the app surface mode explicitly.
    pub fn surface(mut self, mode: SurfaceMode) -> Self {
        self.surface_mode = mode.normalized();
        self
    }

    /// Use fullscreen alternate-screen rendering.
    pub fn fullscreen(self) -> Self {
        self.surface(SurfaceMode::Fullscreen)
    }

    /// Render the app inline for ephemeral (non-transcript) sessions.
    ///
    /// Height is clamped to at least one row.
    pub fn inline_ephemeral(self, height: u16) -> Self {
        self.surface(SurfaceMode::InlineEphemeral { height })
    }

    /// Render the app inline for transcript sessions.
    ///
    /// Defaults to preserving host terminal content on startup.
    pub fn inline_transcript(self, height: u16) -> Self {
        self.surface(SurfaceMode::InlineTranscript {
            height,
            startup: InlineStartupPolicy::PreserveHost,
        })
    }

    /// Render the app inline for transcript sessions with explicit startup behavior.
    ///
    /// Height is clamped to at least one row.
    pub fn inline_transcript_with_startup(self, height: u16, startup: InlineStartupPolicy) -> Self {
        self.surface(SurfaceMode::InlineTranscript { height, startup })
    }

    /// Configure mouse capture behavior.
    ///
    /// This sets the initial runtime state. Components can later change it with
    /// `Context::set_mouse_capture(...)` or `Context::toggle_mouse_capture()`.
    ///
    /// Defaults:
    /// - fullscreen mode: enabled
    /// - inline mode: disabled
    pub fn mouse(mut self, enabled: bool) -> Self {
        self.mouse_enabled = Some(enabled);
        self
    }

    /// Set the app-wide mouse wheel step multiplier.
    ///
    /// Each wheel tick scrolls `multiplier` lines instead of the default single
    /// line. Coalesced wheel bursts multiply by this value too, so two ticks with
    /// `multiplier = 3` scroll six lines total.
    pub fn scroll_wheel_multiplier(mut self, multiplier: u16) -> Self {
        self.scroll_wheel_multiplier = multiplier.max(1);
        self
    }

    /// Set the app-wide default theme.
    ///
    /// This theme is applied to the root tree every render.
    /// Use `ThemeProvider` to override a specific subtree.
    pub fn theme(mut self, theme: Theme) -> Self {
        self.theme = theme;
        self
    }

    /// Paint the root viewport background before rendering the UI tree.
    ///
    /// By default the framework paints nothing behind the tree (the host
    /// terminal background shows through). This opts into a filled background so
    /// the UI reads as a designed surface. Accepts a [`Color`], [`Paint`],
    /// [`Style`], or a [`ScreenBackground`] directly:
    ///
    /// ```no_run
    /// use tui_lipan::prelude::*;
    ///
    /// let app = App::new().screen_background(Color::hex_u24(0x04090D));
    /// ```
    ///
    /// Use [`fill_background`](Self::fill_background) to track the active theme's
    /// backdrop automatically.
    pub fn screen_background(mut self, background: impl Into<ScreenBackground>) -> Self {
        self.screen_background = background.into();
        self
    }

    /// Fill the root viewport with the active theme's backdrop surface.
    ///
    /// Shorthand for `screen_background(ScreenBackground::Theme)`. The fill tracks
    /// the app theme, so swapping themes keeps the backdrop in sync.
    pub fn fill_background(mut self) -> Self {
        self.screen_background = ScreenBackground::Theme;
        self
    }

    /// Set where toasts appear on screen.
    pub fn toast_placement(mut self, placement: ToastPlacement) -> Self {
        self.toast_placement = placement;
        self
    }

    /// Set vertical gap between stacked toasts.
    pub fn toast_gap(mut self, gap: u16) -> Self {
        self.toast_gap = gap;
        self
    }

    /// Set outside margin between toasts and the viewport edge.
    pub fn toast_margin(mut self, margin: impl Into<Padding>) -> Self {
        self.toast_margin = margin.into();
        self
    }

    /// Configure clipboard behavior.
    pub fn clipboard_config(mut self, config: ClipboardConfig) -> Self {
        self.clipboard_config = config;
        self
    }

    /// Use a specific keymap file path for this app instance.
    ///
    /// This path has higher priority than `TUI_LIPAN_KEYMAP` and the default
    /// `$XDG_CONFIG_HOME/tui-lipan/keymap.conf` fallback.
    pub fn keymap_path(mut self, path: impl Into<PathBuf>) -> Self {
        self.keymap_path = Some(path.into());
        self
    }

    /// Configure which Enter key combination inserts new lines in `TextArea`.
    ///
    /// This policy is scoped to `TextArea` and does not change single-line
    /// `Input` behavior.
    pub fn text_area_newline_binding(mut self, binding: TextAreaNewlineBinding) -> Self {
        self.text_area_newline_binding = binding;
        self
    }

    /// Configure app-wide text contrast behavior for interactive widget states.
    ///
    /// Individual styles can override this per-state by setting
    /// `Style::contrast_policy(...)` on the relevant style (base, hover,
    /// selection, focus, theme role, etc.).
    pub fn contrast_policy(mut self, policy: ContrastPolicy) -> Self {
        self.contrast_policy = policy;
        self
    }

    /// Provide a custom clipboard provider implementation.
    pub fn clipboard_provider(mut self, provider: impl ClipboardProvider + 'static) -> Self {
        self.clipboard_provider = Some(Box::new(provider));
        self
    }

    /// Provide a custom clipboard error reporter.
    pub fn clipboard_reporter(mut self, reporter: impl Fn(ClipboardError) + 'static) -> Self {
        self.clipboard_reporter = std::rc::Rc::new(reporter);
        self
    }

    /// Set the resolved terminal background color.
    ///
    /// When set, [`crate::style::ColorTransform::Opacity`] can blend foreground colors
    /// toward the real terminal background even when a cell's background is
    /// [`Color::Reset`].  Obtain this value from [`crate::style::query_host_colors()`]
    /// before starting the app:
    ///
    /// ```ignore
    /// let bg = query_host_colors().map(|c| c.bg);
    /// App::new().terminal_bg(bg).run(MyComponent);
    /// ```
    pub fn terminal_bg(mut self, color: Option<Color>) -> Self {
        self.terminal_bg = color;
        self
    }

    /// Enable runner-managed host terminal color refreshes.
    ///
    /// When enabled, the runner queries the host terminal palette before component
    /// init, refreshes on terminal focus gained, and services
    /// `Context::request_host_terminal_color_refresh()` on the UI thread while
    /// coordinating with tui-lipan's input reader. Refreshed colors are exposed
    /// through `Context::host_terminal_colors()` and the resolved terminal
    /// background is kept in sync for opacity blending.
    ///
    /// Disabled by default so static apps do not poll the terminal.
    pub fn live_host_terminal_colors(mut self, enabled: bool) -> Self {
        self.live_host_terminal_colors = enabled;
        self
    }

    /// Use the host terminal palette as the app theme once colors are probed.
    ///
    /// The current app theme remains the fallback until the runner successfully
    /// receives host colors. Later failed refreshes keep the last applied theme.
    pub fn system_theme(mut self) -> Self {
        self.system_theme = true;
        self
    }

    /// Configure runtime devtools subsystem behavior.
    #[cfg(feature = "devtools")]
    pub fn devtools_config(mut self, config: DevToolsConfig) -> Self {
        self.devtools_config = config;
        self
    }

    /// Mount the root component with default properties.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn mount<C>(self, component: C) -> AppRunner<C>
    where
        C: Component,
        C::Properties: Default,
    {
        self.mount_with_props(component, C::Properties::default())
    }

    /// Mount the root component with explicit properties.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn mount_with_props<C>(self, component: C, props: C::Properties) -> AppRunner<C>
    where
        C: Component,
    {
        AppRunner::new(self, component, props)
    }
}