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
//! A searchable, fuzzy-filtered action/item picker overlay.
//!
//! [`CommandPalette`] provides a popup-style command picker that users can
//! search with fuzzy matching, navigate with arrow keys, and confirm with
//! Enter. State is stored in [`CommandPaletteState`], updated via
//! [`CommandPaletteMessage`], and produces [`CommandPaletteOutput`].
//!
//! Implements [`Toggleable`].
//!
//! See also [`SearchableList`](super::SearchableList) for an inline
//! (non-overlay) searchable list.
//!
//! # Example
//!
//! ```rust
//! use envision::component::{
//!     CommandPalette, CommandPaletteMessage, CommandPaletteOutput,
//!     CommandPaletteState, Component, PaletteItem,
//! };
//!
//! let items = vec![
//!     PaletteItem::new("open", "Open File").with_shortcut("Ctrl+O"),
//!     PaletteItem::new("save", "Save File").with_shortcut("Ctrl+S"),
//!     PaletteItem::new("quit", "Quit Application").with_shortcut("Ctrl+Q"),
//! ];
//!
//! let mut state = CommandPaletteState::new(items);
//! state.set_visible(true);
//!
//! // Type to filter
//! CommandPalette::update(&mut state, CommandPaletteMessage::TypeChar('o'));
//! assert_eq!(state.query(), "o");
//!
//! // Confirm selection
//! let output = CommandPalette::update(&mut state, CommandPaletteMessage::Confirm);
//! assert!(matches!(output, Some(CommandPaletteOutput::Selected(_))));
//! ```

mod item;
mod render;

pub use item::{PaletteItem, fuzzy_score};

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

/// Messages that can be sent to a CommandPalette.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CommandPaletteMessage {
    /// Update the full query text.
    SetQuery(String),
    /// Append a character to the query.
    TypeChar(char),
    /// Delete the last character from the query.
    Backspace,
    /// Clear the entire query.
    ClearQuery,
    /// Move selection down.
    SelectNext,
    /// Move selection up.
    SelectPrev,
    /// Confirm the currently selected item.
    Confirm,
    /// Dismiss (hide) the palette.
    Dismiss,
    /// Show the palette.
    Show,
    /// Replace all items.
    SetItems(Vec<PaletteItem>),
}

/// Output messages from a CommandPalette.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CommandPaletteOutput {
    /// An item was confirmed/selected.
    Selected(PaletteItem),
    /// The palette was dismissed.
    Dismissed,
    /// The query text changed.
    QueryChanged(String),
}

/// State for a CommandPalette component.
///
/// Contains all available items, the current search query, filtered results,
/// and display configuration.
///
/// # Example
///
/// ```rust
/// use envision::component::{CommandPaletteState, PaletteItem};
///
/// let items = vec![
///     PaletteItem::new("open", "Open File"),
///     PaletteItem::new("save", "Save File"),
/// ];
/// let state = CommandPaletteState::new(items)
///     .with_title("Actions")
///     .with_placeholder("Search actions...")
///     .with_max_visible(5);
///
/// assert_eq!(state.items().len(), 2);
/// assert_eq!(state.query(), "");
/// ```
#[derive(Clone, Debug)]
#[cfg_attr(
    feature = "serialization",
    derive(serde::Serialize, serde::Deserialize)
)]
pub struct CommandPaletteState {
    /// All available items.
    items: Vec<PaletteItem>,
    /// Current search query.
    query: String,
    /// Indices into `items` that match the current query, sorted by score.
    filtered_indices: Vec<usize>,
    /// Selected index within the filtered list.
    selected: Option<usize>,
    /// Whether the palette is shown.
    visible: bool,
    /// Maximum items visible at once (default: 10).
    max_visible: usize,
    /// Input placeholder text.
    placeholder: String,
    /// Optional title.
    title: Option<String>,
    /// Scroll state for scrollbar rendering.
    #[cfg_attr(feature = "serialization", serde(skip))]
    scroll: ScrollState,
}

