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
//! A dropdown selection component.
//!
//! [`Select`] provides a compact dropdown menu for selecting a single option
//! from a list. It displays the selected value when closed and shows all
//! options when opened. State is stored in [`SelectState`], updated via
//! [`SelectMessage`], and produces [`SelectOutput`].
//!
//!
//! See also [`Dropdown`](super::Dropdown) for a variant with search filtering.
//!
//! # Example
//!
//! ```rust
//! use envision::component::{Select, SelectMessage, SelectOutput, SelectState, Component};
//!
//! // Create a select with options
//! let mut state = SelectState::new(vec!["Red", "Green", "Blue"]);
//! state.set_placeholder("Choose a color");
//!
//! // Open it
//! let _ = Select::update(&mut state, SelectMessage::Open);
//!
//! // Select an option (navigating to index 1, then confirming)
//! let _ = Select::update(&mut state, SelectMessage::Down);
//! let output = Select::update(&mut state, SelectMessage::Confirm);
//! assert_eq!(output, Some(SelectOutput::Selected("Green".to_string())));
//! ```

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 Select.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SelectMessage {
    /// Open the dropdown.
    Open,
    /// Close the dropdown.
    Close,
    /// Toggle the dropdown open/closed.
    Toggle,
    /// Move selection down to the next option.
    Down,
    /// Move selection up to the previous option.
    Up,
    /// Confirm current selection.
    Confirm,
}

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

/// State for a Select component.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct SelectState {
    /// Available options.
    options: Vec<String>,
    /// Currently selected option index.
    selected_index: Option<usize>,
    /// Currently highlighted option (when dropdown is open).
    highlighted_index: usize,
    /// Whether the dropdown is open.
    is_open: bool,
    /// Placeholder text when nothing is selected.
    placeholder: String,
}

impl Default for SelectState {
    /// Creates a default empty select with `"Select..."` placeholder.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::SelectState;
    ///
    /// let state = SelectState::default();
    /// assert!(state.options().is_empty());
    /// assert!(state.selected_index().is_none());
    /// assert_eq!(state.placeholder(), "Select...");
    /// ```
    fn default() -> Self {
        Self {
            options: Vec::new(),
            selected_index: None,
            highlighted_index: 0,
            is_open: false,
            placeholder: String::from("Select..."),
        }
    }
}

impl SelectState {
    /// Creates a new select with the given options.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::SelectState;
    ///
    /// let state = SelectState::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 {
        Self {
            options: options.into_iter().map(|s| s.into()).collect(),
            ..Self::default()
        }
    }

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

        Self {
            options: options_vec,
            selected_index,
            highlighted_index: selected_index.unwrap_or(0),
            ..Self::default()
        }
    }

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

    /// Sets the options list.
    ///
    /// Resets selection if the current selected index is out of bounds.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::prelude::*;
    ///
    /// let mut state = SelectState::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;
            }
        }

        // Reset highlight if out of bounds
        if self.highlighted_index >= self.options.len() && !self.options.is_empty() {
            self.highlighted_index = 0;
        }
    }

    /// Returns the selected option index.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::prelude::*;
    ///
    /// let state = SelectState::new(vec!["A", "B"]);
    /// assert_eq!(state.selected_index(), None);
    ///
    /// let state = SelectState::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).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{SelectState};
    ///
    /// let state = SelectState::with_selection(vec!["A", "B", "C"], 1);
    /// assert_eq!(state.selected(), Some(1));
    /// ```
    pub fn selected(&self) -> Option<usize> {
        self.selected_index()
    }

    /// Returns the selected option value.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::prelude::*;
    ///
    /// let state = SelectState::with_selection(vec!["Red", "Green", "Blue"], 2);
    /// assert_eq!(state.selected_value(), Some("Blue"));
    ///
    /// let state = SelectState::new(vec!["Red", "Green", "Blue"]);
    /// 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 = SelectState::with_selection(vec!["Red", "Green"], 0);
    /// assert_eq!(state.selected_item(), Some("Red"));
    /// ```
    pub fn selected_item(&self) -> Option<&str> {
        self.selected_value()
    }

    /// Sets the selected option index.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::prelude::*;
    ///
    /// let mut state = SelectState::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);
                self.highlighted_index = idx;
            }
        } else {
            self.selected_index = None;
        }
    }

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

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

    /// Sets the placeholder text.
    ///
    /// # Examples
    ///
    /// ```
    /// use envision::prelude::*;
    ///
    /// let mut state = SelectState::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::SelectState;
    ///
    /// let state = SelectState::new(vec!["Red", "Green", "Blue"])
    ///     .with_placeholder("Choose a color...");
    /// assert_eq!(state.placeholder(), "Choose a color...");
    /// ```
    pub fn with_placeholder(mut self, placeholder: impl Into<String>) -> Self {
        self.placeholder = placeholder.into();
        self
    }

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

