envision 0.15.1

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
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
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
//! A text input field component with cursor navigation and editing.
//!
//! [`InputField`] provides a single-line text input with cursor movement,
//! text insertion, deletion, and selection. State is stored in
//! [`InputFieldState`], updated via [`InputFieldMessage`], and produces
//! [`InputFieldOutput`].
//!
//!
//! See also [`LineInput`](super::LineInput) for a multi-row wrapping input,
//! and [`TextArea`](super::TextArea) for multi-line editing.
//!
//! # Example
//!
//! ```rust
//! use envision::component::{Component, InputField, InputFieldState, InputFieldMessage};
//!
//! // Create an input field
//! let mut state = InputField::init();
//!
//! // Type some text
//! InputField::update(&mut state, InputFieldMessage::Insert('H'));
//! InputField::update(&mut state, InputFieldMessage::Insert('i'));
//!
//! assert_eq!(state.value(), "Hi");
//! assert_eq!(state.cursor_position(), 2);
//! ```

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

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

mod editing;

#[cfg(feature = "clipboard")]
use crate::clipboard::{system_clipboard_get, system_clipboard_set};

/// A snapshot of InputField state for undo/redo.
#[derive(Debug, Clone)]
struct InputSnapshot {
    value: String,
    cursor: usize,
}

/// Messages that can be sent to an InputField.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum InputFieldMessage {
    /// Insert a character at the cursor position.
    Insert(char),
    /// Delete the character before the cursor (backspace).
    Backspace,
    /// Delete the character at the cursor position.
    Delete,
    /// Move cursor left by one character.
    Left,
    /// Move cursor right by one character.
    Right,
    /// Move cursor to the beginning of the input.
    Home,
    /// Move cursor to the end of the input.
    End,
    /// Move cursor left by one word.
    WordLeft,
    /// Move cursor right by one word.
    WordRight,
    /// Extend selection left by one character.
    SelectLeft,
    /// Extend selection right by one character.
    SelectRight,
    /// Extend selection to the beginning of the input.
    SelectHome,
    /// Extend selection to the end of the input.
    SelectEnd,
    /// Extend selection left by one word.
    SelectWordLeft,
    /// Extend selection right by one word.
    SelectWordRight,
    /// Select all text.
    SelectAll,
    /// Copy the selected text to the internal clipboard.
    Copy,
    /// Cut the selected text to the internal clipboard.
    Cut,
    /// Paste text at the cursor position, replacing any selection.
    Paste(String),
    /// Delete from cursor to beginning of word.
    DeleteWordBack,
    /// Delete from cursor to end of word.
    DeleteWordForward,
    /// Clear the entire input.
    Clear,
    /// Set the entire input value.
    SetValue(String),
    /// Submit the current value.
    Submit,
    /// Undo the last edit.
    Undo,
    /// Redo the last undone edit.
    Redo,
}

/// Output messages from an InputField.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum InputFieldOutput {
    /// The value was submitted (e.g., Enter pressed).
    Submitted(String),
    /// The value changed.
    Changed(String),
    /// Text was copied to the internal clipboard.
    Copied(String),
}

/// State for an InputField component.
#[derive(Clone, Debug, Default, PartialEq)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct InputFieldState {
    /// The current text value.
    value: String,
    /// Cursor position (byte offset into value).
    cursor: usize,
    /// Placeholder text shown when empty.
    placeholder: String,
    /// Selection anchor (byte offset). When `Some`, text is selected from
    /// the anchor to the cursor. The anchor stays fixed while the cursor moves.
    selection_anchor: Option<usize>,
    /// Internal clipboard buffer for copy/cut/paste operations.
    clipboard: String,
    /// Undo/redo history stack.
    #[cfg_attr(feature = "serialization", serde(skip))]
    undo_stack: UndoStack<InputSnapshot>,
}

impl InputFieldState {
    /// Creates a new empty input field state.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::prelude::*;
    ///
    /// let state = InputFieldState::new();
    /// assert_eq!(state.value(), "");
    /// assert_eq!(state.cursor_position(), 0);
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a new state with the given initial value.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::prelude::*;
    ///
    /// let state = InputFieldState::with_value("hello");
    /// assert_eq!(state.value(), "hello");
    /// assert_eq!(state.cursor_position(), 5);
    /// ```
    pub fn with_value(value: impl Into<String>) -> Self {
        let value = value.into();
        let cursor = value.len();
        Self {
            value,
            cursor,
            placeholder: String::new(),
            selection_anchor: None,
            clipboard: String::new(),
            undo_stack: UndoStack::default(),
        }
    }