impl PartialEq for CommandPaletteState {
    fn eq(&self, other: &Self) -> bool {
        self.items == other.items
            && self.query == other.query
            && self.filtered_indices == other.filtered_indices
            && self.selected == other.selected
            && self.visible == other.visible
            && self.max_visible == other.max_visible
            && self.placeholder == other.placeholder
            && self.title == other.title
    }
}

impl Default for CommandPaletteState {
    fn default() -> Self {
        Self {
            items: Vec::new(),
            query: String::new(),
            filtered_indices: Vec::new(),
            selected: None,
            visible: false,
            max_visible: 10,
            placeholder: "Type to search...".to_string(),
            title: Some("Command Palette".to_string()),
            scroll: ScrollState::default(),
        }
    }
}

impl CommandPaletteState {
    /// Creates a new command palette state with the given items.
    ///
    /// All items are initially visible. If the list is non-empty, the
    /// first item is selected. The palette starts hidden.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{CommandPaletteState, PaletteItem};
    ///
    /// let state = CommandPaletteState::new(vec![
    ///     PaletteItem::new("a", "Alpha"),
    ///     PaletteItem::new("b", "Beta"),
    /// ]);
    /// assert_eq!(state.items().len(), 2);
    /// assert_eq!(state.filtered_items().len(), 2);
    /// assert!(!state.is_visible());
    /// ```
    pub fn new(items: Vec<PaletteItem>) -> Self {
        let filtered_indices: Vec<usize> = (0..items.len()).collect();
        let selected = if items.is_empty() { None } else { Some(0) };
        let scroll = ScrollState::new(filtered_indices.len());
        Self {
            items,
            filtered_indices,
            selected,
            scroll,
            ..Default::default()
        }
    }

    /// Sets the title (builder pattern).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{CommandPaletteState, PaletteItem};
    ///
    /// let state = CommandPaletteState::new(vec![]).with_title("Actions");
    /// assert_eq!(state.title(), Some("Actions"));
    /// ```
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

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

    /// Sets the maximum number of visible items (builder pattern).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{CommandPaletteState, PaletteItem};
    ///
    /// let state = CommandPaletteState::new(vec![]).with_max_visible(5);
    /// assert_eq!(state.max_visible(), 5);
    /// ```
    pub fn with_max_visible(mut self, max_visible: usize) -> Self {
        self.max_visible = max_visible;
        self
    }

    /// Sets the initial visibility (builder pattern).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{CommandPaletteState, PaletteItem};
    ///
    /// let state = CommandPaletteState::new(vec![]).with_visible(true);
    /// assert!(state.is_visible());
    /// ```
    pub fn with_visible(mut self, visible: bool) -> Self {
        self.visible = visible;
        self
    }

    /// Returns all items (unfiltered).
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{CommandPaletteState, PaletteItem};
    ///
    /// let state = CommandPaletteState::new(vec![
    ///     PaletteItem::new("a", "Alpha"),
    /// ]);
    /// assert_eq!(state.items().len(), 1);
    /// assert_eq!(state.items()[0].label, "Alpha");
    /// ```
    pub fn items(&self) -> &[PaletteItem] {
        &self.items
    }

    /// Returns the current search query.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{CommandPaletteState, PaletteItem};
    ///
    /// let state = CommandPaletteState::new(vec![]);
    /// assert_eq!(state.query(), "");
    /// ```
    pub fn query(&self) -> &str {
        &self.query
    }

    /// Returns the items matching the current query.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{CommandPaletteState, PaletteItem};
    ///
    /// let state = CommandPaletteState::new(vec![
    ///     PaletteItem::new("a", "Alpha"),
    ///     PaletteItem::new("b", "Beta"),
    /// ]);
    /// assert_eq!(state.filtered_items().len(), 2);
    /// ```
    pub fn filtered_items(&self) -> Vec<&PaletteItem> {
        self.filtered_indices
            .iter()
            .filter_map(|&i| self.items.get(i))
            .collect()
    }

