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
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
//! A searchable dropdown selection component.
//!
//! [`Dropdown`] provides a filterable dropdown menu for selecting a single option
//! from a list. Users can type to filter options, then navigate and select
//! using keyboard controls. State is stored in [`DropdownState`], updated via
//! [`DropdownMessage`], and produces [`DropdownOutput`].
//!
//!
//! See also [`Select`](super::Select) for a simpler dropdown without filtering.
//!
//! # Example
//!
//! ```rust
//! use envision::component::{Dropdown, DropdownMessage, DropdownOutput, DropdownState, Component};
//!
//! // Create a dropdown with options
//! let mut state = DropdownState::new(vec!["Apple", "Banana", "Cherry", "Date"]);
//! state.set_placeholder("Search fruits...");
//!
//! // Open it
//! let _ = Dropdown::update(&mut state, DropdownMessage::Open);
//!
//! // Type to filter (shows Apple, Banana, Date - all contain 'a')
//! let _ = Dropdown::update(&mut state, DropdownMessage::Insert('a'));
//!
//! // Navigate to second filtered option and confirm
//! let _ = Dropdown::update(&mut state, DropdownMessage::Down);
//! let output = Dropdown::update(&mut state, DropdownMessage::Confirm);
//! assert_eq!(output, Some(DropdownOutput::Selected("Banana".to_string()))); // Banana selected
//! ```

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

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

/// Messages that can be sent to a Dropdown.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DropdownMessage {
    /// Open the dropdown.
    Open,
    /// Close the dropdown.
    Close,
    /// Toggle the dropdown open/closed.
    Toggle,
    /// Insert a character into the filter.
    Insert(char),
    /// Delete character before cursor (backspace).
    Backspace,
    /// Clear the filter text.
    ClearFilter,
    /// Move highlight down to the next filtered option.
    Down,
    /// Move highlight up to the previous filtered option.
    Up,
    /// Confirm current highlighted selection.
    Confirm,
    /// Set the filter text directly.
    SetFilter(String),
}

/// Output messages from a Dropdown.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DropdownOutput {
    /// A new item was selected (contains the selected value).
    Selected(String),
    /// The highlight changed during navigation (contains the highlighted option's original index).
    SelectionChanged(usize),
    /// User re-confirmed an already-selected item (contains the index).
    Submitted(usize),
    /// Filter text changed.
    FilterChanged(String),
}

/// State for a Dropdown component.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct DropdownState {
    /// All available options.
    options: Vec<String>,
    /// Currently selected option index (into options).
    selected_index: Option<usize>,
    /// Current filter/search text.
    filter_text: String,
    /// Indices of options matching the filter.
    filtered_indices: Vec<usize>,
    /// Currently highlighted index (into filtered_indices).
    highlighted_index: usize,
    /// Whether the dropdown is open.
    is_open: bool,
    /// Placeholder text when nothing selected and filter empty.
    placeholder: String,
}

impl Default for DropdownState {
    fn default() -> Self {
        Self {
            options: Vec::new(),
            selected_index: None,
            filter_text: String::new(),
            filtered_indices: Vec::new(),
            highlighted_index: 0,
            is_open: false,
            placeholder: String::from("Search..."),
        }
    }
}

impl DropdownState {
    /// Creates a new dropdown with the given options.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::DropdownState;
    ///
    /// let state = DropdownState::new(vec!["Option 1", "Option 2", "Option 3"]);
    /// assert_eq!(state.options().len(), 3);
    /// assert!(state.selected_index().is_none());
    /// ```
    pub fn new<S: Into<String>>(options: Vec<S>) -> Self {
        let options: Vec<String> = options.into_iter().map(|s| s.into()).collect();
        let filtered_indices: Vec<usize> = (0..options.len()).collect();

        Self {
            options,
            filtered_indices,
            ..Default::default()
        }
    }

    /// Creates a new dropdown with the given options and a pre-selected index.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::DropdownState;
    ///
    /// let state = DropdownState::with_selection(vec!["A", "B", "C"], 1);
    /// assert_eq!(state.selected_index(), Some(1));
    /// assert_eq!(state.selected_value(), Some("B"));
    /// ```
    pub fn with_selection<S: Into<String>>(options: Vec<S>, selected: usize) -> Self {
        let options: Vec<String> = options.into_iter().map(|s| s.into()).collect();
        let selected_index = if selected < options.len() {
            Some(selected)
        } else {
            None
        };
        let filtered_indices: Vec<usize> = (0..options.len()).collect();

        Self {
            options,
            selected_index,
            filtered_indices,
            ..Default::default()
        }
    }

