revue 2.71.1

A Vue-style TUI framework for Rust with CSS styling
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
//! Autocomplete widget for input suggestions
//!
//! Provides a text input with dropdown suggestions based on user input.

#![allow(clippy::iter_skip_next)]
use crate::event::{Key, KeyEvent};
use crate::render::Cell;
use crate::style::Color;
use crate::utils::{fuzzy_match, FilterMode, Selection};
use crate::widget::theme::{DARK_BG, DISABLED_FG, EDITOR_BG, SUBTLE_GRAY};
use crate::widget::traits::{RenderContext, View, WidgetProps};
use crate::{impl_props_builders, impl_styled_view};

use super::types::Suggestion;

/// Autocomplete widget
#[derive(Clone, Debug)]
pub struct Autocomplete {
    /// Current input value
    value: String,
    /// Cursor position
    cursor: usize,
    /// All suggestions
    suggestions: Vec<Suggestion>,
    /// Filtered suggestions
    filtered: Vec<usize>,
    /// Selected suggestion index in filtered list
    selection: Selection,
    /// Is dropdown visible
    dropdown_visible: bool,
    /// Filter mode
    filter_mode: FilterMode,
    /// Minimum characters to trigger suggestions
    min_chars: usize,
    /// Maximum suggestions to show
    max_suggestions: usize,
    /// Placeholder text
    placeholder: String,
    /// Input foreground
    input_fg: Color,
    /// Input background
    input_bg: Color,
    /// Placeholder color
    placeholder_fg: Color,
    /// Dropdown background
    dropdown_bg: Color,
    /// Selected item background
    selected_bg: Color,
    /// Selected item foreground
    selected_fg: Color,
    /// Description color
    description_fg: Color,
    /// Highlight color (for matched characters)
    highlight_fg: Color,
    /// Is focused
    focused: bool,
    /// CSS styling properties (id, classes)
    props: WidgetProps,
}

impl Autocomplete {
    /// Create a new autocomplete widget
    pub fn new() -> Self {
        Self {
            value: String::new(),
            cursor: 0,
            suggestions: Vec::new(),
            filtered: Vec::new(),
            selection: Selection::new(0),
            dropdown_visible: false,
            filter_mode: FilterMode::Fuzzy,
            min_chars: 1,
            max_suggestions: 10,
            placeholder: String::new(),
            input_fg: Color::WHITE,
            input_bg: EDITOR_BG,
            placeholder_fg: DISABLED_FG,
            dropdown_bg: DARK_BG,
            selected_bg: Color::rgb(60, 100, 180),
            selected_fg: Color::WHITE,
            description_fg: SUBTLE_GRAY,
            highlight_fg: Color::rgb(255, 200, 0),
            focused: false,
            props: WidgetProps::new(),
        }
    }

