scrin 0.1.74

A terminal UI toolkit with panes, widgets, overlays, animations, and Aisling-powered effects/loaders.
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
use crate::core::buffer::Buffer;
use crate::core::color::Color;
use crate::core::rect::Rect;
use crate::style::Style;
use crate::widgets::Widget;
use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FormAction {
    None,
    Submit,
    Cancel,
    FocusNext,
    FocusPrevious,
}

#[derive(Debug, Clone)]
pub struct TextInput {
    pub label: String,
    pub value: String,
    pub cursor: usize,
    pub masked: bool,
    pub focused: bool,
    pub style: Style,
    pub focus_style: Style,
    pub placeholder: String,
}

impl TextInput {
    pub fn new(label: &str) -> Self {
        Self {
            label: label.to_string(),
            value: String::new(),
            cursor: 0,
            masked: false,
            focused: false,
            style: Style::new().fg(Color::rgb(201, 209, 217)),
            focus_style: Style::new()
                .fg(Color::WHITE)
                .bg(Color::rgb(31, 111, 235))
                .bold(),
            placeholder: String::new(),
        }
    }

    pub fn with_value(mut self, value: &str) -> Self {
        self.value = value.to_string();
        self.cursor = self.value.chars().count();
        self
    }

    pub fn with_placeholder(mut self, placeholder: &str) -> Self {
        self.placeholder = placeholder.to_string();
        self
    }

    pub fn masked(mut self, masked: bool) -> Self {
        self.masked = masked;
        self
    }

    pub fn focused(mut self, focused: bool) -> Self {
        self.focused = focused;
        self
    }

    pub fn handle_event(&mut self, event: &Event) -> FormAction {
        match event {
            Event::Key(key) => self.handle_key(*key),
            Event::Paste(text) => {
                self.insert_str(text);
                FormAction::None
            }
            _ => FormAction::None,
        }
    }

    pub fn handle_key(&mut self, key: KeyEvent) -> FormAction {
        match key.code {
            KeyCode::Esc => FormAction::Cancel,
            KeyCode::Enter => FormAction::Submit,
            KeyCode::Tab => FormAction::FocusNext,
            KeyCode::BackTab => FormAction::FocusPrevious,
            KeyCode::Left => {
                self.cursor = self.cursor.saturating_sub(1);
                FormAction::None
            }
            KeyCode::Right => {
                self.cursor = (self.cursor + 1).min(self.value.chars().count());
                FormAction::None
            }
            KeyCode::Home => {
                self.cursor = 0;
                FormAction::None
            }
            KeyCode::End => {
                self.cursor = self.value.chars().count();
                FormAction::None
            }
            KeyCode::Backspace => {
                if self.cursor > 0 {
                    self.cursor -= 1;
                    remove_char(&mut self.value, self.cursor);
                }
                FormAction::None
            }
            KeyCode::Delete => {
                if self.cursor < self.value.chars().count() {
                    remove_char(&mut self.value, self.cursor);
                }
                FormAction::None
            }
            KeyCode::Char(c) => {
                if !key.modifiers.contains(KeyModifiers::CONTROL) {
                    self.insert_char(c);
                }
                FormAction::None
            }
            _ => FormAction::None,
        }
    }

    fn insert_str(&mut self, text: &str) {
        for ch in text.chars() {
            if ch != '\n' && ch != '\r' {
                self.insert_char(ch);
            }
        }
    }

    fn insert_char(&mut self, ch: char) {
        let byte_idx = byte_index_for_char(&self.value, self.cursor);
        self.value.insert(byte_idx, ch);
        self.cursor += 1;
    }

    pub fn rendered_value(&self) -> String {
        if self.value.is_empty() {
            self.placeholder.clone()
        } else if self.masked {
            "*".repeat(self.value.chars().count())
        } else {
            self.value.clone()
        }
    }
}

