fresh-editor 0.4.0

A lightweight, fast terminal-based text editor with LSP support and TypeScript plugins
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
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
//! Number input control
//!
//! Renders as: `Label: [  42 ]` — direct-typing only; focus the field and
//! type digits / `-` / `.` to replace the value.
//!
//! This module provides a complete number input component with:
//! - State management (`NumberInputState`)
//! - Rendering (`render_number_input`, `render_number_input_aligned`)
//! - Input handling (`NumberInputState::handle_mouse`, `handle_key`)
//! - Layout/hit testing (`NumberInputLayout`)

mod input;
mod render;

use ratatui::layout::Rect;
use ratatui::style::Color;

pub use input::NumberInputEvent;
pub use render::{render_number_input, render_number_input_aligned};

use super::FocusState;
use crate::primitives::text_edit::TextEdit;

/// State for a number input control
#[derive(Debug, Clone)]
pub struct NumberInputState {
    /// Current value
    pub value: i64,
    /// Minimum allowed value
    pub min: Option<i64>,
    /// Maximum allowed value
    pub max: Option<i64>,
    /// Step amount for increment/decrement
    pub step: i64,
    /// Label displayed before the input
    pub label: String,
    /// Focus state
    pub focus: FocusState,
    /// Text editor for editing mode (None when not editing)
    pub editor: Option<TextEdit>,
    /// Whether this value is a percentage (float value * 100 for display)
    /// When true, the value should be divided by 100 when converting back to JSON
    pub is_percentage: bool,
}

impl NumberInputState {
    /// Create a new number input state
    pub fn new(value: i64, label: impl Into<String>) -> Self {
        Self {
            value,
            min: None,
            max: None,
            step: 1,
            label: label.into(),
            focus: FocusState::Normal,
            editor: None,
            is_percentage: false,
        }
    }

    /// Check if currently editing
    pub fn editing(&self) -> bool {
        self.editor.is_some()
    }

    /// Set the minimum value
    pub fn with_min(mut self, min: i64) -> Self {
        self.min = Some(min);
        self
    }

    /// Set the maximum value
    pub fn with_max(mut self, max: i64) -> Self {
        self.max = Some(max);
        self
    }

    /// Set the step amount
    pub fn with_step(mut self, step: i64) -> Self {
        self.step = step;
        self
    }

    /// Set the focus state
    pub fn with_focus(mut self, focus: FocusState) -> Self {
        self.focus = focus;
        self
    }

    /// Mark this value as a percentage (float * 100 for display)
    pub fn with_percentage(mut self) -> Self {
        self.is_percentage = true;
        self
    }

    /// Check if the control is enabled
    pub fn is_enabled(&self) -> bool {
        self.focus != FocusState::Disabled
    }

    /// Increment the value by step
    pub fn increment(&mut self) {
        if !self.is_enabled() {
            return;
        }
        let new_value = self.value.saturating_add(self.step);
        self.value = match self.max {
            Some(max) => new_value.min(max),
            None => new_value,
        };
    }

    /// Decrement the value by step
    pub fn decrement(&mut self) {
        if !self.is_enabled() {
            return;
        }
        let new_value = self.value.saturating_sub(self.step);
        self.value = match self.min {
            Some(min) => new_value.max(min),
            None => new_value,
        };
    }

    /// Set the value directly, respecting min/max
    pub fn set_value(&mut self, value: i64) {
        if !self.is_enabled() {
            return;
        }
        let mut v = value;
        if let Some(min) = self.min {
            v = v.max(min);
        }
        if let Some(max) = self.max {
            v = v.min(max);
        }
        self.value = v;
    }

    /// Start editing mode
    pub fn start_editing(&mut self) {
        if !self.is_enabled() {
            return;
        }
        let mut editor = TextEdit::single_line();
        editor.set_value(&self.value.to_string());
        // Select all text so typing replaces the value
        editor.select_all();
        self.editor = Some(editor);
    }

    /// Cancel editing and restore original value
    pub fn cancel_editing(&mut self) {
        self.editor = None;
    }

