petitcarnets 0.0.10

Terminal user interfaces in the Elm architecture (model, update, view), with no dependencies.
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
//! One line of text to edit, scrolled sideways when it is wider than
//! its width: Bubbles' `textinput` package, with its key bindings,
//! echo modes (passwords), character limit, suggestions and validation.
//!
//! ```
//! use petitcarnets as tea;
//! use tea::bubbles::textinput;
//!
//! let mut input = textinput::Model::new();
//! input.placeholder = "Pikachu".into();
//! let _ = input.focus();
//! for c in "Hi".chars() {
//!     let _ = input.update(&tea::Msg::KeyPress(tea::Key::char(c)));
//! }
//! let _ = input.update(&tea::Msg::KeyPress(tea::Key::new(tea::KeyCode::Left)));
//! assert_eq!(input.value(), "Hi");
//! assert_eq!(input.position(), 1);
//! assert_eq!(tea::style::strip_ansi(&input.view()), "> Hi");
//! ```

pub(super) mod edit;
mod keymap;
mod style;
mod suggest;
mod value;
mod view;

pub use keymap::KeyMap;
pub use style::{CursorStyle, StyleState, Styles};

use super::Flags;
use super::cursor::{self, Mode};
use crate::style::Style;
use crate::{Cmd, Msg as TeaMsg, batch};
use std::sync::Arc;

/// A text input's messages: its cursor's blinks.
pub type Msg = cursor::Msg;

/// How the text shows: Bubbles' `textinput.EchoMode`.
///
/// ```
/// use petitcarnets as tea;
/// use tea::bubbles::textinput;
///
/// let mut input = textinput::Model::new();
/// input.echo_mode = textinput::EchoMode::Password;
/// input.set_value("abc");
/// assert_eq!(input.value(), "abc");
/// assert_eq!(tea::style::strip_ansi(&input.view()), "> *** ");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum EchoMode {
    /// As typed.
    #[default]
    Normal,
    /// A [`Model::echo_character`] a cell, for passwords.
    Password,
    /// Nothing at all.
    None,
}

/// A check run on every change; its error is kept in [`Model::err`]:
/// Bubbles' `textinput.ValidateFunc`. A closure, so it may capture
/// state; a plain `fn` works too.
///
/// ```
/// use petitcarnets as tea;
/// use std::sync::Arc;
/// use tea::bubbles::textinput;
///
/// let max = 3;
/// let mut input = textinput::Model::new();
/// input.validate = Some(Arc::new(move |s: &str| {
///     if s.len() > max { Err(format!("over {max}")) } else { Ok(()) }
/// }));
/// input.set_value("abcd");
/// assert_eq!(input.err.as_deref(), Some("over 3"));
/// ```
pub type ValidateFn = Arc<dyn Fn(&str) -> Result<(), String> + Send + Sync>;

/// A [`Model`] setting's bit.
const FOCUS: u16 = 1 << 0;
/// A [`Model`] setting's bit.
const USE_VIRTUAL_CURSOR: u16 = 1 << 1;
/// A [`Model`] setting's bit.
const PASTE_PENDING: u16 = 1 << 2;

/// A text input: Bubbles' `textinput.Model`.
///
/// ```
/// use petitcarnets as tea;
/// use tea::bubbles::textinput;
///
/// let mut input = textinput::Model::new();
/// input.prompt = "$ ".into();
/// input.placeholder = "command".into();
/// assert_eq!(tea::style::strip_ansi(&input.view()), "$ command");
/// ```
#[derive(Clone)]
pub struct Model {
    /// The last validation error, if any.
    pub err: Option<String>,
    /// Shown before the text.
    pub prompt: String,
    /// Shown when there is no text.
    pub placeholder: String,
    /// How the text shows.
    pub echo_mode: EchoMode,
    /// The character a password shows as.
    pub echo_character: char,
    /// The most characters the text may hold; 0 is no limit.
    pub char_limit: usize,
    /// The keys.
    pub key_map: KeyMap,
    /// A check run on every change.
    pub validate: Option<ValidateFn>,
    /// Whether to offer suggestions.
    pub show_suggestions: bool,
    styles: Styles,
    width: usize,
    value: Vec<char>,
    pos: usize,
    offset: usize,
    offset_right: usize,
    virtual_cursor: cursor::Model,
    suggestions: Vec<Vec<char>>,
    matched: Vec<Vec<char>>,
    current_suggestion: usize,
    flags: Flags,
}