    /// Returns the options list.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::prelude::*;
    ///
    /// let state = DropdownState::new(vec!["Apple", "Banana"]);
    /// assert_eq!(state.options(), &["Apple", "Banana"]);
    /// ```
    pub fn options(&self) -> &[String] {
        &self.options
    }

    /// Sets the options list.
    ///
    /// Resets selection if the current selected index is out of bounds.
    /// Also updates the filtered indices.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::prelude::*;
    ///
    /// let mut state = DropdownState::with_selection(vec!["A", "B"], 1);
    /// state.set_options(vec!["X", "Y", "Z"]);
    /// assert_eq!(state.options(), &["X", "Y", "Z"]);
    /// assert_eq!(state.selected_index(), Some(1));
    /// ```
    pub fn set_options<S: Into<String>>(&mut self, options: Vec<S>) {
        self.options = options.into_iter().map(|s| s.into()).collect();

        // Reset selection if out of bounds
        if let Some(idx) = self.selected_index {
            if idx >= self.options.len() {
                self.selected_index = None;
            }
        }

        // Re-filter with current filter text
        self.update_filter();
    }

    /// Returns the selected option index.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::prelude::*;
    ///
    /// let state = DropdownState::new(vec!["A", "B"]);
    /// assert_eq!(state.selected_index(), None);
    ///
    /// let state = DropdownState::with_selection(vec!["A", "B"], 0);
    /// assert_eq!(state.selected_index(), Some(0));
    /// ```
    pub fn selected_index(&self) -> Option<usize> {
        self.selected_index
    }

    /// Alias for [`selected_index()`](Self::selected_index).
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::prelude::*;
    ///
    /// let state = DropdownState::with_selection(vec!["A", "B"], 1);
    /// assert_eq!(state.selected(), state.selected_index());
    /// ```
    pub fn selected(&self) -> Option<usize> {
        self.selected_index()
    }

    /// Returns the selected option value.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::prelude::*;
    ///
    /// let state = DropdownState::with_selection(vec!["Apple", "Banana"], 1);
    /// assert_eq!(state.selected_value(), Some("Banana"));
    ///
    /// let state = DropdownState::new(vec!["Apple", "Banana"]);
    /// assert_eq!(state.selected_value(), None);
    /// ```
    pub fn selected_value(&self) -> Option<&str> {
        self.selected_index
            .and_then(|idx| self.options.get(idx).map(|s| s.as_str()))
    }

    /// Returns the selected option value as a string reference.
    ///
    /// This is an alias for [`selected_value()`](Self::selected_value) that provides a
    /// consistent accessor name across all selection-based components.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::prelude::*;
    ///
    /// let state = DropdownState::with_selection(vec!["Apple", "Banana"], 0);
    /// assert_eq!(state.selected_item(), Some("Apple"));
    /// ```
    pub fn selected_item(&self) -> Option<&str> {
        self.selected_value()
    }

    /// Sets the selected option index.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::prelude::*;
    ///
    /// let mut state = DropdownState::new(vec!["A", "B", "C"]);
    /// state.set_selected(Some(2));
    /// assert_eq!(state.selected_value(), Some("C"));
    ///
    /// state.set_selected(None);
    /// assert_eq!(state.selected_value(), None);
    /// ```
    pub fn set_selected(&mut self, index: Option<usize>) {
        if let Some(idx) = index {
            if idx < self.options.len() {
                self.selected_index = Some(idx);
            }
        } else {
            self.selected_index = None;
        }
    }

    /// Returns the current filter text.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::prelude::*;
    ///
    /// let mut state = DropdownState::new(vec!["Apple", "Banana"]);
    /// assert_eq!(state.filter_text(), "");
    ///
    /// state.update(DropdownMessage::Insert('a'));
    /// assert_eq!(state.filter_text(), "a");
    /// ```
    pub fn filter_text(&self) -> &str {
        &self.filter_text
    }

    /// Returns the filtered options (values, not indices).
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::prelude::*;
    ///
    /// let mut state = DropdownState::new(vec!["Apple", "Banana", "Cherry"]);
    /// state.update(DropdownMessage::Insert('a'));
    /// assert_eq!(state.filtered_options(), vec!["Apple", "Banana"]);
    /// ```
    pub fn filtered_options(&self) -> Vec<&str> {
        self.filtered_indices
            .iter()
            .filter_map(|&idx| self.options.get(idx).map(|s| s.as_str()))
            .collect()
    }

