envision 0.16.0

A ratatui framework for collaborative TUI development with headless testing support
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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
//! A numeric input component with validation, increment/decrement, and optional bounds.
//!
//! [`NumberInput`] provides a focused numeric entry field that supports
//! Up/Down (or k/j) for increment/decrement, Enter to switch into text-edit
//! mode, and optional min/max clamping.
//!
//! State is stored in [`NumberInputState`], updated via [`NumberInputMessage`],
//! and produces [`NumberInputOutput`].
//!
//!
//! See also [`Slider`](super::Slider) for range selection with a visual track,
//! and [`InputField`](super::InputField) for general text input.
//!
//! # Example
//!
//! ```rust
//! use envision::component::{NumberInput, NumberInputMessage, NumberInputOutput, NumberInputState, Component};
//!
//! // Create a number input starting at 42
//! let mut state = NumberInputState::new(42.0);
//! assert_eq!(state.value(), 42.0);
//!
//! // Increment the value
//! let output = NumberInput::update(&mut state, NumberInputMessage::Increment);
//! assert_eq!(output, Some(NumberInputOutput::ValueChanged(43.0)));
//! assert_eq!(state.value(), 43.0);
//!
//! // Set value directly
//! let output = NumberInput::update(&mut state, NumberInputMessage::SetValue(100.0));
//! assert_eq!(output, Some(NumberInputOutput::ValueChanged(100.0)));
//! ```

use ratatui::prelude::*;
use ratatui::widgets::{Block, Borders, Paragraph};

use super::{Component, EventContext, RenderContext};
use crate::input::{Event, Key};

/// Messages that can be sent to a NumberInput.
#[derive(Clone, Debug, PartialEq)]
pub enum NumberInputMessage {
    /// Increase value by one step.
    Increment,
    /// Decrease value by one step.
    Decrement,
    /// Set value directly (clamped to bounds).
    SetValue(f64),
    /// Enter text edit mode.
    StartEdit,
    /// Parse edit buffer and apply the value.
    ConfirmEdit,
    /// Discard edit buffer and exit edit mode.
    CancelEdit,
    /// Append a character to the edit buffer.
    EditChar(char),
    /// Delete the last character from the edit buffer.
    EditBackspace,
}

/// Output messages from a NumberInput.
#[derive(Clone, Debug, PartialEq)]
pub enum NumberInputOutput {
    /// The numeric value changed. Contains the new value.
    ValueChanged(f64),
    /// Entered text edit mode.
    EditStarted,
    /// Edit confirmed with a new value.
    EditConfirmed(f64),
    /// Edit was cancelled.
    EditCancelled,
}

/// State for a NumberInput component.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct NumberInputState {
    /// The current numeric value.
    value: f64,
    /// Optional minimum bound.
    min: Option<f64>,
    /// Optional maximum bound.
    max: Option<f64>,
    /// Increment/decrement step size.
    step: f64,
    /// Decimal places to display.
    precision: usize,
    /// Optional label.
    label: Option<String>,
    /// Placeholder text shown when empty in edit mode.
    placeholder: Option<String>,
    /// Whether currently in text edit mode.
    editing: bool,
    /// Text buffer used during edit mode.
    edit_buffer: String,
}

impl Default for NumberInputState {
    fn default() -> Self {
        Self {
            value: 0.0,
            min: None,
            max: None,
            step: 1.0,
            precision: 0,
            label: None,
            placeholder: None,
            editing: false,
            edit_buffer: String::new(),
        }
    }
}

impl NumberInputState {
    /// Creates a new number input with the given initial value.
    ///
    /// Defaults to step 1.0 and precision 0 (integer display).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::NumberInputState;
    ///
    /// let state = NumberInputState::new(42.0);
    /// assert_eq!(state.value(), 42.0);
    /// assert_eq!(state.format_value(), "42");
    /// ```
    pub fn new(value: f64) -> Self {
        Self {
            value,
            ..Self::default()
        }
    }

    /// Creates a new number input configured for integer values.
    ///
    /// Convenience constructor that sets precision to 0 and step to 1.0.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::NumberInputState;
    ///
    /// let state = NumberInputState::integer(42);
    /// assert_eq!(state.value(), 42.0);
    /// assert_eq!(state.format_value(), "42");
    /// ```
    pub fn integer(value: i64) -> Self {
        Self {
            value: value as f64,
            step: 1.0,
            precision: 0,
            ..Self::default()
        }
    }

    /// Sets the minimum bound (builder pattern).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::NumberInputState;
    ///
    /// let state = NumberInputState::new(5.0).with_min(0.0);
    /// ```
    pub fn with_min(mut self, min: f64) -> Self {
        self.min = Some(min);
        self.value = self.clamp(self.value);
        self
    }

