superlighttui 0.19.2

Super Light TUI - A lightweight, ergonomic terminal UI library
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
use super::*;
use crate::KeyMap;

impl Context {
    /// Render a text element. Returns `&mut Self` for style chaining.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # slt::run(|ui: &mut slt::Context| {
    /// use slt::Color;
    /// ui.text("hello").bold().fg(Color::Cyan);
    /// # });
    /// ```
    pub fn text(&mut self, s: impl Into<String>) -> &mut Self {
        let content = s.into();
        let default_fg = self
            .rollback
            .text_color_stack
            .iter()
            .rev()
            .find_map(|c| *c)
            .unwrap_or(self.theme.text);
        self.commands.push(Command::Text {
            content,
            cursor_offset: None,
            style: Style::new().fg(default_fg),
            grow: 0,
            align: Align::Start,
            wrap: false,
            truncate: false,
            margin: Margin::default(),
            constraints: Constraints::default(),
        });
        self.rollback.last_text_idx = Some(self.commands.len() - 1);
        self
    }

    /// Render a clickable hyperlink.
    ///
    /// The link is interactive: clicking it (or pressing Enter/Space when
    /// focused) opens the URL in the system browser. OSC 8 is also emitted
    /// for terminals that support native hyperlinks.
    #[allow(clippy::print_stderr)]
    pub fn link(&mut self, text: impl Into<String>, url: impl Into<String>) -> &mut Self {
        let url_str = url.into();
        let focused = self.register_focusable();
        let (_interaction_id, response) = self.begin_widget_interaction(focused);

        let activated = response.clicked || self.consume_activation_keys(focused);

        if activated {
            if let Err(e) = open_url(&url_str) {
                eprintln!("[slt] failed to open URL: {e}");
            }
        }

        let style = if focused {
            Style::new()
                .fg(self.theme.primary)
                .bg(self.theme.surface_hover)
                .underline()
                .bold()
        } else if response.hovered {
            Style::new()
                .fg(self.theme.accent)
                .bg(self.theme.surface_hover)
                .underline()
        } else {
            Style::new().fg(self.theme.primary).underline()
        };

        self.commands.push(Command::Link {
            text: text.into(),
            url: url_str,
            style,
            margin: Margin::default(),
            constraints: Constraints::default(),
        });
        self.rollback.last_text_idx = Some(self.commands.len() - 1);
        self
    }

    /// Render an elapsed time display.
    ///
    /// Formats as `HH:MM:SS.CC` when hours are non-zero, otherwise `MM:SS.CC`.
    pub fn timer_display(&mut self, elapsed: std::time::Duration) -> &mut Self {
        let total_centis = elapsed.as_millis() / 10;
        let centis = total_centis % 100;
        let total_seconds = total_centis / 100;
        let seconds = total_seconds % 60;
        let minutes = (total_seconds / 60) % 60;
        let hours = total_seconds / 3600;

        let content = if hours > 0 {
            format!("{hours:02}:{minutes:02}:{seconds:02}.{centis:02}")
        } else {
            format!("{minutes:02}:{seconds:02}.{centis:02}")
        };

        self.commands.push(Command::Text {
            content,
            cursor_offset: None,
            style: Style::new().fg(self.theme.text),
            grow: 0,
            align: Align::Start,
            wrap: false,
            truncate: false,
            margin: Margin::default(),
            constraints: Constraints::default(),
        });
        self.rollback.last_text_idx = Some(self.commands.len() - 1);
        self
    }

    /// Render help bar from a KeyMap. Shows visible bindings as key-description pairs.
    pub fn help_from_keymap(&mut self, keymap: &KeyMap) -> Response {
        let pairs: Vec<(&str, &str)> = keymap
            .visible_bindings()
            .map(|binding| (binding.display.as_str(), binding.description.as_str()))
            .collect();
        self.help(&pairs)
    }

    // ── style chain (applies to last text) ───────────────────────────

    /// Apply bold to the last rendered text element.
    pub fn bold(&mut self) -> &mut Self {
        self.modify_last_style(|s| s.modifiers |= Modifiers::BOLD);
        self
    }