    /// Confirm editing and apply the new value
    pub fn confirm_editing(&mut self) {
        if let Some(editor) = self.editor.take() {
            if let Ok(new_value) = editor.value().parse::<i64>() {
                self.set_value(new_value);
            }
        }
    }

    /// Insert a character while editing
    /// Allows digits, minus sign, and decimal point for number input
    pub fn insert_char(&mut self, c: char) {
        if let Some(editor) = &mut self.editor {
            // Allow digits, minus sign, and decimal point
            if c.is_ascii_digit() || c == '-' || c == '.' {
                editor.insert_char(c);
            }
        }
    }

    /// Backspace while editing
    pub fn backspace(&mut self) {
        if let Some(editor) = &mut self.editor {
            editor.backspace();
        }
    }

    /// Delete character at cursor
    pub fn delete(&mut self) {
        if let Some(editor) = &mut self.editor {
            editor.delete();
        }
    }

    /// Move cursor left
    pub fn move_left(&mut self) {
        if let Some(editor) = &mut self.editor {
            editor.move_left();
        }
    }

    /// Move cursor right
    pub fn move_right(&mut self) {
        if let Some(editor) = &mut self.editor {
            editor.move_right();
        }
    }

    /// Move cursor to start of text
    pub fn move_home(&mut self) {
        if let Some(editor) = &mut self.editor {
            editor.move_home();
        }
    }

    /// Move cursor to end of text
    pub fn move_end(&mut self) {
        if let Some(editor) = &mut self.editor {
            editor.move_end();
        }
    }

    /// Move cursor left by word (Ctrl+Left)
    pub fn move_word_left(&mut self) {
        if let Some(editor) = &mut self.editor {
            editor.move_word_left();
        }
    }

    /// Move cursor right by word (Ctrl+Right)
    pub fn move_word_right(&mut self) {
        if let Some(editor) = &mut self.editor {
            editor.move_word_right();
        }
    }

    /// Move cursor left with selection (Shift+Left)
    pub fn move_left_selecting(&mut self) {
        if let Some(editor) = &mut self.editor {
            editor.move_left_selecting();
        }
    }

    /// Move cursor right with selection (Shift+Right)
    pub fn move_right_selecting(&mut self) {
        if let Some(editor) = &mut self.editor {
            editor.move_right_selecting();
        }
    }

    /// Move to start with selection (Shift+Home)
    pub fn move_home_selecting(&mut self) {
        if let Some(editor) = &mut self.editor {
            editor.move_home_selecting();
        }
    }

    /// Move to end with selection (Shift+End)
    pub fn move_end_selecting(&mut self) {
        if let Some(editor) = &mut self.editor {
            editor.move_end_selecting();
        }
    }

    /// Move word left with selection (Ctrl+Shift+Left)
    pub fn move_word_left_selecting(&mut self) {
        if let Some(editor) = &mut self.editor {
            editor.move_word_left_selecting();
        }
    }

    /// Move word right with selection (Ctrl+Shift+Right)
    pub fn move_word_right_selecting(&mut self) {
        if let Some(editor) = &mut self.editor {
            editor.move_word_right_selecting();
        }
    }

    /// Select all text (Ctrl+A)
    pub fn select_all(&mut self) {
        if let Some(editor) = &mut self.editor {
            editor.select_all();
        }
    }

    /// Delete from cursor to end of word (Ctrl+Delete)
    pub fn delete_word_forward(&mut self) {
        if let Some(editor) = &mut self.editor {
            editor.delete_word_forward();
        }
    }

    /// Delete from start of word to cursor (Ctrl+Backspace)
    pub fn delete_word_backward(&mut self) {
        if let Some(editor) = &mut self.editor {
            editor.delete_word_backward();
        }
    }

    /// Get selected text for copy
    pub fn selected_text(&self) -> Option<String> {
        self.editor.as_ref().and_then(|e| e.selected_text())
    }

    /// Delete selection and return deleted text (for cut)
    pub fn delete_selection(&mut self) -> Option<String> {
        self.editor.as_mut().and_then(|e| e.delete_selection())
    }