    /// Sets the maximum bound (builder pattern).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::NumberInputState;
    ///
    /// let state = NumberInputState::new(5.0).with_max(10.0);
    /// ```
    pub fn with_max(mut self, max: f64) -> Self {
        self.max = Some(max);
        self.value = self.clamp(self.value);
        self
    }

    /// Sets both minimum and maximum bounds (builder pattern).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::NumberInputState;
    ///
    /// let state = NumberInputState::new(5.0).with_range(0.0, 10.0);
    /// ```
    pub fn with_range(mut self, min: f64, max: f64) -> Self {
        self.min = Some(min);
        self.max = Some(max);
        self.value = self.clamp(self.value);
        self
    }

    /// Sets the step size (builder pattern).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::NumberInputState;
    ///
    /// let state = NumberInputState::new(0.0).with_step(0.5);
    /// ```
    pub fn with_step(mut self, step: f64) -> Self {
        self.step = step;
        self
    }

    /// Sets the decimal precision (builder pattern).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::NumberInputState;
    ///
    /// let state = NumberInputState::new(3.75).with_precision(2);
    /// assert_eq!(state.format_value(), "3.75");
    /// ```
    pub fn with_precision(mut self, precision: usize) -> Self {
        self.precision = precision;
        self
    }

    /// Sets the label (builder pattern).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::NumberInputState;
    ///
    /// let state = NumberInputState::new(0.0).with_label("Quantity");
    /// assert_eq!(state.label(), Some("Quantity"));
    /// ```
    pub fn with_label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// Sets the placeholder text (builder pattern).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::NumberInputState;
    ///
    /// let state = NumberInputState::new(0.0).with_placeholder("Enter value...");
    /// ```
    pub fn with_placeholder(mut self, placeholder: impl Into<String>) -> Self {
        self.placeholder = Some(placeholder.into());
        self
    }

    /// Returns the current numeric value.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::NumberInputState;
    ///
    /// let state = NumberInputState::new(42.0);
    /// assert_eq!(state.value(), 42.0);
    /// ```
    pub fn value(&self) -> f64 {
        self.value
    }

    /// Sets the current value, clamping to any configured bounds.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::NumberInputState;
    ///
    /// let mut state = NumberInputState::new(0.0).with_range(0.0, 100.0);
    /// state.set_value(50.0);
    /// assert_eq!(state.value(), 50.0);
    ///
    /// state.set_value(200.0);
    /// assert_eq!(state.value(), 100.0);
    /// ```
    pub fn set_value(&mut self, value: f64) {
        self.value = self.clamp(value);
    }

    /// Returns true if the component is in text edit mode.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{NumberInputState, NumberInputMessage, NumberInput, Component};
    ///
    /// let mut state = NumberInputState::new(0.0);
    /// assert!(!state.is_editing());
    /// NumberInput::update(&mut state, NumberInputMessage::StartEdit);
    /// assert!(state.is_editing());
    /// ```
    pub fn is_editing(&self) -> bool {
        self.editing
    }

    /// Returns the current edit buffer contents.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{NumberInputState, NumberInputMessage, NumberInput, Component};
    ///
    /// let mut state = NumberInputState::new(42.0);
    /// NumberInput::update(&mut state, NumberInputMessage::StartEdit);
    /// assert_eq!(state.edit_buffer(), "42");
    /// ```
    pub fn edit_buffer(&self) -> &str {
        &self.edit_buffer
    }

    /// Returns the label, if set.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::NumberInputState;
    ///
    /// let state = NumberInputState::new(0.0).with_label("Speed");
    /// assert_eq!(state.label(), Some("Speed"));
    /// ```
    pub fn label(&self) -> Option<&str> {
        self.label.as_deref()
    }

    /// Returns the placeholder, if set.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::NumberInputState;
    ///
    /// let state = NumberInputState::new(0.0).with_placeholder("Enter value");
    /// assert_eq!(state.placeholder(), Some("Enter value"));
    /// ```
    pub fn placeholder(&self) -> Option<&str> {
        self.placeholder.as_deref()
    }

    /// Sets the placeholder text.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::NumberInputState;
    ///
    /// let mut state = NumberInputState::new(0.0);
    /// state.set_placeholder("Enter a number...");
    /// assert_eq!(state.placeholder(), Some("Enter a number..."));
    /// ```
    pub fn set_placeholder(&mut self, placeholder: impl Into<String>) {
        self.placeholder = Some(placeholder.into());
    }

    /// Returns the step size.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::NumberInputState;
    ///
    /// let state = NumberInputState::new(0.0).with_step(0.5);
    /// assert_eq!(state.step(), 0.5);
    /// ```
    pub fn step(&self) -> f64 {
        self.step
    }