    /// Apply dim styling to the last rendered text element.
    ///
    /// Also sets the foreground color to the theme's `text_dim` color if no
    /// explicit foreground has been set.
    pub fn dim(&mut self) -> &mut Self {
        let text_dim = self.theme.text_dim;
        self.modify_last_style(|s| {
            s.modifiers |= Modifiers::DIM;
            if s.fg.is_none() {
                s.fg = Some(text_dim);
            }
        });
        self
    }

    /// Apply italic to the last rendered text element.
    pub fn italic(&mut self) -> &mut Self {
        self.modify_last_style(|s| s.modifiers |= Modifiers::ITALIC);
        self
    }

    /// Apply underline to the last rendered text element.
    pub fn underline(&mut self) -> &mut Self {
        self.modify_last_style(|s| s.modifiers |= Modifiers::UNDERLINE);
        self
    }

    /// Apply reverse-video to the last rendered text element.
    pub fn reversed(&mut self) -> &mut Self {
        self.modify_last_style(|s| s.modifiers |= Modifiers::REVERSED);
        self
    }

    /// Apply strikethrough to the last rendered text element.
    pub fn strikethrough(&mut self) -> &mut Self {
        self.modify_last_style(|s| s.modifiers |= Modifiers::STRIKETHROUGH);
        self
    }

    /// Set the foreground color of the last rendered text element.
    pub fn fg(&mut self, color: Color) -> &mut Self {
        self.modify_last_style(|s| s.fg = Some(color));
        self
    }

    /// Set the background color of the last rendered text element.
    pub fn bg(&mut self, color: Color) -> &mut Self {
        self.modify_last_style(|s| s.bg = Some(color));
        self
    }

    /// Apply a per-character foreground gradient to the last rendered text.
    pub fn gradient(&mut self, from: Color, to: Color) -> &mut Self {
        if let Some(idx) = self.rollback.last_text_idx {
            let replacement = match &self.commands[idx] {
                Command::Text {
                    content,
                    style,
                    wrap,
                    align,
                    margin,
                    constraints,
                    ..
                } => {
                    let chars: Vec<char> = content.chars().collect();
                    let len = chars.len();
                    let denom = len.saturating_sub(1).max(1) as f32;
                    let segments = chars
                        .into_iter()
                        .enumerate()
                        .map(|(i, ch)| {
                            let mut seg_style = *style;
                            seg_style.fg = Some(from.blend(to, i as f32 / denom));
                            (ch.to_string(), seg_style)
                        })
                        .collect();

                    Some(Command::RichText {
                        segments,
                        wrap: *wrap,
                        align: *align,
                        margin: *margin,
                        constraints: *constraints,
                    })
                }
                _ => None,
            };

            if let Some(command) = replacement {
                self.commands[idx] = command;
            }
        }

        self
    }

    /// Set foreground color when the current group is hovered or focused.
    pub fn group_hover_fg(&mut self, color: Color) -> &mut Self {
        let apply_group_style = self
            .rollback
            .group_stack
            .last()
            .map(|name| self.is_group_hovered(name) || self.is_group_focused(name))
            .unwrap_or(false);
        if apply_group_style {
            self.modify_last_style(|s| s.fg = Some(color));
        }
        self
    }

    /// Set background color when the current group is hovered or focused.
    pub fn group_hover_bg(&mut self, color: Color) -> &mut Self {
        let apply_group_style = self
            .rollback
            .group_stack
            .last()
            .map(|name| self.is_group_hovered(name) || self.is_group_focused(name))
            .unwrap_or(false);
        if apply_group_style {
            self.modify_last_style(|s| s.bg = Some(color));
        }
        self
    }

    /// Render a text element with an explicit [`Style`] applied immediately.
    ///
    /// Equivalent to calling `text(s)` followed by style-chain methods, but
    /// more concise when you already have a `Style` value.
    pub fn styled(&mut self, s: impl Into<String>, style: Style) -> &mut Self {
        self.styled_with_cursor(s, style, None)
    }