    /// Returns the number of filtered options.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::prelude::*;
    ///
    /// let mut state = DropdownState::new(vec!["Apple", "Banana", "Cherry"]);
    /// assert_eq!(state.filtered_count(), 3);
    ///
    /// state.update(DropdownMessage::Insert('a'));
    /// assert_eq!(state.filtered_count(), 2);
    /// ```
    pub fn filtered_count(&self) -> usize {
        self.filtered_indices.len()
    }

    /// Returns true if the dropdown is open.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::prelude::*;
    ///
    /// let mut state = DropdownState::new(vec!["A", "B"]);
    /// assert!(!state.is_open());
    ///
    /// state.update(DropdownMessage::Open);
    /// assert!(state.is_open());
    /// ```
    pub fn is_open(&self) -> bool {
        self.is_open
    }

    /// Returns the placeholder text.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::prelude::*;
    ///
    /// let state = DropdownState::new(vec!["A", "B"]);
    /// assert_eq!(state.placeholder(), "Search...");
    /// ```
    pub fn placeholder(&self) -> &str {
        &self.placeholder
    }

    /// Sets the placeholder text.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::prelude::*;
    ///
    /// let mut state = DropdownState::new(vec!["A", "B"]);
    /// state.set_placeholder("Pick one...");
    /// assert_eq!(state.placeholder(), "Pick one...");
    /// ```
    pub fn set_placeholder(&mut self, placeholder: impl Into<String>) {
        self.placeholder = placeholder.into();
    }

    /// Sets the placeholder text (builder pattern).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::DropdownState;
    ///
    /// let state = DropdownState::new(vec!["Apple", "Banana", "Cherry"])
    ///     .with_placeholder("Search fruits...");
    /// assert_eq!(state.placeholder(), "Search fruits...");
    /// ```
    pub fn with_placeholder(mut self, placeholder: impl Into<String>) -> Self {
        self.placeholder = placeholder.into();
        self
    }

    /// Updates the dropdown state with a message, returning any output.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::prelude::*;
    ///
    /// let mut state = DropdownState::new(vec!["Apple", "Banana", "Cherry"]);
    /// state.update(DropdownMessage::Open);
    /// state.update(DropdownMessage::Down);
    /// let output = state.update(DropdownMessage::Confirm);
    /// assert_eq!(output, Some(DropdownOutput::Selected("Banana".to_string())));
    /// ```
    pub fn update(&mut self, msg: DropdownMessage) -> Option<DropdownOutput> {
        Dropdown::update(self, msg)
    }

    /// Updates the filtered indices based on current filter text.
    fn update_filter(&mut self) {
        let filter_lower = self.filter_text.to_lowercase();

        self.filtered_indices = self
            .options
            .iter()
            .enumerate()
            .filter(|(_, opt)| {
                if filter_lower.is_empty() {
                    true
                } else {
                    opt.to_lowercase().contains(&filter_lower)
                }
            })
            .map(|(i, _)| i)
            .collect();

        // Reset highlight to first match (or 0 if no matches)
        self.highlighted_index = 0;
    }
}