    /// Set suggestions
    pub fn suggestions<I, S>(mut self, suggestions: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<Suggestion>,
    {
        self.suggestions = suggestions.into_iter().map(|s| s.into()).collect();
        self
    }

    /// Set initial value
    pub fn value(mut self, value: impl Into<String>) -> Self {
        self.value = value.into();
        self.cursor = self.value.chars().count();
        self
    }

    /// Set placeholder
    pub fn placeholder(mut self, text: impl Into<String>) -> Self {
        self.placeholder = text.into();
        self
    }

    /// Set filter mode
    pub fn filter_mode(mut self, mode: FilterMode) -> Self {
        self.filter_mode = mode;
        self
    }

    /// Set minimum characters to trigger suggestions
    pub fn min_chars(mut self, chars: usize) -> Self {
        self.min_chars = chars;
        self
    }

    /// Set maximum suggestions to show
    pub fn max_suggestions(mut self, max: usize) -> Self {
        self.max_suggestions = max;
        self
    }

    /// Set input colors
    pub fn input_style(mut self, fg: Color, bg: Color) -> Self {
        self.input_fg = fg;
        self.input_bg = bg;
        self
    }

    /// Set dropdown colors
    pub fn dropdown_style(mut self, bg: Color, selected_fg: Color, selected_bg: Color) -> Self {
        self.dropdown_bg = bg;
        self.selected_fg = selected_fg;
        self.selected_bg = selected_bg;
        self
    }

    /// Set highlight color
    pub fn highlight_fg(mut self, color: Color) -> Self {
        self.highlight_fg = color;
        self
    }

    /// Get current value
    pub fn get_value(&self) -> &str {
        &self.value
    }

    /// Set value programmatically
    pub fn set_value(&mut self, value: impl Into<String>) {
        self.value = value.into();
        self.cursor = self.value.len();
        self.update_filter();
    }

    /// Set suggestions programmatically
    pub fn set_suggestions(&mut self, suggestions: Vec<Suggestion>) {
        self.suggestions = suggestions;
        self.update_filter();
    }

    /// Focus the input
    pub fn focus(&mut self) {
        self.focused = true;
        self.update_filter();
    }

    /// Unfocus the input
    pub fn blur(&mut self) {
        self.focused = false;
        self.dropdown_visible = false;
    }

    /// Check if focused
    pub fn is_focused(&self) -> bool {
        self.focused
    }

    /// Get selected suggestion
    pub fn selected_suggestion(&self) -> Option<&Suggestion> {
        self.filtered
            .get(self.selection.index)
            .and_then(|&idx| self.suggestions.get(idx))
    }

    /// Accept current selection
    pub fn accept_selection(&mut self) -> bool {
        if let Some(suggestion) = self.selected_suggestion() {
            self.value = suggestion.value.clone();
            self.cursor = self.value.len();
            self.dropdown_visible = false;
            true
        } else {
            false
        }
    }

    /// Update filtered suggestions
    fn update_filter(&mut self) {
        if self.value.len() < self.min_chars {
            self.filtered.clear();
            self.dropdown_visible = false;
            return;
        }

        let query = &self.value;
        self.filtered = self
            .suggestions
            .iter()
            .enumerate()
            .filter_map(|(idx, suggestion)| {
                let matches = match self.filter_mode {
                    FilterMode::Fuzzy => fuzzy_match(query, &suggestion.label).is_some(),
                    FilterMode::Prefix => suggestion
                        .label
                        .to_lowercase()
                        .starts_with(&query.to_lowercase()),
                    FilterMode::Contains => suggestion
                        .label
                        .to_lowercase()
                        .contains(&query.to_lowercase()),
                    FilterMode::Exact => suggestion.label.to_lowercase() == query.to_lowercase(),
                    FilterMode::None => true,
                };
                if matches {
                    Some(idx)
                } else {
                    None
                }
            })
            .take(self.max_suggestions)
            .collect();

        self.dropdown_visible = !self.filtered.is_empty();
        self.selection.set_len(self.filtered.len());
        self.selection.first();
    }

    /// Handle key event
    pub fn handle_key(&mut self, key: KeyEvent) -> bool {
        match key.key {
            Key::Char(c) => {
                let byte_idx = crate::utils::text::char_to_byte_index(&self.value, self.cursor);
                self.value.insert(byte_idx, c);
                self.cursor += 1;
                self.update_filter();
                true
            }
            Key::Backspace => {
                if self.cursor > 0 {
                    self.cursor -= 1;
                    let byte_idx = crate::utils::text::char_to_byte_index(&self.value, self.cursor);
                    self.value.remove(byte_idx);
                    self.update_filter();
                }
                true
            }
            Key::Delete => {
                if self.cursor < self.value.chars().count() {
                    let byte_idx = crate::utils::text::char_to_byte_index(&self.value, self.cursor);
                    self.value.remove(byte_idx);
                    self.update_filter();
                }
                true
            }
            Key::Left => {
                self.cursor = self.cursor.saturating_sub(1);
                true
            }
            Key::Right => {
                self.cursor = (self.cursor + 1).min(self.value.chars().count());
                true
            }
            Key::Home => {
                self.cursor = 0;
                true
            }
            Key::End => {
                self.cursor = self.value.chars().count();
                true
            }
            Key::Up if self.dropdown_visible => {
                self.selection.up();
                true
            }
            Key::Down if self.dropdown_visible => {
                self.selection.down();
                true
            }
            Key::Enter | Key::Tab if self.dropdown_visible => {
                self.accept_selection();
                true
            }
            Key::Escape if self.dropdown_visible => {
                self.dropdown_visible = false;
                true
            }
            _ => false,
        }
    }
}

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

impl View for Autocomplete {
    crate::impl_view_meta!("Autocomplete");