    /// Creates a new state with placeholder text.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::prelude::*;
    ///
    /// let state = InputFieldState::with_placeholder("Enter name...");
    /// assert_eq!(state.placeholder(), "Enter name...");
    /// assert_eq!(state.value(), "");
    /// ```
    pub fn with_placeholder(placeholder: impl Into<String>) -> Self {
        Self {
            value: String::new(),
            cursor: 0,
            placeholder: placeholder.into(),
            selection_anchor: None,
            clipboard: String::new(),
            undo_stack: UndoStack::default(),
        }
    }

    /// Returns the current value.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::prelude::*;
    ///
    /// let state = InputFieldState::with_value("hello");
    /// assert_eq!(state.value(), "hello");
    /// ```
    pub fn value(&self) -> &str {
        &self.value
    }

    /// Sets the value and moves cursor to the end.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::prelude::*;
    ///
    /// let mut state = InputFieldState::new();
    /// state.set_value("world");
    /// assert_eq!(state.value(), "world");
    /// assert_eq!(state.cursor_position(), 5);
    /// ```
    pub fn set_value(&mut self, value: impl Into<String>) {
        self.value = value.into();
        self.cursor = self.value.len();
        self.selection_anchor = None;
    }

    /// Returns the cursor position (character index).
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::prelude::*;
    ///
    /// let state = InputFieldState::with_value("abc");
    /// assert_eq!(state.cursor_position(), 3);
    /// ```
    pub fn cursor_position(&self) -> usize {
        self.value[..self.cursor].chars().count()
    }

    /// Returns the cursor display position (terminal column width).
    ///
    /// Unlike [`cursor_position()`](Self::cursor_position) which returns the
    /// character count, this returns the display width accounting for
    /// wide characters (emoji, CJK) that occupy 2 terminal columns.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{InputField, InputFieldState, InputFieldMessage, Component};
    ///
    /// let mut state = InputField::init();
    /// InputField::update(&mut state, InputFieldMessage::Insert('A'));
    /// InputField::update(&mut state, InputFieldMessage::Insert('\u{1F600}')); // emoji
    ///
    /// // Character count is 2 (two characters)
    /// assert_eq!(state.cursor_position(), 2);
    /// // Display width is 3 (A=1 + 😀=2)
    /// assert_eq!(state.cursor_display_position(), 3);
    /// ```
    pub fn cursor_display_position(&self) -> usize {
        self.value[..self.cursor].width()
    }

    /// Returns the cursor byte offset.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::InputFieldState;
    ///
    /// let state = InputFieldState::with_value("abc");
    /// assert_eq!(state.cursor_byte_offset(), 3);
    /// ```
    pub fn cursor_byte_offset(&self) -> usize {
        self.cursor
    }

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

    /// Returns the placeholder text.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::InputFieldState;
    ///
    /// let state = InputFieldState::with_placeholder("Type something");
    /// assert_eq!(state.placeholder(), "Type something");
    /// ```
    pub fn placeholder(&self) -> &str {
        &self.placeholder
    }

