tui-lipan 0.2.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
//! Theme showcase example - demonstrates ThemeProvider with switchable themes.
//!
//! Run with: cargo run --example theme_showcase
//!
//! Controls:
//! - 1-7: Switch between themes
//! - Tab: Navigate between widgets
//! - Ctrl+Q: Quit

#[cfg(feature = "syntax-syntect")]
use tui_lipan::SyntectStrategy;
use tui_lipan::prelude::*;

/// Available themes in the showcase.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum ThemeChoice {
    #[default]
    Lipan,
    OneDark,
    Dracula,
    Nord,
    Gruvbox,
    Catppuccin,
    Ansi,
}

impl ThemeChoice {
    fn name(self) -> &'static str {
        match self {
            Self::Lipan => "Lipan",
            Self::OneDark => "One Dark",
            Self::Dracula => "Dracula",
            Self::Nord => "Nord",
            Self::Gruvbox => "Gruvbox",
            Self::Catppuccin => "Catppuccin",
            Self::Ansi => "ANSI",
        }
    }

    fn theme(self) -> Theme {
        // Use the built-in theme presets from the library
        match self {
            Self::Lipan => Theme::lipan(),
            Self::OneDark => Theme::one_dark(),
            Self::Dracula => Theme::dracula(),
            Self::Nord => Theme::nord(),
            Self::Gruvbox => Theme::gruvbox_dark(),
            Self::Catppuccin => Theme::catppuccin_mocha(),
            Self::Ansi => Theme::ansi(),
        }
    }

    fn all() -> &'static [Self] {
        &[
            Self::Lipan,
            Self::OneDark,
            Self::Dracula,
            Self::Nord,
            Self::Gruvbox,
            Self::Catppuccin,
            Self::Ansi,
        ]
    }
}

#[cfg(feature = "markdown")]
const MARKDOWN_THEME_SAMPLE: &str = r#"# Markdown + Syntax

Theme palettes now drive headings, links, quotes, and code blocks.

> Blockquotes and table borders pick up themed document styles.

- Themed links and emphasis stay in sync with the selected preset.
- Lists and separators should also shift with the theme.
"#;

#[cfg(feature = "syntax-syntect")]
const SYNTAX_THEME_SAMPLE: &str = r#"// Theme-native syntax preview
struct ThemePreview {
    title: String,
    count: usize,
}

fn greet(name: &str) -> String {
    let preview = ThemePreview {
        title: name.to_string(),
        count: 42,
    };

    if preview.count > 10 {
        format!("Hello, {} #{}", preview.title, preview.count)
    } else {
        "small".to_string()
    }
}"#;

#[cfg(feature = "syntax-syntect")]
fn syntax_legend(theme: &Theme) -> Element {
    HStack::new()
        .gap(1)
        .child(Text::new("keyword").style(theme.syntax.keyword))
        .child(Text::new("string").style(theme.syntax.string))
        .child(Text::new("number").style(theme.syntax.number))
        .child(Text::new("function").style(theme.syntax.function))
        .child(Text::new("type").style(theme.syntax.type_name))
        .child(Text::new("comment").style(theme.syntax.comment))
        .into()
}

#[cfg(all(feature = "markdown", feature = "syntax-syntect"))]
fn theme_preview_panel(theme: Theme) -> Element {
    Frame::new()
        .header_left("Markdown + Syntax")
        .border(true)
        .border_style(BorderStyle::Rounded)
        .height(Length::Flex(1))
        .child(
            VStack::new()
                .gap(1)
                .child(
                    DocumentView::new(MARKDOWN_THEME_SAMPLE)
                        .markdown()
                        .border(true)
                        .height(Length::Px(8))
                        .wrap(true),
                )
                .child(syntax_legend(&theme))
                .child(
                    TextArea::new(SYNTAX_THEME_SAMPLE)
                        .read_only(true)
                        .border(true)
                        .height(Length::Flex(1))
                        .line_numbers(true)
                        .language("rust")
                        .color_strategy(
                            SyntectStrategy::default()
                                .default_theme("One Dark (Atom)")
                                .syntax_palette(theme.syntax),
                        ),
                ),
        )
        .into()
}

#[cfg(all(feature = "markdown", not(feature = "syntax-syntect")))]
fn theme_preview_panel(_theme: Theme) -> Element {
    Frame::new()
        .header_left("Markdown")
        .border(true)
        .border_style(BorderStyle::Rounded)
        .height(Length::Flex(1))
        .child(
            DocumentView::new(MARKDOWN_THEME_SAMPLE)
                .markdown()
                .border(false)
                .wrap(true),
        )
        .into()
}