/// A dropdown selection component.
///
/// This component provides a compact dropdown menu for selecting a single
/// option from a list. When closed, it displays the currently selected value
/// or a placeholder. When opened, it shows all available options with keyboard
/// navigation.
///
/// # Keyboard Navigation
///
/// The select itself doesn't handle keyboard events directly. Your application
/// should map:
/// - Enter/Space to [`SelectMessage::Toggle`] (open/close)
/// - Down arrow to [`SelectMessage::Down`]
/// - Up arrow to [`SelectMessage::Up`]
/// - Enter to [`SelectMessage::Confirm`] (when open)
/// - Escape to [`SelectMessage::Close`]
///
/// # Visual States
///
/// **Closed:**
/// ```text
/// ┌────────────────┐
/// │ Selected Value ▼│
/// └────────────────┘
/// ```
///
/// **Open:**
/// ```text
/// ┌────────────────┐
/// │ Selected Value ▲│
/// ├────────────────┤
/// │ Option 1       │
/// │ > Option 2     │  ← highlighted
/// │ Option 3       │
/// └────────────────┘
/// ```
///
/// # Example
///
/// ```rust
/// use envision::component::{Select, SelectMessage, SelectOutput, SelectState, Component};
///
/// let mut state = SelectState::new(vec!["Small", "Medium", "Large"]);
///
/// // Open dropdown
/// Select::update(&mut state, SelectMessage::Open);
///
/// // Navigate to index 1 and confirm (selection changes from None to Some(1))
/// Select::update(&mut state, SelectMessage::Down);
/// let output = Select::update(&mut state, SelectMessage::Confirm);
/// assert_eq!(output, Some(SelectOutput::Selected("Medium".to_string())));
/// ```
pub struct Select;

impl Component for Select {
    type State = SelectState;
    type Message = SelectMessage;
    type Output = SelectOutput;

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

    fn update(state: &mut Self::State, msg: Self::Message) -> Option<Self::Output> {
        match msg {
            SelectMessage::Open => {
                if !state.options.is_empty() {
                    state.is_open = true;
                    // Set highlight to current selection or first item
                    state.highlighted_index = state.selected_index.unwrap_or(0);
                }
                None
            }
            SelectMessage::Close => {
                state.is_open = false;
                None
            }
            SelectMessage::Toggle => {
                if state.is_open {
                    state.is_open = false;
                } else if !state.options.is_empty() {
                    state.is_open = true;
                    state.highlighted_index = state.selected_index.unwrap_or(0);
                }
                None
            }
            SelectMessage::Down => {
                if state.is_open && !state.options.is_empty() {
                    state.highlighted_index = (state.highlighted_index + 1) % state.options.len();
                    Some(SelectOutput::SelectionChanged(state.highlighted_index))
                } else {
                    None
                }
            }
            SelectMessage::Up => {
                if state.is_open && !state.options.is_empty() {
                    if state.highlighted_index == 0 {
                        state.highlighted_index = state.options.len() - 1;
                    } else {
                        state.highlighted_index -= 1;
                    }
                    Some(SelectOutput::SelectionChanged(state.highlighted_index))
                } else {
                    None
                }
            }
            SelectMessage::Confirm => {
                if state.is_open && !state.options.is_empty() {
                    let old_selection = state.selected_index;
                    let highlighted = state.highlighted_index;
                    state.selected_index = Some(highlighted);
                    state.is_open = false;

                    if old_selection != state.selected_index {
                        Some(SelectOutput::Selected(state.options[highlighted].clone()))
                    } else {
                        Some(SelectOutput::Submitted(highlighted))
                    }
                } 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(SelectMessage::Confirm),
                    Key::Esc => Some(SelectMessage::Close),
                    Key::Up | Key::Char('k') => Some(SelectMessage::Up),
                    Key::Down | Key::Char('j') => Some(SelectMessage::Down),
                    _ => None,
                }
            } else {
                match key.code {
                    Key::Enter | Key::Char(' ') => Some(SelectMessage::Toggle),
                    _ => None,
                }
            }
        } else {
            None
        }
    }

    fn view(state: &Self::State, ctx: &mut RenderContext<'_, '_>) {
        crate::annotation::with_registry(|reg| {
            let mut ann = crate::annotation::Annotation::new(crate::annotation::WidgetType::Select)
                .with_id("select")
                .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()
        };

        // Display selected value or placeholder
        let display_text = if let Some(value) = state.selected_value() {
            let arrow = if state.is_open { "" } else { "" };
            format!("{} {}", value, arrow)
        } else {
            let arrow = if state.is_open { "" } else { "" };
            format!("{} {}", state.placeholder, arrow)
        };

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

        if !state.is_open {
            ctx.frame.render_widget(paragraph, ctx.area);
        } else {
            // Render closed state in first line
            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),
                };

                let items: Vec<ListItem> = state
                    .options
                    .iter()
                    .enumerate()
                    .map(|(idx, opt)| {
                        let prefix = if idx == state.highlighted_index {
                            "> "
                        } else {
                            "  "
                        };
                        let text = format!("{}{}", prefix, opt);
                        let item_style = if idx == 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;