    /// Returns the currently highlighted/selected item.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{CommandPaletteState, PaletteItem};
    ///
    /// let state = CommandPaletteState::new(vec![
    ///     PaletteItem::new("a", "Alpha"),
    ///     PaletteItem::new("b", "Beta"),
    /// ]);
    /// assert_eq!(state.selected_item().map(|i| &i.label), Some(&"Alpha".to_string()));
    /// ```
    pub fn selected_item(&self) -> Option<&PaletteItem> {
        self.selected
            .and_then(|si| self.filtered_indices.get(si))
            .and_then(|&i| self.items.get(i))
    }

    /// Replaces all items and refilters.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{CommandPaletteState, PaletteItem};
    ///
    /// let mut state = CommandPaletteState::new(vec![PaletteItem::new("a", "Alpha")]);
    /// state.set_items(vec![
    ///     PaletteItem::new("x", "X-ray"),
    ///     PaletteItem::new("y", "Yankee"),
    /// ]);
    /// assert_eq!(state.items().len(), 2);
    /// ```
    pub fn set_items(&mut self, items: Vec<PaletteItem>) {
        self.items = items;
        self.refilter();
    }

    /// Shows the palette and gives it focus.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{CommandPaletteState, PaletteItem};
    ///
    /// let mut state = CommandPaletteState::new(vec![]);
    /// state.show();
    /// assert!(state.is_visible());
    /// ```
    pub fn show(&mut self) {
        self.visible = true;
    }

    /// Dismisses the palette: hides it and clears the query.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{
    ///     CommandPalette, CommandPaletteState, CommandPaletteMessage, PaletteItem, Component,
    /// };
    ///
    /// let mut state = CommandPaletteState::new(vec![PaletteItem::new("a", "Alpha")]);
    /// state.show();
    /// CommandPalette::update(&mut state, CommandPaletteMessage::TypeChar('a'));
    /// state.dismiss();
    /// assert!(!state.is_visible());
    /// assert_eq!(state.query(), "");
    /// ```
    pub fn dismiss(&mut self) {
        self.visible = false;
        self.query.clear();
        self.refilter();
    }

    /// Returns the title.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{CommandPaletteState, PaletteItem};
    ///
    /// let state = CommandPaletteState::new(vec![]);
    /// assert_eq!(state.title(), Some("Command Palette"));
    /// ```
    pub fn title(&self) -> Option<&str> {
        self.title.as_deref()
    }

    /// Sets the title.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{CommandPaletteState, PaletteItem};
    ///
    /// let mut state = CommandPaletteState::new(vec![]);
    /// state.set_title("Actions");
    /// assert_eq!(state.title(), Some("Actions"));
    /// ```
    pub fn set_title(&mut self, title: impl Into<String>) {
        self.title = Some(title.into());
    }

    /// Returns the placeholder text.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{CommandPaletteState, PaletteItem};
    ///
    /// let state = CommandPaletteState::new(vec![]);
    /// assert_eq!(state.placeholder(), "Type to search...");
    /// ```
    pub fn placeholder(&self) -> &str {
        &self.placeholder
    }

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

    /// Returns the maximum number of visible items.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{CommandPaletteState, PaletteItem};
    ///
    /// let state = CommandPaletteState::new(vec![]);
    /// assert_eq!(state.max_visible(), 10);
    /// ```
    pub fn max_visible(&self) -> usize {
        self.max_visible
    }

    /// Sets the maximum number of visible items.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{CommandPaletteState, PaletteItem};
    ///
    /// let mut state = CommandPaletteState::new(vec![]);
    /// state.set_max_visible(20);
    /// assert_eq!(state.max_visible(), 20);
    /// ```
    pub fn set_max_visible(&mut self, max_visible: usize) {
        self.max_visible = max_visible;
    }

    /// Returns the number of items matching the current query.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{CommandPaletteState, PaletteItem};
    ///
    /// let state = CommandPaletteState::new(vec![
    ///     PaletteItem::new("a", "Alpha"),
    ///     PaletteItem::new("b", "Beta"),
    /// ]);
    /// assert_eq!(state.filtered_count(), 2);
    /// ```
    pub fn filtered_count(&self) -> usize {
        self.filtered_indices.len()
    }