    pub(crate) fn styled_with_cursor(
        &mut self,
        s: impl Into<String>,
        style: Style,
        cursor_offset: Option<usize>,
    ) -> &mut Self {
        self.commands.push(Command::Text {
            content: s.into(),
            cursor_offset,
            style,
            grow: 0,
            align: Align::Start,
            wrap: false,
            truncate: false,
            margin: Margin::default(),
            constraints: Constraints::default(),
        });
        self.rollback.last_text_idx = Some(self.commands.len() - 1);
        self
    }

    /// Enable word-boundary wrapping on the last rendered text element.
    pub fn wrap(&mut self) -> &mut Self {
        if let Some(idx) = self.rollback.last_text_idx {
            if let Command::Text { wrap, .. } = &mut self.commands[idx] {
                *wrap = true;
            }
        }
        self
    }

    /// Truncate the last rendered text with `…` when it exceeds its allocated width.
    /// Use with `.w()` to set a fixed width, or let the parent container constrain it.
    pub fn truncate(&mut self) -> &mut Self {
        if let Some(idx) = self.rollback.last_text_idx {
            if let Command::Text { truncate, .. } = &mut self.commands[idx] {
                *truncate = true;
            }
        }
        self
    }

    fn modify_last_style(&mut self, f: impl FnOnce(&mut Style)) {
        if let Some(idx) = self.rollback.last_text_idx {
            match &mut self.commands[idx] {
                Command::Text { style, .. } | Command::Link { style, .. } => f(style),
                _ => {}
            }
        }
    }

    fn modify_last_constraints(&mut self, f: impl FnOnce(&mut Constraints)) {
        if let Some(idx) = self.rollback.last_text_idx {
            match &mut self.commands[idx] {
                Command::Text { constraints, .. } | Command::Link { constraints, .. } => {
                    f(constraints)
                }
                _ => {}
            }
        }
    }

    fn modify_last_margin(&mut self, f: impl FnOnce(&mut Margin)) {
        if let Some(idx) = self.rollback.last_text_idx {
            match &mut self.commands[idx] {
                Command::Text { margin, .. } | Command::Link { margin, .. } => f(margin),
                _ => {}
            }
        }
    }

    // ── containers ───────────────────────────────────────────────────

    /// Set the flex-grow factor of the last rendered text element.
    ///
    /// A value of `1` causes the element to expand and fill remaining space
    /// along the main axis.
    pub fn grow(&mut self, value: u16) -> &mut Self {
        if let Some(idx) = self.rollback.last_text_idx {
            if let Command::Text { grow, .. } = &mut self.commands[idx] {
                *grow = value;
            }
        }
        self
    }

    /// Set the text alignment of the last rendered text element.
    pub fn align(&mut self, align: Align) -> &mut Self {
        if let Some(idx) = self.rollback.last_text_idx {
            if let Command::Text {
                align: text_align, ..
            } = &mut self.commands[idx]
            {
                *text_align = align;
            }
        }
        self
    }

    /// Center-align the last rendered text element horizontally.
    /// Shorthand for `.align(Align::Center)`. Requires the text to have
    /// a width constraint (via `.w()` or parent container) to be visible.
    pub fn text_center(&mut self) -> &mut Self {
        self.align(Align::Center)
    }

    /// Right-align the last rendered text element horizontally.
    /// Shorthand for `.align(Align::End)`.
    pub fn text_right(&mut self) -> &mut Self {
        self.align(Align::End)
    }

    // ── size constraints on last text/link ──────────────────────────

    /// Set a fixed width on the last rendered text or link element.
    ///
    /// Sets both `min_width` and `max_width` to `value`, making the element
    /// occupy exactly that many columns (padded with spaces or truncated).
    pub fn w(&mut self, value: u32) -> &mut Self {
        self.modify_last_constraints(|c| {
            c.min_width = Some(value);
            c.max_width = Some(value);
        });
        self
    }

    /// Set a fixed height on the last rendered text or link element.
    ///
    /// Sets both `min_height` and `max_height` to `value`.
    pub fn h(&mut self, value: u32) -> &mut Self {
        self.modify_last_constraints(|c| {
            c.min_height = Some(value);
            c.max_height = Some(value);
        });
        self
    }