/// A searchable dropdown selection component.
///
/// This component provides a filterable dropdown menu for selecting a single
/// option from a list. Users can type to filter options, then navigate and
/// select using keyboard controls.
///
/// # Features
///
/// - Case-insensitive "contains" matching
/// - Keyboard navigation through filtered results
/// - Selection from existing options only
/// - Filter clears on close/confirm
///
/// # Keyboard Navigation
///
/// The dropdown itself doesn't handle keyboard events directly. Your application
/// should map:
/// - Characters to [`DropdownMessage::Insert`]
/// - Backspace to [`DropdownMessage::Backspace`]
/// - Down arrow to [`DropdownMessage::Down`]
/// - Up arrow to [`DropdownMessage::Up`]
/// - Enter to [`DropdownMessage::Confirm`]
/// - Escape to [`DropdownMessage::Close`]
///
/// # Visual States
///
/// **Closed (no selection):**
/// ```text
/// ┌──────────────────────┐
/// │ Search...          ▼ │
/// └──────────────────────┘
/// ```
///
/// **Closed (with selection):**
/// ```text
/// ┌──────────────────────┐
/// │ Apple              ▼ │
/// └──────────────────────┘
/// ```
///
/// **Open (with filter):**
/// ```text
/// ┌──────────────────────┐
/// │ app█               ▲ │
/// ├──────────────────────┤
/// │ > Apple              │  ← highlighted
/// │   Pineapple          │
/// └──────────────────────┘
/// ```
///
/// # Example
///
/// ```rust
/// use envision::component::{Dropdown, DropdownMessage, DropdownOutput, DropdownState, Component};
///
/// let mut state = DropdownState::new(vec!["Apple", "Banana", "Cherry"]);
///
/// // Open and filter
/// Dropdown::update(&mut state, DropdownMessage::Open);
/// Dropdown::update(&mut state, DropdownMessage::Insert('a'));
///
/// // Navigate and select
/// Dropdown::update(&mut state, DropdownMessage::Down);
/// let output = Dropdown::update(&mut state, DropdownMessage::Confirm);
/// assert_eq!(output, Some(DropdownOutput::Selected("Banana".to_string()))); // Banana
/// ```
pub struct Dropdown;

impl Component for Dropdown {
    type State = DropdownState;
    type Message = DropdownMessage;
    type Output = DropdownOutput;

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