    /// Returns the selected index within the filtered list.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{CommandPaletteState, PaletteItem};
    ///
    /// let state = CommandPaletteState::new(vec![PaletteItem::new("a", "Alpha")]);
    /// assert_eq!(state.selected_index(), Some(0));
    ///
    /// let empty = CommandPaletteState::new(vec![]);
    /// assert_eq!(empty.selected_index(), None);
    /// ```
    pub fn selected_index(&self) -> Option<usize> {
        self.selected
    }

    /// Returns true if the palette is visible.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{CommandPaletteState, PaletteItem};
    ///
    /// let state = CommandPaletteState::new(vec![]);
    /// assert!(!state.is_visible());
    /// ```
    pub fn is_visible(&self) -> bool {
        self.visible
    }

    /// Sets the visibility.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{CommandPaletteState, PaletteItem};
    ///
    /// let mut state = CommandPaletteState::new(vec![]);
    /// state.set_visible(true);
    /// assert!(state.is_visible());
    /// ```
    pub fn set_visible(&mut self, visible: bool) {
        self.visible = visible;
    }

    /// Updates the state with a message, returning any output.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::component::{CommandPaletteState, CommandPaletteMessage, CommandPaletteOutput, PaletteItem};
    ///
    /// let mut state = CommandPaletteState::new(vec![PaletteItem::new("a", "Alpha")]);
    /// state.set_visible(true);
    /// let output = state.update(CommandPaletteMessage::TypeChar('a'));
    /// assert!(matches!(output, Some(CommandPaletteOutput::QueryChanged(_))));
    /// ```
    pub fn update(&mut self, msg: CommandPaletteMessage) -> Option<CommandPaletteOutput> {
        CommandPalette::update(self, msg)
    }

    /// Recomputes filtered indices based on the current query.
    fn refilter(&mut self) {
        if self.query.is_empty() {
            self.filtered_indices = (0..self.items.len()).collect();
        } else {
            let mut scored: Vec<(usize, usize)> = self
                .items
                .iter()
                .enumerate()
                .filter_map(|(i, item)| {
                    fuzzy_score(&self.query, &item.label).map(|score| (i, score))
                })
                .collect();
            scored.sort_by_key(|b| std::cmp::Reverse(b.1));
            self.filtered_indices = scored.into_iter().map(|(i, _)| i).collect();
        }

        self.scroll.set_content_length(self.filtered_indices.len());

        if self.filtered_indices.is_empty() {
            self.selected = None;
        } else {
            self.selected = Some(0);
        }
    }
}

/// A searchable, fuzzy-filtered command palette overlay component.
///
/// Displays a popup-style list of actions/items that can be searched,
/// navigated, and selected. Designed to be used as an overlay.
///
/// # Keyboard Navigation
///
/// - Character keys: type to filter
/// - Backspace: delete last character
/// - Up / Ctrl+P: move selection up
/// - Down / Ctrl+N: move selection down
/// - Enter: confirm selection
/// - Escape: dismiss palette
/// - Ctrl+U: clear query
///
/// # Example
///
/// ```rust
/// use envision::component::{
///     CommandPalette, CommandPaletteMessage, CommandPaletteOutput,
///     CommandPaletteState, Component, PaletteItem,
/// };
///
/// let items = vec![
///     PaletteItem::new("open", "Open File"),
///     PaletteItem::new("save", "Save File"),
/// ];
/// let mut state = CommandPaletteState::new(items);
/// state.set_visible(true);
///
/// // Filter to "save"
/// CommandPalette::update(&mut state, CommandPaletteMessage::TypeChar('s'));
/// CommandPalette::update(&mut state, CommandPaletteMessage::TypeChar('a'));
///
/// // Confirm selection
/// let output = CommandPalette::update(&mut state, CommandPaletteMessage::Confirm);
/// assert!(matches!(output, Some(CommandPaletteOutput::Selected(_))));
/// ```
pub struct CommandPalette;

impl Component for CommandPalette {
    type State = CommandPaletteState;
    type Message = CommandPaletteMessage;
    type Output = CommandPaletteOutput;

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

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