    /// Returns true if the input is empty.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::InputFieldState;
    ///
    /// assert!(InputFieldState::new().is_empty());
    /// assert!(!InputFieldState::with_value("hi").is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.value.is_empty()
    }

    /// Returns the number of characters in the input.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::InputFieldState;
    ///
    /// let state = InputFieldState::with_value("hello");
    /// assert_eq!(state.len(), 5);
    /// ```
    pub fn len(&self) -> usize {
        self.value.chars().count()
    }

    /// Moves cursor to the given character position.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::InputFieldState;
    ///
    /// let mut state = InputFieldState::with_value("hello");
    /// state.set_cursor_position(2);
    /// assert_eq!(state.cursor_position(), 2);
    /// ```
    pub fn set_cursor_position(&mut self, char_pos: usize) {
        let char_count = self.value.chars().count();
        let clamped = char_pos.min(char_count);
        self.cursor = self
            .value
            .char_indices()
            .nth(clamped)
            .map(|(i, _)| i)
            .unwrap_or(self.value.len());
    }

    /// Returns true if there is an active text selection.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{InputField, InputFieldMessage, InputFieldState, Component};
    ///
    /// let mut state = InputFieldState::with_value("hello");
    /// assert!(!state.has_selection());
    /// InputField::update(&mut state, InputFieldMessage::SelectAll);
    /// assert!(state.has_selection());
    /// ```
    pub fn has_selection(&self) -> bool {
        self.selection_anchor.is_some() && self.selection_anchor != Some(self.cursor)
    }

    /// Returns the selected byte range as `(start, end)` where `start < end`.
    ///
    /// Returns `None` if there is no active selection or the selection is empty.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{InputField, InputFieldMessage, InputFieldState, Component};
    ///
    /// let mut state = InputFieldState::with_value("hello");
    /// InputField::update(&mut state, InputFieldMessage::SelectAll);
    /// assert_eq!(state.selection_range(), Some((0, 5)));
    /// ```
    pub fn selection_range(&self) -> Option<(usize, usize)> {
        self.selection_anchor.and_then(|anchor| {
            if anchor == self.cursor {
                None
            } else {
                let start = anchor.min(self.cursor);
                let end = anchor.max(self.cursor);
                Some((start, end))
            }
        })
    }

    /// Returns the currently selected text, or `None` if no selection.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{InputField, InputFieldMessage, InputFieldState, Component};
    ///
    /// let mut state = InputFieldState::with_value("hello world");
    /// InputField::update(&mut state, InputFieldMessage::SelectAll);
    /// assert_eq!(state.selected_text(), Some("hello world"));
    /// ```
    pub fn selected_text(&self) -> Option<&str> {
        self.selection_range()
            .map(|(start, end)| &self.value[start..end])
    }

    /// Returns a reference to the internal clipboard contents.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{InputField, InputFieldMessage, InputFieldState, Component};
    ///
    /// let mut state = InputFieldState::with_value("hello");
    /// InputField::update(&mut state, InputFieldMessage::SelectAll);
    /// InputField::update(&mut state, InputFieldMessage::Copy);
    /// assert_eq!(state.clipboard(), "hello");
    /// ```
    pub fn clipboard(&self) -> &str {
        &self.clipboard
    }

    /// Clears the current selection without modifying text.
    fn clear_selection(&mut self) {
        self.selection_anchor = None;
    }

    /// Sets the selection anchor to the current cursor position if not already set.
    fn ensure_selection_anchor(&mut self) {
        if self.selection_anchor.is_none() {
            self.selection_anchor = Some(self.cursor);
        }
    }

    /// Deletes the currently selected text, returning the deleted text.
    ///
    /// Moves the cursor to the start of the selection. Clears the selection.
    /// Returns `None` if no text was selected.
    fn delete_selection(&mut self) -> Option<String> {
        let (start, end) = self.selection_range()?;
        let deleted: String = self.value[start..end].to_string();
        self.value.drain(start..end);
        self.cursor = start;
        self.selection_anchor = None;
        Some(deleted)
    }

    /// Returns true if there are edits that can be undone.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{InputField, InputFieldMessage, InputFieldState, Component};
    ///
    /// let mut state = InputFieldState::new();
    /// assert!(!state.can_undo());
    /// InputField::update(&mut state, InputFieldMessage::Insert('a'));
    /// assert!(state.can_undo());
    /// ```
    pub fn can_undo(&self) -> bool {
        self.undo_stack.can_undo()
    }

    /// Returns true if there are edits that can be redone.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{InputField, InputFieldMessage, InputFieldState, Component};
    ///
    /// let mut state = InputFieldState::new();
    /// InputField::update(&mut state, InputFieldMessage::Insert('a'));
    /// InputField::update(&mut state, InputFieldMessage::Undo);
    /// assert!(state.can_redo());
    /// ```
    pub fn can_redo(&self) -> bool {
        self.undo_stack.can_redo()
    }

    /// Creates a snapshot of the current state for undo.
    fn snapshot(&self) -> InputSnapshot {
        InputSnapshot {
            value: self.value.clone(),
            cursor: self.cursor,
        }
    }

    /// Restores state from a snapshot.
    fn restore(&mut self, snapshot: InputSnapshot) {
        self.value = snapshot.value;
        self.cursor = snapshot.cursor;
        self.clear_selection();
    }

    /// Updates the input field state with a message, returning any output.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{InputFieldMessage, InputFieldState};
    ///
    /// let mut state = InputFieldState::new();
    /// state.update(InputFieldMessage::Insert('h'));
    /// state.update(InputFieldMessage::Insert('i'));
    /// assert_eq!(state.value(), "hi");
    /// ```
    pub fn update(&mut self, msg: InputFieldMessage) -> Option<InputFieldOutput> {
        InputField::update(self, msg)
    }
}