    /// Returns the precision (decimal places).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::NumberInputState;
    ///
    /// let state = NumberInputState::new(0.0).with_precision(2);
    /// assert_eq!(state.precision(), 2);
    /// ```
    pub fn precision(&self) -> usize {
        self.precision
    }

    /// Returns the minimum bound, if set.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::NumberInputState;
    ///
    /// let state = NumberInputState::new(0.0).with_min(0.0);
    /// assert_eq!(state.min(), Some(0.0));
    /// ```
    pub fn min(&self) -> Option<f64> {
        self.min
    }

    /// Returns the maximum bound, if set.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::NumberInputState;
    ///
    /// let state = NumberInputState::new(0.0).with_max(100.0);
    /// assert_eq!(state.max(), Some(100.0));
    /// ```
    pub fn max(&self) -> Option<f64> {
        self.max
    }

    /// Formats the current value according to the configured precision.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::NumberInputState;
    ///
    /// let state = NumberInputState::new(42.0);
    /// assert_eq!(state.format_value(), "42");
    ///
    /// let state = NumberInputState::new(3.75).with_precision(2);
    /// assert_eq!(state.format_value(), "3.75");
    /// ```
    pub fn format_value(&self) -> String {
        format!("{:.prec$}", self.value, prec = self.precision)
    }

    /// Updates the number input state with a message, returning any output.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{NumberInputMessage, NumberInputOutput, NumberInputState};
    ///
    /// let mut state = NumberInputState::new(10.0);
    /// let output = state.update(NumberInputMessage::Increment);
    /// assert_eq!(output, Some(NumberInputOutput::ValueChanged(11.0)));
    /// assert_eq!(state.value(), 11.0);
    /// ```
    pub fn update(&mut self, msg: NumberInputMessage) -> Option<NumberInputOutput> {
        NumberInput::update(self, msg)
    }

    /// Clamps a value to the configured bounds.
    fn clamp(&self, value: f64) -> f64 {
        let mut v = value;
        if let Some(min) = self.min {
            if v < min {
                v = min;
            }
        }
        if let Some(max) = self.max {
            if v > max {
                v = max;
            }
        }
        v
    }
}

/// A numeric input component with validation and increment/decrement support.
///
/// `NumberInput` provides a focused entry field for numeric values. It supports:
///
/// - **Increment/Decrement** via Up/Down arrow keys (or k/j)
/// - **Direct text editing** by pressing Enter to switch into edit mode
/// - **Validation** with optional min/max bounds
/// - **Configurable precision** for integer or floating-point display
///
/// # Keyboard Controls
///
/// Normal mode (not editing):
/// - Up / k: increment by step
/// - Down / j: decrement by step
/// - Enter: enter text edit mode
///
/// Edit mode:
/// - 0-9, '.', '-': append to edit buffer
/// - Backspace: delete last character
/// - Enter: confirm edit (parse and apply)
/// - Escape: cancel edit
///
/// # Visual Format
///
/// Normal mode:
/// ```text
/// ┌──────────────────┐
/// │ Label:       42  │
/// └──────────────────┘
/// ```
///
/// Edit mode:
/// ```text
/// ┌──────────────────┐
/// │ Label:      42_  │
/// └──────────────────┘
/// ```
///
/// # Example
///
/// ```rust
/// use envision::component::{NumberInput, NumberInputMessage, NumberInputOutput, NumberInputState, Component};
///
/// let mut state = NumberInputState::new(50.0)
///     .with_range(0.0, 100.0)
///     .with_step(5.0)
///     .with_label("Volume");
///
/// let output = NumberInput::update(&mut state, NumberInputMessage::Increment);
/// assert_eq!(output, Some(NumberInputOutput::ValueChanged(55.0)));
/// assert_eq!(state.value(), 55.0);
/// ```
pub struct NumberInput;

impl Component for NumberInput {
    type State = NumberInputState;
    type Message = NumberInputMessage;
    type Output = NumberInputOutput;

    fn init() -> Self::State {
        NumberInputState::default()
    }