#[cfg(all(feature = "syntax-syntect", not(feature = "markdown")))]
fn theme_preview_panel(theme: Theme) -> Element {
    Frame::new()
        .header_left("Syntax (syntect)")
        .border(true)
        .border_style(BorderStyle::Rounded)
        .height(Length::Flex(1))
        .child(
            VStack::new().gap(1).child(syntax_legend(&theme)).child(
                TextArea::new(SYNTAX_THEME_SAMPLE)
                    .read_only(true)
                    .border(false)
                    .line_numbers(true)
                    .language("rust")
                    .color_strategy(
                        SyntectStrategy::default()
                            .default_theme("One Dark (Atom)")
                            .syntax_palette(theme.syntax),
                    ),
            ),
        )
        .into()
}

#[cfg(not(any(feature = "markdown", feature = "syntax-syntect")))]
fn theme_preview_panel(_theme: Theme) -> Element {
    Frame::new()
        .header_left("Markdown + Syntax")
        .border(true)
        .border_style(BorderStyle::Rounded)
        .height(Length::Flex(1))
        .padding(1)
        .child(
            Text::new(
                "Enable `markdown` and `syntax-syntect` to preview theme-native document and code styling.",
            ),
        )
        .into()
}

// --- App component ---

struct ThemeShowcase;

struct State {
    current_theme: ThemeChoice,
    input: TextInput,
    list_selected: usize,
    checkbox_checked: bool,
    slider_value: f64,
}

impl Default for State {
    fn default() -> Self {
        Self {
            current_theme: ThemeChoice::default(),
            input: TextInput::new("Sample text"),
            list_selected: 0,
            checkbox_checked: true,
            slider_value: 50.0,
        }
    }
}

#[derive(Clone, Debug)]
enum Msg {
    SetTheme(ThemeChoice),
    InputChanged(InputEvent),
    ListSelected(ListEvent),
    CheckboxToggled(CheckboxEvent),
    SliderChanged(f64),
}

impl Component for ThemeShowcase {
    type Message = Msg;
    type Properties = ();
    type State = State;

    fn create_state(&self, _props: &Self::Properties) -> Self::State {
        State::default()
    }

    fn on_key(&mut self, key: KeyEvent, ctx: &mut Context<Self>) -> KeyUpdate {
        // Ctrl+Q to quit
        if key.mods.ctrl && matches!(key.code, KeyCode::Char('q') | KeyCode::Char('Q')) {
            ctx.quit();
            return KeyUpdate::handled(Update::full());
        }

        // Number keys to switch themes
        let theme = match key.code {
            KeyCode::Char('1') => Some(ThemeChoice::Lipan),
            KeyCode::Char('2') => Some(ThemeChoice::OneDark),
            KeyCode::Char('3') => Some(ThemeChoice::Dracula),
            KeyCode::Char('4') => Some(ThemeChoice::Nord),
            KeyCode::Char('5') => Some(ThemeChoice::Gruvbox),
            KeyCode::Char('6') => Some(ThemeChoice::Catppuccin),
            KeyCode::Char('7') => Some(ThemeChoice::Ansi),
            _ => None,
        };

        if let Some(choice) = theme {
            ctx.link().send(Msg::SetTheme(choice));
            return KeyUpdate::handled(Update::full());
        }

        KeyUpdate::unhandled(Update::none())
    }

    fn update(&mut self, msg: Self::Message, ctx: &mut Context<Self>) -> Update {
        match msg {
            Msg::SetTheme(theme_choice) => {
                ctx.state.current_theme = theme_choice;
                ctx.toast()
                    .push(Toast::new(format!("Switched to {}", theme_choice.name())));
            }
            Msg::InputChanged(ev) => {
                ctx.state.input.set_text(ev.value.to_string());
                ctx.state.input.set_cursor(ev.cursor);
            }
            Msg::ListSelected(ev) => {
                ctx.state.list_selected = ev.index;
            }
            Msg::CheckboxToggled(ev) => {
                ctx.state.checkbox_checked = ev.state == CheckboxState::Checked;
            }
            Msg::SliderChanged(value) => {
                ctx.state.slider_value = value;
            }
        }
        Update::full()
    }