/// A text input field component.
///
/// This component provides a single-line text input with cursor navigation
/// and editing capabilities.
///
/// # Navigation
///
/// - `Left` / `Right` - Move cursor by one character
/// - `Home` / `End` - Jump to beginning/end
/// - `WordLeft` / `WordRight` - Move by word
///
/// # Editing
///
/// - `Insert(char)` - Insert a character
/// - `Backspace` - Delete before cursor
/// - `Delete` - Delete at cursor
/// - `DeleteWordBack` / `DeleteWordForward` - Delete by word
/// - `Clear` - Clear all text
/// - `SetValue(String)` - Replace all text
pub struct InputField;

impl Component for InputField {
    type State = InputFieldState;
    type Message = InputFieldMessage;
    type Output = InputFieldOutput;

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

    fn update(state: &mut Self::State, msg: Self::Message) -> Option<Self::Output> {
        match msg {
            InputFieldMessage::Insert(c) => {
                if c.is_whitespace() {
                    state.undo_stack.break_group();
                }
                let snapshot = state.snapshot();
                state.undo_stack.save(snapshot, EditKind::Insert);
                state.delete_selection();
                state.insert(c);
                if c.is_whitespace() {
                    state.undo_stack.break_group();
                }
                Some(InputFieldOutput::Changed(state.value.clone()))
            }
            InputFieldMessage::Backspace => {
                let snapshot = state.snapshot();
                if state.has_selection() {
                    state.delete_selection();
                    state.undo_stack.save(snapshot, EditKind::Delete);
                    Some(InputFieldOutput::Changed(state.value.clone()))
                } else if state.backspace() {
                    state.undo_stack.save(snapshot, EditKind::Delete);
                    Some(InputFieldOutput::Changed(state.value.clone()))
                } else {
                    None
                }
            }
            InputFieldMessage::Delete => {
                let snapshot = state.snapshot();
                if state.has_selection() {
                    state.delete_selection();
                    state.undo_stack.save(snapshot, EditKind::Delete);
                    Some(InputFieldOutput::Changed(state.value.clone()))
                } else if state.delete() {
                    state.undo_stack.save(snapshot, EditKind::Delete);
                    Some(InputFieldOutput::Changed(state.value.clone()))
                } else {
                    None
                }
            }
            InputFieldMessage::Left => {
                if state.has_selection() {
                    // Move cursor to start of selection
                    if let Some((start, _)) = state.selection_range() {
                        state.cursor = start;
                    }
                    state.clear_selection();
                } else {
                    state.move_left();
                }
                None
            }
            InputFieldMessage::Right => {
                if state.has_selection() {
                    // Move cursor to end of selection
                    if let Some((_, end)) = state.selection_range() {
                        state.cursor = end;
                    }
                    state.clear_selection();
                } else {
                    state.move_right();
                }
                None
            }
            InputFieldMessage::Home => {
                state.clear_selection();
                state.cursor = 0;
                None
            }
            InputFieldMessage::End => {
                state.clear_selection();
                state.cursor = state.value.len();
                None
            }
            InputFieldMessage::WordLeft => {
                state.clear_selection();
                state.move_word_left();
                None
            }
            InputFieldMessage::WordRight => {
                state.clear_selection();
                state.move_word_right();
                None
            }
            InputFieldMessage::SelectLeft => {
                state.ensure_selection_anchor();
                state.move_left();
                None
            }
            InputFieldMessage::SelectRight => {
                state.ensure_selection_anchor();
                state.move_right();
                None
            }
            InputFieldMessage::SelectHome => {
                state.ensure_selection_anchor();
                state.cursor = 0;
                None
            }
            InputFieldMessage::SelectEnd => {
                state.ensure_selection_anchor();
                state.cursor = state.value.len();
                None
            }
            InputFieldMessage::SelectWordLeft => {
                state.ensure_selection_anchor();
                state.move_word_left();
                None
            }
            InputFieldMessage::SelectWordRight => {
                state.ensure_selection_anchor();
                state.move_word_right();
                None
            }
            InputFieldMessage::SelectAll => {
                if state.value.is_empty() {
                    return None;
                }
                state.selection_anchor = Some(0);
                state.cursor = state.value.len();
                None
            }
            InputFieldMessage::Copy => {
                if let Some(text) = state.selected_text() {
                    let text = text.to_string();
                    state.clipboard = text.clone();
                    #[cfg(feature = "clipboard")]
                    system_clipboard_set(&text);
                    Some(InputFieldOutput::Copied(text))
                } else {
                    None
                }
            }
            InputFieldMessage::Cut => {
                if let Some(text) = state.selected_text() {
                    let text = text.to_string();
                    let snapshot = state.snapshot();
                    state.clipboard = text.clone();
                    #[cfg(feature = "clipboard")]
                    system_clipboard_set(&text);
                    state.delete_selection();
                    state.undo_stack.save(snapshot, EditKind::Other);
                    Some(InputFieldOutput::Changed(state.value.clone()))
                } else {
                    None
                }
            }
            InputFieldMessage::Paste(text) => {
                if text.is_empty() {
                    return None;
                }
                let snapshot = state.snapshot();
                state.undo_stack.save(snapshot, EditKind::Other);
                state.delete_selection();
                // Insert each character at cursor position
                for c in text.chars() {
                    state.insert(c);
                }
                Some(InputFieldOutput::Changed(state.value.clone()))
            }
            InputFieldMessage::DeleteWordBack => {
                let snapshot = state.snapshot();
                if state.has_selection() {
                    state.delete_selection();
                    state.undo_stack.save(snapshot, EditKind::Other);
                    Some(InputFieldOutput::Changed(state.value.clone()))
                } else if state.delete_word_back() {
                    state.undo_stack.save(snapshot, EditKind::Other);
                    Some(InputFieldOutput::Changed(state.value.clone()))
                } else {
                    None
                }
            }
            InputFieldMessage::DeleteWordForward => {
                let snapshot = state.snapshot();
                if state.has_selection() {
                    state.delete_selection();
                    state.undo_stack.save(snapshot, EditKind::Other);
                    Some(InputFieldOutput::Changed(state.value.clone()))
                } else if state.delete_word_forward() {
                    state.undo_stack.save(snapshot, EditKind::Other);
                    Some(InputFieldOutput::Changed(state.value.clone()))
                } else {
                    None
                }
            }
            InputFieldMessage::Clear => {
                state.clear_selection();
                if !state.value.is_empty() {
                    let snapshot = state.snapshot();
                    state.undo_stack.save(snapshot, EditKind::Other);
                    state.value.clear();
                    state.cursor = 0;
                    Some(InputFieldOutput::Changed(state.value.clone()))
                } else {
                    None
                }
            }
            InputFieldMessage::SetValue(value) => {
                if state.value != value {
                    let snapshot = state.snapshot();
                    state.undo_stack.save(snapshot, EditKind::Other);
                    state.set_value(value);
                    Some(InputFieldOutput::Changed(state.value.clone()))
                } else {
                    None
                }
            }
            InputFieldMessage::Submit => Some(InputFieldOutput::Submitted(state.value.clone())),
            InputFieldMessage::Undo => {
                let snapshot = state.snapshot();
                if let Some(restored) = state.undo_stack.undo(snapshot) {
                    state.restore(restored);
                    Some(InputFieldOutput::Changed(state.value.clone()))
                } else {
                    None
                }
            }
            InputFieldMessage::Redo => {
                let snapshot = state.snapshot();
                if let Some(restored) = state.undo_stack.redo(snapshot) {
                    state.restore(restored);
                    Some(InputFieldOutput::Changed(state.value.clone()))
                } else {
                    None
                }
            }
        }
    }

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

