superlighttui 0.18.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
/// State for a command palette overlay.
///
/// Renders as a modal with a search input and filtered command list.
#[derive(Debug, Clone)]
pub struct CommandPaletteState {
    /// Available commands.
    pub commands: Vec<PaletteCommand>,
    /// Current search query.
    pub input: String,
    /// Cursor index within `input`.
    pub cursor: usize,
    /// Whether the palette modal is open.
    pub open: bool,
    /// The last selected command index, set when the user confirms a selection.
    /// Check this after `response.changed` is true.
    pub last_selected: Option<usize>,
    selected: usize,
}

impl CommandPaletteState {
    /// Create command palette state from a command list.
    pub fn new(commands: Vec<PaletteCommand>) -> Self {
        Self {
            commands,
            input: String::new(),
            cursor: 0,
            open: false,
            last_selected: None,
            selected: 0,
        }
    }

    /// Toggle open/closed state and reset input when opening.
    pub fn toggle(&mut self) {
        self.open = !self.open;
        if self.open {
            self.input.clear();
            self.cursor = 0;
            self.selected = 0;
        }
    }

    fn fuzzy_score(pattern: &str, text: &str) -> Option<i32> {
        let pattern = pattern.trim();
        if pattern.is_empty() {
            return Some(0);
        }

        let text_chars: Vec<char> = text.chars().collect();
        let mut score = 0;
        let mut search_start = 0usize;
        let mut prev_match: Option<usize> = None;

        for p in pattern.chars() {
            let mut found = None;
            for (idx, ch) in text_chars.iter().enumerate().skip(search_start) {
                if ch.eq_ignore_ascii_case(&p) {
                    found = Some(idx);
                    break;
                }
            }

            let idx = found?;
            if prev_match.is_some_and(|prev| idx == prev + 1) {
                score += 3;
            } else {
                score += 1;
            }

            if idx == 0 {
                score += 2;
            } else {
                let prev = text_chars[idx - 1];
                let curr = text_chars[idx];
                if matches!(prev, ' ' | '_' | '-') || prev.is_uppercase() || curr.is_uppercase() {
                    score += 2;
                }
            }

            prev_match = Some(idx);
            search_start = idx + 1;
        }

        Some(score)
    }

    pub(crate) fn filtered_indices(&self) -> Vec<usize> {
        let query = self.input.trim();
        if query.is_empty() {
            return (0..self.commands.len()).collect();
        }

        let mut scored: Vec<(usize, i32)> = self
            .commands
            .iter()
            .enumerate()
            .filter_map(|(i, cmd)| {
                let mut haystack =
                    String::with_capacity(cmd.label.len() + cmd.description.len() + 1);
                haystack.push_str(&cmd.label);
                haystack.push(' ');
                haystack.push_str(&cmd.description);
                Self::fuzzy_score(query, &haystack).map(|score| (i, score))
            })
            .collect();

        if scored.is_empty() {
            let tokens: Vec<String> = query.split_whitespace().map(|t| t.to_lowercase()).collect();
            return self
                .commands
                .iter()
                .enumerate()
                .filter(|(_, cmd)| {
                    let label = cmd.label.to_lowercase();
                    let desc = cmd.description.to_lowercase();
                    tokens.iter().all(|token| {
                        label.contains(token.as_str()) || desc.contains(token.as_str())
                    })
                })
                .map(|(i, _)| i)
                .collect();
        }

        scored.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
        scored.into_iter().map(|(idx, _)| idx).collect()
    }

    pub(crate) fn selected(&self) -> usize {
        self.selected
    }

    pub(crate) fn set_selected(&mut self, s: usize) {
        self.selected = s;
    }
}

/// State for a streaming text display.
///
/// Accumulates text chunks as they arrive from an LLM stream.
/// Pass to [`Context::streaming_text`](crate::Context::streaming_text) each frame.
#[derive(Debug, Clone)]
pub struct StreamingTextState {
    /// The accumulated text content.
    pub content: String,
    /// Whether the stream is still receiving data.
    pub streaming: bool,
    /// Cursor blink state (for the typing indicator).
    pub(crate) cursor_visible: bool,
    pub(crate) cursor_tick: u64,
}

impl StreamingTextState {
    /// Create a new empty streaming text state.
    pub fn new() -> Self {
        Self {
            content: String::new(),
            streaming: false,
            cursor_visible: true,
            cursor_tick: 0,
        }
    }

    /// Append a chunk of text (e.g., from an LLM stream delta).
    pub fn push(&mut self, chunk: &str) {
        self.content.push_str(chunk);
    }

    /// Mark the stream as complete (hides the typing cursor).
    pub fn finish(&mut self) {
        self.streaming = false;
    }