impl std::fmt::Debug for Model {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Model")
            .field("err", &self.err)
            .field("prompt", &self.prompt)
            .field("placeholder", &self.placeholder)
            .field("echo_mode", &self.echo_mode)
            .field("echo_character", &self.echo_character)
            .field("char_limit", &self.char_limit)
            .field("key_map", &self.key_map)
            .field("validate", &super::opaque(self.validate.as_ref()))
            .field("show_suggestions", &self.show_suggestions)
            .field("styles", &self.styles)
            .field("width", &self.width)
            .field("value", &self.value)
            .field("pos", &self.pos)
            .field("offset", &self.offset)
            .field("offset_right", &self.offset_right)
            .field("virtual_cursor", &self.virtual_cursor)
            .field("suggestions", &self.suggestions)
            .field("matched", &self.matched)
            .field("current_suggestion", &self.current_suggestion)
            .field("flags", &self.flags)
            .finish()
    }
}

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

impl Model {
    /// An empty, blurred input with the prompt `"> "`: `textinput.New`.
    ///
    /// ```
    /// use petitcarnets as tea;
    /// use tea::bubbles::textinput;
    ///
    /// let input = textinput::Model::new();
    /// assert_eq!(input.prompt, "> ");
    /// assert_eq!(input.value(), "");
    /// assert!(!input.focused());
    /// ```
    #[must_use]
    pub fn new() -> Self {
        let mut m = Self {
            err: None,
            prompt: "> ".into(),
            placeholder: String::new(),
            echo_mode: EchoMode::Normal,
            echo_character: '*',
            char_limit: 0,
            key_map: KeyMap::default(),
            validate: None,
            show_suggestions: false,
            styles: Styles::new(true),
            width: 0,
            value: Vec::new(),
            pos: 0,
            offset: 0,
            offset_right: 0,
            virtual_cursor: cursor::Model::new(),
            suggestions: Vec::new(),
            matched: Vec::new(),
            current_suggestion: 0,
            flags: Flags(USE_VIRTUAL_CURSOR),
        };
        m.update_cursor_style();
        m
    }

    /// Whether the cursor is drawn in the view (the default) rather
    /// than being the terminal's own, from [`Model::cursor`].
    ///
    /// ```
    /// use petitcarnets as tea;
    /// use tea::bubbles::textinput;
    ///
    /// let mut input = textinput::Model::new();
    /// assert!(input.virtual_cursor());
    /// input.set_virtual_cursor(false);
    /// assert!(!input.virtual_cursor());
    /// ```
    #[must_use]
    pub const fn virtual_cursor(&self) -> bool {
        self.flags.get(USE_VIRTUAL_CURSOR)
    }

    /// Draws the cursor in the view, or leaves it to the terminal.
    ///
    /// ```
    /// use petitcarnets as tea;
    /// use tea::bubbles::textinput;
    ///
    /// let mut input = textinput::Model::new();
    /// let _ = input.focus();
    /// input.set_value("hi");
    /// assert_eq!(input.cursor(), None, "drawn in the view");
    /// input.set_virtual_cursor(false);
    /// assert_eq!(
    ///     input.cursor().map(|c| c.x),
    ///     Some(4),
    ///     "the terminal's, after \"> hi\""
    /// );
    /// ```
    pub fn set_virtual_cursor(&mut self, on: bool) {
        self.flags.set(USE_VIRTUAL_CURSOR, on);
        self.update_cursor_style();
    }