        if let Some(key) = event.as_key() {
            match key.code {
                Key::Esc => Some(CommandPaletteMessage::Dismiss),
                Key::Enter => Some(CommandPaletteMessage::Confirm),
                Key::Backspace => Some(CommandPaletteMessage::Backspace),
                Key::Up => Some(CommandPaletteMessage::SelectPrev),
                Key::Down => Some(CommandPaletteMessage::SelectNext),
                Key::Char('p') if key.modifiers.ctrl() => Some(CommandPaletteMessage::SelectPrev),
                Key::Char('n') if key.modifiers.ctrl() => Some(CommandPaletteMessage::SelectNext),
                Key::Char('u') if key.modifiers.ctrl() => Some(CommandPaletteMessage::ClearQuery),
                Key::Char(_) if !key.modifiers.ctrl() && !key.modifiers.alt() => {
                    key.raw_char.map(CommandPaletteMessage::TypeChar)
                }
                _ => None,
            }
        } else {
            None
        }
    }

    fn update(state: &mut Self::State, msg: Self::Message) -> Option<Self::Output> {
        match msg {
            CommandPaletteMessage::SetQuery(text) => {
                state.query = text.clone();
                state.refilter();
                Some(CommandPaletteOutput::QueryChanged(text))
            }
            CommandPaletteMessage::TypeChar(c) => {
                state.query.push(c);
                let text = state.query.clone();
                state.refilter();
                Some(CommandPaletteOutput::QueryChanged(text))
            }
            CommandPaletteMessage::Backspace => {
                if !state.query.is_empty() {
                    state.query.pop();
                    let text = state.query.clone();
                    state.refilter();
                    Some(CommandPaletteOutput::QueryChanged(text))
                } else {
                    None
                }
            }
            CommandPaletteMessage::ClearQuery => {
                if !state.query.is_empty() {
                    state.query.clear();
                    state.refilter();
                    Some(CommandPaletteOutput::QueryChanged(String::new()))
                } else {
                    None
                }
            }
            CommandPaletteMessage::SelectNext => {
                if let Some(current) = state.selected {
                    let len = state.filtered_indices.len();
                    if len > 0 {
                        let new_index = (current + 1) % len;
                        state.selected = Some(new_index);
                        state.scroll.ensure_visible(new_index);
                    }
                }
                None
            }
            CommandPaletteMessage::SelectPrev => {
                if let Some(current) = state.selected {
                    let len = state.filtered_indices.len();
                    if len > 0 {
                        let new_index = if current == 0 { len - 1 } else { current - 1 };
                        state.selected = Some(new_index);
                        state.scroll.ensure_visible(new_index);
                    }
                }
                None
            }
            CommandPaletteMessage::Confirm => {
                let item = state
                    .selected
                    .and_then(|si| state.filtered_indices.get(si).copied())
                    .and_then(|i| state.items.get(i).cloned());
                if let Some(item) = item {
                    state.visible = false;
                    state.query.clear();
                    state.refilter();
                    Some(CommandPaletteOutput::Selected(item))
                } else {
                    None
                }
            }
            CommandPaletteMessage::Dismiss => {
                state.visible = false;
                state.query.clear();
                state.refilter();
                Some(CommandPaletteOutput::Dismissed)
            }
            CommandPaletteMessage::Show => {
                state.visible = true;
                None
            }
            CommandPaletteMessage::SetItems(items) => {
                state.items = items;
                state.refilter();
                None
            }
        }
    }

    fn view(state: &Self::State, ctx: &mut RenderContext<'_, '_>) {
        render::render_command_palette(
            state,
            ctx.frame,
            ctx.area,
            ctx.theme,
            ctx.focused,
            ctx.disabled,
        );
    }
}

impl Toggleable for CommandPalette {
    fn is_visible(state: &Self::State) -> bool {
        state.visible
    }

    fn set_visible(state: &mut Self::State, visible: bool) {
        state.visible = visible;
    }
}

#[cfg(test)]
mod event_tests;
#[cfg(test)]
mod snapshot_tests;
#[cfg(test)]
mod tests;