    /// Insert string at cursor (for paste)
    pub fn insert_str(&mut self, text: &str) {
        if let Some(editor) = &mut self.editor {
            // Filter to only allow valid number characters
            let filtered: String = text
                .chars()
                .filter(|c| c.is_ascii_digit() || *c == '-' || *c == '.')
                .collect();
            editor.insert_str(&filtered);
        }
    }

    /// Get the display text (edit text when editing, value otherwise)
    pub fn display_text(&self) -> String {
        if let Some(editor) = &self.editor {
            editor.value()
        } else {
            self.value.to_string()
        }
    }

    /// Get cursor position when editing (column in single-line text)
    pub fn cursor_col(&self) -> usize {
        self.editor.as_ref().map(|e| e.cursor_col).unwrap_or(0)
    }

    /// Check if there's an active selection
    pub fn has_selection(&self) -> bool {
        self.editor
            .as_ref()
            .map(|e| e.has_selection())
            .unwrap_or(false)
    }

    /// Get selection range as (start, end) column positions
    pub fn selection_range(&self) -> Option<(usize, usize)> {
        self.editor.as_ref().and_then(|e| {
            e.selection_range()
                .map(|((_, start_col), (_, end_col))| (start_col, end_col))
        })
    }
}

/// Colors for the number input control
#[derive(Debug, Clone, Copy)]
pub struct NumberInputColors {
    /// Label color
    pub label: Color,
    /// Value text color
    pub value: Color,
    /// Border/bracket color
    pub border: Color,
    /// Button color (increment/decrement)
    pub button: Color,
    /// Focused highlight background color
    pub focused: Color,
    /// Focused highlight foreground color (text on focused background)
    pub focused_fg: Color,
    /// Background colour for the in-edit selection range. Must contrast
    /// with `focused`, otherwise the selection is invisible whenever the
    /// row is also the focused (selected) row.
    pub selection_bg: Color,
    /// Disabled color
    pub disabled: Color,
}

impl Default for NumberInputColors {
    fn default() -> Self {
        Self {
            label: Color::White,
            value: Color::Yellow,
            border: Color::Gray,
            button: Color::Cyan,
            focused: Color::Cyan,
            focused_fg: Color::Black,
            selection_bg: Color::Blue,
            disabled: Color::DarkGray,
        }
    }
}

impl NumberInputColors {
    /// Create colors from theme
    pub fn from_theme(theme: &crate::view::theme::Theme) -> Self {
        Self {
            label: theme.editor_fg,
            value: theme.help_key_fg,
            border: theme.line_number_fg,
            button: theme.menu_active_fg,
            focused: theme.settings_selected_bg,
            focused_fg: theme.settings_selected_fg,
            // Use the editor's text-selection bg so the in-edit selection
            // is visible against the row's focus highlight (`focused`).
            selection_bg: theme.selection_bg,
            disabled: theme.line_number_fg,
        }
    }
}

/// Layout information returned after rendering for hit testing
#[derive(Debug, Clone, Copy, Default)]
pub struct NumberInputLayout {
    /// The value display area
    pub value_area: Rect,
    /// Legacy decrement-button area. Always empty since the buttons were
    /// removed in favour of direct typing; preserved so downstream layout
    /// code keeps compiling.
    pub decrement_area: Rect,
    /// Legacy increment-button area. Always empty (see `decrement_area`).
    pub increment_area: Rect,
    /// The full control area
    pub full_area: Rect,
}

impl NumberInputLayout {
    /// Check if a point is on the decrement button
    pub fn is_decrement(&self, x: u16, y: u16) -> bool {
        x >= self.decrement_area.x
            && x < self.decrement_area.x + self.decrement_area.width
            && y >= self.decrement_area.y
            && y < self.decrement_area.y + self.decrement_area.height
    }

    /// Check if a point is on the increment button
    pub fn is_increment(&self, x: u16, y: u16) -> bool {
        x >= self.increment_area.x
            && x < self.increment_area.x + self.increment_area.width
            && y >= self.increment_area.y
            && y < self.increment_area.y + self.increment_area.height
    }