    /// The styles.
    ///
    /// ```
    /// use petitcarnets as tea;
    /// use tea::bubbles::textinput;
    ///
    /// let input = textinput::Model::new();
    /// assert_eq!(input.styles(), textinput::Styles::new(true));
    /// ```
    #[must_use]
    pub const fn styles(&self) -> Styles {
        self.styles
    }

    /// Replaces the styles.
    ///
    /// ```
    /// use petitcarnets as tea;
    /// use tea::bubbles::textinput;
    ///
    /// let mut styles = textinput::Styles::new(false);
    /// styles.focused.prompt = tea::style::Style::new().bold(true);
    /// let mut input = textinput::Model::new();
    /// input.set_styles(styles);
    /// assert_eq!(input.styles(), styles);
    /// ```
    pub fn set_styles(&mut self, styles: Styles) {
        self.styles = styles;
        self.update_cursor_style();
    }

    /// The cursor drawn in the view follows the styles.
    fn update_cursor_style(&mut self) {
        let c = self.styles.cursor;
        let mode = if !self.flags.get(USE_VIRTUAL_CURSOR) {
            Mode::Hide
        } else if c.blink {
            Mode::Blink
        } else {
            Mode::Static
        };
        if self.flags.get(USE_VIRTUAL_CURSOR) {
            self.virtual_cursor.style = Style::new().foreground(c.color);
            if c.blink && !c.blink_speed.is_zero() {
                self.virtual_cursor.blink_speed = c.blink_speed;
            }
        }
        let _ = self.virtual_cursor.set_mode(mode);
    }

    /// The width the text shows in, in cells; 0 is no limit.
    ///
    /// ```
    /// use petitcarnets as tea;
    /// use tea::bubbles::textinput;
    ///
    /// let mut input = textinput::Model::new();
    /// assert_eq!(input.width(), 0, "no limit");
    /// input.set_width(20);
    /// assert_eq!(input.width(), 20);
    /// ```
    #[must_use]
    pub const fn width(&self) -> usize {
        self.width
    }

    /// Sets the width.
    ///
    /// ```
    /// use petitcarnets as tea;
    /// use tea::bubbles::textinput;
    ///
    /// let mut input = textinput::Model::new();
    /// input.set_width(3);
    /// let _ = input.focus();
    /// input.set_value("abcdef");
    /// assert_eq!(
    ///     tea::style::strip_ansi(&input.view()),
    ///     "> def ",
    ///     "scrolled to the cursor"
    /// );
    /// ```
    pub const fn set_width(&mut self, columns: usize) {
        self.width = columns;
    }

    /// Whether it is focused: only a focused input takes keys.
    ///
    /// ```
    /// use petitcarnets as tea;
    /// use tea::bubbles::textinput;
    ///
    /// let mut input = textinput::Model::new();
    /// assert!(!input.focused());
    /// let _ = input.focus();
    /// assert!(input.focused());
    /// ```
    #[must_use]
    pub const fn focused(&self) -> bool {
        self.flags.get(FOCUS)
    }

    /// Focuses it; the command starts the cursor blinking.
    ///
    /// ```
    /// use petitcarnets as tea;
    /// use tea::bubbles::textinput;
    ///
    /// let mut input = textinput::Model::new();
    /// let blink = input.focus();
    /// assert!(input.focused());
    /// assert!(!blink.is_none(), "the cursor starts blinking");
    /// ```
    pub fn focus(&mut self) -> Cmd<Msg> {
        self.flags.set(FOCUS, true);
        self.virtual_cursor.focus()
    }