impl Widget for TextInput {
    fn render(&self, buffer: &mut Buffer, area: Rect) {
        if area.width == 0 || area.height == 0 {
            return;
        }
        let style = if self.focused {
            self.focus_style
        } else {
            self.style
        };
        let fg = style.fg_or_default();
        let bg = style.bg;
        let label = format!("{}: ", self.label);
        buffer.fill(area, ' ', fg, bg);
        buffer.set_str(area.x as usize, area.y as usize, &label, fg, bg);
        let value_x = area.x as usize + label.chars().count();
        if value_x < area.right() as usize {
            let max = area.right() as usize - value_x;
            let display: String = self.rendered_value().chars().take(max).collect();
            let value_color = if self.value.is_empty() {
                Color::rgb(110, 118, 129)
            } else {
                fg
            };
            buffer.set_str(value_x, area.y as usize, &display, value_color, bg);
            if self.focused {
                let cursor_x = (value_x + self.cursor).min(area.right() as usize - 1);
                buffer.set(
                    cursor_x,
                    area.y as usize,
                    crate::core::buffer::Cell::new('â–ˆ', fg, bg),
                );
            }
        }
    }
}

#[derive(Debug, Clone)]
pub struct Dropdown {
    pub label: String,
    pub options: Vec<String>,
    pub selected: usize,
    pub focused: bool,
    pub style: Style,
    pub focus_style: Style,
}

impl Dropdown {
    pub fn new(label: &str, options: Vec<String>) -> Self {
        Self {
            label: label.to_string(),
            options,
            selected: 0,
            focused: false,
            style: Style::new().fg(Color::rgb(201, 209, 217)),
            focus_style: Style::new()
                .fg(Color::WHITE)
                .bg(Color::rgb(31, 111, 235))
                .bold(),
        }
    }

    pub fn focused(mut self, focused: bool) -> Self {
        self.focused = focused;
        self
    }

    pub fn selected_value(&self) -> Option<&str> {
        self.options.get(self.selected).map(String::as_str)
    }

    pub fn handle_key(&mut self, key: KeyEvent) -> FormAction {
        match key.code {
            KeyCode::Esc => FormAction::Cancel,
            KeyCode::Enter => FormAction::Submit,
            KeyCode::Tab => FormAction::FocusNext,
            KeyCode::BackTab => FormAction::FocusPrevious,
            KeyCode::Up | KeyCode::Left => {
                self.selected = self.selected.saturating_sub(1);
                FormAction::None
            }
            KeyCode::Down | KeyCode::Right => {
                if !self.options.is_empty() {
                    self.selected = (self.selected + 1).min(self.options.len() - 1);
                }
                FormAction::None
            }
            _ => FormAction::None,
        }
    }
}

impl Widget for Dropdown {
    fn render(&self, buffer: &mut Buffer, area: Rect) {
        if area.width == 0 || area.height == 0 {
            return;
        }
        let style = if self.focused {
            self.focus_style
        } else {
            self.style
        };
        let fg = style.fg_or_default();
        let bg = style.bg;
        let value = self.selected_value().unwrap_or("none");
        let text = format!("{}: < {} >", self.label, value);
        buffer.fill(area, ' ', fg, bg);
        buffer.set_str(area.x as usize, area.y as usize, &text, fg, bg);
    }
}

#[derive(Debug, Clone)]
pub enum FormField {
    TextInput(TextInput),
    Dropdown(Dropdown),
    Toggle { label: String, value: bool },
}

#[derive(Debug, Clone)]
pub struct Form {
    pub title: String,
    pub fields: Vec<FormField>,
    pub focus: usize,
    pub status: Option<String>,
}

impl Form {
    pub fn new(title: &str) -> Self {
        Self {
            title: title.to_string(),
            fields: Vec::new(),
            focus: 0,
            status: None,
        }
    }

    pub fn with_field(mut self, field: FormField) -> Self {
        self.fields.push(field);
        self
    }

    pub fn set_status(&mut self, status: impl Into<String>) {
        self.status = Some(status.into());
    }

    pub fn focus_next(&mut self) {
        if !self.fields.is_empty() {
            self.focus = (self.focus + 1) % self.fields.len();
        }
    }

    pub fn focus_previous(&mut self) {
        if !self.fields.is_empty() {
            self.focus = if self.focus == 0 {
                self.fields.len() - 1
            } else {
                self.focus - 1
            };
        }
    }