    fn render(&self, ctx: &mut RenderContext) {
        let area = ctx.area;
        if area.width < 3 || area.height < 1 {
            return;
        }

        // Render input box
        let input_width = area.width;
        for x in 0..input_width {
            ctx.set(x, 0, Cell::new(' ').bg(self.input_bg));
        }

        // Render input text or placeholder
        let display_text = if self.value.is_empty() {
            &self.placeholder
        } else {
            &self.value
        };
        let text_fg = if self.value.is_empty() {
            self.placeholder_fg
        } else {
            self.input_fg
        };

        for (i, ch) in display_text.chars().enumerate() {
            let x = i as u16;
            if x >= input_width {
                break;
            }
            ctx.set(x, 0, Cell::new(ch).fg(text_fg).bg(self.input_bg));
        }

        // Render cursor if focused
        if self.focused {
            let cursor_x = self.cursor as u16;
            if cursor_x < input_width {
                // Use skip().next() for O(n) instead of O(n²) with .chars().nth()
                let cursor_char = self.value.chars().skip(self.cursor).next().unwrap_or(' ');
                ctx.set(
                    cursor_x,
                    0,
                    Cell::new(cursor_char).fg(self.input_bg).bg(self.input_fg),
                );
            }
        }

        // Render dropdown if visible and there's room
        if self.dropdown_visible && area.height > 1 && !self.filtered.is_empty() {
            let dropdown_height = (self.filtered.len() as u16).min(area.height - 1);
            let dropdown_y: u16 = 1;

            for (i, &suggestion_idx) in self
                .filtered
                .iter()
                .enumerate()
                .take(dropdown_height as usize)
            {
                let suggestion = &self.suggestions[suggestion_idx];
                let y = dropdown_y + i as u16;
                let is_selected = i == self.selection.index;

                let (fg, bg) = if is_selected {
                    (self.selected_fg, self.selected_bg)
                } else {
                    (self.input_fg, self.dropdown_bg)
                };

                // Fill background
                for x in 0..input_width {
                    ctx.set(x, y, Cell::new(' ').bg(bg));
                }

                let mut x: u16 = 0;

                // Icon
                if let Some(icon) = suggestion.icon {
                    ctx.set(x, y, Cell::new(icon).fg(fg).bg(bg));
                    x += 2;
                }

                // Label with highlight
                if let Some(fm) = fuzzy_match(&self.value, &suggestion.label) {
                    for (j, ch) in suggestion.label.chars().enumerate() {
                        if x >= input_width {
                            break;
                        }
                        let char_fg = if fm.indices.contains(&j) {
                            self.highlight_fg
                        } else {
                            fg
                        };
                        ctx.set(x, y, Cell::new(ch).fg(char_fg).bg(bg));
                        x += 1;
                    }
                } else {
                    for ch in suggestion.label.chars() {
                        if x >= input_width {
                            break;
                        }
                        ctx.set(x, y, Cell::new(ch).fg(fg).bg(bg));
                        x += 1;
                    }
                }

                // Description (if fits)
                if let Some(ref desc) = suggestion.description {
                    x += 1;
                    for ch in desc.chars() {
                        if x >= input_width {
                            break;
                        }
                        ctx.set(x, y, Cell::new(ch).fg(self.description_fg).bg(bg));
                        x += 1;
                    }
                }
            }
        }
    }
}

impl_styled_view!(Autocomplete);
impl_props_builders!(Autocomplete);