    fn view(&self, ctx: &Context<Self>) -> Element {
        let current = ctx.state.current_theme;
        let theme = current.theme();

        // Theme selector buttons
        let theme_buttons: Vec<Element> = ThemeChoice::all()
            .iter()
            .enumerate()
            .map(|(i, &choice)| {
                let is_active = choice == current;
                let variant = if is_active {
                    ButtonVariant::Filled
                } else {
                    ButtonVariant::Outlined
                };

                Button::new(format!("[{}] {}", i + 1, choice.name()))
                    .variant(variant)
                    .width(Length::Flex(1))
                    .on_click(ctx.link().callback(move |_| Msg::SetTheme(choice)))
                    .into()
            })
            .collect();

        // Sample list items (more items to demonstrate scrollbar)
        let list_items: Vec<ListItem> = vec![
            ListItem::new("First item"),
            ListItem::new("Second item"),
            ListItem::new("Third item"),
            ListItem::new("Fourth item"),
            ListItem::new("Fifth item"),
            ListItem::new("Sixth item"),
            ListItem::new("Seventh item"),
            ListItem::new("Eighth item"),
        ];

        // Build the theme selector bar
        let theme_bar = HStack::new()
            .gap(1)
            .height(Length::Px(3))
            .children(theme_buttons);

        let left_column = VStack::new()
            .gap(1)
            .child(
                Frame::new()
                    .header_left("FileTree (themed icons)")
                    .height(Length::Px(12))
                    .border(true)
                    .border_style(BorderStyle::Rounded)
                    .child(
                        FileTree::new(".")
                            .show_hidden(false)
                            .git_status(true)
                            .icon_style(FileIconStyle::NerdFontColored),
                    ),
            )
            .child(theme_preview_panel(theme.clone()));

        // Main content wrapped in ThemeProvider
        let themed_content = ThemeProvider::new(theme.clone()).child(rsx! {
            VStack {
                gap: 1,
                padding: 1,
                Frame {
                    header_left: format!("Theme Showcase - {}", current.name()),
                    border: true,
                    border_style: BorderStyle::Rounded,
                    padding: 1,
                    height: Length::Auto,
                    VStack {
                        gap: 1,
                        Text {
                            content: "Press 1-7 to switch themes. Tab to navigate. Ctrl+Q to quit.",
                            style: Style::new().dim(),
                        },
                        theme_bar,
                    },
                },
                HStack {
                    gap: 1,
                    left_column,
                    VStack {
                        gap: 1,
                        Frame {
                            header_left: "Input",
                            border: true,
                            border_style: BorderStyle::Rounded,
                            padding: 1,
                            height: Length::Auto,
                            Input {
                                value: ctx.state.input.text().to_owned(),
                                cursor: ctx.state.input.cursor(),
                                placeholder: "Type something...",
                                border: true,
                                on_change: ctx.link().callback(Msg::InputChanged),
                            },
                        },
                        Frame {
                            header_left: "List",
                            border: true,
                            border_style: BorderStyle::Rounded,
                            List {
                                items: list_items,
                                selected: ctx.state.list_selected,
                                on_select: ctx.link().callback(Msg::ListSelected),
                            },
                        },
                        Frame {
                            header_left: "Other Widgets",
                            border: true,
                            border_style: BorderStyle::Rounded,
                            padding: 1,
                            VStack {
                                gap: 1,
                                HStack {
                                    gap: 2,
                                    Checkbox {
                                        label: "Themed checkbox",
                                        checked: ctx.state.checkbox_checked,
                                        on_toggle: ctx.link().callback(Msg::CheckboxToggled),
                                    },
                                    Spinner {},
                                },
                                ProgressBar {
                                    progress: 0.65,
                                    width: Length::Flex(1),
                                },
                                Slider {
                                    value: ctx.state.slider_value,
                                    min: 0.0,
                                    max: 100.0,
                                    label: "Themed slider",
                                    on_change: ctx.link().callback(Msg::SliderChanged),
                                },
                                HStack {
                                    gap: 2,
                                    Text {
                                        content: "Git:",
                                        style: Style::new().bold(),
                                    },
                                    Text {
                                        content: " Modified",
                                        style: Style::new().fg(theme.git_status.modified),
                                    },
                                    Text {
                                        content: " Added",
                                        style: Style::new().fg(theme.git_status.added),
                                    },
                                    Text {
                                        content: " Deleted",
                                        style: Style::new().fg(theme.git_status.deleted),
                                    },
                                    Text {
                                        content: " Untracked",
                                        style: Style::new().fg(theme.git_status.untracked),
                                    },
                                },
                            },
                        },
                    },
                },
            }
        });

        themed_content.into()
    }
}

fn main() -> Result<()> {
    App::new()
        .toast_placement(ToastPlacement::BottomEnd)
        .mount(ThemeShowcase)
        .run()
}