    /// Set the minimum width on the last rendered text or link element.
    pub fn min_w(&mut self, value: u32) -> &mut Self {
        self.modify_last_constraints(|c| c.min_width = Some(value));
        self
    }

    /// Set the maximum width on the last rendered text or link element.
    pub fn max_w(&mut self, value: u32) -> &mut Self {
        self.modify_last_constraints(|c| c.max_width = Some(value));
        self
    }

    /// Set the minimum height on the last rendered text or link element.
    pub fn min_h(&mut self, value: u32) -> &mut Self {
        self.modify_last_constraints(|c| c.min_height = Some(value));
        self
    }

    /// Set the maximum height on the last rendered text or link element.
    pub fn max_h(&mut self, value: u32) -> &mut Self {
        self.modify_last_constraints(|c| c.max_height = Some(value));
        self
    }

    // ── margin on last text/link ────────────────────────────────────

    /// Set uniform margin on all sides of the last rendered text or link element.
    pub fn m(&mut self, value: u32) -> &mut Self {
        self.modify_last_margin(|m| *m = Margin::all(value));
        self
    }

    /// Set horizontal margin (left + right) on the last rendered text or link.
    pub fn mx(&mut self, value: u32) -> &mut Self {
        self.modify_last_margin(|m| {
            m.left = value;
            m.right = value;
        });
        self
    }

    /// Set vertical margin (top + bottom) on the last rendered text or link.
    pub fn my(&mut self, value: u32) -> &mut Self {
        self.modify_last_margin(|m| {
            m.top = value;
            m.bottom = value;
        });
        self
    }

    /// Set top margin on the last rendered text or link element.
    pub fn mt(&mut self, value: u32) -> &mut Self {
        self.modify_last_margin(|m| m.top = value);
        self
    }

    /// Set right margin on the last rendered text or link element.
    pub fn mr(&mut self, value: u32) -> &mut Self {
        self.modify_last_margin(|m| m.right = value);
        self
    }

    /// Set bottom margin on the last rendered text or link element.
    pub fn mb(&mut self, value: u32) -> &mut Self {
        self.modify_last_margin(|m| m.bottom = value);
        self
    }

    /// Set left margin on the last rendered text or link element.
    pub fn ml(&mut self, value: u32) -> &mut Self {
        self.modify_last_margin(|m| m.left = value);
        self
    }

    /// Render an invisible spacer that expands to fill available space.
    ///
    /// Useful for pushing siblings to opposite ends of a row or column.
    pub fn spacer(&mut self) -> &mut Self {
        self.commands.push(Command::Spacer { grow: 1 });
        self.rollback.last_text_idx = None;
        self
    }

    // ── conditional / grouped style helpers ─────────────────────────

    /// Apply `f` only if `cond` is true. Returns `self` so chaining continues.
    ///
    /// Use this to attach a block of style modifiers to the last rendered text
    /// without breaking the fluent chain. The closure receives the same
    /// `&mut Context`, so any style-chain method (`.bold()`, `.fg()`, etc.)
    /// applies to the most recent text element.
    ///
    /// Zero allocation: the closure is inlined and skipped entirely when
    /// `cond` is `false`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # slt::run(|ui: &mut slt::Context| {
    /// use slt::Color;
    /// let is_error = true;
    /// let is_selected = false;
    /// ui.text("Status")
    ///     .with_if(is_error, |t| {
    ///         t.bold().fg(Color::Red);
    ///     })
    ///     .with_if(is_selected, |t| {
    ///         t.bg(Color::DarkGray);
    ///     });
    /// # });
    /// ```
    pub fn with_if(&mut self, cond: bool, f: impl FnOnce(&mut Self)) -> &mut Self {
        if cond {
            f(self);
        }
        self
    }

    /// Apply `f` unconditionally. Useful for factoring out a block of modifier
    /// calls that should always run, while keeping the fluent chain intact.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # slt::run(|ui: &mut slt::Context| {
    /// use slt::Color;
    /// ui.text("hi").with(|t| {
    ///     t.bold().fg(Color::Cyan);
    /// });
    /// # });
    /// ```
    pub fn with(&mut self, f: impl FnOnce(&mut Self)) -> &mut Self {
        f(self);
        self
    }
}