    pub fn handle_event(&mut self, event: &Event) -> FormAction {
        let action = match self.fields.get_mut(self.focus) {
            Some(FormField::TextInput(input)) => input.handle_event(event),
            Some(FormField::Dropdown(dropdown)) => match event {
                Event::Key(key) => dropdown.handle_key(*key),
                _ => FormAction::None,
            },
            Some(FormField::Toggle { value, .. }) => match event {
                Event::Key(key) => match key.code {
                    KeyCode::Char(' ') | KeyCode::Enter => {
                        *value = !*value;
                        FormAction::None
                    }
                    KeyCode::Tab => FormAction::FocusNext,
                    KeyCode::BackTab => FormAction::FocusPrevious,
                    KeyCode::Esc => FormAction::Cancel,
                    _ => FormAction::None,
                },
                _ => FormAction::None,
            },
            None => FormAction::None,
        };
        match action {
            FormAction::FocusNext => {
                self.focus_next();
                FormAction::None
            }
            FormAction::FocusPrevious => {
                self.focus_previous();
                FormAction::None
            }
            other => other,
        }
    }
}

impl Widget for Form {
    fn render(&self, buffer: &mut Buffer, area: Rect) {
        if area.width == 0 || area.height == 0 {
            return;
        }
        buffer.fill(
            area,
            ' ',
            Color::rgb(201, 209, 217),
            Some(Color::rgb(13, 17, 23)),
        );
        buffer.set_str_bold(
            area.x as usize,
            area.y as usize,
            &self.title,
            Color::WHITE,
            Some(Color::rgb(13, 17, 23)),
        );
        for (idx, field) in self.fields.iter().enumerate() {
            let y = area.y + 2 + idx as u16;
            if y >= area.bottom() {
                break;
            }
            let row = Rect::new(area.x, y, area.width, 1);
            match field {
                FormField::TextInput(input) => {
                    input.clone().focused(idx == self.focus).render(buffer, row)
                }
                FormField::Dropdown(dropdown) => dropdown
                    .clone()
                    .focused(idx == self.focus)
                    .render(buffer, row),
                FormField::Toggle { label, value } => {
                    let prefix = if idx == self.focus { ">" } else { " " };
                    let checked = if *value { "on" } else { "off" };
                    buffer.set_str(
                        row.x as usize,
                        row.y as usize,
                        &format!("{} {}: {}", prefix, label, checked),
                        Color::WHITE,
                        Some(Color::rgb(13, 17, 23)),
                    );
                }
            }
        }
        if let Some(status) = &self.status {
            let y = area.bottom().saturating_sub(1);
            buffer.set_str(
                area.x as usize,
                y as usize,
                status,
                Color::rgb(255, 178, 72),
                Some(Color::rgb(13, 17, 23)),
            );
        }
    }
}

fn byte_index_for_char(s: &str, char_idx: usize) -> usize {
    s.char_indices()
        .nth(char_idx)
        .map(|(idx, _)| idx)
        .unwrap_or(s.len())
}

fn remove_char(s: &mut String, char_idx: usize) {
    let start = byte_index_for_char(s, char_idx);
    let end = byte_index_for_char(s, char_idx + 1);
    if start < end && start < s.len() {
        s.replace_range(start..end, "");
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn text_input_supports_insert_and_backspace() {
        let mut input = TextInput::new("Key");
        input.handle_key(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE));
        input.handle_key(KeyEvent::new(KeyCode::Char('b'), KeyModifiers::NONE));
        input.handle_key(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE));
        assert_eq!(input.value, "a");
    }

    #[test]
    fn text_input_masks_value() {
        let input = TextInput::new("Secret").with_value("token").masked(true);
        assert_eq!(input.rendered_value(), "*****");
    }

    #[test]
    fn dropdown_changes_selection() {
        let mut dropdown = Dropdown::new("Provider", vec!["A".into(), "B".into()]);
        dropdown.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
        assert_eq!(dropdown.selected_value(), Some("B"));
    }
}