        // Handle paste events from terminal (bracketed paste)
        if let Event::Paste(text) = event {
            return Some(InputFieldMessage::Paste(text.clone()));
        }

        if let Some(key) = event.as_key() {
            let ctrl = key.modifiers.ctrl();
            let shift = key.modifiers.shift();
            match key.code {
                // Undo/redo
                Key::Char('z') if ctrl => Some(InputFieldMessage::Undo),
                Key::Char('y') if ctrl => Some(InputFieldMessage::Redo),
                // Clipboard operations
                Key::Char('c') if ctrl => Some(InputFieldMessage::Copy),
                Key::Char('x') if ctrl => Some(InputFieldMessage::Cut),
                Key::Char('v') if ctrl => {
                    // Try system clipboard first, fall back to internal
                    #[cfg(feature = "clipboard")]
                    if let Some(text) = system_clipboard_get() {
                        return Some(InputFieldMessage::Paste(text));
                    }
                    if state.clipboard.is_empty() {
                        None
                    } else {
                        Some(InputFieldMessage::Paste(state.clipboard.clone()))
                    }
                }
                Key::Char('a') if ctrl => Some(InputFieldMessage::SelectAll),
                // Character input (only when no ctrl modifier)
                Key::Char(_) if !ctrl => key.raw_char.map(InputFieldMessage::Insert),
                // Selection movement (shift+key)
                Key::Left if ctrl && shift => Some(InputFieldMessage::SelectWordLeft),
                Key::Right if ctrl && shift => Some(InputFieldMessage::SelectWordRight),
                Key::Left if shift => Some(InputFieldMessage::SelectLeft),
                Key::Right if shift => Some(InputFieldMessage::SelectRight),
                Key::Home if shift => Some(InputFieldMessage::SelectHome),
                Key::End if shift => Some(InputFieldMessage::SelectEnd),
                // Deletion
                Key::Backspace if ctrl => Some(InputFieldMessage::DeleteWordBack),
                Key::Delete if ctrl => Some(InputFieldMessage::DeleteWordForward),
                Key::Backspace => Some(InputFieldMessage::Backspace),
                Key::Delete => Some(InputFieldMessage::Delete),
                // Navigation (clears selection)
                Key::Left if ctrl => Some(InputFieldMessage::WordLeft),
                Key::Right if ctrl => Some(InputFieldMessage::WordRight),
                Key::Left => Some(InputFieldMessage::Left),
                Key::Right => Some(InputFieldMessage::Right),
                Key::Home => Some(InputFieldMessage::Home),
                Key::End => Some(InputFieldMessage::End),
                Key::Enter => Some(InputFieldMessage::Submit),
                _ => None,
            }
        } else {
            None
        }
    }

    fn view(state: &Self::State, ctx: &mut RenderContext<'_, '_>) {
        crate::annotation::with_registry(|reg| {
            reg.register(
                ctx.area,
                crate::annotation::Annotation::input("input_field")
                    .with_value(state.value.as_str())
                    .with_focus(ctx.focused)
                    .with_disabled(ctx.disabled),
            );
        });

        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 is_placeholder = state.value.is_empty() && !state.placeholder.is_empty();

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

        let text = if is_placeholder {
            &state.placeholder
        } else {
            &state.value
        };

        // Build line with selection highlighting
        let line = if let Some((sel_start, sel_end)) = state.selection_range() {
            let selection_style = ctx.theme.selection_style();
            let before = &state.value[..sel_start];
            let selected = &state.value[sel_start..sel_end];
            let after = &state.value[sel_end..];
            Line::from(vec![
                Span::styled(before.to_string(), base_style),
                Span::styled(selected.to_string(), selection_style),
                Span::styled(after.to_string(), base_style),
            ])
        } else {
            Line::from(Span::styled(text.to_string(), base_style))
        };

        let paragraph = Paragraph::new(line).block(block);
        ctx.frame.render_widget(paragraph, ctx.area);

        // Show cursor when focused
        if ctx.focused && ctx.area.width > 2 && ctx.area.height > 2 {
            let cursor_x = ctx.area.x + 1 + state.cursor_display_position() as u16;
            let cursor_y = ctx.area.y + 1;

            if cursor_x < ctx.area.x + ctx.area.width - 1 {
                ctx.frame.set_cursor_position((cursor_x, cursor_y));
            }
        }
    }
}

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