Skip to main content

ftui_widgets/command_palette/
mod.rs

1#![forbid(unsafe_code)]
2
3//! Command Palette widget for instant action search.
4//!
5//! This module provides a fuzzy-search command palette with:
6//! - Bayesian match scoring with evidence ledger
7//! - Incremental scoring with query-prefix pruning
8//! - Word-start, prefix, substring, and fuzzy matching
9//! - Conformal rank confidence for tie-break stability
10//! - Match position tracking for highlighting
11//!
12//! # Usage
13//!
14//! ```ignore
15//! let mut palette = CommandPalette::new();
16//! palette.register("Open File", Some("Open a file from disk"), &["file", "open"]);
17//! palette.register("Save File", Some("Save current file"), &["file", "save"]);
18//! palette.open(); // Show the palette
19//!
20//! // In your update loop, handle events:
21//! if let Some(action) = palette.handle_event(event) {
22//!     match action {
23//!         PaletteAction::Execute(id) => { /* run the action */ }
24//!         PaletteAction::Dismiss => { /* palette was closed */ }
25//!     }
26//! }
27//!
28//! // Render as a Widget
29//! palette.render(area, &mut frame);
30//! ```
31//!
32//! # Submodules
33//!
34//! - [`scorer`]: Bayesian fuzzy matcher with explainable scoring
35
36pub mod scorer;
37
38#[cfg(feature = "experimental")]
39pub use scorer::ConformalRanker;
40pub use scorer::{
41    BayesianScorer, EvidenceKind, EvidenceLedger, IncrementalScorer, IncrementalStats, MatchResult,
42    MatchType, RankConfidence, RankStability, RankedItem, RankedResults, RankingSummary,
43};
44
45use ftui_a11y::node::{A11yNodeInfo, A11yRole, LiveRegion};
46use ftui_core::event::{Event, KeyCode, KeyEvent, KeyEventKind, Modifiers};
47use ftui_core::geometry::Rect;
48use ftui_render::cell::{Cell, CellAttrs, CellContent, PackedRgba, StyleFlags as CellStyleFlags};
49use ftui_render::frame::Frame;
50use ftui_style::Style;
51use ftui_text::{display_width, grapheme_width, graphemes};
52
53use crate::Widget;
54use crate::adaptive_radix::AdaptiveRadixTree;
55
56#[cfg(feature = "tracing")]
57use tracing::{debug, info};
58#[cfg(feature = "tracing")]
59use web_time::Instant;
60
61#[cfg(feature = "tracing")]
62const TELEMETRY_TARGET: &str = "ftui_widgets::command_palette";
63
64#[cfg(feature = "tracing")]
65fn emit_palette_opened(action_count: usize, result_count: usize) {
66    info!(
67        target: TELEMETRY_TARGET,
68        event = "palette_opened",
69        action_count,
70        result_count
71    );
72}
73
74#[cfg(feature = "tracing")]
75fn emit_palette_query_updated(query: &str, match_count: usize, latency_ms: u128) {
76    info!(
77        target: TELEMETRY_TARGET,
78        event = "palette_query_updated",
79        query_len = query.len(),
80        match_count,
81        latency_ms
82    );
83    if tracing::enabled!(target: TELEMETRY_TARGET, tracing::Level::DEBUG) {
84        debug!(
85            target: TELEMETRY_TARGET,
86            event = "palette_query_text",
87            query
88        );
89    }
90}
91
92#[cfg(feature = "tracing")]
93fn emit_palette_action_executed(action_id: &str, latency_ms: Option<u128>) {
94    if let Some(latency_ms) = latency_ms {
95        info!(
96            target: TELEMETRY_TARGET,
97            event = "palette_action_executed",
98            action_id,
99            latency_ms
100        );
101    } else {
102        info!(
103            target: TELEMETRY_TARGET,
104            event = "palette_action_executed",
105            action_id
106        );
107    }
108}
109
110#[cfg(feature = "tracing")]
111fn emit_palette_closed(reason: PaletteCloseReason) {
112    info!(
113        target: TELEMETRY_TARGET,
114        event = "palette_closed",
115        reason = reason.as_str()
116    );
117}
118
119// ---------------------------------------------------------------------------
120// Action Item
121// ---------------------------------------------------------------------------
122
123/// A single action that can be invoked from the command palette.
124#[derive(Debug, Clone)]
125pub struct ActionItem {
126    /// Unique identifier for this action.
127    pub id: String,
128    /// Display title (searched by the scorer).
129    pub title: String,
130    /// Optional description shown below the title.
131    pub description: Option<String>,
132    /// Tags for boosting search relevance.
133    pub tags: Vec<String>,
134    /// Category for visual grouping (e.g., "Git", "File", "View").
135    pub category: Option<String>,
136}
137
138impl ActionItem {
139    /// Create a new action item.
140    pub fn new(id: impl Into<String>, title: impl Into<String>) -> Self {
141        Self {
142            id: id.into(),
143            title: title.into(),
144            description: None,
145            tags: Vec::new(),
146            category: None,
147        }
148    }
149
150    /// Set description (builder).
151    #[must_use]
152    pub fn with_description(mut self, desc: impl Into<String>) -> Self {
153        self.description = Some(desc.into());
154        self
155    }
156
157    /// Set tags (builder).
158    #[must_use]
159    pub fn with_tags(mut self, tags: &[&str]) -> Self {
160        self.tags = tags.iter().map(|s| (*s).to_string()).collect();
161        self
162    }
163
164    /// Set category (builder).
165    #[must_use]
166    pub fn with_category(mut self, cat: impl Into<String>) -> Self {
167        self.category = Some(cat.into());
168        self
169    }
170}
171
172// ---------------------------------------------------------------------------
173// Palette Action
174// ---------------------------------------------------------------------------
175
176/// Action returned from event handling.
177#[derive(Debug, Clone, PartialEq, Eq)]
178pub enum PaletteAction {
179    /// User selected an action to execute (contains the action ID).
180    Execute(String),
181    /// User dismissed the palette (Esc).
182    Dismiss,
183}
184
185#[derive(Debug, Clone, Copy, PartialEq, Eq)]
186enum PaletteCloseReason {
187    Dismiss,
188    Execute,
189    Toggle,
190    Programmatic,
191}
192
193impl PaletteCloseReason {
194    #[cfg(feature = "tracing")]
195    const fn as_str(self) -> &'static str {
196        match self {
197            Self::Dismiss => "dismiss",
198            Self::Execute => "execute",
199            Self::Toggle => "toggle",
200            Self::Programmatic => "programmatic",
201        }
202    }
203}
204
205fn compute_word_starts(title_lower: &str) -> Vec<usize> {
206    let bytes = title_lower.as_bytes();
207    title_lower
208        .char_indices()
209        .filter_map(|(i, _)| {
210            let is_word_start = i == 0 || {
211                let prev = bytes.get(i.saturating_sub(1)).copied().unwrap_or(b' ');
212                prev == b' ' || prev == b'-' || prev == b'_'
213            };
214            is_word_start.then_some(i)
215        })
216        .collect()
217}
218
219// ---------------------------------------------------------------------------
220// Palette Style
221// ---------------------------------------------------------------------------
222
223/// Visual styling for the command palette.
224#[derive(Debug, Clone)]
225pub struct PaletteStyle {
226    /// Border style.
227    pub border: Style,
228    /// Query input style.
229    pub input: Style,
230    /// Normal result item style.
231    pub item: Style,
232    /// Selected/highlighted result item style.
233    pub item_selected: Style,
234    /// Match highlight style (for matched characters).
235    pub match_highlight: Style,
236    /// Description text style.
237    pub description: Style,
238    /// Category badge style.
239    pub category: Style,
240    /// Empty state / hint text style.
241    pub hint: Style,
242}
243
244impl Default for PaletteStyle {
245    fn default() -> Self {
246        // Colors chosen for WCAG AA contrast ratios against bg(30,30,40):
247        // - item (190,190,200) on bg(30,30,40) ≈ 9.5:1 (AAA)
248        // - selected (255,255,255) on bg(50,50,75) ≈ 8.8:1 (AAA)
249        // - highlight (255,210,60) on bg(30,30,40) ≈ 11:1 (AAA)
250        // - description (140,140,160) on bg(30,30,40) ≈ 5.2:1 (AA)
251        Self {
252            border: Style::new().fg(PackedRgba::rgb(100, 100, 120)),
253            input: Style::new().fg(PackedRgba::rgb(220, 220, 230)),
254            item: Style::new().fg(PackedRgba::rgb(190, 190, 200)),
255            item_selected: Style::new()
256                .fg(PackedRgba::rgb(255, 255, 255))
257                .bg(PackedRgba::rgb(50, 50, 75)),
258            match_highlight: Style::new().fg(PackedRgba::rgb(255, 210, 60)),
259            description: Style::new().fg(PackedRgba::rgb(140, 140, 160)),
260            category: Style::new().fg(PackedRgba::rgb(100, 180, 255)),
261            hint: Style::new().fg(PackedRgba::rgb(100, 100, 120)),
262        }
263    }
264}
265
266// ---------------------------------------------------------------------------
267// Scored Item (internal)
268// ---------------------------------------------------------------------------
269
270/// Internal: a scored result with corpus index.
271#[derive(Debug)]
272struct ScoredItem {
273    /// Index into the actions vec.
274    action_index: usize,
275    /// Match result from scorer.
276    result: MatchResult,
277}
278
279// ---------------------------------------------------------------------------
280// Public Result View
281// ---------------------------------------------------------------------------
282
283/// Read-only view of a scored palette item.
284#[derive(Debug, Clone, Copy)]
285pub struct PaletteMatch<'a> {
286    /// Action metadata.
287    pub action: &'a ActionItem,
288    /// Match result (score, match type, evidence).
289    pub result: &'a MatchResult,
290}
291
292// ---------------------------------------------------------------------------
293// Match Filter
294// ---------------------------------------------------------------------------
295
296/// Optional match-type filter for palette results.
297#[derive(Debug, Clone, Copy, PartialEq, Eq)]
298pub enum MatchFilter {
299    /// Show all matches.
300    All,
301    /// Exact match only.
302    Exact,
303    /// Prefix match only.
304    Prefix,
305    /// Word-start match only.
306    WordStart,
307    /// Substring match only.
308    Substring,
309    /// Fuzzy match only.
310    Fuzzy,
311}
312
313impl MatchFilter {
314    fn allows(self, match_type: MatchType) -> bool {
315        matches!(
316            (self, match_type),
317            (Self::All, _)
318                | (Self::Exact, MatchType::Exact)
319                | (Self::Prefix, MatchType::Prefix)
320                | (Self::WordStart, MatchType::WordStart)
321                | (Self::Substring, MatchType::Substring)
322                | (Self::Fuzzy, MatchType::Fuzzy)
323        )
324    }
325}
326
327// ---------------------------------------------------------------------------
328// Command Palette Widget
329// ---------------------------------------------------------------------------
330
331/// Command palette widget for instant action search.
332///
333/// Provides a fuzzy-search overlay with keyboard navigation, match highlighting,
334/// and incremental scoring for responsive keystroke handling.
335///
336/// # Invariants
337///
338/// 1. `selected` is always < `filtered.len()` (or 0 when empty).
339/// 2. Results are sorted by descending score with stable tie-breaking.
340/// 3. Query changes trigger incremental re-scoring (not full rescan)
341///    when the query extends the previous one.
342#[derive(Debug)]
343pub struct CommandPalette {
344    /// Registered actions.
345    actions: Vec<ActionItem>,
346    /// Cached titles for scoring (avoids per-keystroke Vec allocation).
347    titles_cache: Vec<String>,
348    /// Cached lowercased titles for scoring.
349    titles_lower: Vec<String>,
350    /// Cached word-start positions for each lowercased title.
351    titles_word_starts: Vec<Vec<usize>>,
352    /// Adaptive radix index over lowercased titles for prefix-only searches.
353    prefix_index: AdaptiveRadixTree<usize>,
354    /// Current query text.
355    query: String,
356    /// Cursor position in the query (byte offset for simplicity).
357    cursor: usize,
358    /// Currently selected index in filtered results.
359    selected: usize,
360    /// Scroll offset for visible window.
361    scroll_offset: usize,
362    /// Whether the palette is visible.
363    visible: bool,
364    /// Visual styling.
365    style: PaletteStyle,
366    /// Incremental scorer for fast keystroke handling.
367    scorer: IncrementalScorer,
368    /// Current filtered results.
369    filtered: Vec<ScoredItem>,
370    /// Optional match-type filter.
371    match_filter: MatchFilter,
372    /// Generation counter for corpus invalidation.
373    generation: u64,
374    /// Maximum visible results.
375    max_visible: usize,
376    /// Custom title for the palette border (default: " Command Palette ").
377    title: String,
378    /// When true, use the full `Rect` passed to `render()` instead of
379    /// computing a centered sub-area.
380    fill_area: bool,
381    /// Stable identity for this palette's semantic dialog tree.
382    accessibility_id: u64,
383    /// Telemetry timing anchor (only when tracing feature is enabled).
384    #[cfg(feature = "tracing")]
385    opened_at: Option<Instant>,
386}
387
388impl Default for CommandPalette {
389    fn default() -> Self {
390        Self::new()
391    }
392}
393
394impl CommandPalette {
395    fn next_accessibility_id() -> u64 {
396        use std::hash::{Hash, Hasher};
397        static NEXT_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
398        let sequence = NEXT_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
399        let mut hasher = std::collections::hash_map::DefaultHasher::new();
400        ("ftui.command_palette", sequence).hash(&mut hasher);
401        hasher.finish()
402    }
403
404    /// Create a new empty command palette.
405    pub fn new() -> Self {
406        Self {
407            actions: Vec::new(),
408            titles_cache: Vec::new(),
409            titles_lower: Vec::new(),
410            titles_word_starts: Vec::new(),
411            prefix_index: AdaptiveRadixTree::new(),
412            query: String::new(),
413            cursor: 0,
414            selected: 0,
415            scroll_offset: 0,
416            visible: false,
417            style: PaletteStyle::default(),
418            scorer: IncrementalScorer::new(),
419            filtered: Vec::new(),
420            match_filter: MatchFilter::All,
421            generation: 0,
422            max_visible: 10,
423            title: " Command Palette ".to_string(),
424            fill_area: false,
425            accessibility_id: Self::next_accessibility_id(),
426            #[cfg(feature = "tracing")]
427            opened_at: None,
428        }
429    }
430
431    /// Set the visual style (builder).
432    #[must_use]
433    pub fn with_style(mut self, style: PaletteStyle) -> Self {
434        self.style = style;
435        self
436    }
437
438    /// Set the visual style.
439    pub fn set_style(&mut self, style: PaletteStyle) {
440        self.style = style;
441    }
442
443    /// Set max visible results (builder).
444    #[must_use]
445    pub fn with_max_visible(mut self, n: usize) -> Self {
446        self.max_visible = n;
447        self
448    }
449
450    /// Set a custom title for the palette border (builder).
451    ///
452    /// Defaults to `" Command Palette "`. The title is rendered centered in the
453    /// top border. Surrounding spaces are the caller's responsibility.
454    #[must_use]
455    pub fn with_title(mut self, title: impl Into<String>) -> Self {
456        self.title = title.into();
457        self
458    }
459
460    /// Set a custom title for the palette border.
461    pub fn set_title(&mut self, title: impl Into<String>) {
462        self.title = title.into();
463    }
464
465    /// Use the full area passed to `render()` instead of computing a centered
466    /// sub-area (builder).
467    ///
468    /// When `true`, the palette fills the entire `Rect` handed to
469    /// [`Widget::render`], letting the caller control position and size
470    /// externally. When `false` (the default), the palette computes its own
471    /// dimensions (~60 % width, centered, 1/6 from top).
472    #[must_use]
473    pub fn with_fill_area(mut self, fill: bool) -> Self {
474        self.fill_area = fill;
475        self
476    }
477
478    /// Set whether the palette should fill the entire render area.
479    pub fn set_fill_area(&mut self, fill: bool) {
480        self.fill_area = fill;
481    }
482
483    /// Override the stable accessibility identity for this palette instance.
484    #[must_use]
485    pub fn with_accessibility_id(mut self, id: u64) -> Self {
486        self.accessibility_id = id;
487        self
488    }
489
490    /// Update the stable accessibility identity in place.
491    pub fn set_accessibility_id(&mut self, id: u64) {
492        self.accessibility_id = id;
493    }
494
495    /// Enable or disable evidence tracking for match results.
496    pub fn enable_evidence_tracking(&mut self, enabled: bool) {
497        self.scorer = if enabled {
498            IncrementalScorer::with_scorer(BayesianScorer::new())
499        } else {
500            IncrementalScorer::new()
501        };
502        self.update_filtered(false);
503    }
504
505    // --- Action Registration ---
506
507    fn push_title_cache_into(
508        titles_cache: &mut Vec<String>,
509        titles_lower: &mut Vec<String>,
510        titles_word_starts: &mut Vec<Vec<usize>>,
511        title: &str,
512    ) {
513        titles_cache.push(title.to_string());
514        let lower = title.to_lowercase();
515        titles_word_starts.push(compute_word_starts(&lower));
516        titles_lower.push(lower);
517    }
518
519    fn push_title_cache(&mut self, title: &str) {
520        Self::push_title_cache_into(
521            &mut self.titles_cache,
522            &mut self.titles_lower,
523            &mut self.titles_word_starts,
524            title,
525        );
526    }
527
528    fn prefix_index_key(title_lower: &str, action_index: usize) -> String {
529        format!("{title_lower}\u{1f}{action_index:020}")
530    }
531
532    fn insert_prefix_index_entry(&mut self, action_index: usize) {
533        let key = self
534            .titles_lower
535            .get(action_index)
536            .map(|title_lower| Self::prefix_index_key(title_lower, action_index));
537        if let Some(key) = key {
538            self.prefix_index.insert(&key, action_index);
539        }
540    }
541
542    fn rebuild_prefix_index(&mut self) {
543        let mut prefix_index = AdaptiveRadixTree::new();
544        for (action_index, title_lower) in self.titles_lower.iter().enumerate() {
545            let key = Self::prefix_index_key(title_lower, action_index);
546            prefix_index.insert(&key, action_index);
547        }
548        self.prefix_index = prefix_index;
549    }
550
551    fn rebuild_title_cache(&mut self) {
552        self.titles_cache.clear();
553        self.titles_lower.clear();
554        self.titles_word_starts.clear();
555
556        self.titles_cache.reserve(self.actions.len());
557        self.titles_lower.reserve(self.actions.len());
558        self.titles_word_starts.reserve(self.actions.len());
559
560        let titles_cache = &mut self.titles_cache;
561        let titles_lower = &mut self.titles_lower;
562        let titles_word_starts = &mut self.titles_word_starts;
563        for action in &self.actions {
564            Self::push_title_cache_into(
565                titles_cache,
566                titles_lower,
567                titles_word_starts,
568                &action.title,
569            );
570        }
571    }
572
573    fn rebuild_search_cache(&mut self) {
574        self.rebuild_title_cache();
575        self.rebuild_prefix_index();
576    }
577
578    /// Register a new action.
579    pub fn register(
580        &mut self,
581        title: impl Into<String>,
582        description: Option<&str>,
583        tags: &[&str],
584    ) -> &mut Self {
585        let title = title.into();
586        let id = title.to_lowercase().replace(' ', "_");
587        let mut item = ActionItem::new(id, title);
588        if let Some(desc) = description {
589            item.description = Some(desc.to_string());
590        }
591        item.tags = tags.iter().map(|s| (*s).to_string()).collect();
592        let action_index = self.actions.len();
593        self.push_title_cache(&item.title);
594        self.insert_prefix_index_entry(action_index);
595        self.actions.push(item);
596        self.generation = self.generation.wrapping_add(1);
597        self.refresh_filtered_after_action_change();
598        self
599    }
600
601    /// Register an action item directly.
602    pub fn register_action(&mut self, action: ActionItem) -> &mut Self {
603        let action_index = self.actions.len();
604        self.push_title_cache(&action.title);
605        self.insert_prefix_index_entry(action_index);
606        self.actions.push(action);
607        self.generation = self.generation.wrapping_add(1);
608        self.refresh_filtered_after_action_change();
609        self
610    }
611
612    /// Replace all actions with a new list.
613    ///
614    /// This resets caches and refreshes the filtered results.
615    pub fn replace_actions(&mut self, actions: Vec<ActionItem>) {
616        self.actions = actions;
617        self.rebuild_search_cache();
618        self.generation = self.generation.wrapping_add(1);
619        self.scorer.invalidate();
620        self.selected = 0;
621        self.scroll_offset = 0;
622        self.update_filtered(false);
623    }
624
625    /// Clear all registered actions.
626    pub fn clear_actions(&mut self) {
627        self.replace_actions(Vec::new());
628    }
629
630    /// Number of registered actions.
631    pub fn action_count(&self) -> usize {
632        self.actions.len()
633    }
634
635    fn refresh_filtered_after_action_change(&mut self) {
636        if self.visible
637            || !self.query.is_empty()
638            || !self.filtered.is_empty()
639            || self.match_filter != MatchFilter::All
640        {
641            self.update_filtered(false);
642        }
643    }
644
645    // --- Visibility ---
646
647    /// Open the palette (show it and focus the query input).
648    pub fn open(&mut self) {
649        self.visible = true;
650        self.query.clear();
651        self.cursor = 0;
652        self.selected = 0;
653        self.scroll_offset = 0;
654        self.scorer.invalidate();
655        #[cfg(feature = "tracing")]
656        {
657            self.opened_at = Some(Instant::now());
658        }
659        self.update_filtered(false);
660        #[cfg(feature = "tracing")]
661        emit_palette_opened(self.actions.len(), self.filtered.len());
662    }
663
664    /// Close the palette.
665    pub fn close(&mut self) {
666        self.close_with_reason(PaletteCloseReason::Programmatic);
667    }
668
669    /// Toggle visibility.
670    pub fn toggle(&mut self) {
671        if self.visible {
672            self.close_with_reason(PaletteCloseReason::Toggle);
673        } else {
674            self.open();
675        }
676    }
677
678    /// Whether the palette is currently visible.
679    #[inline]
680    pub fn is_visible(&self) -> bool {
681        self.visible
682    }
683
684    // --- Query Access ---
685
686    /// Current query string.
687    pub fn query(&self) -> &str {
688        &self.query
689    }
690
691    /// Replace the query string and re-run filtering.
692    pub fn set_query(&mut self, query: impl Into<String>) {
693        self.query = query.into();
694        self.cursor = self.query.len();
695        self.selected = 0;
696        self.scroll_offset = 0;
697        self.scorer.invalidate();
698        self.update_filtered(false);
699    }
700
701    /// Number of filtered results.
702    pub fn result_count(&self) -> usize {
703        self.filtered.len()
704    }
705
706    /// Currently selected index.
707    #[inline]
708    pub fn selected_index(&self) -> usize {
709        self.selected
710    }
711
712    /// Get the currently selected action, if any.
713    #[must_use = "use the selected action (if any)"]
714    pub fn selected_action(&self) -> Option<&ActionItem> {
715        self.filtered
716            .get(self.selected)
717            .map(|si| &self.actions[si.action_index])
718    }
719
720    /// Read-only access to the selected match (action + result).
721    #[must_use = "use the selected match (if any)"]
722    pub fn selected_match(&self) -> Option<PaletteMatch<'_>> {
723        self.filtered.get(self.selected).map(|si| PaletteMatch {
724            action: &self.actions[si.action_index],
725            result: &si.result,
726        })
727    }
728
729    /// Iterate over the current filtered results.
730    pub fn results(&self) -> impl Iterator<Item = PaletteMatch<'_>> {
731        self.filtered.iter().map(|si| PaletteMatch {
732            action: &self.actions[si.action_index],
733            result: &si.result,
734        })
735    }
736
737    /// Set a match-type filter and refresh results.
738    pub fn set_match_filter(&mut self, filter: MatchFilter) {
739        if self.match_filter == filter {
740            return;
741        }
742        self.match_filter = filter;
743        self.selected = 0;
744        self.scroll_offset = 0;
745        self.update_filtered(false);
746    }
747
748    /// Get scorer statistics for diagnostics.
749    pub fn scorer_stats(&self) -> &IncrementalStats {
750        self.scorer.stats()
751    }
752
753    // --- Event Handling ---
754
755    /// Handle an input event. Returns a `PaletteAction` if the user executed
756    /// or dismissed the palette.
757    ///
758    /// Returns `None` if the event was consumed but no action was triggered,
759    /// or if the palette is not visible.
760    #[must_use = "use the returned action (if any) to execute or dismiss"]
761    pub fn handle_event(&mut self, event: &Event) -> Option<PaletteAction> {
762        if !self.visible {
763            // Check for open shortcut (Ctrl+P)
764            if let Event::Key(KeyEvent {
765                code: KeyCode::Char('p'),
766                modifiers,
767                kind: KeyEventKind::Press,
768            }) = event
769                && modifiers.contains(Modifiers::CTRL)
770            {
771                self.open();
772            }
773            return None;
774        }
775
776        match event {
777            Event::Key(KeyEvent {
778                code,
779                modifiers,
780                kind: KeyEventKind::Press,
781            }) => self.handle_key(*code, *modifiers),
782            _ => None,
783        }
784    }
785
786    /// Handle a key press while the palette is open.
787    fn handle_key(&mut self, code: KeyCode, modifiers: Modifiers) -> Option<PaletteAction> {
788        match code {
789            KeyCode::Escape => {
790                self.close_with_reason(PaletteCloseReason::Dismiss);
791                return Some(PaletteAction::Dismiss);
792            }
793
794            KeyCode::Enter => {
795                if let Some(si) = self.filtered.get(self.selected) {
796                    let id = self.actions[si.action_index].id.clone();
797                    #[cfg(feature = "tracing")]
798                    {
799                        let latency_ms = self.opened_at.map(|start| start.elapsed().as_millis());
800                        emit_palette_action_executed(&id, latency_ms);
801                    }
802                    self.close_with_reason(PaletteCloseReason::Execute);
803                    return Some(PaletteAction::Execute(id));
804                }
805            }
806
807            KeyCode::Up if self.selected > 0 => {
808                self.selected -= 1;
809                self.adjust_scroll();
810            }
811
812            KeyCode::Down
813                if !self.filtered.is_empty() && self.selected < self.filtered.len() - 1 =>
814            {
815                self.selected += 1;
816                self.adjust_scroll();
817            }
818
819            KeyCode::PageUp => {
820                self.selected = self.selected.saturating_sub(self.max_visible);
821                self.adjust_scroll();
822            }
823
824            KeyCode::PageDown if !self.filtered.is_empty() => {
825                self.selected = (self.selected + self.max_visible).min(self.filtered.len() - 1);
826                self.adjust_scroll();
827            }
828
829            KeyCode::Home => {
830                self.selected = 0;
831                self.scroll_offset = 0;
832            }
833
834            KeyCode::End if !self.filtered.is_empty() => {
835                self.selected = self.filtered.len() - 1;
836                self.adjust_scroll();
837            }
838
839            KeyCode::Backspace if self.cursor > 0 => {
840                // Find the previous char boundary before the cursor and remove that char.
841                let prev = self.query[..self.cursor]
842                    .char_indices()
843                    .next_back()
844                    .map(|(i, _)| i)
845                    .unwrap_or(0);
846                self.query.drain(prev..self.cursor);
847                self.cursor = prev;
848                self.selected = 0;
849                self.scroll_offset = 0;
850                self.update_filtered(true);
851            }
852
853            KeyCode::Delete if self.cursor < self.query.len() => {
854                // Find the next char boundary after the cursor and remove that char.
855                let next = self.query[self.cursor..]
856                    .char_indices()
857                    .nth(1)
858                    .map(|(i, _)| self.cursor + i)
859                    .unwrap_or(self.query.len());
860                self.query.drain(self.cursor..next);
861                self.selected = 0;
862                self.scroll_offset = 0;
863                self.update_filtered(true);
864            }
865
866            KeyCode::Left if self.cursor > 0 => {
867                // Move cursor to previous char boundary.
868                self.cursor = self.query[..self.cursor]
869                    .char_indices()
870                    .next_back()
871                    .map(|(i, _)| i)
872                    .unwrap_or(0);
873            }
874
875            KeyCode::Right if self.cursor < self.query.len() => {
876                // Move cursor to next char boundary.
877                self.cursor = self.query[self.cursor..]
878                    .char_indices()
879                    .nth(1)
880                    .map(|(i, _)| self.cursor + i)
881                    .unwrap_or(self.query.len());
882            }
883
884            KeyCode::Char(c) => {
885                if modifiers.contains(Modifiers::CTRL) {
886                    // Ctrl+A: move cursor to start
887                    if c == 'a' {
888                        self.cursor = 0;
889                    }
890                    // Ctrl+E: move cursor to end
891                    if c == 'e' {
892                        self.cursor = self.query.len();
893                    }
894                    // Ctrl+U: clear query
895                    if c == 'u' {
896                        self.query.clear();
897                        self.cursor = 0;
898                        self.selected = 0;
899                        self.scroll_offset = 0;
900                        self.update_filtered(true);
901                    }
902                } else {
903                    // Insert character at cursor position.
904                    self.query.insert(self.cursor, c);
905                    self.cursor += c.len_utf8();
906                    self.selected = 0;
907                    self.scroll_offset = 0;
908                    self.update_filtered(true);
909                }
910            }
911
912            _ => {}
913        }
914
915        None
916    }
917
918    /// Re-score the corpus against the current query.
919    fn update_filtered(&mut self, _emit_telemetry: bool) {
920        #[cfg(feature = "tracing")]
921        // Don't gate on `tracing::enabled!` here: callsite interest can be cached across
922        // dynamic subscribers (tests), which may suppress telemetry unexpectedly.
923        // Emitting the event is already cheap when disabled.
924        let start = _emit_telemetry.then(Instant::now);
925
926        if self.titles_cache.len() != self.actions.len()
927            || self.titles_lower.len() != self.actions.len()
928            || self.titles_word_starts.len() != self.actions.len()
929            || self.prefix_index.len() != self.actions.len()
930        {
931            self.rebuild_search_cache();
932        }
933
934        let mut results = if self.match_filter == MatchFilter::Prefix && !self.query.is_empty() {
935            let query_lower = self.query.to_lowercase();
936            let candidate_indices: Vec<usize> = self
937                .prefix_index
938                .prefix_scan(&query_lower)
939                .into_iter()
940                .map(|(_, action_index)| *action_index)
941                .collect();
942            self.scorer.score_candidate_indices_with_lowered_and_words(
943                &self.query,
944                &self.titles_cache,
945                &self.titles_lower,
946                &self.titles_word_starts,
947                &candidate_indices,
948                Some(self.generation),
949            )
950        } else {
951            self.scorer.score_corpus_with_lowered_and_words(
952                &self.query,
953                &self.titles_cache,
954                &self.titles_lower,
955                &self.titles_word_starts,
956                Some(self.generation),
957            )
958        };
959        // `ActionItem::tags` is documented as "for boosting search relevance",
960        // but the corpus scorers take titles only and nothing passed the tags
961        // on: every action ranked by its title alone, however it was tagged.
962        self.scorer
963            .apply_tag_boosts(&self.query, &mut results, |index| {
964                self.actions[index].tags.as_slice()
965            });
966
967        self.filtered = results
968            .into_iter()
969            .filter(|(_, result)| self.match_filter.allows(result.match_type))
970            .map(|(idx, result)| ScoredItem {
971                action_index: idx,
972                result,
973            })
974            .collect();
975
976        // Clamp selection.
977        if !self.filtered.is_empty() {
978            self.selected = self.selected.min(self.filtered.len() - 1);
979            self.adjust_scroll();
980        } else {
981            self.selected = 0;
982            self.scroll_offset = 0;
983        }
984
985        #[cfg(feature = "tracing")]
986        if let Some(start) = start {
987            emit_palette_query_updated(
988                &self.query,
989                self.filtered.len(),
990                start.elapsed().as_millis(),
991            );
992        }
993    }
994
995    fn close_with_reason(&mut self, _reason: PaletteCloseReason) {
996        self.visible = false;
997        self.query.clear();
998        self.cursor = 0;
999        self.filtered.clear();
1000        #[cfg(feature = "tracing")]
1001        {
1002            self.opened_at = None;
1003            emit_palette_closed(_reason);
1004        }
1005    }
1006
1007    /// Adjust scroll_offset to keep selected item visible.
1008    fn adjust_scroll(&mut self) {
1009        if self.selected < self.scroll_offset {
1010            self.scroll_offset = self.selected;
1011        } else if self.selected >= self.scroll_offset.saturating_add(self.max_visible) {
1012            self.scroll_offset = self
1013                .selected
1014                .saturating_sub(self.max_visible.saturating_sub(1));
1015        }
1016    }
1017}
1018
1019// ---------------------------------------------------------------------------
1020// Widget Implementation
1021// ---------------------------------------------------------------------------
1022
1023impl Widget for CommandPalette {
1024    fn render(&self, area: Rect, frame: &mut Frame) {
1025        if !self.visible || area.width < 10 || area.height < 5 {
1026            return;
1027        }
1028
1029        let palette_area = if self.fill_area {
1030            // Caller controls layout — use the full area as-is.
1031            area
1032        } else {
1033            // Calculate palette dimensions: centered, ~60% width, height based on results.
1034            let palette_width = (area.width * 3 / 5).max(30).min(area.width - 2);
1035            let result_rows = self.filtered.len().min(self.max_visible);
1036            // +3 for: border top, query line, border bottom. +1 if empty hint.
1037            let palette_height = (result_rows as u16 + 3)
1038                .max(5)
1039                .min(area.height.saturating_sub(2));
1040            let palette_x = area.x + (area.width.saturating_sub(palette_width)) / 2;
1041            let palette_y = area.y + area.height / 6; // ~1/6 from top
1042            Rect::new(palette_x, palette_y, palette_width, palette_height)
1043        };
1044
1045        // Clear the palette area.
1046        self.clear_area(palette_area, frame);
1047
1048        // Draw border.
1049        self.draw_border(palette_area, frame);
1050
1051        // Draw query input line.
1052        let input_area = Rect::new(
1053            palette_area.x + 2,
1054            palette_area.y + 1,
1055            palette_area.width.saturating_sub(4),
1056            1,
1057        );
1058        self.draw_query_input(input_area, frame);
1059
1060        // Draw results list.
1061        let results_y = palette_area.y + 2;
1062        let results_height = palette_area.height.saturating_sub(3);
1063        let results_area = Rect::new(
1064            palette_area.x + 1,
1065            results_y,
1066            palette_area.width.saturating_sub(2),
1067            results_height,
1068        );
1069        self.draw_results(results_area, frame);
1070
1071        self.emit_accessibility(palette_area, input_area, results_area, frame);
1072
1073        // Position cursor in query input.
1074        // Calculate visual cursor position from byte offset by computing display width
1075        // of the text up to the cursor position.
1076        let cursor_visual_pos = display_width(&self.query[..self.cursor.min(self.query.len())]);
1077        let cursor_x = input_area.x + cursor_visual_pos.min(input_area.width as usize) as u16;
1078        frame.cursor_position = Some((cursor_x, input_area.y));
1079        frame.cursor_visible = true;
1080    }
1081
1082    fn is_essential(&self) -> bool {
1083        true
1084    }
1085}
1086
1087impl CommandPalette {
1088    fn accessibility_child_id(&self, kind: &str, key: usize) -> u64 {
1089        use std::hash::{Hash, Hasher};
1090        let mut hasher = std::collections::hash_map::DefaultHasher::new();
1091        (
1092            "ftui.command_palette.child",
1093            self.accessibility_id,
1094            kind,
1095            key,
1096        )
1097            .hash(&mut hasher);
1098        hasher.finish()
1099    }
1100
1101    fn emit_accessibility(
1102        &self,
1103        palette_area: Rect,
1104        input_area: Rect,
1105        results_area: Rect,
1106        frame: &mut Frame,
1107    ) {
1108        if !frame.a11y_enabled() {
1109            return;
1110        }
1111        let bounds = palette_area.intersection(&frame.buffer.current_scissor());
1112        if bounds.is_empty() {
1113            return;
1114        }
1115        let name = self.title.trim();
1116        let root = A11yNodeInfo::new(self.accessibility_id, A11yRole::Dialog, bounds).with_name(
1117            if name.is_empty() {
1118                "Command Palette"
1119            } else {
1120                name
1121            },
1122        );
1123
1124        frame.with_a11y_scope(root, |frame| {
1125            let query_bounds = input_area.intersection(&frame.buffer.current_scissor());
1126            if !query_bounds.is_empty() {
1127                let mut query = A11yNodeInfo::new(
1128                    self.accessibility_child_id("query", 0),
1129                    A11yRole::TextInput,
1130                    query_bounds,
1131                )
1132                .with_name("Search commands")
1133                .with_description("Type to filter commands");
1134                query.state.focused = true;
1135                query.state.value_text = Some(self.query.clone());
1136                frame.push_a11y(query);
1137            }
1138
1139            let menu_bounds = results_area.intersection(&frame.buffer.current_scissor());
1140            if !menu_bounds.is_empty() {
1141                let menu_id = self.accessibility_child_id("results", 0);
1142                let menu = A11yNodeInfo::new(menu_id, A11yRole::Menu, menu_bounds)
1143                    .with_name("Command results")
1144                    .with_description(format!("{} results", self.filtered.len()));
1145                frame.with_a11y_scope(menu, |frame| {
1146                    let visible_end = (self.scroll_offset + results_area.height as usize)
1147                        .min(self.filtered.len());
1148                    for (row_idx, scored) in self.filtered[self.scroll_offset..visible_end]
1149                        .iter()
1150                        .enumerate()
1151                    {
1152                        let y = results_area.y.saturating_add(row_idx as u16);
1153                        let item_bounds = Rect::new(results_area.x, y, results_area.width, 1)
1154                            .intersection(&frame.buffer.current_scissor());
1155                        if item_bounds.is_empty() {
1156                            continue;
1157                        }
1158                        let action = &self.actions[scored.action_index];
1159                        let mut item = A11yNodeInfo::new(
1160                            self.accessibility_child_id("item", scored.action_index),
1161                            A11yRole::MenuItem,
1162                            item_bounds,
1163                        )
1164                        .with_name(&action.title);
1165                        item.state.selected =
1166                            self.scroll_offset.saturating_add(row_idx) == self.selected;
1167                        let mut details = Vec::new();
1168                        if let Some(category) = action.category.as_deref() {
1169                            details.push(category.to_owned());
1170                        }
1171                        if let Some(description) = action.description.as_deref() {
1172                            details.push(description.to_owned());
1173                        }
1174                        if !details.is_empty() {
1175                            item.description = Some(details.join(". "));
1176                        }
1177                        frame.push_a11y(item);
1178                    }
1179                });
1180            }
1181
1182            let status_bounds = input_area.intersection(&frame.buffer.current_scissor());
1183            if !status_bounds.is_empty() {
1184                let status_name = self.selected_action().map_or_else(
1185                    || {
1186                        if self.query.is_empty() {
1187                            "No actions registered".to_owned()
1188                        } else {
1189                            "No matching commands".to_owned()
1190                        }
1191                    },
1192                    |action| {
1193                        format!(
1194                            "{}. Result {}",
1195                            action.title,
1196                            self.selected.saturating_add(1)
1197                        )
1198                    },
1199                );
1200                let mut status = A11yNodeInfo::new(
1201                    self.accessibility_child_id("selection", 0),
1202                    A11yRole::Label,
1203                    status_bounds,
1204                )
1205                .with_name(status_name)
1206                .with_live_region(LiveRegion::Polite);
1207                if let Some(description) = self
1208                    .selected_action()
1209                    .and_then(|action| action.description.as_deref())
1210                {
1211                    status.description = Some(description.to_owned());
1212                }
1213                frame.push_a11y(status);
1214            }
1215        });
1216    }
1217
1218    /// Resolve the palette surface background.
1219    ///
1220    /// Prefer explicit style backgrounds when provided so host apps can
1221    /// theme the overlay; otherwise fall back to the historical dark surface.
1222    fn palette_background(&self) -> PackedRgba {
1223        self.style
1224            .border
1225            .bg
1226            .or(self.style.input.bg)
1227            .or(self.style.item.bg)
1228            .or(self.style.hint.bg)
1229            .or(self.style.item_selected.bg)
1230            .unwrap_or(PackedRgba::rgb(30, 30, 40))
1231    }
1232
1233    /// Clear the palette area with a background color.
1234    fn clear_area(&self, area: Rect, frame: &mut Frame) {
1235        let bg = self.palette_background();
1236        for y in area.y..area.bottom() {
1237            for x in area.x..area.right() {
1238                if let Some(cell) = frame.buffer.get_mut(x, y) {
1239                    *cell = Cell::from_char(' ');
1240                    cell.bg = bg;
1241                }
1242            }
1243        }
1244    }
1245
1246    /// Draw a rounded border around the palette.
1247    fn draw_border(&self, area: Rect, frame: &mut Frame) {
1248        let border_fg = self
1249            .style
1250            .border
1251            .fg
1252            .unwrap_or(PackedRgba::rgb(100, 100, 120));
1253        let bg = self.palette_background();
1254
1255        // Top border with title.
1256        let mut cell = Cell::from_char('╭');
1257        cell.fg = border_fg;
1258        cell.bg = bg;
1259        frame.buffer.set_fast(area.x, area.y, cell);
1260
1261        for x in (area.x + 1)..area.right().saturating_sub(1) {
1262            let mut cell = Cell::from_char('─');
1263            cell.fg = border_fg;
1264            cell.bg = bg;
1265            frame.buffer.set_fast(x, area.y, cell);
1266        }
1267        if area.width > 1 {
1268            let mut cell = Cell::from_char('╮');
1269            cell.fg = border_fg;
1270            cell.bg = bg;
1271            frame.buffer.set_fast(area.right() - 1, area.y, cell);
1272        }
1273
1274        // Title in top border.
1275        let title = &self.title;
1276        let title_width = display_width(title).min(area.width as usize);
1277        let title_x = area.x + (area.width.saturating_sub(title_width as u16)) / 2;
1278        let title_style = Style::new().fg(PackedRgba::rgb(200, 200, 220)).bg(bg);
1279        crate::draw_text_span(frame, title_x, area.y, title, title_style, area.right());
1280
1281        // Side borders.
1282        for y in (area.y + 1)..area.bottom().saturating_sub(1) {
1283            let mut cell_l = Cell::from_char('│');
1284            cell_l.fg = border_fg;
1285            cell_l.bg = bg;
1286            frame.buffer.set_fast(area.x, y, cell_l);
1287
1288            if area.width > 1 {
1289                let mut cell_r = Cell::from_char('│');
1290                cell_r.fg = border_fg;
1291                cell_r.bg = bg;
1292                frame.buffer.set_fast(area.right() - 1, y, cell_r);
1293            }
1294        }
1295
1296        // Bottom border.
1297        if area.height > 1 {
1298            let by = area.bottom() - 1;
1299            let mut cell_bl = Cell::from_char('╰');
1300            cell_bl.fg = border_fg;
1301            cell_bl.bg = bg;
1302            frame.buffer.set_fast(area.x, by, cell_bl);
1303
1304            for x in (area.x + 1)..area.right().saturating_sub(1) {
1305                let mut cell = Cell::from_char('─');
1306                cell.fg = border_fg;
1307                cell.bg = bg;
1308                frame.buffer.set_fast(x, by, cell);
1309            }
1310            if area.width > 1 {
1311                let mut cell_br = Cell::from_char('╯');
1312                cell_br.fg = border_fg;
1313                cell_br.bg = bg;
1314                frame.buffer.set_fast(area.right() - 1, by, cell_br);
1315            }
1316        }
1317    }
1318
1319    /// Draw the query input line with prompt.
1320    fn draw_query_input(&self, area: Rect, frame: &mut Frame) {
1321        let input_fg = self
1322            .style
1323            .input
1324            .fg
1325            .unwrap_or(PackedRgba::rgb(220, 220, 230));
1326        let bg = self.palette_background();
1327        let prompt_fg = PackedRgba::rgb(100, 180, 255);
1328
1329        // Draw ">" prompt.
1330        if let Some(cell) = frame.buffer.get_mut(area.x.saturating_sub(1), area.y) {
1331            cell.content = CellContent::from_char('>');
1332            cell.fg = prompt_fg;
1333            cell.bg = bg;
1334        }
1335
1336        // Draw query text.
1337        if self.query.is_empty() {
1338            // Placeholder.
1339            let hint = "Type to search...";
1340            let hint_fg = self.style.hint.fg.unwrap_or(PackedRgba::rgb(100, 100, 120));
1341            for (i, ch) in hint.chars().enumerate() {
1342                let x = area.x + i as u16;
1343                if x >= area.right() {
1344                    break;
1345                }
1346                if let Some(cell) = frame.buffer.get_mut(x, area.y) {
1347                    cell.content = CellContent::from_char(ch);
1348                    cell.fg = hint_fg;
1349                    cell.bg = bg;
1350                }
1351            }
1352        } else {
1353            // Render query text with proper grapheme/width handling.
1354            let mut col = area.x;
1355            for grapheme in graphemes(&self.query) {
1356                let w = grapheme_width(grapheme);
1357                if w == 0 {
1358                    continue;
1359                }
1360                if col >= area.right() {
1361                    break;
1362                }
1363                if col.saturating_add(w as u16) > area.right() {
1364                    break;
1365                }
1366                let content = if w > 1 || grapheme.chars().count() > 1 {
1367                    let id = frame.intern_with_width(grapheme, w as u8);
1368                    CellContent::from_grapheme(id)
1369                } else if let Some(ch) = grapheme.chars().next() {
1370                    CellContent::from_char(ch)
1371                } else {
1372                    continue;
1373                };
1374                let mut cell = Cell::new(content);
1375                cell.fg = input_fg;
1376                cell.bg = bg;
1377                frame.buffer.set_fast(col, area.y, cell);
1378                col = col.saturating_add(w as u16);
1379            }
1380        }
1381    }
1382
1383    /// Draw the filtered results list.
1384    fn draw_results(&self, area: Rect, frame: &mut Frame) {
1385        if self.filtered.is_empty() {
1386            // Empty state.
1387            let msg = if self.query.is_empty() {
1388                "No actions registered"
1389            } else {
1390                "No results"
1391            };
1392            let hint_fg = self.style.hint.fg.unwrap_or(PackedRgba::rgb(100, 100, 120));
1393            let bg = self.palette_background();
1394            for (i, ch) in msg.chars().enumerate() {
1395                let x = area.x + 1 + i as u16;
1396                if x >= area.right() {
1397                    break;
1398                }
1399                if let Some(cell) = frame.buffer.get_mut(x, area.y) {
1400                    cell.content = CellContent::from_char(ch);
1401                    cell.fg = hint_fg;
1402                    cell.bg = bg;
1403                }
1404            }
1405            return;
1406        }
1407
1408        let item_fg = self.style.item.fg.unwrap_or(PackedRgba::rgb(180, 180, 190));
1409        let selected_fg = self
1410            .style
1411            .item_selected
1412            .fg
1413            .unwrap_or(PackedRgba::rgb(255, 255, 255));
1414        let selected_bg = self
1415            .style
1416            .item_selected
1417            .bg
1418            .unwrap_or(PackedRgba::rgb(60, 60, 80));
1419        let highlight_fg = self
1420            .style
1421            .match_highlight
1422            .fg
1423            .unwrap_or(PackedRgba::rgb(255, 200, 50));
1424        let desc_fg = self
1425            .style
1426            .description
1427            .fg
1428            .unwrap_or(PackedRgba::rgb(120, 120, 140));
1429        let cat_fg = self
1430            .style
1431            .category
1432            .fg
1433            .unwrap_or(PackedRgba::rgb(100, 180, 255));
1434        let bg = self.palette_background();
1435
1436        let visible_end = (self.scroll_offset + area.height as usize).min(self.filtered.len());
1437
1438        for (row_idx, si) in self.filtered[self.scroll_offset..visible_end]
1439            .iter()
1440            .enumerate()
1441        {
1442            let y = area.y + row_idx as u16;
1443            if y >= area.bottom() {
1444                break;
1445            }
1446
1447            let action = &self.actions[si.action_index];
1448            let is_selected = (self.scroll_offset + row_idx) == self.selected;
1449
1450            let row_fg = if is_selected { selected_fg } else { item_fg };
1451            let row_bg = if is_selected { selected_bg } else { bg };
1452
1453            // Bold attribute for selected row (accessible without color).
1454            let row_attrs = if is_selected {
1455                CellAttrs::new(CellStyleFlags::BOLD, 0)
1456            } else {
1457                CellAttrs::default()
1458            };
1459
1460            // Clear row.
1461            for x in area.x..area.right() {
1462                if let Some(cell) = frame.buffer.get_mut(x, y) {
1463                    cell.content = CellContent::from_char(' ');
1464                    cell.fg = row_fg;
1465                    cell.bg = row_bg;
1466                    cell.attrs = row_attrs;
1467                }
1468            }
1469
1470            // Selection marker (visible without color — structural indicator).
1471            let mut col = area.x;
1472            if is_selected && let Some(cell) = frame.buffer.get_mut(col, y) {
1473                cell.content = CellContent::from_char('>');
1474                cell.fg = highlight_fg;
1475                cell.bg = row_bg;
1476                cell.attrs = CellAttrs::new(CellStyleFlags::BOLD, 0);
1477            }
1478            col += 2;
1479
1480            // Category badge (if present).
1481            if let Some(ref cat) = action.category {
1482                let badge = format!("[{}] ", cat);
1483                for grapheme in graphemes(&badge) {
1484                    let w = grapheme_width(grapheme);
1485                    if w == 0 {
1486                        continue;
1487                    }
1488                    if col >= area.right() || col.saturating_add(w as u16) > area.right() {
1489                        break;
1490                    }
1491                    let content = if w > 1 || grapheme.chars().count() > 1 {
1492                        let id = frame.intern_with_width(grapheme, w as u8);
1493                        CellContent::from_grapheme(id)
1494                    } else if let Some(ch) = grapheme.chars().next() {
1495                        CellContent::from_char(ch)
1496                    } else {
1497                        continue;
1498                    };
1499                    let mut cell = Cell::new(content);
1500                    cell.fg = cat_fg;
1501                    cell.bg = row_bg;
1502                    cell.attrs = row_attrs;
1503                    frame.buffer.set_fast(col, y, cell);
1504                    col = col.saturating_add(w as u16);
1505                }
1506            }
1507
1508            // Title with match highlighting and ellipsis truncation.
1509            let title_max_width = area.right().saturating_sub(col) as usize;
1510            let title_width = display_width(action.title.as_str());
1511            let needs_ellipsis = title_width > title_max_width && title_max_width > 3;
1512            let title_display_width = if needs_ellipsis {
1513                title_max_width.saturating_sub(1) // leave room for '…'
1514            } else {
1515                title_max_width
1516            };
1517
1518            let mut title_used_width = 0usize;
1519            let mut char_idx = 0usize;
1520            let mut match_cursor = 0usize;
1521            let match_positions = &si.result.match_positions;
1522            for grapheme in graphemes(action.title.as_str()) {
1523                let g_chars = grapheme.chars().count();
1524                let char_end = char_idx + g_chars;
1525                while match_cursor < match_positions.len()
1526                    && match_positions[match_cursor] < char_idx
1527                {
1528                    match_cursor += 1;
1529                }
1530                let is_match = match_cursor < match_positions.len()
1531                    && match_positions[match_cursor] < char_end;
1532
1533                let w = grapheme_width(grapheme);
1534                if w == 0 {
1535                    char_idx = char_end;
1536                    continue;
1537                }
1538                if title_used_width + w > title_display_width || col >= area.right() {
1539                    break;
1540                }
1541                if col.saturating_add(w as u16) > area.right() {
1542                    break;
1543                }
1544
1545                let content = if w > 1 || grapheme.chars().count() > 1 {
1546                    let id = frame.intern_with_width(grapheme, w as u8);
1547                    CellContent::from_grapheme(id)
1548                } else if let Some(ch) = grapheme.chars().next() {
1549                    CellContent::from_char(ch)
1550                } else {
1551                    char_idx = char_end;
1552                    continue;
1553                };
1554
1555                let mut cell = Cell::new(content);
1556                cell.fg = if is_match { highlight_fg } else { row_fg };
1557                cell.bg = row_bg;
1558                cell.attrs = row_attrs;
1559                frame.buffer.set_fast(col, y, cell);
1560
1561                col = col.saturating_add(w as u16);
1562                title_used_width += w;
1563                char_idx = char_end;
1564            }
1565
1566            // Ellipsis for truncated titles.
1567            if needs_ellipsis && col < area.right() {
1568                if let Some(cell) = frame.buffer.get_mut(col, y) {
1569                    cell.content = CellContent::from_char('\u{2026}'); // …
1570                    cell.fg = row_fg;
1571                    cell.bg = row_bg;
1572                    cell.attrs = row_attrs;
1573                }
1574                col += 1;
1575            }
1576
1577            // Description (if space allows, with ellipsis truncation).
1578            if let Some(ref desc) = action.description {
1579                col += 2; // gap
1580                let max_desc_width = area.right().saturating_sub(col) as usize;
1581                if max_desc_width > 5 {
1582                    let desc_width = display_width(desc.as_str());
1583                    let desc_needs_ellipsis = desc_width > max_desc_width && max_desc_width > 3;
1584                    let desc_display_width = if desc_needs_ellipsis {
1585                        max_desc_width.saturating_sub(1)
1586                    } else {
1587                        max_desc_width
1588                    };
1589
1590                    let mut desc_used_width = 0usize;
1591                    for grapheme in graphemes(desc.as_str()) {
1592                        let w = grapheme_width(grapheme);
1593                        if w == 0 {
1594                            continue;
1595                        }
1596                        if desc_used_width + w > desc_display_width || col >= area.right() {
1597                            break;
1598                        }
1599                        if col.saturating_add(w as u16) > area.right() {
1600                            break;
1601                        }
1602                        let content = if w > 1 || grapheme.chars().count() > 1 {
1603                            let id = frame.intern_with_width(grapheme, w as u8);
1604                            CellContent::from_grapheme(id)
1605                        } else if let Some(ch) = grapheme.chars().next() {
1606                            CellContent::from_char(ch)
1607                        } else {
1608                            continue;
1609                        };
1610                        let mut cell = Cell::new(content);
1611                        cell.fg = desc_fg;
1612                        cell.bg = row_bg;
1613                        cell.attrs = row_attrs;
1614                        frame.buffer.set_fast(col, y, cell);
1615                        col = col.saturating_add(w as u16);
1616                        desc_used_width += w;
1617                    }
1618
1619                    if desc_needs_ellipsis
1620                        && col < area.right()
1621                        && let Some(cell) = frame.buffer.get_mut(col, y)
1622                    {
1623                        cell.content = CellContent::from_char('\u{2026}');
1624                        cell.fg = desc_fg;
1625                        cell.bg = row_bg;
1626                        cell.attrs = row_attrs;
1627                    }
1628                }
1629            }
1630        }
1631    }
1632}
1633
1634// ---------------------------------------------------------------------------
1635// Tests
1636// ---------------------------------------------------------------------------
1637
1638#[cfg(test)]
1639mod widget_tests {
1640    use super::*;
1641    use ftui_a11y::tree::{A11yTree, A11yTreeBuilder, AnnouncementReason, ScreenReaderPolicy};
1642    use ftui_render::grapheme_pool::GraphemePool;
1643
1644    fn render_palette_a11y(palette: &CommandPalette, area: Rect) -> A11yTree {
1645        let mut builder = A11yTreeBuilder::new();
1646        {
1647            let mut pool = GraphemePool::new();
1648            let mut frame = Frame::new(100, 40, &mut pool);
1649            frame.set_a11y(&mut builder);
1650            palette.render(area, &mut frame);
1651            frame.finish_a11y();
1652        }
1653        builder.build()
1654    }
1655
1656    #[test]
1657    fn palette_accessibility_exposes_dialog_query_menu_and_selection() {
1658        let mut palette = CommandPalette::new().with_accessibility_id(6001);
1659        palette.register_action(
1660            ActionItem::new("open", "Open File")
1661                .with_description("Open a file from disk")
1662                .with_category("File"),
1663        );
1664        palette.register_action(ActionItem::new("save", "Save File"));
1665        palette.open();
1666
1667        let tree = render_palette_a11y(&palette, Rect::new(0, 0, 80, 24));
1668        assert_eq!(tree.root_id(), Some(6001));
1669        let root = tree.root().unwrap();
1670        assert_eq!(root.role, A11yRole::Dialog);
1671        assert_eq!(root.name.as_deref(), Some("Command Palette"));
1672        assert_eq!(root.children.len(), 3);
1673
1674        let query = tree.focused().expect("query focus");
1675        assert_eq!(query.role, A11yRole::TextInput);
1676        assert_eq!(query.name.as_deref(), Some("Search commands"));
1677        assert_eq!(query.state.value_text.as_deref(), Some(""));
1678
1679        let menu = root
1680            .children
1681            .iter()
1682            .filter_map(|id| tree.node(*id))
1683            .find(|node| node.role == A11yRole::Menu)
1684            .unwrap();
1685        assert_eq!(menu.children.len(), 2);
1686        assert!(tree.node(menu.children[0]).unwrap().state.selected);
1687        assert_eq!(
1688            tree.node(menu.children[0]).unwrap().description.as_deref(),
1689            Some("File. Open a file from disk")
1690        );
1691    }
1692
1693    #[test]
1694    fn palette_typing_stays_quiet_when_selected_command_does_not_change() {
1695        let mut palette = CommandPalette::new().with_accessibility_id(6002);
1696        palette.register("Open File", None, &["file"]);
1697        palette.register("Save File", None, &["file"]);
1698        palette.open();
1699        let before = render_palette_a11y(&palette, Rect::new(0, 0, 80, 24));
1700
1701        palette.set_query("O");
1702        let after = render_palette_a11y(&palette, Rect::new(0, 0, 80, 24));
1703        assert_eq!(after.focused_id(), before.focused_id());
1704        let batch = after.screen_reader_announcements_since(&before, ScreenReaderPolicy::default());
1705        assert!(
1706            batch.announcements.is_empty(),
1707            "query edits should not reread the palette when the selected command is unchanged"
1708        );
1709    }
1710
1711    #[test]
1712    fn palette_arrow_selection_announces_one_polite_status_update() {
1713        let mut palette = CommandPalette::new().with_accessibility_id(6003);
1714        palette.register("Alpha", Some("First command"), &[]);
1715        palette.register("Beta", Some("Second command"), &[]);
1716        palette.open();
1717        let before = render_palette_a11y(&palette, Rect::new(0, 0, 80, 24));
1718
1719        assert!(
1720            palette
1721                .handle_event(&Event::Key(KeyEvent {
1722                    code: KeyCode::Down,
1723                    modifiers: Modifiers::empty(),
1724                    kind: KeyEventKind::Press,
1725                }))
1726                .is_none(),
1727            "arrow navigation moves the selection without emitting an action"
1728        );
1729        assert_eq!(palette.selected_index(), 1, "Down should move to index 1");
1730        // Not "Beta". An empty query is scored purely by title length -
1731        // `FuzzyScorer::score_empty_query` prefers shorter titles - so the
1732        // open palette lists "Beta" (4) above "Alpha" (5) regardless of
1733        // registration order, and result 2 is "Alpha".
1734        assert_eq!(
1735            palette.selected_action().map(|a| a.title.as_str()),
1736            Some("Alpha")
1737        );
1738        let after = render_palette_a11y(&palette, Rect::new(0, 0, 80, 24));
1739        assert_eq!(after.focused_id(), before.focused_id());
1740        let batch = after.screen_reader_announcements_since(&before, ScreenReaderPolicy::default());
1741        assert_eq!(batch.announcements.len(), 1);
1742        assert_eq!(batch.dropped_count, 0);
1743        assert_eq!(
1744            batch.announcements[0].reason,
1745            AnnouncementReason::LiveContentChanged
1746        );
1747        assert_eq!(batch.announcements[0].urgency, LiveRegion::Polite);
1748        let spoken = &batch.announcements[0].text;
1749        assert!(spoken.contains("Alpha. Result 2"), "announced: {spoken:?}");
1750        assert!(spoken.contains("First command"), "announced: {spoken:?}");
1751    }
1752
1753    #[test]
1754    fn palette_no_results_announces_once_and_closing_removes_semantics_silently() {
1755        let mut palette = CommandPalette::new().with_accessibility_id(6004);
1756        palette.register("Alpha", None, &[]);
1757        palette.open();
1758        let before = render_palette_a11y(&palette, Rect::new(0, 0, 80, 24));
1759        palette.set_query("zzz");
1760        let empty = render_palette_a11y(&palette, Rect::new(0, 0, 80, 24));
1761        let batch = empty.screen_reader_announcements_since(&before, ScreenReaderPolicy::default());
1762        assert_eq!(batch.announcements.len(), 1);
1763        assert!(batch.announcements[0].text.contains("No matching commands"));
1764
1765        palette.close();
1766        let closed = render_palette_a11y(&palette, Rect::new(0, 0, 80, 24));
1767        assert!(closed.is_empty());
1768        assert!(
1769            closed
1770                .screen_reader_announcements_since(&empty, ScreenReaderPolicy::default())
1771                .announcements
1772                .is_empty()
1773        );
1774    }
1775
1776    #[test]
1777    fn palette_accessibility_ids_survive_resize_and_scrolling() {
1778        let mut palette = CommandPalette::new()
1779            .with_accessibility_id(6005)
1780            .with_max_visible(2);
1781        for title in ["Alpha", "Beta", "Gamma", "Delta"] {
1782            palette.register(title, None, &[]);
1783        }
1784        palette.open();
1785        let before = render_palette_a11y(&palette, Rect::new(0, 0, 80, 20));
1786
1787        assert!(
1788            palette
1789                .handle_event(&Event::Key(KeyEvent {
1790                    code: KeyCode::End,
1791                    modifiers: Modifiers::empty(),
1792                    kind: KeyEventKind::Press,
1793                }))
1794                .is_none(),
1795            "jumping to the last entry moves the selection without emitting an action"
1796        );
1797        let after = render_palette_a11y(&palette, Rect::new(4, 3, 90, 30));
1798        assert_eq!(before.root_id(), after.root_id());
1799        assert_eq!(before.focused_id(), after.focused_id());
1800        assert_eq!(
1801            after.focused().unwrap().name.as_deref(),
1802            Some("Search commands")
1803        );
1804    }
1805
1806    #[test]
1807    fn new_palette_is_hidden() {
1808        let palette = CommandPalette::new();
1809        assert!(!palette.is_visible());
1810        assert_eq!(palette.action_count(), 0);
1811    }
1812
1813    #[test]
1814    fn register_actions() {
1815        let mut palette = CommandPalette::new();
1816        palette.register("Open File", Some("Open a file"), &["file"]);
1817        palette.register("Save File", None, &[]);
1818        assert_eq!(palette.action_count(), 2);
1819    }
1820
1821    #[test]
1822    fn open_shows_all_actions() {
1823        let mut palette = CommandPalette::new();
1824        palette.register("Open File", None, &[]);
1825        palette.register("Save File", None, &[]);
1826        palette.register("Close Tab", None, &[]);
1827        palette.open();
1828        assert!(palette.is_visible());
1829        assert_eq!(palette.result_count(), 3);
1830    }
1831
1832    #[test]
1833    fn close_hides_palette() {
1834        let mut palette = CommandPalette::new();
1835        palette.open();
1836        assert!(palette.is_visible());
1837        palette.close();
1838        assert!(!palette.is_visible());
1839    }
1840
1841    #[test]
1842    fn toggle_visibility() {
1843        let mut palette = CommandPalette::new();
1844        palette.toggle();
1845        assert!(palette.is_visible());
1846        palette.toggle();
1847        assert!(!palette.is_visible());
1848    }
1849
1850    #[test]
1851    fn typing_filters_results() {
1852        let mut palette = CommandPalette::new();
1853        palette.register("Open File", None, &[]);
1854        palette.register("Save File", None, &[]);
1855        palette.register("Git: Commit", None, &[]);
1856        palette.open();
1857        assert_eq!(palette.result_count(), 3);
1858
1859        // Type "git"
1860        let g = Event::Key(KeyEvent {
1861            code: KeyCode::Char('g'),
1862            modifiers: Modifiers::empty(),
1863            kind: KeyEventKind::Press,
1864        });
1865        let i = Event::Key(KeyEvent {
1866            code: KeyCode::Char('i'),
1867            modifiers: Modifiers::empty(),
1868            kind: KeyEventKind::Press,
1869        });
1870        let t = Event::Key(KeyEvent {
1871            code: KeyCode::Char('t'),
1872            modifiers: Modifiers::empty(),
1873            kind: KeyEventKind::Press,
1874        });
1875
1876        let _ = palette.handle_event(&g);
1877        let _ = palette.handle_event(&i);
1878        let _ = palette.handle_event(&t);
1879
1880        assert_eq!(palette.query(), "git");
1881        // Only "Git: Commit" should match well
1882        assert!(palette.result_count() >= 1);
1883    }
1884
1885    #[test]
1886    fn backspace_removes_character() {
1887        let mut palette = CommandPalette::new();
1888        palette.register("Open File", None, &[]);
1889        palette.open();
1890
1891        let o = Event::Key(KeyEvent {
1892            code: KeyCode::Char('o'),
1893            modifiers: Modifiers::empty(),
1894            kind: KeyEventKind::Press,
1895        });
1896        let bs = Event::Key(KeyEvent {
1897            code: KeyCode::Backspace,
1898            modifiers: Modifiers::empty(),
1899            kind: KeyEventKind::Press,
1900        });
1901
1902        let _ = palette.handle_event(&o);
1903        assert_eq!(palette.query(), "o");
1904        let _ = palette.handle_event(&bs);
1905        assert_eq!(palette.query(), "");
1906    }
1907
1908    #[test]
1909    fn esc_dismisses_palette() {
1910        let mut palette = CommandPalette::new();
1911        palette.open();
1912
1913        let esc = Event::Key(KeyEvent {
1914            code: KeyCode::Escape,
1915            modifiers: Modifiers::empty(),
1916            kind: KeyEventKind::Press,
1917        });
1918
1919        let result = palette.handle_event(&esc);
1920        assert_eq!(result, Some(PaletteAction::Dismiss));
1921        assert!(!palette.is_visible());
1922    }
1923
1924    #[test]
1925    fn enter_executes_selected() {
1926        let mut palette = CommandPalette::new();
1927        palette.register("Open File", None, &[]);
1928        palette.open();
1929
1930        let enter = Event::Key(KeyEvent {
1931            code: KeyCode::Enter,
1932            modifiers: Modifiers::empty(),
1933            kind: KeyEventKind::Press,
1934        });
1935
1936        let result = palette.handle_event(&enter);
1937        assert_eq!(result, Some(PaletteAction::Execute("open_file".into())));
1938    }
1939
1940    #[test]
1941    fn arrow_keys_navigate() {
1942        let mut palette = CommandPalette::new();
1943        palette.register("A", None, &[]);
1944        palette.register("B", None, &[]);
1945        palette.register("C", None, &[]);
1946        palette.open();
1947
1948        assert_eq!(palette.selected_index(), 0);
1949
1950        let down = Event::Key(KeyEvent {
1951            code: KeyCode::Down,
1952            modifiers: Modifiers::empty(),
1953            kind: KeyEventKind::Press,
1954        });
1955        let up = Event::Key(KeyEvent {
1956            code: KeyCode::Up,
1957            modifiers: Modifiers::empty(),
1958            kind: KeyEventKind::Press,
1959        });
1960
1961        let _ = palette.handle_event(&down);
1962        assert_eq!(palette.selected_index(), 1);
1963        let _ = palette.handle_event(&down);
1964        assert_eq!(palette.selected_index(), 2);
1965        // Can't go past end
1966        let _ = palette.handle_event(&down);
1967        assert_eq!(palette.selected_index(), 2);
1968
1969        let _ = palette.handle_event(&up);
1970        assert_eq!(palette.selected_index(), 1);
1971        let _ = palette.handle_event(&up);
1972        assert_eq!(palette.selected_index(), 0);
1973        // Can't go below 0
1974        let _ = palette.handle_event(&up);
1975        assert_eq!(palette.selected_index(), 0);
1976    }
1977
1978    #[test]
1979    fn home_end_navigation() {
1980        let mut palette = CommandPalette::new();
1981        for i in 0..20 {
1982            palette.register(format!("Action {}", i), None, &[]);
1983        }
1984        palette.open();
1985
1986        let end = Event::Key(KeyEvent {
1987            code: KeyCode::End,
1988            modifiers: Modifiers::empty(),
1989            kind: KeyEventKind::Press,
1990        });
1991        let home = Event::Key(KeyEvent {
1992            code: KeyCode::Home,
1993            modifiers: Modifiers::empty(),
1994            kind: KeyEventKind::Press,
1995        });
1996
1997        let _ = palette.handle_event(&end);
1998        assert_eq!(palette.selected_index(), 19);
1999
2000        let _ = palette.handle_event(&home);
2001        assert_eq!(palette.selected_index(), 0);
2002    }
2003
2004    #[test]
2005    fn ctrl_u_clears_query() {
2006        let mut palette = CommandPalette::new();
2007        palette.register("Open File", None, &[]);
2008        palette.open();
2009
2010        let o = Event::Key(KeyEvent {
2011            code: KeyCode::Char('o'),
2012            modifiers: Modifiers::empty(),
2013            kind: KeyEventKind::Press,
2014        });
2015        let _ = palette.handle_event(&o);
2016        assert_eq!(palette.query(), "o");
2017
2018        let ctrl_u = Event::Key(KeyEvent {
2019            code: KeyCode::Char('u'),
2020            modifiers: Modifiers::CTRL,
2021            kind: KeyEventKind::Press,
2022        });
2023        let _ = palette.handle_event(&ctrl_u);
2024        assert_eq!(palette.query(), "");
2025    }
2026
2027    #[test]
2028    fn ctrl_p_opens_palette() {
2029        let mut palette = CommandPalette::new();
2030        assert!(!palette.is_visible());
2031
2032        let ctrl_p = Event::Key(KeyEvent {
2033            code: KeyCode::Char('p'),
2034            modifiers: Modifiers::CTRL,
2035            kind: KeyEventKind::Press,
2036        });
2037        let _ = palette.handle_event(&ctrl_p);
2038        assert!(palette.is_visible());
2039    }
2040
2041    #[test]
2042    fn selected_action_returns_correct_item() {
2043        let mut palette = CommandPalette::new();
2044        palette.register("Alpha", None, &[]);
2045        palette.register("Beta", None, &[]);
2046        palette.open();
2047
2048        let action = palette.selected_action().unwrap();
2049        // With empty query, all items shown — first by score (neutral, so first registered)
2050        assert!(!action.title.is_empty());
2051    }
2052
2053    #[test]
2054    fn register_action_item_directly() {
2055        let mut palette = CommandPalette::new();
2056        let item = ActionItem::new("custom_id", "Custom Action")
2057            .with_description("A custom action")
2058            .with_tags(&["custom", "test"])
2059            .with_category("Testing");
2060
2061        palette.register_action(item);
2062        assert_eq!(palette.action_count(), 1);
2063    }
2064
2065    #[test]
2066    fn register_refreshes_visible_filtered_results() {
2067        let mut palette = CommandPalette::new();
2068        palette.register("Alpha", None, &[]);
2069        palette.open();
2070        palette.set_query("Beta");
2071        assert!(palette.selected_action().is_none());
2072
2073        palette.register("Beta", None, &[]);
2074
2075        assert_eq!(palette.result_count(), 1);
2076        assert_eq!(
2077            palette
2078                .selected_action()
2079                .map(|action| action.title.as_str()),
2080            Some("Beta")
2081        );
2082    }
2083
2084    #[test]
2085    fn register_action_refreshes_visible_filtered_results() {
2086        let mut palette = CommandPalette::new();
2087        palette.register("Alpha", None, &[]);
2088        palette.open();
2089        palette.set_query("Beta");
2090        assert!(palette.selected_action().is_none());
2091
2092        palette.register_action(ActionItem::new("beta", "Beta"));
2093
2094        assert_eq!(palette.result_count(), 1);
2095        assert_eq!(
2096            palette
2097                .selected_action()
2098                .map(|action| action.title.as_str()),
2099            Some("Beta")
2100        );
2101    }
2102
2103    #[test]
2104    fn replace_actions_refreshes_results() {
2105        let mut palette = CommandPalette::new();
2106        palette.register("Alpha", None, &[]);
2107        palette.register("Beta", None, &[]);
2108        palette.open();
2109        palette.set_query("Beta");
2110        assert_eq!(
2111            palette.selected_action().map(|a| a.title.as_str()),
2112            Some("Beta")
2113        );
2114
2115        let actions = vec![
2116            ActionItem::new("gamma", "Gamma"),
2117            ActionItem::new("delta", "Delta"),
2118        ];
2119        palette.replace_actions(actions);
2120        palette.set_query("Delta");
2121        assert_eq!(
2122            palette.selected_action().map(|a| a.title.as_str()),
2123            Some("Delta")
2124        );
2125    }
2126
2127    #[test]
2128    fn clear_actions_resets_results() {
2129        let mut palette = CommandPalette::new();
2130        palette.register("Alpha", None, &[]);
2131        palette.register("Beta", None, &[]);
2132        palette.open();
2133        palette.set_query("Alpha");
2134        assert!(palette.selected_action().is_some());
2135
2136        palette.clear_actions();
2137        assert_eq!(palette.action_count(), 0);
2138        assert!(palette.selected_action().is_none());
2139    }
2140
2141    #[test]
2142    fn set_query_refilters() {
2143        let mut palette = CommandPalette::new();
2144        palette.register("Alpha", None, &[]);
2145        palette.register("Beta", None, &[]);
2146        palette.open();
2147        palette.set_query("Alpha");
2148        assert_eq!(palette.query(), "Alpha");
2149        assert_eq!(
2150            palette.selected_action().map(|a| a.title.as_str()),
2151            Some("Alpha")
2152        );
2153        palette.set_query("Beta");
2154        assert_eq!(palette.query(), "Beta");
2155        assert_eq!(
2156            palette.selected_action().map(|a| a.title.as_str()),
2157            Some("Beta")
2158        );
2159    }
2160
2161    #[test]
2162    fn events_ignored_when_hidden() {
2163        let mut palette = CommandPalette::new();
2164        // Not Ctrl+P, so should be ignored
2165        let a = Event::Key(KeyEvent {
2166            code: KeyCode::Char('a'),
2167            modifiers: Modifiers::empty(),
2168            kind: KeyEventKind::Press,
2169        });
2170        assert!(palette.handle_event(&a).is_none());
2171        assert!(!palette.is_visible());
2172    }
2173
2174    // -----------------------------------------------------------------------
2175    // Accessibility / UX tests (bd-39y4.10)
2176    // -----------------------------------------------------------------------
2177
2178    #[test]
2179    fn selected_row_has_bold_attribute() {
2180        use ftui_render::grapheme_pool::GraphemePool;
2181
2182        let mut palette = CommandPalette::new();
2183        palette.register("Alpha", None, &[]);
2184        palette.register("Beta", None, &[]);
2185        palette.open();
2186
2187        let area = Rect::from_size(60, 10);
2188        let mut pool = GraphemePool::new();
2189        let mut frame = Frame::new(60, 10, &mut pool);
2190        palette.render(area, &mut frame);
2191
2192        // The selected row (first result) should have bold cells.
2193        // Results start at y=2 inside the palette (after border + query).
2194        let palette_y = area.y + area.height / 6;
2195        let result_y = palette_y + 2;
2196
2197        // Check that at least one cell in the first result row is bold
2198        let mut found_bold = false;
2199        for x in 0..60u16 {
2200            if let Some(cell) = frame.buffer.get(x, result_y)
2201                && cell.attrs.flags().contains(CellStyleFlags::BOLD)
2202            {
2203                found_bold = true;
2204                break;
2205            }
2206        }
2207        assert!(
2208            found_bold,
2209            "Selected row should have bold attribute for accessibility"
2210        );
2211    }
2212
2213    #[test]
2214    fn selection_marker_visible() {
2215        use ftui_render::grapheme_pool::GraphemePool;
2216
2217        let mut palette = CommandPalette::new();
2218        palette.register("Alpha", None, &[]);
2219        palette.open();
2220
2221        let area = Rect::from_size(60, 10);
2222        let mut pool = GraphemePool::new();
2223        let mut frame = Frame::new(60, 10, &mut pool);
2224        palette.render(area, &mut frame);
2225
2226        // Find the '>' selection marker in the results area
2227        let palette_y = area.y + area.height / 6;
2228        let result_y = palette_y + 2;
2229        let mut found_marker = false;
2230        for x in 0..60u16 {
2231            if let Some(cell) = frame.buffer.get(x, result_y)
2232                && cell.content.as_char() == Some('>')
2233            {
2234                found_marker = true;
2235                break;
2236            }
2237        }
2238        assert!(
2239            found_marker,
2240            "Selection marker '>' should be visible (color-independent indicator)"
2241        );
2242    }
2243
2244    #[test]
2245    fn long_title_truncated_with_ellipsis() {
2246        use ftui_render::grapheme_pool::GraphemePool;
2247
2248        let mut palette = CommandPalette::new().with_max_visible(5);
2249        palette.register(
2250            "This Is A Very Long Action Title That Should Be Truncated With Ellipsis",
2251            None,
2252            &[],
2253        );
2254        palette.open();
2255
2256        // Render in a narrow area
2257        let area = Rect::from_size(40, 10);
2258        let mut pool = GraphemePool::new();
2259        let mut frame = Frame::new(40, 10, &mut pool);
2260        palette.render(area, &mut frame);
2261
2262        // Find the ellipsis character '…' in the results area
2263        let palette_y = area.y + area.height / 6;
2264        let result_y = palette_y + 2;
2265        let mut found_ellipsis = false;
2266        for x in 0..40u16 {
2267            if let Some(cell) = frame.buffer.get(x, result_y)
2268                && cell.content.as_char() == Some('\u{2026}')
2269            {
2270                found_ellipsis = true;
2271                break;
2272            }
2273        }
2274        assert!(
2275            found_ellipsis,
2276            "Long titles should be truncated with '…' ellipsis"
2277        );
2278    }
2279
2280    #[test]
2281    fn keyboard_only_flow_end_to_end() {
2282        let mut palette = CommandPalette::new();
2283        palette.register("Open File", Some("Open a file from disk"), &["file"]);
2284        palette.register("Save File", Some("Save current file"), &["file"]);
2285        palette.register("Git: Commit", Some("Commit changes"), &["git"]);
2286
2287        // Step 1: Open with Ctrl+P
2288        let ctrl_p = Event::Key(KeyEvent {
2289            code: KeyCode::Char('p'),
2290            modifiers: Modifiers::CTRL,
2291            kind: KeyEventKind::Press,
2292        });
2293        let _ = palette.handle_event(&ctrl_p);
2294        assert!(palette.is_visible());
2295        assert_eq!(palette.result_count(), 3);
2296
2297        // Step 2: Type query to filter
2298        for ch in "git".chars() {
2299            let event = Event::Key(KeyEvent {
2300                code: KeyCode::Char(ch),
2301                modifiers: Modifiers::empty(),
2302                kind: KeyEventKind::Press,
2303            });
2304            let _ = palette.handle_event(&event);
2305        }
2306        assert!(palette.result_count() >= 1);
2307
2308        // Step 3: Navigate down (in case selected isn't the right one)
2309        let down = Event::Key(KeyEvent {
2310            code: KeyCode::Down,
2311            modifiers: Modifiers::empty(),
2312            kind: KeyEventKind::Press,
2313        });
2314        let _ = palette.handle_event(&down);
2315
2316        // Step 4: Navigate back up
2317        let up = Event::Key(KeyEvent {
2318            code: KeyCode::Up,
2319            modifiers: Modifiers::empty(),
2320            kind: KeyEventKind::Press,
2321        });
2322        let _ = palette.handle_event(&up);
2323        assert_eq!(palette.selected_index(), 0);
2324
2325        // Step 5: Execute with Enter
2326        let enter = Event::Key(KeyEvent {
2327            code: KeyCode::Enter,
2328            modifiers: Modifiers::empty(),
2329            kind: KeyEventKind::Press,
2330        });
2331        let result = palette.handle_event(&enter);
2332        assert!(matches!(result, Some(PaletteAction::Execute(_))));
2333        assert!(!palette.is_visible());
2334    }
2335
2336    #[test]
2337    fn no_focus_trap_esc_always_dismisses() {
2338        let mut palette = CommandPalette::new();
2339        palette.register("Alpha", None, &[]);
2340        palette.open();
2341
2342        // Type some query
2343        for ch in "xyz".chars() {
2344            let event = Event::Key(KeyEvent {
2345                code: KeyCode::Char(ch),
2346                modifiers: Modifiers::empty(),
2347                kind: KeyEventKind::Press,
2348            });
2349            let _ = palette.handle_event(&event);
2350        }
2351        assert_eq!(palette.result_count(), 0); // no matches
2352
2353        // Esc should still dismiss even with no results
2354        let esc = Event::Key(KeyEvent {
2355            code: KeyCode::Escape,
2356            modifiers: Modifiers::empty(),
2357            kind: KeyEventKind::Press,
2358        });
2359        let result = palette.handle_event(&esc);
2360        assert_eq!(result, Some(PaletteAction::Dismiss));
2361        assert!(!palette.is_visible());
2362    }
2363
2364    #[test]
2365    fn unicode_query_renders_correctly() {
2366        use ftui_render::grapheme_pool::GraphemePool;
2367
2368        let mut palette = CommandPalette::new();
2369        palette.register("Café Menu", None, &["food"]);
2370        palette.open();
2371        palette.set_query("café");
2372
2373        assert_eq!(palette.query(), "café");
2374
2375        let area = Rect::from_size(60, 10);
2376        let mut pool = GraphemePool::new();
2377        let mut frame = Frame::new(60, 10, &mut pool);
2378        palette.render(area, &mut frame);
2379
2380        // The query "café" should be visible in the input area
2381        // palette_y ≈ 1 (10/6), query line is at palette_y + 1 = 2
2382        let palette_y = area.y + area.height / 6;
2383        let input_y = palette_y + 1;
2384
2385        // Find the query characters in the input row
2386        let mut found_query_chars = 0;
2387        for x in 0..60u16 {
2388            if let Some(cell) = frame.buffer.get(x, input_y)
2389                && let Some(ch) = cell.content.as_char()
2390                && "café".contains(ch)
2391            {
2392                found_query_chars += 1;
2393            }
2394        }
2395        // Should find at least 3 of the 4 characters (c, a, f, é may be grapheme)
2396        assert!(
2397            found_query_chars >= 3,
2398            "Unicode query should render (found {} chars)",
2399            found_query_chars
2400        );
2401    }
2402
2403    #[test]
2404    fn wide_char_query_renders_correctly() {
2405        use ftui_render::grapheme_pool::GraphemePool;
2406
2407        let mut palette = CommandPalette::new();
2408        palette.register("日本語メニュー", None, &["japanese"]);
2409        palette.open();
2410        palette.set_query("日本");
2411
2412        assert_eq!(palette.query(), "日本");
2413
2414        let area = Rect::from_size(60, 10);
2415        let mut pool = GraphemePool::new();
2416        let mut frame = Frame::new(60, 10, &mut pool);
2417        palette.render(area, &mut frame);
2418
2419        // Wide characters should be rendered (each takes 2 columns)
2420        let palette_y = area.y + area.height / 6;
2421        let input_y = palette_y + 1;
2422
2423        // Find grapheme cells in the input row
2424        let mut found_grapheme = false;
2425        for x in 0..60u16 {
2426            if let Some(cell) = frame.buffer.get(x, input_y)
2427                && cell.content.is_grapheme()
2428            {
2429                found_grapheme = true;
2430                break;
2431            }
2432        }
2433        assert!(
2434            found_grapheme,
2435            "Wide character query should render as graphemes"
2436        );
2437    }
2438
2439    #[test]
2440    fn wcag_aa_contrast_ratios() {
2441        // Verify the default style colors meet WCAG AA contrast requirements.
2442        // WCAG AA requires >= 4.5:1 for normal text.
2443        let style = PaletteStyle::default();
2444        let bg = PackedRgba::rgb(30, 30, 40);
2445
2446        // Helper: relative luminance per WCAG 2.0
2447        fn relative_luminance(color: PackedRgba) -> f64 {
2448            fn linearize(c: u8) -> f64 {
2449                let v = c as f64 / 255.0;
2450                if v <= 0.04045 {
2451                    v / 12.92
2452                } else {
2453                    ((v + 0.055) / 1.055).powf(2.4)
2454                }
2455            }
2456            let r = linearize(color.r());
2457            let g = linearize(color.g());
2458            let b = linearize(color.b());
2459            0.2126 * r + 0.7152 * g + 0.0722 * b
2460        }
2461
2462        fn contrast_ratio(fg: PackedRgba, bg: PackedRgba) -> f64 {
2463            let l1 = relative_luminance(fg);
2464            let l2 = relative_luminance(bg);
2465            let (lighter, darker) = if l1 > l2 { (l1, l2) } else { (l2, l1) };
2466            (lighter + 0.05) / (darker + 0.05)
2467        }
2468
2469        // Item text on palette background
2470        let item_fg = style.item.fg.unwrap();
2471        let item_ratio = contrast_ratio(item_fg, bg);
2472        assert!(
2473            item_ratio >= 4.5,
2474            "Item text contrast {:.1}:1 < 4.5:1 (WCAG AA)",
2475            item_ratio
2476        );
2477
2478        // Selected text on selected background
2479        let sel_fg = style.item_selected.fg.unwrap();
2480        let sel_bg = style.item_selected.bg.unwrap();
2481        let sel_ratio = contrast_ratio(sel_fg, sel_bg);
2482        assert!(
2483            sel_ratio >= 4.5,
2484            "Selected text contrast {:.1}:1 < 4.5:1 (WCAG AA)",
2485            sel_ratio
2486        );
2487
2488        // Match highlight on palette background
2489        let hl_fg = style.match_highlight.fg.unwrap();
2490        let hl_ratio = contrast_ratio(hl_fg, bg);
2491        assert!(
2492            hl_ratio >= 4.5,
2493            "Highlight text contrast {:.1}:1 < 4.5:1 (WCAG AA)",
2494            hl_ratio
2495        );
2496
2497        // Description text on palette background
2498        let desc_fg = style.description.fg.unwrap();
2499        let desc_ratio = contrast_ratio(desc_fg, bg);
2500        assert!(
2501            desc_ratio >= 4.5,
2502            "Description text contrast {:.1}:1 < 4.5:1 (WCAG AA)",
2503            desc_ratio
2504        );
2505    }
2506
2507    #[test]
2508    fn action_item_builder_fields() {
2509        let item = ActionItem::new("my_id", "My Action")
2510            .with_description("A description")
2511            .with_tags(&["tag1", "tag2"])
2512            .with_category("Category");
2513
2514        assert_eq!(item.id, "my_id");
2515        assert_eq!(item.title, "My Action");
2516        assert_eq!(item.description.as_deref(), Some("A description"));
2517        assert_eq!(item.tags, vec!["tag1", "tag2"]);
2518        assert_eq!(item.category.as_deref(), Some("Category"));
2519    }
2520
2521    #[test]
2522    fn action_item_defaults_none() {
2523        let item = ActionItem::new("id", "title");
2524        assert!(item.description.is_none());
2525        assert!(item.tags.is_empty());
2526        assert!(item.category.is_none());
2527    }
2528
2529    #[test]
2530    fn palette_action_equality() {
2531        assert_eq!(PaletteAction::Dismiss, PaletteAction::Dismiss);
2532        assert_eq!(
2533            PaletteAction::Execute("x".into()),
2534            PaletteAction::Execute("x".into())
2535        );
2536        assert_ne!(PaletteAction::Dismiss, PaletteAction::Execute("x".into()));
2537    }
2538
2539    #[test]
2540    fn match_filter_allows_all() {
2541        assert!(MatchFilter::All.allows(MatchType::Exact));
2542        assert!(MatchFilter::All.allows(MatchType::Prefix));
2543        assert!(MatchFilter::All.allows(MatchType::WordStart));
2544        assert!(MatchFilter::All.allows(MatchType::Substring));
2545        assert!(MatchFilter::All.allows(MatchType::Fuzzy));
2546    }
2547
2548    #[test]
2549    fn match_filter_specific_types() {
2550        assert!(MatchFilter::Exact.allows(MatchType::Exact));
2551        assert!(!MatchFilter::Exact.allows(MatchType::Fuzzy));
2552        assert!(MatchFilter::Fuzzy.allows(MatchType::Fuzzy));
2553        assert!(!MatchFilter::Fuzzy.allows(MatchType::Exact));
2554    }
2555
2556    #[test]
2557    fn palette_default_trait() {
2558        let palette = CommandPalette::default();
2559        assert!(!palette.is_visible());
2560        assert_eq!(palette.action_count(), 0);
2561        assert_eq!(palette.query(), "");
2562    }
2563
2564    #[test]
2565    fn with_max_visible_builder() {
2566        let palette = CommandPalette::new().with_max_visible(5);
2567        // Verify by registering more than 5 items and checking rendering doesn't panic
2568        let mut palette = palette;
2569        for i in 0..10 {
2570            palette.register(format!("Action {i}"), None, &[]);
2571        }
2572        palette.open();
2573        assert_eq!(palette.result_count(), 10);
2574    }
2575
2576    #[test]
2577    fn scorer_stats_accessible() {
2578        let mut palette = CommandPalette::new();
2579        palette.register("Alpha", None, &[]);
2580        palette.open();
2581        palette.set_query("a");
2582        let stats = palette.scorer_stats();
2583        assert!(stats.full_scans + stats.incremental_scans >= 1);
2584    }
2585
2586    #[test]
2587    fn selected_match_returns_match() {
2588        let mut palette = CommandPalette::new();
2589        palette.register("Hello World", None, &[]);
2590        palette.open();
2591        palette.set_query("hello");
2592        let m = palette.selected_match();
2593        assert!(m.is_some());
2594        assert_eq!(m.unwrap().action.title, "Hello World");
2595    }
2596
2597    #[test]
2598    fn results_iterator_returns_matches() {
2599        let mut palette = CommandPalette::new();
2600        palette.register("Alpha", None, &[]);
2601        palette.register("Beta", None, &[]);
2602        palette.open();
2603        let count = palette.results().count();
2604        assert_eq!(count, 2);
2605    }
2606
2607    #[test]
2608    fn set_match_filter_narrows_results() {
2609        let mut palette = CommandPalette::new();
2610        palette.register("Open File", None, &[]);
2611        palette.register("Save File", None, &[]);
2612        palette.open();
2613        palette.set_query("open");
2614        let before = palette.result_count();
2615
2616        // Setting to Exact should narrow or keep results
2617        palette.set_match_filter(MatchFilter::Exact);
2618        let after = palette.result_count();
2619        assert!(after <= before);
2620    }
2621
2622    #[test]
2623    fn prefix_filter_uses_art_candidate_set() {
2624        let mut palette = CommandPalette::new();
2625        for idx in 0..40 {
2626            palette.register_action(ActionItem::new(
2627                format!("file-{idx:02}"),
2628                format!("File Command {idx:02}"),
2629            ));
2630        }
2631        for idx in 0..80 {
2632            palette.register_action(ActionItem::new(
2633                format!("edit-{idx:02}"),
2634                format!("Edit Command {idx:02}"),
2635            ));
2636        }
2637
2638        palette.open();
2639        palette.set_match_filter(MatchFilter::Prefix);
2640
2641        let before = palette.scorer_stats().total_evaluated;
2642        palette.set_query("file");
2643        let evaluated_for_query = palette.scorer_stats().total_evaluated - before;
2644
2645        assert_eq!(palette.result_count(), 40);
2646        assert_eq!(evaluated_for_query, 40);
2647    }
2648
2649    #[test]
2650    fn prefix_filter_preserves_duplicate_titles() {
2651        let mut palette = CommandPalette::new();
2652        palette.register_action(ActionItem::new("open-file-a", "Open File"));
2653        palette.register_action(ActionItem::new("open-file-b", "Open File"));
2654        palette.register_action(ActionItem::new("open-folder", "Open Folder"));
2655
2656        palette.open();
2657        palette.set_match_filter(MatchFilter::Prefix);
2658        palette.set_query("open f");
2659
2660        let ids: Vec<&str> = palette.results().map(|m| m.action.id.as_str()).collect();
2661        assert_eq!(ids.len(), 3);
2662        assert!(ids.contains(&"open-file-a"));
2663        assert!(ids.contains(&"open-file-b"));
2664        assert!(ids.contains(&"open-folder"));
2665    }
2666
2667    #[test]
2668    fn prefix_filter_does_not_poison_all_match_cache() {
2669        let mut palette = CommandPalette::new();
2670        palette.register("Open Preferences", None, &[]);
2671        palette.register("Preferences: Open", None, &[]);
2672
2673        palette.open();
2674        palette.set_match_filter(MatchFilter::Prefix);
2675        palette.set_query("pref");
2676        assert_eq!(palette.result_count(), 1);
2677
2678        palette.set_match_filter(MatchFilter::All);
2679        let titles: Vec<&str> = palette.results().map(|m| m.action.title.as_str()).collect();
2680        assert!(titles.contains(&"Open Preferences"));
2681        assert!(titles.contains(&"Preferences: Open"));
2682    }
2683
2684    #[test]
2685    fn replace_actions_rebuilds_prefix_index() {
2686        let mut palette = CommandPalette::new();
2687        palette.register_action(ActionItem::new("open-file", "Open File"));
2688
2689        palette.open();
2690        palette.set_match_filter(MatchFilter::Prefix);
2691        palette.set_query("open");
2692        assert_eq!(palette.result_count(), 1);
2693
2694        palette.replace_actions(vec![ActionItem::new("save-file", "Save File")]);
2695        assert_eq!(palette.result_count(), 0);
2696
2697        palette.set_query("save");
2698        assert_eq!(palette.result_count(), 1);
2699        assert_eq!(
2700            palette.selected_action().map(|action| action.id.as_str()),
2701            Some("save-file")
2702        );
2703    }
2704
2705    #[test]
2706    fn enter_with_no_results_returns_none() {
2707        let mut palette = CommandPalette::new();
2708        palette.register("Alpha", None, &[]);
2709        palette.open();
2710        palette.set_query("zzzznotfound");
2711        assert_eq!(palette.result_count(), 0);
2712
2713        let enter = Event::Key(KeyEvent {
2714            code: KeyCode::Enter,
2715            modifiers: Modifiers::empty(),
2716            kind: KeyEventKind::Press,
2717        });
2718        let result = palette.handle_event(&enter);
2719        assert!(result.is_none());
2720    }
2721
2722    #[cfg(feature = "tracing")]
2723    #[test]
2724    fn telemetry_emits_in_order() {
2725        use std::sync::{Arc, Mutex};
2726        use tracing::Subscriber;
2727        use tracing_subscriber::Layer;
2728        use tracing_subscriber::filter::Targets;
2729        use tracing_subscriber::layer::{Context, SubscriberExt};
2730
2731        #[derive(Default)]
2732        struct EventCapture {
2733            events: Arc<Mutex<Vec<String>>>,
2734        }
2735
2736        impl<S> Layer<S> for EventCapture
2737        where
2738            S: Subscriber,
2739        {
2740            fn on_event(&self, event: &tracing::Event<'_>, _ctx: Context<'_, S>) {
2741                use tracing::field::{Field, Visit};
2742
2743                struct EventVisitor {
2744                    name: Option<String>,
2745                }
2746
2747                impl Visit for EventVisitor {
2748                    fn record_str(&mut self, field: &Field, value: &str) {
2749                        if field.name() == "event" {
2750                            self.name = Some(value.to_string());
2751                        }
2752                    }
2753
2754                    fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
2755                        if field.name() == "event" {
2756                            let raw = format!("{value:?}");
2757                            let normalized = raw.trim_matches('\"').to_string();
2758                            self.name = Some(normalized);
2759                        }
2760                    }
2761                }
2762
2763                let mut visitor = EventVisitor { name: None };
2764                event.record(&mut visitor);
2765                if let Some(name) = visitor.name {
2766                    self.events
2767                        .lock()
2768                        .expect("lock telemetry events")
2769                        .push(name);
2770                }
2771            }
2772        }
2773
2774        let events = Arc::new(Mutex::new(Vec::new()));
2775        let capture = EventCapture {
2776            events: Arc::clone(&events),
2777        };
2778        let _trace_test_guard = crate::tracing_test_support::acquire();
2779
2780        let subscriber = tracing_subscriber::registry()
2781            .with(capture)
2782            .with(Targets::new().with_target(TELEMETRY_TARGET, tracing::Level::INFO));
2783        let _guard = tracing::subscriber::set_default(subscriber);
2784
2785        // Rebuild interest cache before each step that emits tracing events.
2786        // Parallel workspace tests can poison the global callsite interest
2787        // cache between our operations, causing `info!` macros to short-circuit.
2788        let mut palette = CommandPalette::new();
2789        palette.register("Alpha", None, &[]);
2790        tracing::callsite::rebuild_interest_cache();
2791        palette.open();
2792
2793        let a = Event::Key(KeyEvent {
2794            code: KeyCode::Char('a'),
2795            modifiers: Modifiers::empty(),
2796            kind: KeyEventKind::Press,
2797        });
2798        tracing::callsite::rebuild_interest_cache();
2799        let _ = palette.handle_event(&a);
2800
2801        let enter = Event::Key(KeyEvent {
2802            code: KeyCode::Enter,
2803            modifiers: Modifiers::empty(),
2804            kind: KeyEventKind::Press,
2805        });
2806        tracing::callsite::rebuild_interest_cache();
2807        let _ = palette.handle_event(&enter);
2808        tracing::callsite::rebuild_interest_cache();
2809        palette.close();
2810
2811        let events = events.lock().expect("lock telemetry events");
2812        let open_idx = events
2813            .iter()
2814            .position(|e| e == "palette_opened")
2815            .expect("palette_opened missing");
2816        let query_idx = events
2817            .iter()
2818            .position(|e| e == "palette_query_updated")
2819            .expect("palette_query_updated missing");
2820        let exec_idx = events
2821            .iter()
2822            .position(|e| e == "palette_action_executed")
2823            .expect("palette_action_executed missing");
2824        let close_idx = events
2825            .iter()
2826            .position(|e| e == "palette_closed")
2827            .expect("palette_closed missing");
2828
2829        assert!(open_idx < query_idx);
2830        assert!(query_idx < exec_idx);
2831        assert!(exec_idx < close_idx);
2832    }
2833
2834    // -----------------------------------------------------------------------
2835    // Edge-case tests (bd-2svld)
2836    // -----------------------------------------------------------------------
2837
2838    #[test]
2839    fn compute_word_starts_empty() {
2840        let starts = compute_word_starts("");
2841        assert!(starts.is_empty());
2842    }
2843
2844    #[test]
2845    fn compute_word_starts_single_word() {
2846        let starts = compute_word_starts("hello");
2847        assert_eq!(starts, vec![0]);
2848    }
2849
2850    #[test]
2851    fn compute_word_starts_spaces() {
2852        let starts = compute_word_starts("open file now");
2853        assert_eq!(starts, vec![0, 5, 10]);
2854    }
2855
2856    #[test]
2857    fn compute_word_starts_hyphen_underscore() {
2858        let starts = compute_word_starts("git-commit_push");
2859        // Positions: g=0, c=4, p=11
2860        assert_eq!(starts, vec![0, 4, 11]);
2861    }
2862
2863    #[test]
2864    fn compute_word_starts_all_separators() {
2865        let starts = compute_word_starts("- _");
2866        // '-' at 0 is word start (i==0), ' ' at 1 follows '-' so word start,
2867        // '_' at 2 follows ' ' so word start
2868        assert_eq!(starts, vec![0, 1, 2]);
2869    }
2870
2871    #[test]
2872    fn backspace_on_empty_query_is_noop() {
2873        let mut palette = CommandPalette::new();
2874        palette.register("Alpha", None, &[]);
2875        palette.open();
2876        assert_eq!(palette.query(), "");
2877
2878        let bs = Event::Key(KeyEvent {
2879            code: KeyCode::Backspace,
2880            modifiers: Modifiers::empty(),
2881            kind: KeyEventKind::Press,
2882        });
2883        let _ = palette.handle_event(&bs);
2884        assert_eq!(palette.query(), "");
2885        // Results should still show all items
2886        assert_eq!(palette.result_count(), 1);
2887    }
2888
2889    #[test]
2890    fn ctrl_a_moves_cursor_to_start() {
2891        let mut palette = CommandPalette::new();
2892        palette.register("Alpha", None, &[]);
2893        palette.open();
2894
2895        // Type "abc"
2896        for ch in "abc".chars() {
2897            let event = Event::Key(KeyEvent {
2898                code: KeyCode::Char(ch),
2899                modifiers: Modifiers::empty(),
2900                kind: KeyEventKind::Press,
2901            });
2902            let _ = palette.handle_event(&event);
2903        }
2904        assert_eq!(palette.query(), "abc");
2905
2906        let ctrl_a = Event::Key(KeyEvent {
2907            code: KeyCode::Char('a'),
2908            modifiers: Modifiers::CTRL,
2909            kind: KeyEventKind::Press,
2910        });
2911        let _ = palette.handle_event(&ctrl_a);
2912        // Cursor should move to 0 but query unchanged
2913        assert_eq!(palette.query(), "abc");
2914    }
2915
2916    #[test]
2917    fn key_release_events_ignored() {
2918        let mut palette = CommandPalette::new();
2919        palette.register("Alpha", None, &[]);
2920        palette.open();
2921
2922        let release = Event::Key(KeyEvent {
2923            code: KeyCode::Char('x'),
2924            modifiers: Modifiers::empty(),
2925            kind: KeyEventKind::Release,
2926        });
2927        let result = palette.handle_event(&release);
2928        assert!(result.is_none());
2929        assert_eq!(palette.query(), "");
2930    }
2931
2932    #[test]
2933    fn resize_event_ignored() {
2934        let mut palette = CommandPalette::new();
2935        palette.open();
2936
2937        let resize = Event::Resize {
2938            width: 80,
2939            height: 24,
2940        };
2941        let result = palette.handle_event(&resize);
2942        assert!(result.is_none());
2943    }
2944
2945    #[test]
2946    fn is_essential_returns_true() {
2947        let palette = CommandPalette::new();
2948        assert!(palette.is_essential());
2949    }
2950
2951    #[test]
2952    fn render_too_small_area_noop() {
2953        use ftui_render::grapheme_pool::GraphemePool;
2954
2955        let mut palette = CommandPalette::new();
2956        palette.register("Alpha", None, &[]);
2957        palette.open();
2958
2959        // Width < 10
2960        let area = Rect::new(0, 0, 9, 10);
2961        let mut pool = GraphemePool::new();
2962        let mut frame = Frame::new(20, 20, &mut pool);
2963        palette.render(area, &mut frame);
2964        // Should not panic, cursor not set
2965        assert!(frame.cursor_position.is_none());
2966    }
2967
2968    #[test]
2969    fn render_too_short_area_noop() {
2970        use ftui_render::grapheme_pool::GraphemePool;
2971
2972        let mut palette = CommandPalette::new();
2973        palette.register("Alpha", None, &[]);
2974        palette.open();
2975
2976        // Height < 5
2977        let area = Rect::new(0, 0, 60, 4);
2978        let mut pool = GraphemePool::new();
2979        let mut frame = Frame::new(60, 10, &mut pool);
2980        palette.render(area, &mut frame);
2981        assert!(frame.cursor_position.is_none());
2982    }
2983
2984    #[test]
2985    fn render_hidden_palette_noop() {
2986        use ftui_render::grapheme_pool::GraphemePool;
2987
2988        let palette = CommandPalette::new();
2989        assert!(!palette.is_visible());
2990
2991        let area = Rect::from_size(60, 10);
2992        let mut pool = GraphemePool::new();
2993        let mut frame = Frame::new(60, 10, &mut pool);
2994        palette.render(area, &mut frame);
2995        assert!(frame.cursor_position.is_none());
2996    }
2997
2998    #[test]
2999    fn render_empty_palette_shows_no_actions_hint() {
3000        use ftui_render::grapheme_pool::GraphemePool;
3001
3002        let mut palette = CommandPalette::new();
3003        // No actions registered
3004        palette.open();
3005
3006        let area = Rect::from_size(60, 15);
3007        let mut pool = GraphemePool::new();
3008        let mut frame = Frame::new(60, 15, &mut pool);
3009        palette.render(area, &mut frame);
3010
3011        // Should show "No actions registered" somewhere in the results area
3012        let palette_y = area.y + area.height / 6;
3013        let result_y = palette_y + 2;
3014        let mut found_n = false;
3015        for x in 0..60u16 {
3016            if let Some(cell) = frame.buffer.get(x, result_y)
3017                && cell.content.as_char() == Some('N')
3018            {
3019                found_n = true;
3020                break;
3021            }
3022        }
3023        assert!(found_n, "Should render 'No actions registered' hint");
3024    }
3025
3026    #[test]
3027    fn render_query_no_results_shows_hint() {
3028        use ftui_render::grapheme_pool::GraphemePool;
3029
3030        let mut palette = CommandPalette::new();
3031        palette.register("Alpha", None, &[]);
3032        palette.open();
3033        palette.set_query("zzzznotfound");
3034        assert_eq!(palette.result_count(), 0);
3035
3036        let area = Rect::from_size(60, 15);
3037        let mut pool = GraphemePool::new();
3038        let mut frame = Frame::new(60, 15, &mut pool);
3039        palette.render(area, &mut frame);
3040
3041        // Should show "No results"
3042        let palette_y = area.y + area.height / 6;
3043        let result_y = palette_y + 2;
3044        let mut found_n = false;
3045        for x in 0..60u16 {
3046            if let Some(cell) = frame.buffer.get(x, result_y)
3047                && cell.content.as_char() == Some('N')
3048            {
3049                found_n = true;
3050                break;
3051            }
3052        }
3053        assert!(found_n, "Should render 'No results' hint");
3054    }
3055
3056    #[test]
3057    fn render_with_category_badge() {
3058        use ftui_render::grapheme_pool::GraphemePool;
3059
3060        let mut palette = CommandPalette::new();
3061        let item = ActionItem::new("git_commit", "Commit Changes").with_category("Git");
3062        palette.register_action(item);
3063        palette.open();
3064
3065        let area = Rect::from_size(80, 15);
3066        let mut pool = GraphemePool::new();
3067        let mut frame = Frame::new(80, 15, &mut pool);
3068        palette.render(area, &mut frame);
3069
3070        // Should render "[Git] " badge - look for '[' in results area
3071        let palette_y = area.y + area.height / 6;
3072        let result_y = palette_y + 2;
3073        let mut found_bracket = false;
3074        for x in 0..80u16 {
3075            if let Some(cell) = frame.buffer.get(x, result_y)
3076                && cell.content.as_char() == Some('[')
3077            {
3078                found_bracket = true;
3079                break;
3080            }
3081        }
3082        assert!(found_bracket, "Should render category badge '[Git]'");
3083    }
3084
3085    #[test]
3086    fn render_with_description_text() {
3087        use ftui_render::grapheme_pool::GraphemePool;
3088
3089        let mut palette = CommandPalette::new();
3090        palette.register("Open File", Some("Opens a file from disk"), &[]);
3091        palette.open();
3092
3093        let area = Rect::from_size(80, 15);
3094        let mut pool = GraphemePool::new();
3095        let mut frame = Frame::new(80, 15, &mut pool);
3096        palette.render(area, &mut frame);
3097
3098        // Description text should appear after the title
3099        let palette_y = area.y + area.height / 6;
3100        let result_y = palette_y + 2;
3101        let mut found_desc_char = false;
3102        // Description starts with 'O' in "Opens..."
3103        for x in 20..80u16 {
3104            if let Some(cell) = frame.buffer.get(x, result_y)
3105                && cell.content.as_char() == Some('O')
3106            {
3107                found_desc_char = true;
3108                break;
3109            }
3110        }
3111        assert!(found_desc_char, "Description text should be rendered");
3112    }
3113
3114    #[test]
3115    fn open_resets_previous_state() {
3116        let mut palette = CommandPalette::new();
3117        palette.register("Alpha", None, &[]);
3118        palette.register("Beta", None, &[]);
3119        palette.open();
3120        palette.set_query("Alpha");
3121
3122        // Navigate down
3123        let down = Event::Key(KeyEvent {
3124            code: KeyCode::Down,
3125            modifiers: Modifiers::empty(),
3126            kind: KeyEventKind::Press,
3127        });
3128        let _ = palette.handle_event(&down);
3129
3130        // Re-open should reset everything
3131        palette.open();
3132        assert_eq!(palette.query(), "");
3133        assert_eq!(palette.selected_index(), 0);
3134        assert_eq!(palette.result_count(), 2);
3135    }
3136
3137    #[test]
3138    fn set_match_filter_same_value_is_noop() {
3139        let mut palette = CommandPalette::new();
3140        palette.register("Alpha", None, &[]);
3141        palette.open();
3142        palette.set_query("alpha");
3143
3144        palette.set_match_filter(MatchFilter::All);
3145        let count1 = palette.result_count();
3146        // Setting same filter again — should not change anything
3147        palette.set_match_filter(MatchFilter::All);
3148        assert_eq!(palette.result_count(), count1);
3149    }
3150
3151    #[test]
3152    fn generation_increments_on_register() {
3153        let mut palette = CommandPalette::new();
3154        palette.register("A", None, &[]);
3155        palette.register("B", None, &[]);
3156        // Can't read generation directly, but replace_actions also bumps it
3157        // and invalidates scorer — verify it doesn't panic
3158        palette.replace_actions(vec![ActionItem::new("c", "C")]);
3159        palette.open();
3160        assert_eq!(palette.action_count(), 1);
3161    }
3162
3163    #[test]
3164    fn enable_evidence_tracking_toggle() {
3165        let mut palette = CommandPalette::new();
3166        palette.register("Alpha", None, &[]);
3167        palette.open();
3168
3169        palette.enable_evidence_tracking(true);
3170        palette.set_query("alpha");
3171        assert!(palette.result_count() >= 1);
3172
3173        palette.enable_evidence_tracking(false);
3174        palette.set_query("alpha");
3175        assert!(palette.result_count() >= 1);
3176    }
3177
3178    #[test]
3179    fn register_chaining() {
3180        let mut palette = CommandPalette::new();
3181        palette
3182            .register("A", None, &[])
3183            .register("B", None, &[])
3184            .register("C", Some("desc"), &["tag"]);
3185        assert_eq!(palette.action_count(), 3);
3186    }
3187
3188    #[test]
3189    fn register_action_chaining() {
3190        let mut palette = CommandPalette::new();
3191        palette
3192            .register_action(ActionItem::new("a", "A"))
3193            .register_action(ActionItem::new("b", "B"));
3194        assert_eq!(palette.action_count(), 2);
3195    }
3196
3197    #[test]
3198    fn page_up_down_navigation() {
3199        let mut palette = CommandPalette::new().with_max_visible(3);
3200        for i in 0..10 {
3201            palette.register(format!("Action {i}"), None, &[]);
3202        }
3203        palette.open();
3204        assert_eq!(palette.selected_index(), 0);
3205
3206        let pgdn = Event::Key(KeyEvent {
3207            code: KeyCode::PageDown,
3208            modifiers: Modifiers::empty(),
3209            kind: KeyEventKind::Press,
3210        });
3211        let _ = palette.handle_event(&pgdn);
3212        assert_eq!(palette.selected_index(), 3); // 0 + max_visible
3213
3214        let _ = palette.handle_event(&pgdn);
3215        assert_eq!(palette.selected_index(), 6);
3216
3217        let _ = palette.handle_event(&pgdn);
3218        assert_eq!(palette.selected_index(), 9); // clamped to last
3219
3220        let pgup = Event::Key(KeyEvent {
3221            code: KeyCode::PageUp,
3222            modifiers: Modifiers::empty(),
3223            kind: KeyEventKind::Press,
3224        });
3225        let _ = palette.handle_event(&pgup);
3226        assert_eq!(palette.selected_index(), 6); // 9 - 3
3227
3228        let _ = palette.handle_event(&pgup);
3229        assert_eq!(palette.selected_index(), 3);
3230
3231        let _ = palette.handle_event(&pgup);
3232        assert_eq!(palette.selected_index(), 0);
3233    }
3234
3235    #[test]
3236    fn page_down_empty_results_is_noop() {
3237        let mut palette = CommandPalette::new();
3238        palette.open();
3239        assert_eq!(palette.result_count(), 0);
3240
3241        let pgdn = Event::Key(KeyEvent {
3242            code: KeyCode::PageDown,
3243            modifiers: Modifiers::empty(),
3244            kind: KeyEventKind::Press,
3245        });
3246        let _ = palette.handle_event(&pgdn);
3247        assert_eq!(palette.selected_index(), 0);
3248    }
3249
3250    #[test]
3251    fn end_empty_results_is_noop() {
3252        let mut palette = CommandPalette::new();
3253        palette.open();
3254        assert_eq!(palette.result_count(), 0);
3255
3256        let end = Event::Key(KeyEvent {
3257            code: KeyCode::End,
3258            modifiers: Modifiers::empty(),
3259            kind: KeyEventKind::Press,
3260        });
3261        let _ = palette.handle_event(&end);
3262        assert_eq!(palette.selected_index(), 0);
3263    }
3264
3265    #[test]
3266    fn down_empty_results_is_noop() {
3267        let mut palette = CommandPalette::new();
3268        palette.open();
3269        assert_eq!(palette.result_count(), 0);
3270
3271        let down = Event::Key(KeyEvent {
3272            code: KeyCode::Down,
3273            modifiers: Modifiers::empty(),
3274            kind: KeyEventKind::Press,
3275        });
3276        let _ = palette.handle_event(&down);
3277        assert_eq!(palette.selected_index(), 0);
3278    }
3279
3280    #[test]
3281    fn selected_action_none_when_empty() {
3282        let mut palette = CommandPalette::new();
3283        palette.open();
3284        assert!(palette.selected_action().is_none());
3285        assert!(palette.selected_match().is_none());
3286    }
3287
3288    #[test]
3289    fn results_iterator_empty() {
3290        let mut palette = CommandPalette::new();
3291        palette.open();
3292        assert_eq!(palette.results().count(), 0);
3293    }
3294
3295    #[test]
3296    fn scroll_adjust_keeps_selection_visible() {
3297        let mut palette = CommandPalette::new().with_max_visible(3);
3298        for i in 0..10 {
3299            palette.register(format!("Action {i}"), None, &[]);
3300        }
3301        palette.open();
3302
3303        let end = Event::Key(KeyEvent {
3304            code: KeyCode::End,
3305            modifiers: Modifiers::empty(),
3306            kind: KeyEventKind::Press,
3307        });
3308        let _ = palette.handle_event(&end);
3309        assert_eq!(palette.selected_index(), 9);
3310        // scroll_offset should have adjusted so item 9 is visible
3311        // (scroll_offset = selected + 1 - max_visible = 9 + 1 - 3 = 7)
3312
3313        let home = Event::Key(KeyEvent {
3314            code: KeyCode::Home,
3315            modifiers: Modifiers::empty(),
3316            kind: KeyEventKind::Press,
3317        });
3318        let _ = palette.handle_event(&home);
3319        assert_eq!(palette.selected_index(), 0);
3320    }
3321
3322    #[test]
3323    fn update_filtered_clamps_scroll_offset_after_results_shrink() {
3324        let mut palette = CommandPalette::new().with_max_visible(3);
3325        for i in 0..10 {
3326            palette.register(format!("Action {i}"), None, &[]);
3327        }
3328        palette.open();
3329
3330        let end = Event::Key(KeyEvent {
3331            code: KeyCode::End,
3332            modifiers: Modifiers::empty(),
3333            kind: KeyEventKind::Press,
3334        });
3335        let _ = palette.handle_event(&end);
3336        assert!(palette.scroll_offset > 0);
3337
3338        palette.actions.truncate(1);
3339        palette.rebuild_title_cache();
3340        palette.generation = palette.generation.wrapping_add(1);
3341        palette.update_filtered(false);
3342
3343        assert_eq!(palette.result_count(), 1);
3344        assert_eq!(palette.selected, 0);
3345        assert_eq!(palette.scroll_offset, 0);
3346        assert_eq!(
3347            palette
3348                .selected_action()
3349                .map(|action| action.title.as_str()),
3350            Some("Action 0")
3351        );
3352    }
3353
3354    #[test]
3355    fn action_item_clone() {
3356        let item = ActionItem::new("id", "Title")
3357            .with_description("Desc")
3358            .with_tags(&["a", "b"])
3359            .with_category("Cat");
3360        let cloned = item.clone();
3361        assert_eq!(cloned.id, "id");
3362        assert_eq!(cloned.title, "Title");
3363        assert_eq!(cloned.description.as_deref(), Some("Desc"));
3364        assert_eq!(cloned.tags, vec!["a", "b"]);
3365        assert_eq!(cloned.category.as_deref(), Some("Cat"));
3366    }
3367
3368    #[test]
3369    fn action_item_debug() {
3370        let item = ActionItem::new("id", "Title");
3371        let debug = format!("{:?}", item);
3372        assert!(debug.contains("ActionItem"));
3373        assert!(debug.contains("Title"));
3374    }
3375
3376    #[test]
3377    fn palette_action_clone_and_debug() {
3378        let exec = PaletteAction::Execute("test".into());
3379        let cloned = exec.clone();
3380        assert_eq!(exec, cloned);
3381
3382        let dismiss = PaletteAction::Dismiss;
3383        let debug = format!("{:?}", dismiss);
3384        assert!(debug.contains("Dismiss"));
3385    }
3386
3387    #[test]
3388    fn match_filter_traits() {
3389        // Debug
3390        let f = MatchFilter::Fuzzy;
3391        let debug = format!("{:?}", f);
3392        assert!(debug.contains("Fuzzy"));
3393
3394        // Clone + Copy
3395        let f2 = f;
3396        assert_eq!(f, f2);
3397
3398        // PartialEq
3399        assert_eq!(MatchFilter::All, MatchFilter::All);
3400        assert_ne!(MatchFilter::Exact, MatchFilter::Prefix);
3401    }
3402
3403    #[test]
3404    fn match_filter_specific_allows() {
3405        assert!(MatchFilter::Prefix.allows(MatchType::Prefix));
3406        assert!(!MatchFilter::Prefix.allows(MatchType::Exact));
3407        assert!(!MatchFilter::Prefix.allows(MatchType::Substring));
3408
3409        assert!(MatchFilter::WordStart.allows(MatchType::WordStart));
3410        assert!(!MatchFilter::WordStart.allows(MatchType::Fuzzy));
3411
3412        assert!(MatchFilter::Substring.allows(MatchType::Substring));
3413        assert!(!MatchFilter::Substring.allows(MatchType::WordStart));
3414    }
3415
3416    #[test]
3417    fn palette_style_default_has_all_colors() {
3418        let style = PaletteStyle::default();
3419        assert!(style.border.fg.is_some());
3420        assert!(style.input.fg.is_some());
3421        assert!(style.item.fg.is_some());
3422        assert!(style.item_selected.fg.is_some());
3423        assert!(style.item_selected.bg.is_some());
3424        assert!(style.match_highlight.fg.is_some());
3425        assert!(style.description.fg.is_some());
3426        assert!(style.category.fg.is_some());
3427        assert!(style.hint.fg.is_some());
3428    }
3429
3430    #[test]
3431    fn palette_style_debug_and_clone() {
3432        let style = PaletteStyle::default();
3433        let debug = format!("{:?}", style);
3434        assert!(debug.contains("PaletteStyle"));
3435
3436        let cloned = style.clone();
3437        // Verify cloned fields match
3438        assert_eq!(cloned.border.fg, style.border.fg);
3439    }
3440
3441    #[test]
3442    fn with_style_builder() {
3443        let style = PaletteStyle::default();
3444        let palette = CommandPalette::new().with_style(style);
3445        // Should not panic — style applied
3446        assert!(!palette.is_visible());
3447    }
3448
3449    #[test]
3450    fn command_palette_debug() {
3451        let mut palette = CommandPalette::new();
3452        palette.register("Alpha", None, &[]);
3453        let debug = format!("{:?}", palette);
3454        assert!(debug.contains("CommandPalette"));
3455    }
3456
3457    #[test]
3458    fn unrecognized_key_returns_none() {
3459        let mut palette = CommandPalette::new();
3460        palette.open();
3461
3462        let tab = Event::Key(KeyEvent {
3463            code: KeyCode::Tab,
3464            modifiers: Modifiers::empty(),
3465            kind: KeyEventKind::Press,
3466        });
3467        let result = palette.handle_event(&tab);
3468        assert!(result.is_none());
3469    }
3470
3471    #[test]
3472    fn ctrl_p_when_visible_does_not_reopen() {
3473        let mut palette = CommandPalette::new();
3474        palette.register("Alpha", None, &[]);
3475        palette.open();
3476        palette.set_query("test");
3477
3478        // Ctrl+P while visible should be treated as Ctrl+Char('p')
3479        let ctrl_p = Event::Key(KeyEvent {
3480            code: KeyCode::Char('p'),
3481            modifiers: Modifiers::CTRL,
3482            kind: KeyEventKind::Press,
3483        });
3484        let _ = palette.handle_event(&ctrl_p);
3485        // The visible palette handles Ctrl+P as a Ctrl char, not toggling
3486        assert!(palette.is_visible());
3487    }
3488
3489    #[test]
3490    fn close_clears_query_and_results() {
3491        let mut palette = CommandPalette::new();
3492        palette.register("Alpha", None, &[]);
3493        palette.open();
3494        palette.set_query("alpha");
3495        assert!(!palette.query().is_empty());
3496        assert!(palette.result_count() > 0);
3497
3498        palette.close();
3499        assert!(!palette.is_visible());
3500        assert_eq!(palette.query(), "");
3501        assert_eq!(palette.result_count(), 0);
3502    }
3503
3504    #[test]
3505    fn render_cursor_position_set() {
3506        use ftui_render::grapheme_pool::GraphemePool;
3507
3508        let mut palette = CommandPalette::new();
3509        palette.register("Alpha", None, &[]);
3510        palette.open();
3511
3512        let area = Rect::from_size(60, 15);
3513        let mut pool = GraphemePool::new();
3514        let mut frame = Frame::new(60, 15, &mut pool);
3515        palette.render(area, &mut frame);
3516
3517        assert!(frame.cursor_position.is_some());
3518        assert!(frame.cursor_visible);
3519    }
3520
3521    #[test]
3522    fn render_uses_rounded_corners_for_overlay_border() {
3523        use ftui_render::grapheme_pool::GraphemePool;
3524
3525        let mut palette = CommandPalette::new();
3526        palette.register("Alpha", None, &[]);
3527        palette.open();
3528
3529        let area = Rect::from_size(60, 15);
3530        let mut pool = GraphemePool::new();
3531        let mut frame = Frame::new(60, 15, &mut pool);
3532        palette.render(area, &mut frame);
3533
3534        let palette_width = (area.width * 3 / 5).max(30).min(area.width - 2);
3535        let result_rows = palette.result_count().min(palette.max_visible);
3536        let palette_height = (result_rows as u16 + 3)
3537            .max(5)
3538            .min(area.height.saturating_sub(2));
3539        let palette_x = area.x + (area.width.saturating_sub(palette_width)) / 2;
3540        let palette_y = area.y + area.height / 6;
3541        let right = palette_x + palette_width - 1;
3542        let bottom = palette_y + palette_height - 1;
3543
3544        assert_eq!(
3545            frame
3546                .buffer
3547                .get(palette_x, palette_y)
3548                .and_then(|c| c.content.as_char()),
3549            Some('╭')
3550        );
3551        assert_eq!(
3552            frame
3553                .buffer
3554                .get(right, palette_y)
3555                .and_then(|c| c.content.as_char()),
3556            Some('╮')
3557        );
3558        assert_eq!(
3559            frame
3560                .buffer
3561                .get(palette_x, bottom)
3562                .and_then(|c| c.content.as_char()),
3563            Some('╰')
3564        );
3565        assert_eq!(
3566            frame
3567                .buffer
3568                .get(right, bottom)
3569                .and_then(|c| c.content.as_char()),
3570            Some('╯')
3571        );
3572    }
3573
3574    #[test]
3575    fn render_many_items_with_scroll() {
3576        use ftui_render::grapheme_pool::GraphemePool;
3577
3578        let mut palette = CommandPalette::new().with_max_visible(3);
3579        for i in 0..20 {
3580            palette.register(format!("Action {i}"), None, &[]);
3581        }
3582        palette.open();
3583
3584        // Scroll to bottom
3585        let end = Event::Key(KeyEvent {
3586            code: KeyCode::End,
3587            modifiers: Modifiers::empty(),
3588            kind: KeyEventKind::Press,
3589        });
3590        let _ = palette.handle_event(&end);
3591
3592        let area = Rect::from_size(60, 15);
3593        let mut pool = GraphemePool::new();
3594        let mut frame = Frame::new(60, 15, &mut pool);
3595        // Should render without panic even when scrolled
3596        palette.render(area, &mut frame);
3597        assert!(frame.cursor_position.is_some());
3598    }
3599
3600    /// `register(title, description, tags)` and `ActionItem::with_tags` both
3601    /// take tags "for boosting search relevance", and the scorer implements
3602    /// that boost, but the palette never passed tags to it: search ranked by
3603    /// title alone. "Open Alpha" and "Open Bravo" score identically for
3604    /// "open", so without tags registration order puts Alpha first; Bravo's
3605    /// tag must lift it.
3606    #[test]
3607    fn tags_boost_an_action_whose_title_already_matches() {
3608        for filter in [MatchFilter::All, MatchFilter::Prefix] {
3609            let mut palette = CommandPalette::new();
3610            palette.register("Open Alpha", None, &[]);
3611            palette.register("Open Bravo", None, &["opener"]);
3612            palette.set_match_filter(filter);
3613            palette.open();
3614            palette.set_query("open");
3615
3616            let ranked: Vec<&str> = palette
3617                .results()
3618                .map(|found| found.action.title.as_str())
3619                .collect();
3620            assert_eq!(ranked, ["Open Bravo", "Open Alpha"], "{filter:?}");
3621        }
3622    }
3623
3624    /// A tag never creates a match on its own, and an empty query - the
3625    /// unfiltered list - is not reordered by which actions carry tags.
3626    #[test]
3627    fn tags_neither_create_matches_nor_reorder_the_empty_query() {
3628        let mut palette = CommandPalette::new();
3629        palette.register("Save File", None, &[]);
3630        palette.register("Close Tab", None, &["save"]);
3631        palette.open();
3632
3633        palette.set_query("save");
3634        let ranked: Vec<&str> = palette
3635            .results()
3636            .map(|found| found.action.title.as_str())
3637            .collect();
3638        assert_eq!(ranked, ["Save File"], "a tag alone must not match");
3639
3640        palette.set_query("");
3641        let ranked: Vec<&str> = palette
3642            .results()
3643            .map(|found| found.action.title.as_str())
3644            .collect();
3645        assert_eq!(ranked, ["Save File", "Close Tab"], "registration order");
3646    }
3647}
3648mod property_tests;