    fn update(state: &mut Self::State, msg: Self::Message) -> Option<Self::Output> {
        match msg {
            DropdownMessage::Open => {
                if !state.options.is_empty() {
                    state.is_open = true;
                    // Reset filter and show all options
                    state.filter_text.clear();
                    state.update_filter();
                    // Set highlight to current selection if exists
                    if let Some(selected) = state.selected_index {
                        state.highlighted_index = state
                            .filtered_indices
                            .iter()
                            .position(|&idx| idx == selected)
                            .unwrap_or(0);
                    }
                }
                None
            }
            DropdownMessage::Close => {
                state.is_open = false;
                state.filter_text.clear();
                state.update_filter();
                None
            }
            DropdownMessage::Toggle => {
                if state.is_open {
                    state.is_open = false;
                    state.filter_text.clear();
                    state.update_filter();
                } else if !state.options.is_empty() {
                    state.is_open = true;
                    state.filter_text.clear();
                    state.update_filter();
                    if let Some(selected) = state.selected_index {
                        state.highlighted_index = state
                            .filtered_indices
                            .iter()
                            .position(|&idx| idx == selected)
                            .unwrap_or(0);
                    }
                }
                None
            }
            DropdownMessage::Insert(c) => {
                state.filter_text.push(c);
                state.update_filter();
                // Auto-open when typing
                if !state.is_open && !state.options.is_empty() {
                    state.is_open = true;
                }
                Some(DropdownOutput::FilterChanged(state.filter_text.clone()))
            }
            DropdownMessage::Backspace => {
                if state.filter_text.pop().is_some() {
                    state.update_filter();
                    Some(DropdownOutput::FilterChanged(state.filter_text.clone()))
                } else {
                    None
                }
            }
            DropdownMessage::ClearFilter => {
                if !state.filter_text.is_empty() {
                    state.filter_text.clear();
                    state.update_filter();
                    Some(DropdownOutput::FilterChanged(state.filter_text.clone()))
                } else {
                    None
                }
            }
            DropdownMessage::SetFilter(text) => {
                if state.filter_text != text {
                    state.filter_text = text;
                    state.update_filter();
                    // Auto-open when setting filter
                    if !state.is_open && !state.options.is_empty() {
                        state.is_open = true;
                    }
                    Some(DropdownOutput::FilterChanged(state.filter_text.clone()))
                } else {
                    None
                }
            }
            DropdownMessage::Down => {
                if state.is_open && !state.filtered_indices.is_empty() {
                    state.highlighted_index =
                        (state.highlighted_index + 1) % state.filtered_indices.len();
                    let original_index = state.filtered_indices[state.highlighted_index];
                    Some(DropdownOutput::SelectionChanged(original_index))
                } else {
                    None
                }
            }
            DropdownMessage::Up => {
                if state.is_open && !state.filtered_indices.is_empty() {
                    if state.highlighted_index == 0 {
                        state.highlighted_index = state.filtered_indices.len() - 1;
                    } else {
                        state.highlighted_index -= 1;
                    }
                    let original_index = state.filtered_indices[state.highlighted_index];
                    Some(DropdownOutput::SelectionChanged(original_index))
                } else {
                    None
                }
            }
            DropdownMessage::Confirm => {
                if state.is_open && !state.filtered_indices.is_empty() {
                    let original_index = state.filtered_indices[state.highlighted_index];
                    let old_selection = state.selected_index;
                    state.selected_index = Some(original_index);
                    state.is_open = false;
                    state.filter_text.clear();
                    state.update_filter();

                    if old_selection != state.selected_index {
                        Some(DropdownOutput::Selected(
                            state.options[original_index].clone(),
                        ))
                    } else {
                        Some(DropdownOutput::Submitted(original_index))
                    }
                } else {
                    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.is_open {
                match key.code {
                    Key::Enter => Some(DropdownMessage::Confirm),
                    Key::Esc => Some(DropdownMessage::Close),
                    Key::Up => Some(DropdownMessage::Up),
                    Key::Down => Some(DropdownMessage::Down),
                    Key::Char(c) if key.modifiers.is_none() => Some(DropdownMessage::Insert(c)),
                    Key::Backspace => Some(DropdownMessage::Backspace),
                    _ => None,
                }
            } else {
                match key.code {
                    Key::Enter => Some(DropdownMessage::Toggle),
                    _ => None,
                }
            }
        } else {
            None
        }
    }

    fn view(state: &Self::State, ctx: &mut RenderContext<'_, '_>) {
        crate::annotation::with_registry(|reg| {
            let mut ann = crate::annotation::Annotation::dropdown("dropdown")
                .with_focus(ctx.focused)
                .with_disabled(ctx.disabled)
                .with_expanded(state.is_open);
            if let Some(val) = state.selected_value() {
                ann = ann.with_value(val.to_string());
            }
            reg.register(ctx.area, ann);
        });

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

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

        // Determine what to show in the input ctx.area
        let display_text = if state.is_open {
            // When open, show filter text with cursor indicator
            let arrow = "";
            if state.filter_text.is_empty() {
                format!("{}", arrow)
            } else {
                format!("{}{}", state.filter_text, arrow)
            }
        } else if let Some(value) = state.selected_value() {
            format!("{}", value)
        } else {
            format!("{}", state.placeholder)
        };

        let text_style = if !state.is_open
            && state.selected_value().is_none()
            && !ctx.disabled
            && !ctx.focused
        {
            ctx.theme.placeholder_style()
        } else {
            style
        };

        let paragraph = Paragraph::new(display_text).style(text_style).block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(border_style),
        );

        if !state.is_open {
            ctx.frame.render_widget(paragraph, ctx.area);
        } else {
            // Render input ctx.area at top
            let closed_height = 3; // 1 line + 2 borders
            let closed_area = Rect {
                x: ctx.area.x,
                y: ctx.area.y,
                width: ctx.area.width,
                height: closed_height.min(ctx.area.height),
            };
            ctx.frame.render_widget(paragraph, closed_area);

            // Render dropdown list below
            if ctx.area.height > closed_height {
                let list_area = Rect {
                    x: ctx.area.x,
                    y: ctx.area.y + closed_height,
                    width: ctx.area.width,
                    height: ctx.area.height.saturating_sub(closed_height),
                };

                if state.filtered_indices.is_empty() {
                    // Show "no matches" message
                    let no_match = Paragraph::new("  No matches")
                        .style(ctx.theme.placeholder_style())
                        .block(
                            Block::default()
                                .borders(Borders::ALL)
                                .border_style(border_style),
                        );
                    ctx.frame.render_widget(no_match, list_area);
                } else {
                    let items: Vec<ListItem> = state
                        .filtered_indices
                        .iter()
                        .enumerate()
                        .map(|(i, &orig_idx)| {
                            let opt = &state.options[orig_idx];
                            let prefix = if i == state.highlighted_index {
                                "> "
                            } else {
                                "  "
                            };
                            let text = format!("{}{}", prefix, opt);
                            let item_style = if i == state.highlighted_index {
                                ctx.theme.selected_style(ctx.focused)
                            } else {
                                ctx.theme.normal_style()
                            };
                            ListItem::new(text).style(item_style)
                        })
                        .collect();

                    let list = List::new(items).block(
                        Block::default()
                            .borders(Borders::ALL)
                            .border_style(border_style),
                    );

                    ctx.frame.render_widget(list, list_area);
                }
            }
        }
    }
}

#[cfg(test)]
mod tests;