    fn update(state: &mut Self::State, msg: Self::Message) -> Option<Self::Output> {
        match msg {
            NumberInputMessage::Increment => {
                let old = state.value;
                let new = state.clamp(state.value + state.step);
                if (new - old).abs() > f64::EPSILON {
                    state.value = new;
                    Some(NumberInputOutput::ValueChanged(state.value))
                } else {
                    None
                }
            }
            NumberInputMessage::Decrement => {
                let old = state.value;
                let new = state.clamp(state.value - state.step);
                if (new - old).abs() > f64::EPSILON {
                    state.value = new;
                    Some(NumberInputOutput::ValueChanged(state.value))
                } else {
                    None
                }
            }
            NumberInputMessage::SetValue(v) => {
                let old = state.value;
                let new = state.clamp(v);
                if (new - old).abs() > f64::EPSILON {
                    state.value = new;
                    Some(NumberInputOutput::ValueChanged(state.value))
                } else {
                    None
                }
            }
            NumberInputMessage::StartEdit => {
                state.editing = true;
                state.edit_buffer = state.format_value();
                Some(NumberInputOutput::EditStarted)
            }
            NumberInputMessage::ConfirmEdit => {
                state.editing = false;
                if let Ok(parsed) = state.edit_buffer.parse::<f64>() {
                    let new = state.clamp(parsed);
                    state.value = new;
                    state.edit_buffer.clear();
                    Some(NumberInputOutput::EditConfirmed(state.value))
                } else {
                    // Invalid input: revert to current value
                    state.edit_buffer.clear();
                    Some(NumberInputOutput::EditCancelled)
                }
            }
            NumberInputMessage::CancelEdit => {
                state.editing = false;
                state.edit_buffer.clear();
                Some(NumberInputOutput::EditCancelled)
            }
            NumberInputMessage::EditChar(c) => {
                if is_valid_numeric_char(c, &state.edit_buffer) {
                    state.edit_buffer.push(c);
                }
                None
            }
            NumberInputMessage::EditBackspace => {
                state.edit_buffer.pop();
                None
            }
        }
    }

    fn handle_event(
        state: &Self::State,
        event: &Event,
        ctx: &EventContext,
    ) -> Option<Self::Message> {
        if !ctx.focused || ctx.disabled {
            return None;
        }

        if let Some(key) = event.as_key() {
            if state.editing {
                // Edit mode key handling
                match key.code {
                    Key::Enter => Some(NumberInputMessage::ConfirmEdit),
                    Key::Esc => Some(NumberInputMessage::CancelEdit),
                    Key::Backspace => Some(NumberInputMessage::EditBackspace),
                    Key::Char(_) => key
                        .raw_char
                        .filter(|c| is_valid_numeric_char(*c, &state.edit_buffer))
                        .map(NumberInputMessage::EditChar),
                    _ => None,
                }
            } else {
                // Normal mode key handling
                match key.code {
                    Key::Up | Key::Char('k') => Some(NumberInputMessage::Increment),
                    Key::Down | Key::Char('j') => Some(NumberInputMessage::Decrement),
                    Key::Enter => Some(NumberInputMessage::StartEdit),
                    _ => None,
                }
            }
        } else {
            None
        }
    }

    fn view(state: &Self::State, ctx: &mut RenderContext<'_, '_>) {
        if ctx.area.width == 0 || ctx.area.height == 0 {
            return;
        }

        let border_style = if ctx.focused {
            ctx.theme.focused_border_style()
        } else {
            ctx.theme.border_style()
        };

        let block = Block::default()
            .borders(Borders::ALL)
            .border_style(border_style);

        let content_style = if ctx.disabled {
            ctx.theme.disabled_style()
        } else if ctx.focused {
            ctx.theme.focused_style()
        } else {
            ctx.theme.normal_style()
        };

        // Build the display text
        let display_text = if state.editing {
            let cursor = "_";
            if state.edit_buffer.is_empty() {
                if let Some(placeholder) = &state.placeholder {
                    placeholder.clone()
                } else {
                    cursor.to_string()
                }
            } else {
                format!("{}{cursor}", state.edit_buffer)
            }
        } else {
            state.format_value()
        };

        // Build the full line with optional label
        let full_text = if let Some(label) = &state.label {
            format!("{label}: {display_text}")
        } else {
            display_text
        };

        let paragraph = Paragraph::new(full_text)
            .style(content_style)
            .block(block)
            .alignment(Alignment::Right);

        // Register annotation
        let value_str = state.format_value();
        let annotation = crate::annotation::Annotation::new(crate::annotation::WidgetType::Custom(
            "NumberInput".to_string(),
        ))
        .with_id("number_input")
        .with_value(value_str);

        let annotation = if let Some(label) = &state.label {
            annotation.with_label(label.as_str())
        } else {
            annotation
        };

        let annotated = crate::annotation::Annotate::new(paragraph, annotation)
            .focused(ctx.focused)
            .disabled(ctx.disabled);
        ctx.frame.render_widget(annotated, ctx.area);
    }
}

/// Returns true if the character is valid for numeric input.
///
/// Allows digits, a single decimal point, and a leading minus sign.
fn is_valid_numeric_char(c: char, buffer: &str) -> bool {
    match c {
        '0'..='9' => true,
        '.' => !buffer.contains('.'),
        '-' => buffer.is_empty(),
        _ => false,
    }
}

#[cfg(test)]
mod tests;
#[cfg(test)]
mod view_tests;