    /// Check if a point is on the value area
    pub fn is_value(&self, x: u16, y: u16) -> bool {
        x >= self.value_area.x
            && x < self.value_area.x + self.value_area.width
            && y >= self.value_area.y
            && y < self.value_area.y + self.value_area.height
    }

    /// Check if a point is within any part of the control
    pub fn contains(&self, x: u16, y: u16) -> bool {
        x >= self.full_area.x
            && x < self.full_area.x + self.full_area.width
            && y >= self.full_area.y
            && y < self.full_area.y + self.full_area.height
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ratatui::backend::TestBackend;
    use ratatui::Terminal;

    fn test_frame<F>(width: u16, height: u16, f: F)
    where
        F: FnOnce(&mut ratatui::Frame, Rect),
    {
        let backend = TestBackend::new(width, height);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal
            .draw(|frame| {
                let area = Rect::new(0, 0, width, height);
                f(frame, area);
            })
            .unwrap();
    }

    #[test]
    fn test_number_input_renders() {
        test_frame(40, 1, |frame, area| {
            let state = NumberInputState::new(42, "Count");
            let colors = NumberInputColors::default();
            let layout = render_number_input(frame, area, &state, &colors);

            assert!(layout.value_area.width > 0);
            // Inc/dec buttons removed in favour of direct typing — areas are empty.
            assert_eq!(layout.decrement_area.width, 0);
            assert_eq!(layout.increment_area.width, 0);
        });
    }

    #[test]
    fn test_number_input_increment() {
        let mut state = NumberInputState::new(5, "Value");
        state.increment();
        assert_eq!(state.value, 6);
    }

    #[test]
    fn test_number_input_decrement() {
        let mut state = NumberInputState::new(5, "Value");
        state.decrement();
        assert_eq!(state.value, 4);
    }

    #[test]
    fn test_number_input_min_max() {
        let mut state = NumberInputState::new(5, "Value").with_min(0).with_max(10);

        state.set_value(-5);
        assert_eq!(state.value, 0);

        state.set_value(20);
        assert_eq!(state.value, 10);
    }

    #[test]
    fn test_number_input_step() {
        let mut state = NumberInputState::new(0, "Value").with_step(5);
        state.increment();
        assert_eq!(state.value, 5);
        state.increment();
        assert_eq!(state.value, 10);
    }

    #[test]
    fn test_number_input_disabled() {
        let mut state = NumberInputState::new(5, "Value").with_focus(FocusState::Disabled);
        state.increment();
        assert_eq!(state.value, 5);
    }

    #[test]
    fn test_number_input_hit_detection() {
        test_frame(40, 1, |frame, area| {
            let state = NumberInputState::new(42, "Count");
            let colors = NumberInputColors::default();
            let layout = render_number_input(frame, area, &state, &colors);

            // Value area is hittable; the (removed) inc/dec buttons are not.
            let val_x = layout.value_area.x;
            assert!(layout.is_value(val_x, 0));
            assert!(!layout.is_increment(val_x, 0));
            assert!(!layout.is_decrement(val_x, 0));
        });
    }

    #[test]
    fn test_number_input_start_editing() {
        let mut state = NumberInputState::new(42, "Value");
        assert!(!state.editing());
        assert_eq!(state.display_text(), "42");

        state.start_editing();
        assert!(state.editing());
        assert_eq!(state.display_text(), "42");
    }

    #[test]
    fn test_number_input_cancel_editing() {
        let mut state = NumberInputState::new(42, "Value");
        state.start_editing();
        // After start_editing, text is selected so typing replaces it
        state.insert_char('1');
        state.insert_char('0');
        state.insert_char('0');
        assert_eq!(state.display_text(), "100");

        state.cancel_editing();
        assert!(!state.editing());
        assert_eq!(state.display_text(), "42");
        assert_eq!(state.value, 42);
    }

    #[test]
    fn test_number_input_confirm_editing() {
        let mut state = NumberInputState::new(42, "Value");
        state.start_editing();
        // Clear and type new value
        state.select_all();
        state.insert_str("100");

        state.confirm_editing();
        assert!(!state.editing());
        assert_eq!(state.value, 100);
    }

    #[test]
    fn test_number_input_confirm_invalid_resets() {
        let mut state = NumberInputState::new(42, "Value");
        state.start_editing();
        // Type invalid text - only valid chars will be inserted
        state.select_all();
        state.insert_str("abc"); // This will be filtered to empty

        state.confirm_editing();
        assert!(!state.editing());
        // Value remains unchanged since empty string can't be parsed
        assert_eq!(state.value, 42);
    }

    #[test]
    fn test_number_input_insert_char() {
        let mut state = NumberInputState::new(0, "Value");
        state.start_editing();
        // Clear and insert new chars
        state.select_all();
        state.insert_char('1');
        state.insert_char('2');
        state.insert_char('3');
        assert_eq!(state.display_text(), "123");

        let mut state2 = NumberInputState::new(0, "Value");
        state2.start_editing();
        state2.select_all();
        state2.insert_char('-');
        assert_eq!(state2.display_text(), "-");
        state2.insert_char('-'); // Multiple minus signs allowed by TextEdit
        state2.insert_char('5');
        assert_eq!(state2.display_text(), "--5");
    }

    #[test]
    fn test_number_input_backspace() {
        let mut state = NumberInputState::new(123, "Value");
        state.start_editing();
        assert_eq!(state.display_text(), "123");

        // After start_editing, text is selected. Move to end to deselect.
        state.move_end();

        state.backspace();
        assert_eq!(state.display_text(), "12");
        state.backspace();
        assert_eq!(state.display_text(), "1");
        state.backspace();
        assert_eq!(state.display_text(), "");
        state.backspace();
        assert_eq!(state.display_text(), "");
    }

    #[test]
    fn test_number_input_display_text() {
        let mut state = NumberInputState::new(42, "Value");

        assert_eq!(state.display_text(), "42");

        state.start_editing();
        assert_eq!(state.display_text(), "42");
        // After start_editing, text is selected. Move to end to append.
        state.move_end();
        state.insert_char('0');
        assert_eq!(state.display_text(), "420");
    }

    #[test]
    fn test_number_input_editing_respects_minmax() {
        let mut state = NumberInputState::new(50, "Value").with_min(0).with_max(100);
        state.start_editing();
        state.select_all();
        state.insert_str("200");

        state.confirm_editing();
        assert_eq!(state.value, 100);
    }

    #[test]
    fn test_number_input_disabled_no_editing() {
        let mut state = NumberInputState::new(42, "Value").with_focus(FocusState::Disabled);
        state.start_editing();
        assert!(!state.editing());
    }

    #[test]
    fn test_number_input_decimal_point() {
        let mut state = NumberInputState::new(0, "Value");
        state.start_editing();
        state.select_all();
        state.insert_str("0.25");
        assert_eq!(state.display_text(), "0.25");

        // Confirm won't parse as i64, so value stays at 0
        state.confirm_editing();
        assert_eq!(state.value, 0);
    }

    #[test]
    fn test_number_input_selection() {
        let mut state = NumberInputState::new(12345, "Value");
        state.start_editing();
        assert_eq!(state.display_text(), "12345");

        // Select all and replace
        state.select_all();
        assert!(state.has_selection());
        state.insert_char('9');
        assert_eq!(state.display_text(), "9");
    }

    #[test]
    fn test_number_input_cursor_navigation() {
        let mut state = NumberInputState::new(123, "Value");
        state.start_editing();
        // Cursor starts at end
        assert_eq!(state.cursor_col(), 3);

        state.move_left();
        assert_eq!(state.cursor_col(), 2);

        state.move_home();
        assert_eq!(state.cursor_col(), 0);

        state.move_end();
        assert_eq!(state.cursor_col(), 3);
    }

    /// Regression: entering edit mode used to shrink `[  4  ]` (value cell
    /// rendered as `format!("{:^5}", "4")`) down to `[4]`, shifting the
    /// `[-]` / `[+]` buttons left. Both states must render the value cell
    /// at the same width.
    #[test]
    fn test_value_cell_width_stable_between_edit_and_view() {
        fn bracket_columns(state: &NumberInputState) -> (u16, u16) {
            let backend = TestBackend::new(40, 1);
            let mut terminal = Terminal::new(backend).unwrap();
            terminal
                .draw(|frame| {
                    let area = Rect::new(0, 0, 40, 1);
                    let colors = NumberInputColors::default();
                    render_number_input(frame, area, state, &colors);
                })
                .unwrap();
            let buffer = terminal.backend().buffer().clone();
            let mut open = None;
            let mut close = None;
            for x in 0..40 {
                let symbol = buffer.cell((x, 0)).map(|c| c.symbol()).unwrap_or("");
                if symbol == "[" && open.is_none() {
                    open = Some(x);
                } else if symbol == "]" && open.is_some() && close.is_none() {
                    close = Some(x);
                }
            }
            (
                open.expect("missing opening bracket"),
                close.expect("missing closing bracket"),
            )
        }

        let view_state = NumberInputState::new(4, "Tab Size");
        let mut edit_state = NumberInputState::new(4, "Tab Size");
        edit_state.start_editing();

        let view_brackets = bracket_columns(&view_state);
        let edit_brackets = bracket_columns(&edit_state);
        assert_eq!(
            view_brackets, edit_brackets,
            "value cell brackets must stay at the same columns when entering edit mode"
        );
    }

    /// Regression: the digit's column used to shift left as soon as the
    /// user started typing — the cursor block claimed the last cell and
    /// the right-aligned digit slid one column inward. The trailing
    /// reserved cell now keeps the digit pinned to the same column in
    /// view mode, while-selected, and while-typing.
    #[test]
    fn test_digit_column_stable_across_view_select_and_typing() {
        fn digit_column(state: &NumberInputState, digit: char) -> u16 {
            let backend = TestBackend::new(40, 1);
            let mut terminal = Terminal::new(backend).unwrap();
            terminal
                .draw(|frame| {
                    let area = Rect::new(0, 0, 40, 1);
                    let colors = NumberInputColors::default();
                    render_number_input(frame, area, state, &colors);
                })
                .unwrap();
            let buffer = terminal.backend().buffer().clone();
            let needle = digit.to_string();
            for x in 0..40 {
                let symbol = buffer.cell((x, 0)).map(|c| c.symbol()).unwrap_or("");
                if symbol == needle {
                    return x;
                }
            }
            panic!("digit {digit:?} not found on rendered line");
        }

        // View mode: "4" is rendered right-aligned with the trailing
        // reserved cell.
        let view_state = NumberInputState::new(4, "Tab Size");

        // Edit mode, select-all (cursor at end, value still "4").
        let mut select_state = NumberInputState::new(4, "Tab Size");
        select_state.start_editing();

        // Edit mode, after typing replaces selection with "1" (cursor at
        // end of the new value).
        let mut typed_state = NumberInputState::new(4, "Tab Size");
        typed_state.start_editing();
        typed_state.insert_char('1');

        let view_col = digit_column(&view_state, '4');
        let select_col = digit_column(&select_state, '4');
        let typed_col = digit_column(&typed_state, '1');

        assert_eq!(
            view_col, select_col,
            "digit must stay at the same column when entering edit mode"
        );
        assert_eq!(
            view_col, typed_col,
            "digit must stay at the same column after typing replaces the selection"
        );
    }

    /// Regression: the in-edit selection used to share its bg colour with
    /// the row's focus highlight, so `select_all()` (called on entering
    /// edit mode) rendered as bg-on-bg and was invisible. The two colours
    /// are now decoupled.
    #[test]
    fn test_selection_bg_distinct_from_focus_bg() {
        let theme = crate::view::theme::Theme::load_builtin("dark")
            .or_else(|| crate::view::theme::Theme::load_builtin("default"))
            .expect("expected a builtin theme to load");
        let colors = NumberInputColors::from_theme(&theme);
        assert_ne!(
            colors.selection_bg, colors.focused,
            "selection bg must differ from focus bg, otherwise the in-edit selection is invisible \
             when the row is focused"
        );
    }
}