    /// Blurs it.
    ///
    /// ```
    /// use petitcarnets as tea;
    /// use tea::bubbles::textinput;
    ///
    /// let mut input = textinput::Model::new();
    /// let _ = input.focus();
    /// input.blur();
    /// assert!(!input.focused());
    /// let _ = input.update(&tea::Msg::KeyPress(tea::Key::char('a')));
    /// assert_eq!(input.value(), "", "a blurred input takes no keys");
    /// ```
    pub const fn blur(&mut self) {
        self.flags.set(FOCUS, false);
        self.virtual_cursor.blur();
    }

    /// Empties it.
    ///
    /// ```
    /// use petitcarnets as tea;
    /// use tea::bubbles::textinput;
    ///
    /// let mut input = textinput::Model::new();
    /// input.set_value("abc");
    /// input.reset();
    /// assert_eq!((input.value().as_str(), input.position()), ("", 0));
    /// ```
    pub fn reset(&mut self) {
        self.value.clear();
        self.set_cursor(0);
    }

    /// Edits on its keys and pastes while focused, and blinks its
    /// cursor. Ctrl-V asks the terminal for the clipboard (OSC 52) and
    /// pastes its reply, [`Msg::Clipboard`](crate::Msg::Clipboard).
    ///
    /// ```
    /// use petitcarnets as tea;
    /// use tea::bubbles::textinput;
    ///
    /// let mut input = textinput::Model::new();
    /// let _ = input.focus();
    /// let _ = input.update(&tea::Msg::Paste("hello world".into()));
    /// let _ = input.update(&tea::Msg::KeyPress(tea::Key::ctrl('w')));
    /// assert_eq!(input.value(), "hello ", "Ctrl-W deletes a word");
    /// ```
    pub fn update(&mut self, msg: &TeaMsg<Msg>) -> Cmd<Msg> {
        if !self.flags.get(FOCUS) {
            return Cmd::none();
        }
        let old = self.pos;
        let mut cmds = Vec::new();
        match msg {
            TeaMsg::KeyPress(key) => cmds.push(self.press(key)),
            TeaMsg::Paste(text) => self.insert_from_user(text),
            TeaMsg::Clipboard { content, .. } if self.flags.get(PASTE_PENDING) => {
                self.flags.set(PASTE_PENDING, false);
                self.insert_from_user(content);
            }
            _ => {}
        }
        if self.flags.get(USE_VIRTUAL_CURSOR) {
            cmds.push(self.virtual_cursor.update(msg));
            if old != self.pos && self.virtual_cursor.mode() == Mode::Blink {
                self.virtual_cursor.is_blinked = false;
                cmds.push(self.virtual_cursor.blink());
            }
        }
        self.handle_overflow();
        batch(cmds)
    }

    /// The text cleaned and validated, as a change from the keyboard.
    fn check(&self, chars: &[char]) -> Option<String> {
        let text: String = chars.iter().collect();
        self.validate.as_ref().and_then(|f| f(&text).err())
    }
}

/// A command that starts a focused textinput's cursor blinking: Bubbles'
/// `textinput.Blink`.
///
/// ```
/// use petitcarnets as tea;
/// use tea::bubbles::textinput;
///
/// use std::time::Duration;
///
/// struct App(textinput::Model);
///
/// impl tea::Model for App {
///     type Msg = textinput::Msg;
///     fn init(&mut self) -> tea::Cmd<textinput::Msg> {
///         textinput::blink()
///     }
///     fn update(&mut self, msg: tea::Msg<textinput::Msg>) -> tea::Cmd<textinput::Msg> {
///         self.0.update(&msg)
///     }
///     fn view(&self) -> tea::View {
///         self.0.view().into()
///     }
/// }
///
/// let mut input = textinput::Model::new();
/// let _ = input.focus();
/// let mut p = tea::testing::TestProgram::new(App(input), 10, 1);
/// let shown = p.model().0.view();
/// p.advance(Duration::from_millis(600));
/// assert_ne!(p.model().0.view(), shown, "the cursor blinked off");
/// ```
pub fn blink() -> Cmd<Msg> {
    cursor::blink()
}

#[cfg(test)]
mod tests;