    /// Start a new streaming session, clearing previous content.
    pub fn start(&mut self) {
        self.content.clear();
        self.streaming = true;
        self.cursor_visible = true;
        self.cursor_tick = 0;
    }

    /// Clear all content and reset state.
    pub fn clear(&mut self) {
        self.content.clear();
        self.streaming = false;
        self.cursor_visible = true;
        self.cursor_tick = 0;
    }
}

impl Default for StreamingTextState {
    fn default() -> Self {
        Self::new()
    }
}

/// State for a streaming markdown display.
///
/// Accumulates markdown chunks as they arrive from an LLM stream.
/// Pass to [`Context::streaming_markdown`](crate::Context::streaming_markdown) each frame.
#[derive(Debug, Clone)]
pub struct StreamingMarkdownState {
    /// The accumulated markdown content.
    pub content: String,
    /// Whether the stream is still receiving data.
    pub streaming: bool,
    /// Cursor blink state (for the typing indicator).
    pub cursor_visible: bool,
    /// Cursor animation tick counter.
    pub cursor_tick: u64,
    /// Whether the parser is currently inside a fenced code block.
    pub in_code_block: bool,
    /// Language label of the active fenced code block.
    pub code_block_lang: String,
}

impl StreamingMarkdownState {
    /// Create a new empty streaming markdown state.
    pub fn new() -> Self {
        Self {
            content: String::new(),
            streaming: false,
            cursor_visible: true,
            cursor_tick: 0,
            in_code_block: false,
            code_block_lang: String::new(),
        }
    }

    /// Append a markdown chunk (e.g., from an LLM stream delta).
    pub fn push(&mut self, chunk: &str) {
        self.content.push_str(chunk);
    }

    /// Start a new streaming session, clearing previous content.
    pub fn start(&mut self) {
        self.content.clear();
        self.streaming = true;
        self.cursor_visible = true;
        self.cursor_tick = 0;
        self.in_code_block = false;
        self.code_block_lang.clear();
    }

    /// Mark the stream as complete (hides the typing cursor).
    pub fn finish(&mut self) {
        self.streaming = false;
    }

    /// Clear all content and reset state.
    pub fn clear(&mut self) {
        self.content.clear();
        self.streaming = false;
        self.cursor_visible = true;
        self.cursor_tick = 0;
        self.in_code_block = false;
        self.code_block_lang.clear();
    }
}

impl Default for StreamingMarkdownState {
    fn default() -> Self {
        Self::new()
    }
}

/// Navigation stack state for multi-screen apps.
///
/// Tracks screen names in a push/pop stack while preserving the root screen.
/// Each screen gets isolated focus and hook state when used with
/// [`Context::screen`].
///
/// # Example
///
/// ```no_run
/// let mut screens = slt::ScreenState::new("main");
///
/// slt::run(|ui| {
///     let current = screens.current().to_string();
///     if current == "main" {
///         if ui.button("Settings").clicked { screens.push("settings"); }
///     }
///     if current == "settings" {
///         if ui.button("Back").clicked { screens.pop(); }
///     }
/// });
/// ```
#[derive(Debug, Clone)]
pub struct ScreenState {
    stack: Vec<String>,
    focus_state: std::collections::HashMap<String, (usize, usize)>,
}

impl ScreenState {
    /// Create a screen stack with an initial root screen.
    pub fn new(initial: impl Into<String>) -> Self {
        Self {
            stack: vec![initial.into()],
            focus_state: std::collections::HashMap::new(),
        }
    }

    /// Return the current screen name (top of the stack).
    pub fn current(&self) -> &str {
        self.stack
            .last()
            .expect("ScreenState always contains at least one screen")
            .as_str()
    }

    /// Push a new screen onto the stack.
    pub fn push(&mut self, name: impl Into<String>) {
        self.stack.push(name.into());
    }

    /// Pop the current screen, preserving the root screen.
    pub fn pop(&mut self) {
        if self.can_pop() {
            self.stack.pop();
        }
    }

    /// Return current stack depth.
    pub fn depth(&self) -> usize {
        self.stack.len()
    }

    /// Return `true` if popping is allowed.
    pub fn can_pop(&self) -> bool {
        self.stack.len() > 1
    }

    /// Reset to only the root screen.
    pub fn reset(&mut self) {
        self.stack.truncate(1);
    }

    pub(crate) fn save_focus(&mut self, name: &str, focus_index: usize, focus_count: usize) {
        self.focus_state
            .insert(name.to_string(), (focus_index, focus_count));
    }

    pub(crate) fn restore_focus(&self, name: &str) -> (usize, usize) {
        self.focus_state.get(name).copied().unwrap_or((0, 0))
    }
}

/// Named mode system with independent screen stacks.
///
/// Each mode contains its own [`ScreenState`]. Switching modes preserves
/// the previous mode's screen stack, focus, and hook state.
///
/// # Example
///
/// ```no_run
/// let mut modes = slt::ModeState::new("app", "home");
/// modes.add_mode("settings", "general");
///
/// slt::run(|ui| {
///     if ui.key('1') { modes.switch_mode("app"); }
///     if ui.key('2') { modes.switch_mode("settings"); }
///     let mode = modes.active_mode().to_string();
///     ui.text(format!("Mode: {}", mode));
/// });
/// ```
#[derive(Debug, Clone)]
pub struct ModeState {
    modes: std::collections::HashMap<String, ScreenState>,
    active: String,
}

impl ModeState {
    /// Create a mode system with an initial mode and screen.
    pub fn new(mode: impl Into<String>, screen: impl Into<String>) -> Self {
        let mode = mode.into();
        let mut modes = std::collections::HashMap::new();
        modes.insert(mode.clone(), ScreenState::new(screen));
        Self {
            modes,
            active: mode,
        }
    }

    /// Add a new mode with an initial screen.
    pub fn add_mode(&mut self, mode: impl Into<String>, screen: impl Into<String>) {
        let mode = mode.into();
        self.modes
            .entry(mode)
            .or_insert_with(|| ScreenState::new(screen));
    }

    /// Switch to a different mode. The mode must have been added with [`Self::add_mode`].
    ///
    /// Panics if the mode does not exist. For a non-panicking variant that
    /// reports success, use [`Self::try_switch_mode`].
    pub fn switch_mode(&mut self, mode: impl Into<String>) {
        let mode = mode.into();
        assert!(
            self.modes.contains_key(&mode),
            "mode '{}' not found",
            mode
        );
        self.active = mode;
    }

    /// Switch modes, returning `true` when the mode exists and the switch
    /// happened, or `false` when the mode has not been registered via
    /// [`Self::add_mode`].
    ///
    /// Prefer this over [`Self::switch_mode`] when the mode name comes from
    /// user input, key bindings, or anywhere the value could be unexpected
    /// at runtime — an unknown mode should not crash the host application.
    pub fn try_switch_mode(&mut self, mode: impl Into<String>) -> bool {
        let mode = mode.into();
        if !self.modes.contains_key(&mode) {
            return false;
        }
        self.active = mode;
        true
    }

    /// Return the active mode name.
    pub fn active_mode(&self) -> &str {
        &self.active
    }

    /// Get a reference to the active mode's screen state.
    pub fn screens(&self) -> &ScreenState {
        self.modes
            .get(&self.active)
            .expect("active mode must exist")
    }

    /// Get a mutable reference to the active mode's screen state.
    pub fn screens_mut(&mut self) -> &mut ScreenState {
        self.modes
            .get_mut(&self.active)
            .expect("active mode must exist")
    }
}

#[cfg(test)]
mod mode_state_tests {
    use super::ModeState;

    #[test]
    fn try_switch_mode_returns_false_for_unknown_mode() {
        let mut modes = ModeState::new("app", "home");
        modes.add_mode("settings", "general");
        assert!(modes.try_switch_mode("settings"));
        assert_eq!(modes.active_mode(), "settings");
        assert!(!modes.try_switch_mode("nonexistent"));
        // Active mode must not change when the switch is rejected.
        assert_eq!(modes.active_mode(), "settings");
    }
}

/// Approval state for a tool call.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ApprovalAction {
    /// No action taken yet.
    Pending,
    /// User approved the tool call.
    Approved,
    /// User rejected the tool call.
    Rejected,
}

/// State for a tool approval widget.
///
/// Displays a tool call with approve/reject buttons for human-in-the-loop
/// AI workflows. Pass to [`Context::tool_approval`](crate::Context::tool_approval)
/// each frame.
#[derive(Debug, Clone)]
pub struct ToolApprovalState {
    /// The name of the tool being invoked.
    pub tool_name: String,
    /// A human-readable description of what the tool will do.
    pub description: String,
    /// The current approval status.
    pub action: ApprovalAction,
}

impl ToolApprovalState {
    /// Create a new tool approval prompt.
    pub fn new(tool_name: impl Into<String>, description: impl Into<String>) -> Self {
        Self {
            tool_name: tool_name.into(),
            description: description.into(),
            action: ApprovalAction::Pending,
        }
    }

    /// Reset to pending state.
    pub fn reset(&mut self) {
        self.action = ApprovalAction::Pending;
    }
}

/// Item in a context bar showing active context sources.
#[derive(Debug, Clone)]
pub struct ContextItem {
    /// Display label for this context source.
    pub label: String,
    /// Token count or size indicator.
    pub tokens: usize,
}

impl ContextItem {
    /// Create a new context item with a label and token count.
    pub fn new(label: impl Into<String>, tokens: usize) -> Self {
        Self {
            label: label.into(),
            tokens,
        }
    }
}