ailloli_ui_widgets/controls/
command_palette.rs

1//! Full-slot command palette overlay with editable filtering and keyboard navigation.
2
3use std::{cell::Cell, rc::Rc};
4
5use crate::layout::layout_ext::{apply_layout_size, finish_view_sized};
6use crate::transactional_layout::TransactionalLayoutPending;
7use ailloli_ui_core::event::pointer::{MouseButton, PointerEvent};
8use ailloli_ui_core::event::{Event, Key, KeyState, NamedKey, WheelDelta};
9use ailloli_ui_core::geometry::{Constraints, Rect, Size};
10use ailloli_ui_core::scroll::{ScrollAxes, ScrollBehavior, ScrollMetrics, ScrollState};
11use ailloli_ui_core::style::{
12    Border, BoxShadow, FlexItemStyle, LayoutSizeHint, LayoutStyle, Radius,
13};
14use ailloli_ui_core::{Color, FontId, IconId, Offset, TextStyle, Theme};
15use ailloli_ui_runtime::app::Invalidation;
16use ailloli_ui_runtime::component::reactive::with_untracked_reads;
17use ailloli_ui_runtime::component::{
18    Binding, ComponentNode, Context, IntoView, Signal, View, Widget,
19};
20use ailloli_ui_runtime::input::{ClickAction, EventCtx, FocusPolicy, InputRole, IntoClickAction};
21use ailloli_ui_runtime::layout::{
22    ChildLayout, LayoutArtifact, LayoutChild, LayoutCtx, LayoutPass, LayoutResult,
23};
24use ailloli_ui_runtime::scene::PaintCtx;
25use ailloli_ui_runtime::{
26    DrawBorder, DrawBoxShadow, DrawCmd, DrawImage, DrawRRect, DrawRect, DrawText,
27};
28use ailloli_ui_text::{TextBuffer, TextEditState};
29
30use super::popup::{
31    apply_opacity, measure_text, paint_overlay_text_in_rect, paint_popup_border, paint_popup_shell,
32};
33use super::select::{SelectSize, SelectStyle};
34use super::text_field_core::{
35    display_text_for_edit, handle_single_line_text_event, ime_cursor_rect, layout_single_line_text,
36    read_display_buffer, text_input_content_rect, TextFieldEventOptions,
37};
38use super::text_input::TextInputStyle;
39
40#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
41/// Built-in density choices for a [`CommandPalette`].
42///
43/// # Examples
44///
45/// ```
46/// use ailloli_ui_widgets::controls::CommandPaletteSize;
47/// assert_eq!(CommandPaletteSize::default(), CommandPaletteSize::Default);
48/// ```
49pub enum CommandPaletteSize {
50    /// 430-pixel panel target with 34-pixel input and 38-pixel rows.
51    Compact,
52    /// 520-pixel panel target with 40-pixel input and 44-pixel rows.
53    #[default]
54    Default,
55}
56
57#[derive(Clone, Debug)]
58/// Resolved nested styles, colors, typography, and logical-pixel geometry.
59///
60/// [`Self::popup`] owns the actual panel shell fill/border. The separate
61/// `panel_background` and `border` fields are retained for compatibility but are
62/// not currently read by the painter. `radius` is used for panel shadows while
63/// the popup style owns shell radius.
64///
65/// # Examples
66///
67/// ```
68/// use ailloli_ui_core::Theme;
69/// use ailloli_ui_widgets::controls::{CommandPaletteSize, CommandPaletteStyle};
70/// let style = CommandPaletteStyle::from_theme(Theme::dark(), CommandPaletteSize::Compact);
71/// assert_eq!(style.width, 430.0);
72/// assert_eq!(style.row_height, 38.0);
73/// ```
74pub struct CommandPaletteStyle {
75    /// Single-line query input style.
76    pub input: TextInputStyle,
77    /// Panel shell and active-row style.
78    pub popup: SelectStyle,
79    /// Full-host overlay fill.
80    pub backdrop: Color,
81    /// Reserved panel fill; current shell uses `popup.background`.
82    pub panel_background: Color,
83    /// Reserved panel border; current shell uses `popup.border`.
84    pub border: Border,
85    /// Panel shadows; inset entries are skipped.
86    pub shadows: Vec<BoxShadow>,
87    /// Command title text style.
88    pub title_text: TextStyle,
89    /// Optional command subtitle style.
90    pub subtitle_text: TextStyle,
91    /// Right-aligned shortcut hint style.
92    pub shortcut_text: TextStyle,
93    /// Empty-filter-result message style.
94    pub no_results_text: TextStyle,
95    /// Leading command icon tint.
96    pub icon_tint: Color,
97    /// Alpha multiplier used for disabled items and empty-result text.
98    pub disabled_opacity: f32,
99    /// Preferred panel width and nested popup width.
100    pub width: f32,
101    /// Query input height.
102    pub input_height: f32,
103    /// Command row and scroll-line height; callers should keep it positive.
104    pub row_height: f32,
105    /// Maximum complete panel height.
106    pub panel_max_height: f32,
107    /// Preferred distance from the host's top edge.
108    pub panel_top: f32,
109    /// Panel/input/row horizontal inset.
110    pub padding: f32,
111    /// Gap after leading icons and before shortcut hints.
112    pub gap: f32,
113    /// Leading icon width and height.
114    pub icon_size: f32,
115    /// Radius used for panel shadow bounds.
116    pub radius: Radius,
117}
118
119impl Default for CommandPaletteStyle {
120    fn default() -> Self {
121        Self::from_theme(Theme::default(), CommandPaletteSize::Default)
122    }
123}
124
125impl CommandPaletteStyle {
126    /// Resolves nested input/popup styles and palette geometry from theme/size.
127    ///
128    /// Both built-in sizes cap the list viewport at 260 logical pixels and the
129    /// whole panel at 360 logical pixels.
130    ///
131    /// # Examples
132    ///
133    /// ```
134    /// use ailloli_ui_core::Theme;
135    /// use ailloli_ui_widgets::controls::{CommandPaletteSize, CommandPaletteStyle};
136    /// let style = CommandPaletteStyle::from_theme(Theme::dark(), CommandPaletteSize::Default);
137    /// assert_eq!((style.width, style.input_height), (520.0, 40.0));
138    /// assert_eq!(style.panel_max_height, 360.0);
139    /// ```
140    pub fn from_theme(theme: Theme, size: CommandPaletteSize) -> Self {
141        let palette = theme.palette();
142        let popup = SelectStyle::from_theme(
143            theme,
144            match size {
145                CommandPaletteSize::Compact => SelectSize::Compact,
146                CommandPaletteSize::Default => SelectSize::Default,
147            },
148        );
149        let (width, input_height, row_height, panel_top, padding, text_size) = match size {
150            CommandPaletteSize::Compact => (430.0, 34.0, 38.0, 52.0, 10.0, 12),
151            CommandPaletteSize::Default => (520.0, 40.0, 44.0, 72.0, 12.0, 13),
152        };
153        let mut input = TextInputStyle::from_theme(theme);
154        input.bg = palette.surface;
155        input.border = palette.border;
156        input.border_focused = palette.focus;
157        input.placeholder = palette.text_muted;
158        input.text = TextStyle::new(FontId::Ui, text_size, palette.text);
159        input.pad_x = padding;
160        input.pad_y = ((input_height - input.text.px_size as f32 * 1.2) * 0.5).max(4.0);
161
162        Self {
163            input,
164            popup: SelectStyle {
165                width,
166                height: input_height,
167                option_height: row_height,
168                popup_max_height: 260.0,
169                radius: Radius::uniform(theme.radius().lg),
170                ..popup
171            },
172            backdrop: Color::BLACK.with_alpha(0.32),
173            panel_background: palette.surface_elevated,
174            border: Border::new(1.0, palette.border),
175            shadows: vec![theme.shadows().lg],
176            title_text: TextStyle::new(FontId::Ui, text_size, palette.text),
177            subtitle_text: TextStyle::new(FontId::Ui, 11, palette.text_muted),
178            shortcut_text: TextStyle::new(FontId::Mono, 11, palette.text_muted),
179            no_results_text: TextStyle::new(FontId::Ui, text_size, palette.text_muted),
180            icon_tint: palette.text_muted,
181            disabled_opacity: 0.45,
182            width,
183            input_height,
184            row_height,
185            panel_max_height: 360.0,
186            panel_top,
187            padding,
188            gap: 8.0,
189            icon_size: 16.0,
190            radius: Radius::uniform(theme.radius().lg),
191        }
192    }
193}
194
195/// One searchable command row with an optional action.
196///
197/// Filtering checks trimmed ASCII-lowercased query substrings against title,
198/// subtitle, and keywords. Shortcut hints are not searchable. Disabled commands
199/// remain visible but keyboard navigation skips them and activation is consumed
200/// without closing. Enabled commands close the palette even without an action.
201///
202/// # Examples
203///
204/// ```
205/// use ailloli_ui_widgets::controls::CommandItem;
206/// let item: CommandItem<()> = CommandItem::new("Open file").keyword("search");
207/// let _ = item;
208/// ```
209pub struct CommandItem<A = ()> {
210    /// Primary searchable title.
211    title: String,
212    /// Optional searchable subtitle; `Some("")` still selects two-line geometry.
213    subtitle: Option<String>,
214    /// Optional non-searchable right-aligned hint.
215    shortcut: Option<String>,
216    /// Additional searchable strings; duplicates and empties are retained.
217    keywords: Vec<String>,
218    /// Optional leading icon.
219    icon: Option<IconId>,
220    /// Live disabled state.
221    disabled: Binding<bool>,
222    /// Optional action run before the palette closes.
223    action: Option<Rc<ClickAction<A>>>,
224}
225
226impl<A> Clone for CommandItem<A> {
227    fn clone(&self) -> Self {
228        Self {
229            title: self.title.clone(),
230            subtitle: self.subtitle.clone(),
231            shortcut: self.shortcut.clone(),
232            keywords: self.keywords.clone(),
233            icon: self.icon.clone(),
234            disabled: self.disabled.clone(),
235            action: self.action.clone(),
236        }
237    }
238}
239
240impl<A: 'static> CommandItem<A> {
241    /// Creates an enabled command with no optional metadata or action.
242    ///
243    /// # Examples
244    ///
245    /// ```
246    /// use ailloli_ui_widgets::controls::CommandItem;
247    /// let item: CommandItem<()> = CommandItem::new("Open file");
248    /// let _ = item;
249    /// ```
250    pub fn new(title: impl Into<String>) -> Self {
251        Self {
252            title: title.into(),
253            subtitle: None,
254            shortcut: None,
255            keywords: Vec::new(),
256            icon: None,
257            disabled: Binding::Static(false),
258            action: None,
259        }
260    }
261
262    /// Sets a searchable subtitle, replacing any previous value.
263    ///
264    /// Empty text remains present and selects the two-line row layout.
265    ///
266    /// # Examples
267    ///
268    /// ```
269    /// use ailloli_ui_widgets::controls::CommandItem;
270    /// let item: CommandItem<()> = CommandItem::new("Theme").subtitle("Change appearance");
271    /// let _ = item;
272    /// ```
273    pub fn subtitle(mut self, subtitle: impl Into<String>) -> Self {
274        self.subtitle = Some(subtitle.into());
275        self
276    }
277
278    /// Sets a non-searchable shortcut hint, replacing any previous value.
279    ///
280    /// # Examples
281    ///
282    /// ```
283    /// use ailloli_ui_widgets::controls::CommandItem;
284    /// let item: CommandItem<()> = CommandItem::new("Open").shortcut("Ctrl+O");
285    /// let _ = item;
286    /// ```
287    pub fn shortcut(mut self, shortcut: impl Into<String>) -> Self {
288        self.shortcut = Some(shortcut.into());
289        self
290    }
291
292    /// Appends one searchable keyword without normalization or de-duplication.
293    ///
294    /// # Examples
295    ///
296    /// ```
297    /// use ailloli_ui_widgets::controls::CommandItem;
298    /// let item: CommandItem<()> = CommandItem::new("Preferences").keyword("settings");
299    /// let _ = item;
300    /// ```
301    pub fn keyword(mut self, keyword: impl Into<String>) -> Self {
302        self.keywords.push(keyword.into());
303        self
304    }
305
306    /// Appends searchable keywords in iterator order.
307    ///
308    /// Existing keywords remain, and duplicates/empty strings are retained.
309    ///
310    /// # Examples
311    ///
312    /// ```
313    /// use ailloli_ui_widgets::controls::CommandItem;
314    /// let item: CommandItem<()> = CommandItem::new("Preferences")
315    ///     .keywords(["settings", "configuration"]);
316    /// let _ = item;
317    /// ```
318    pub fn keywords(mut self, keywords: impl IntoIterator<Item = impl Into<String>>) -> Self {
319        self.keywords.extend(keywords.into_iter().map(Into::into));
320        self
321    }
322
323    /// Sets the leading icon, replacing any previous icon.
324    ///
325    /// # Examples
326    ///
327    /// ```
328    /// use ailloli_ui_core::IconId;
329    /// use ailloli_ui_widgets::controls::CommandItem;
330    /// let item: CommandItem<()> = CommandItem::new("History").leading_icon(IconId::History);
331    /// let _ = item;
332    /// ```
333    pub fn leading_icon(mut self, icon: IconId) -> Self {
334        self.icon = Some(icon);
335        self
336    }
337
338    /// Sets static or reactive disabled state.
339    ///
340    /// Disabled commands remain searchable and visible but are skipped by
341    /// navigation and cannot run or close the palette.
342    ///
343    /// # Examples
344    ///
345    /// ```
346    /// use ailloli_ui_widgets::controls::CommandItem;
347    /// let item: CommandItem<()> = CommandItem::new("Unavailable").disabled(true);
348    /// let _ = item;
349    /// ```
350    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
351        self.disabled = disabled.into();
352        self
353    }
354
355    /// Installs the action run when this enabled command activates.
356    ///
357    /// A later call replaces it. Enabled activation closes even when no action
358    /// is installed.
359    ///
360    /// # Examples
361    ///
362    /// ```
363    /// use ailloli_ui_widgets::controls::CommandItem;
364    /// #[derive(Clone)]
365    /// enum Action { Open }
366    /// let item = CommandItem::new("Open").on_select(Action::Open);
367    /// let _ = item;
368    /// ```
369    pub fn on_select(mut self, action: impl IntoClickAction<A>) -> Self {
370        self.action = Some(Rc::new(action.into_click_action()));
371        self
372    }
373}
374
375/// A searchable modal command overlay over one optional host child.
376///
377/// Visibility supports controlled, writable-bound, and internal modes. Query
378/// state supports writable-bound or internal modes. Escape, blur, outside click,
379/// and enabled command activation request close. Controlled visibility requires
380/// the consumer to update its binding. Arrow/Home/End navigation wraps/skips
381/// disabled items. Space is reserved for activation, so it is not inserted into
382/// the query by the keyboard handler.
383///
384/// # Examples
385///
386/// ```
387/// use ailloli_ui_widgets::controls::{CommandItem, CommandPalette};
388/// let palette = CommandPalette::<()>::new()
389///     .item(CommandItem::new("Open file"))
390///     .default_open(true);
391/// let _ = palette;
392/// ```
393pub struct CommandPalette<A = ()> {
394    /// Layout configuration for the full host slot.
395    pub(crate) layout: LayoutStyle,
396    /// Flex-item behavior used by the parent layout.
397    pub(crate) flex_item: FlexItemStyle,
398    /// Optional controlled or bound visibility.
399    open: Option<Binding<bool>>,
400    /// Writable visibility signal in bound mode.
401    bound_open: Option<Signal<bool>>,
402    /// Initial internal visibility used without external state.
403    default_open: bool,
404    /// Optional writable external query signal.
405    query: Option<Signal<String>>,
406    /// Initial internal query used without a signal.
407    default_query: String,
408    /// Live placeholder displayed for an empty query.
409    placeholder: Binding<String>,
410    /// Live disabled state; disabled open palettes are hidden but remain open.
411    disabled: Binding<bool>,
412    /// Command values in insertion order; no capacity bound.
413    items: Vec<CommandItem<A>>,
414    /// Resolved paint and geometry.
415    style: CommandPaletteStyle,
416    /// Optional sole host child painted under the overlay.
417    child: Option<View<A>>,
418}
419
420crate::impl_layout_builders!(CommandPalette);
421
422impl<A: 'static> Default for CommandPalette<A> {
423    fn default() -> Self {
424        Self::new()
425    }
426}
427
428impl<A: 'static> CommandPalette<A> {
429    /// Creates a closed, enabled palette with an empty internal query.
430    ///
431    /// Its default placeholder is `"Type a command..."`; it has no items or child.
432    ///
433    /// # Examples
434    ///
435    /// ```
436    /// use ailloli_ui_widgets::controls::CommandPalette;
437    /// let palette: CommandPalette<()> = CommandPalette::new();
438    /// let _ = palette;
439    /// ```
440    pub fn new() -> Self {
441        Self {
442            layout: LayoutStyle::default(),
443            flex_item: FlexItemStyle::default(),
444            open: None,
445            bound_open: None,
446            default_open: false,
447            query: None,
448            default_query: String::new(),
449            placeholder: Binding::Static("Type a command...".to_string()),
450            disabled: Binding::Static(false),
451            items: Vec::new(),
452            style: CommandPaletteStyle::default(),
453            child: None,
454        }
455    }
456
457    /// Sets controlled static or reactive visibility and clears bound mode.
458    ///
459    /// Close paths reset active selection but cannot mutate this source.
460    ///
461    /// # Examples
462    ///
463    /// ```
464    /// use ailloli_ui_widgets::controls::CommandPalette;
465    /// let palette: CommandPalette<()> = CommandPalette::new().open(true);
466    /// let _ = palette;
467    /// ```
468    pub fn open(mut self, open: impl Into<Binding<bool>>) -> Self {
469        self.open = Some(open.into());
470        self.bound_open = None;
471        self
472    }
473
474    /// Installs a writable signal for two-way close behavior.
475    ///
476    /// # Examples
477    ///
478    /// ```
479    /// use std::{cell::RefCell, rc::Rc};
480    /// use ailloli_ui_runtime::component::Signal;
481    /// use ailloli_ui_widgets::controls::CommandPalette;
482    /// let open = Signal::new(Rc::new(RefCell::new(true)), Rc::new(|| {}));
483    /// let palette: CommandPalette<()> = CommandPalette::new().bind_open(open);
484    /// let _ = palette;
485    /// ```
486    pub fn bind_open(mut self, open: impl Into<Signal<bool>>) -> Self {
487        let signal = open.into();
488        self.open = Some(Binding::Signal(signal.clone()));
489        self.bound_open = Some(signal);
490        self
491    }
492
493    /// Sets initial internal visibility when no external source exists.
494    ///
495    /// It initializes retained state on first build rather than acting as a
496    /// recurring reopen command.
497    ///
498    /// # Examples
499    ///
500    /// ```
501    /// use ailloli_ui_widgets::controls::CommandPalette;
502    /// let palette: CommandPalette<()> = CommandPalette::new().default_open(true);
503    /// let _ = palette;
504    /// ```
505    pub fn default_open(mut self, open: bool) -> Self {
506        self.default_open = open;
507        self
508    }
509
510    /// Installs the writable signal edited by text and IME events.
511    ///
512    /// The current value initializes the persistent text buffer/caret on first
513    /// build and overrides [`Self::default_query`].
514    ///
515    /// # Examples
516    ///
517    /// ```
518    /// use std::{cell::RefCell, rc::Rc};
519    /// use ailloli_ui_runtime::component::Signal;
520    /// use ailloli_ui_widgets::controls::CommandPalette;
521    /// let query = Signal::new(Rc::new(RefCell::new("open".to_string())), Rc::new(|| {}));
522    /// let palette: CommandPalette<()> = CommandPalette::new().bind_query(query);
523    /// let _ = palette;
524    /// ```
525    pub fn bind_query(mut self, query: impl Into<Signal<String>>) -> Self {
526        self.query = Some(query.into());
527        self
528    }
529
530    /// Sets the initial internal query used when no query signal is bound.
531    ///
532    /// # Examples
533    ///
534    /// ```
535    /// use ailloli_ui_widgets::controls::CommandPalette;
536    /// let palette: CommandPalette<()> = CommandPalette::new().default_query("file");
537    /// let _ = palette;
538    /// ```
539    pub fn default_query(mut self, query: impl Into<String>) -> Self {
540        self.default_query = query.into();
541        self
542    }
543
544    /// Sets static or reactive query placeholder text.
545    ///
546    /// Empty placeholder is valid and paints no glyphs.
547    ///
548    /// # Examples
549    ///
550    /// ```
551    /// use ailloli_ui_widgets::controls::CommandPalette;
552    /// let palette: CommandPalette<()> = CommandPalette::new().placeholder("Search commands");
553    /// let _ = palette;
554    /// ```
555    pub fn placeholder(mut self, placeholder: impl Into<Binding<String>>) -> Self {
556        self.placeholder = placeholder.into();
557        self
558    }
559
560    /// Sets static or reactive disabled state.
561    ///
562    /// Disabled state hides overlay/hit bounds and removes focus/input role
563    /// without closing or clearing query/open state.
564    ///
565    /// # Examples
566    ///
567    /// ```
568    /// use ailloli_ui_widgets::controls::CommandPalette;
569    /// let palette: CommandPalette<()> = CommandPalette::new().open(true).disabled(true);
570    /// let _ = palette;
571    /// ```
572    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
573        self.disabled = disabled.into();
574        self
575    }
576
577    /// Appends one command in filter/display order.
578    ///
579    /// # Examples
580    ///
581    /// ```
582    /// use ailloli_ui_widgets::controls::{CommandItem, CommandPalette};
583    /// let palette = CommandPalette::<()>::new().item(CommandItem::new("Open"));
584    /// let _ = palette;
585    /// ```
586    pub fn item(mut self, item: CommandItem<A>) -> Self {
587        self.items.push(item);
588        self
589    }
590
591    /// Replaces complete palette style and geometry.
592    ///
593    /// Callers should keep `row_height` positive for hit testing and scrolling.
594    ///
595    /// # Examples
596    ///
597    /// ```
598    /// use ailloli_ui_core::Theme;
599    /// use ailloli_ui_widgets::controls::{CommandPalette, CommandPaletteSize, CommandPaletteStyle};
600    /// let style = CommandPaletteStyle::from_theme(Theme::dark(), CommandPaletteSize::Compact);
601    /// let palette: CommandPalette<()> = CommandPalette::new().command_style(style);
602    /// let _ = palette;
603    /// ```
604    pub fn command_style(mut self, style: CommandPaletteStyle) -> Self {
605        self.style = style;
606        self
607    }
608
609    /// Replaces complete style with the default-theme built-in size.
610    ///
611    /// # Examples
612    ///
613    /// ```
614    /// use ailloli_ui_widgets::controls::{CommandPalette, CommandPaletteSize};
615    /// let palette: CommandPalette<()> =
616    ///     CommandPalette::new().command_size(CommandPaletteSize::Compact);
617    /// let _ = palette;
618    /// ```
619    pub fn command_size(mut self, size: CommandPaletteSize) -> Self {
620        self.style = CommandPaletteStyle::from_theme(Theme::default(), size);
621        self
622    }
623
624    /// Sets the sole underlying host child, replacing any previous child.
625    ///
626    /// # Examples
627    ///
628    /// ```
629    /// use ailloli_ui_widgets::controls::CommandPalette;
630    /// use ailloli_ui_widgets::text::Text;
631    /// let palette = CommandPalette::<()>::new().child(Text::new("Workspace"));
632    /// let _ = palette;
633    /// ```
634    pub fn child(mut self, child: impl IntoView<A>) -> Self {
635        self.child = Some(child.into_view());
636        self
637    }
638}
639
640/// Component properties used to allocate query/edit/navigation/scroll state.
641struct CommandPaletteComponent<A> {
642    /// Host-slot sizing and flex layout policy.
643    layout: LayoutStyle,
644    /// Optional readable external open state.
645    open: Option<Binding<bool>>,
646    /// Optional writable external open state.
647    bound_open: Option<Signal<bool>>,
648    /// Initial open state used when the component is uncontrolled.
649    default_open: bool,
650    /// Optional caller-owned query state.
651    query: Option<Signal<String>>,
652    /// Initial query used when the component owns its state.
653    default_query: String,
654    /// Reactive placeholder displayed for an empty query.
655    placeholder: Binding<String>,
656    /// Reactive interaction-disable flag.
657    disabled: Binding<bool>,
658    /// Ordered command catalogue filtered by the query.
659    items: Vec<CommandItem<A>>,
660    /// Visual and geometric palette configuration in logical pixels.
661    style: CommandPaletteStyle,
662    /// Optional underlying host content painted below the overlay.
663    child: Option<View<A>>,
664}
665
666impl<A: 'static> ComponentNode<A> for CommandPaletteComponent<A> {
667    fn build(&self, context: &mut Context<A>) -> View<A> {
668        let query = self
669            .query
670            .clone()
671            .unwrap_or_else(|| context.signal(self.default_query.clone()));
672        let current = query.read();
673        let mut children = Vec::new();
674        if let Some(child) = self.child.clone() {
675            children.push(child);
676        }
677        View::node(
678            CommandPaletteWidget {
679                layout: self.layout,
680                open: self.open.clone(),
681                bound_open: self.bound_open.clone(),
682                internal_open: context.signal(self.default_open),
683                query: query.clone(),
684                placeholder: self.placeholder.clone(),
685                disabled: self.disabled.clone(),
686                items: self.items.clone(),
687                style: self.style.clone(),
688                scroll: context.signal_with_invalidation(ScrollState::new(), Invalidation::Paint),
689                active_index: context.signal(None),
690                buffer: context.signal(TextBuffer::from_string(current.clone())),
691                edit: context.signal(edit_at_end(&current)),
692                pending_scroll: Cell::new(None),
693            },
694            children,
695        )
696    }
697}
698
699impl<A: 'static> IntoView<A> for CommandPalette<A> {
700    fn into_view(self) -> View<A> {
701        finish_view_sized(
702            View::component(CommandPaletteComponent {
703                layout: self.layout,
704                open: self.open,
705                bound_open: self.bound_open,
706                default_open: self.default_open,
707                query: self.query,
708                default_query: self.default_query,
709                placeholder: self.placeholder,
710                disabled: self.disabled,
711                items: self.items,
712                style: self.style,
713                child: self.child,
714            }),
715            self.flex_item,
716            LayoutSizeHint::from_layout(self.layout),
717        )
718    }
719}
720
721/// Retained overlay widget implementing text input, filtering, and activation.
722struct CommandPaletteWidget<A> {
723    /// Host-slot sizing and flex layout policy.
724    layout: LayoutStyle,
725    /// Optional readable external open state.
726    open: Option<Binding<bool>>,
727    /// Optional writable external open state.
728    bound_open: Option<Signal<bool>>,
729    /// Retained open state used by an uncontrolled palette.
730    internal_open: Signal<bool>,
731    /// Retained query shared with text editing and filtering.
732    query: Signal<String>,
733    /// Reactive placeholder displayed for an empty query.
734    placeholder: Binding<String>,
735    /// Reactive interaction-disable flag.
736    disabled: Binding<bool>,
737    /// Ordered command catalogue addressed by stable vector indices.
738    items: Vec<CommandItem<A>>,
739    /// Visual and geometric palette configuration in logical pixels.
740    style: CommandPaletteStyle,
741    /// Retained vertical list offset in logical pixels.
742    scroll: Signal<ScrollState>,
743    /// Selected command index in the unfiltered `items` vector.
744    active_index: Signal<Option<usize>>,
745    /// Text buffer mirroring the current query.
746    buffer: Signal<TextBuffer>,
747    /// Caret and selection state for single-line query editing.
748    edit: Signal<TextEditState>,
749    /// Scroll clamp staged for the exact authoritative layout attempt.
750    pending_scroll: Cell<Option<TransactionalLayoutPending<Option<ScrollState>>>>,
751}
752
753impl<A: 'static> Widget<A> for CommandPaletteWidget<A> {
754    fn debug_name(&self) -> &'static str {
755        "CommandPalette"
756    }
757
758    fn layout(
759        &self,
760        engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
761        ctx: &mut LayoutCtx<'_>,
762        children: &mut [LayoutChild],
763        constraints: Constraints,
764    ) -> LayoutResult {
765        let size = host_slot_size(engine, ctx, children, constraints, self.layout);
766        let mut child_layouts = Vec::new();
767        if let Some(child) = children.first_mut() {
768            let r = ctx.with_layout_pass(LayoutPass::Commit, |ctx| {
769                child.layout(engine, ctx, Constraints::tight(size.w, size.h))
770            });
771            child_layouts.push(ChildLayout {
772                offset: Offset::default(),
773                size: r.size,
774                paint_bounds: Rect::new(0.0, 0.0, r.size.w, r.size.h),
775                visual_bounds: r.visual_bounds,
776            });
777        }
778
779        let (_, text_layout) = layout_single_line_text(
780            ctx,
781            Constraints::loose(self.style.width, self.style.input_height),
782            LayoutStyle::default()
783                .width(self.style.width)
784                .height(self.style.input_height),
785            &self.query,
786            &self.buffer,
787            &self.edit,
788            Some(self.placeholder.read()),
789            self.text_style(),
790        );
791
792        let paint_bounds = Rect::new(0.0, 0.0, size.w, size.h);
793        let overlay_hit_bounds = if self.is_open() && !self.disabled.read() {
794            vec![paint_bounds]
795        } else {
796            Vec::new()
797        };
798        if ctx.layout_pass().is_committed() {
799            let state = (self.is_open() && !self.disabled.read())
800                .then(|| self.clamped_scroll(self.list_rect_for_size(size).size()))
801                .flatten();
802            self.pending_scroll
803                .set(TransactionalLayoutPending::new(ctx, state));
804        }
805
806        LayoutResult {
807            size,
808            children: child_layouts,
809            paint_bounds,
810            visual_bounds: paint_bounds,
811            overlay_hit_bounds,
812            clip: None,
813            is_window_root_clip: false,
814            artifact: text_layout.map(LayoutArtifact::Text),
815        }
816    }
817
818    fn paint(&self, _ctx: &mut PaintCtx<'_>, _bounds: Rect, _layout: &LayoutResult) {}
819
820    /// Publishes only the clamp computed by this exact successful attempt.
821    fn layout_committed(&self, ctx: &mut LayoutCtx<'_>, _bounds: Rect, _layout: &LayoutResult) {
822        if let Some(state) = self
823            .pending_scroll
824            .take()
825            .and_then(|pending| pending.into_committed(ctx))
826            .flatten()
827        {
828            self.scroll.set(state);
829        }
830    }
831
832    fn paint_overlay(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, layout: &LayoutResult) {
833        if !self.is_open() || self.disabled.read() {
834            return;
835        }
836        self.paint_palette(ctx, bounds, layout);
837    }
838
839    fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, layout: &LayoutResult) {
840        if !self.is_open() || self.disabled.read() {
841            return;
842        }
843
844        match event {
845            Event::Focus(focus) if !focus.focused => {
846                self.close();
847                ctx.request_repaint();
848            }
849            Event::Pointer(PointerEvent::Button {
850                pos,
851                button: MouseButton::Left,
852                pressed,
853                ..
854            }) if self.input_rect(bounds).contains(pos.x, pos.y) => {
855                let _ = handle_single_line_text_event(
856                    ctx,
857                    event,
858                    self.input_rect(bounds),
859                    layout,
860                    &self.query,
861                    &self.buffer,
862                    &self.edit,
863                    self.text_style(),
864                    TextFieldEventOptions {
865                        consume_handled_events: true,
866                    },
867                );
868                if *pressed {
869                    self.active_index.set(self.first_enabled_index());
870                }
871                ctx.request_repaint();
872                ctx.stop_propagation();
873            }
874            Event::Pointer(PointerEvent::Moved { .. }) => {
875                let _ = handle_single_line_text_event(
876                    ctx,
877                    event,
878                    self.input_rect(bounds),
879                    layout,
880                    &self.query,
881                    &self.buffer,
882                    &self.edit,
883                    self.text_style(),
884                    TextFieldEventOptions {
885                        consume_handled_events: true,
886                    },
887                );
888            }
889            Event::Pointer(PointerEvent::Button {
890                pos,
891                button: MouseButton::Left,
892                pressed: false,
893                ..
894            }) if self.list_rect(bounds).contains(pos.x, pos.y) => {
895                if let Some(index) = self.item_at(bounds, *pos) {
896                    self.activate_item(ctx, index);
897                } else {
898                    ctx.stop_propagation();
899                }
900            }
901            Event::Pointer(PointerEvent::Button {
902                pos,
903                button: MouseButton::Left,
904                pressed: false,
905                ..
906            }) if !self.panel_rect(bounds).contains(pos.x, pos.y) => {
907                self.close();
908                ctx.request_repaint();
909                ctx.stop_propagation();
910            }
911            Event::Pointer(PointerEvent::Wheel {
912                pos,
913                delta,
914                modifiers,
915                ..
916            }) if self.list_rect(bounds).contains(pos.x, pos.y) => {
917                self.scroll_list(ctx, bounds, *delta, *modifiers);
918            }
919            Event::Keyboard(key) if key.state == KeyState::Pressed => {
920                self.handle_keyboard(ctx, &key.key, event, bounds, layout);
921            }
922            Event::Ime(_) => {
923                let before = self.query.read();
924                let handled = handle_single_line_text_event(
925                    ctx,
926                    event,
927                    self.input_rect(bounds),
928                    layout,
929                    &self.query,
930                    &self.buffer,
931                    &self.edit,
932                    self.text_style(),
933                    TextFieldEventOptions {
934                        consume_handled_events: true,
935                    },
936                );
937                self.after_text_event(ctx, before, handled);
938            }
939            _ => {}
940        }
941    }
942
943    fn focus_policy(&self) -> FocusPolicy {
944        if self.is_open() && !self.disabled.read() {
945            FocusPolicy::Focusable
946        } else {
947            FocusPolicy::NotFocusable
948        }
949    }
950
951    fn input_role(&self) -> InputRole {
952        if self.is_open() && !self.disabled.read() {
953            InputRole::TextSingleLine
954        } else {
955            InputRole::None
956        }
957    }
958
959    fn ime_cursor_rect(&self, bounds: Rect, layout: &LayoutResult) -> Option<Rect> {
960        if !self.is_open() || self.disabled.read() {
961            return None;
962        }
963        ime_cursor_rect(
964            self.input_rect(bounds),
965            layout,
966            &self.query,
967            &self.buffer,
968            &self.edit,
969            self.text_style(),
970        )
971    }
972}
973
974impl<A: 'static> CommandPaletteWidget<A> {
975    /// Reads controlled state when present, otherwise the retained local state.
976    fn is_open(&self) -> bool {
977        self.open
978            .as_ref()
979            .map(Binding::read)
980            .unwrap_or_else(|| self.internal_open.read())
981    }
982
983    /// Closes writable or uncontrolled state and clears keyboard selection.
984    fn close(&self) {
985        if let Some(bound) = &self.bound_open {
986            bound.set(false);
987        } else if self.open.is_none() {
988            self.internal_open.set(false);
989        }
990        self.active_index.set(None);
991    }
992
993    /// Resolves input colors, applying disabled opacity when necessary.
994    fn text_style(&self) -> TextInputStyle {
995        if self.disabled.read() {
996            let opacity = self.style.disabled_opacity;
997            let mut input = self.style.input;
998            input.bg = apply_opacity(input.bg, opacity);
999            input.border = apply_opacity(input.border, opacity);
1000            input.border_focused = apply_opacity(input.border_focused, opacity);
1001            input.placeholder = apply_opacity(input.placeholder, opacity);
1002            input.text.color = apply_opacity(input.text.color, opacity);
1003            input
1004        } else {
1005            self.style.input
1006        }
1007    }
1008
1009    /// Computes the centered, host-clamped overlay panel in logical pixels.
1010    fn panel_rect(&self, bounds: Rect) -> Rect {
1011        let width = self.style.width.min((bounds.w - 32.0).max(240.0));
1012        let height = self.panel_height();
1013        Rect::new(
1014            bounds.x + (bounds.w - width) * 0.5,
1015            bounds.y + self.style.panel_top.min((bounds.h - height).max(12.0)),
1016            width,
1017            height.min((bounds.h - 24.0).max(self.style.input_height + 8.0)),
1018        )
1019    }
1020
1021    /// Computes the query field inside the current panel bounds.
1022    fn input_rect(&self, bounds: Rect) -> Rect {
1023        let panel = self.panel_rect(bounds);
1024        Rect::new(
1025            panel.x + self.style.padding,
1026            panel.y + self.style.padding,
1027            (panel.w - self.style.padding * 2.0).max(0.0),
1028            self.style.input_height,
1029        )
1030    }
1031
1032    /// Computes the scrollable result region below the query field.
1033    fn list_rect(&self, bounds: Rect) -> Rect {
1034        let panel = self.panel_rect(bounds);
1035        let input = self.input_rect(bounds);
1036        Rect::new(
1037            panel.x,
1038            input.bottom() + self.style.padding,
1039            panel.w,
1040            (panel.bottom() - input.bottom() - self.style.padding).max(0.0),
1041        )
1042    }
1043
1044    /// Computes the result region for origin-based layout measurement.
1045    fn list_rect_for_size(&self, size: Size) -> Rect {
1046        self.list_rect(Rect::new(0.0, 0.0, size.w, size.h))
1047    }
1048
1049    /// Returns content-driven panel height clamped by configured maxima.
1050    fn panel_height(&self) -> f32 {
1051        let rows = self.filtered_indices().len().max(1) as f32;
1052        let list_h = (rows * self.style.row_height).min(self.style.popup.popup_max_height);
1053        (self.style.padding * 3.0 + self.style.input_height + list_h)
1054            .min(self.style.panel_max_height)
1055    }
1056
1057    /// Returns original item indices matching the current query in source order.
1058    fn filtered_indices(&self) -> Vec<usize> {
1059        filtered_indices(&self.query.read(), &self.items)
1060    }
1061
1062    /// Finds the first enabled result, or `None` when none can activate.
1063    fn first_enabled_index(&self) -> Option<usize> {
1064        self.filtered_indices()
1065            .into_iter()
1066            .find(|idx| !self.items[*idx].disabled.read())
1067    }
1068
1069    /// Finds the last enabled result, or `None` when none can activate.
1070    fn last_enabled_index(&self) -> Option<usize> {
1071        self.filtered_indices()
1072            .into_iter()
1073            .rev()
1074            .find(|idx| !self.items[*idx].disabled.read())
1075    }
1076
1077    /// Advances through filtered enabled items without wrapping past the helper policy.
1078    fn next_enabled_index(&self, current: Option<usize>) -> Option<usize> {
1079        let filtered = self.filtered_indices();
1080        next_enabled(&filtered, current, |idx| !self.items[idx].disabled.read())
1081    }
1082
1083    /// Moves backward through filtered enabled items using the shared policy.
1084    fn previous_enabled_index(&self, current: Option<usize>) -> Option<usize> {
1085        let filtered = self.filtered_indices();
1086        previous_enabled(&filtered, current, |idx| !self.items[idx].disabled.read())
1087    }
1088
1089    /// Returns a changed retained offset clamped to the result viewport.
1090    fn clamped_scroll(&self, viewport: Size) -> Option<ScrollState> {
1091        let rows = self.filtered_indices().len().max(1);
1092        let content = Size::new(viewport.w, rows as f32 * self.style.row_height);
1093        let retained = with_untracked_reads(|| self.scroll.read());
1094        let out = retained.clamp_to(ScrollMetrics::new(viewport, content), ScrollAxes::VERTICAL);
1095        out.changed.then_some(out.state())
1096    }
1097
1098    /// Maps a logical pointer position to an unfiltered item index.
1099    fn item_at(&self, bounds: Rect, pos: ailloli_ui_core::Point) -> Option<usize> {
1100        let list = self.list_rect(bounds);
1101        let filtered = self.filtered_indices();
1102        if filtered.is_empty() {
1103            return None;
1104        }
1105        let y = pos.y - list.y + self.scroll.read().offset.y;
1106        let row = (y / self.style.row_height).floor() as usize;
1107        filtered.get(row).copied()
1108    }
1109
1110    /// Runs one enabled command, closes the palette, and consumes the event.
1111    fn activate_item(&self, ctx: &mut EventCtx<A>, index: usize) {
1112        let Some(item) = self.items.get(index) else {
1113            return;
1114        };
1115        if item.disabled.read() {
1116            ctx.stop_propagation();
1117            return;
1118        }
1119        if let Some(action) = &item.action {
1120            action.run(ctx);
1121        }
1122        self.close();
1123        ctx.request_repaint();
1124        ctx.stop_propagation();
1125    }
1126
1127    /// Applies a wheel delta to the result list and requests repaint on change.
1128    fn scroll_list(
1129        &self,
1130        ctx: &mut EventCtx<A>,
1131        bounds: Rect,
1132        delta: WheelDelta,
1133        modifiers: ailloli_ui_core::event::Modifiers,
1134    ) {
1135        let list = self.list_rect(bounds);
1136        let rows = self.filtered_indices().len().max(1);
1137        let metrics = ScrollMetrics::new(
1138            Size::new(list.w, list.h),
1139            Size::new(list.w, rows as f32 * self.style.row_height),
1140        );
1141        let behavior =
1142            ScrollBehavior::new(ScrollAxes::VERTICAL).with_line_px(self.style.row_height);
1143        let out = self.scroll.read().scroll_by(
1144            behavior.wheel_delta_with_modifiers(delta, modifiers),
1145            metrics,
1146            ScrollAxes::VERTICAL,
1147        );
1148        if out.changed {
1149            self.scroll.set(out.state());
1150            ctx.request_repaint();
1151            ctx.stop_propagation();
1152        }
1153    }
1154
1155    /// Routes navigation/activation keys before forwarding text-edit events.
1156    fn handle_keyboard(
1157        &self,
1158        ctx: &mut EventCtx<A>,
1159        key: &Key,
1160        event: &Event,
1161        bounds: Rect,
1162        layout: &LayoutResult,
1163    ) {
1164        match key {
1165            Key::Named(NamedKey::Escape) => {
1166                self.close();
1167                ctx.request_repaint();
1168                ctx.stop_propagation();
1169                return;
1170            }
1171            Key::Named(NamedKey::ArrowDown) => {
1172                self.move_active(ctx, Direction::Next);
1173                return;
1174            }
1175            Key::Named(NamedKey::ArrowUp) => {
1176                self.move_active(ctx, Direction::Previous);
1177                return;
1178            }
1179            Key::Named(NamedKey::Home) => {
1180                self.set_active(ctx, self.first_enabled_index());
1181                return;
1182            }
1183            Key::Named(NamedKey::End) => {
1184                self.set_active(ctx, self.last_enabled_index());
1185                return;
1186            }
1187            Key::Named(NamedKey::Enter) | Key::Named(NamedKey::Space) => {
1188                if let Some(index) = self
1189                    .active_index
1190                    .read()
1191                    .or_else(|| self.first_enabled_index())
1192                {
1193                    self.activate_item(ctx, index);
1194                }
1195                return;
1196            }
1197            _ => {}
1198        }
1199
1200        let before = self.query.read();
1201        let handled = handle_single_line_text_event(
1202            ctx,
1203            event,
1204            self.input_rect(bounds),
1205            layout,
1206            &self.query,
1207            &self.buffer,
1208            &self.edit,
1209            self.text_style(),
1210            TextFieldEventOptions {
1211                consume_handled_events: true,
1212            },
1213        );
1214        self.after_text_event(ctx, before, handled);
1215    }
1216
1217    /// Resets scroll and selection after a handled query mutation.
1218    fn after_text_event(&self, ctx: &mut EventCtx<A>, before: String, handled: bool) {
1219        if handled && self.query.read() != before {
1220            self.scroll.set(ScrollState::new());
1221            self.active_index.set(self.first_enabled_index());
1222            ctx.request_repaint();
1223        }
1224    }
1225
1226    /// Selects the next enabled result in the requested direction.
1227    fn move_active(&self, ctx: &mut EventCtx<A>, direction: Direction) {
1228        let next = match direction {
1229            Direction::Next => self.next_enabled_index(self.active_index.read()),
1230            Direction::Previous => self.previous_enabled_index(self.active_index.read()),
1231        };
1232        self.set_active(ctx, next);
1233    }
1234
1235    /// Updates keyboard selection, repaints on change, and consumes the event.
1236    fn set_active(&self, ctx: &mut EventCtx<A>, next: Option<usize>) {
1237        if self.active_index.read() != next {
1238            self.active_index.set(next);
1239            ctx.request_repaint();
1240        }
1241        ctx.stop_propagation();
1242    }
1243
1244    /// Paints backdrop, panel shell, query field, results, and final border.
1245    fn paint_palette(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, layout: &LayoutResult) {
1246        ctx.push_overlay(DrawCmd::Rect(DrawRect {
1247            rect: bounds,
1248            color: self.style.backdrop,
1249        }));
1250        let panel = self.panel_rect(bounds);
1251        for shadow in self.style.shadows.iter().copied().filter(|s| !s.inset) {
1252            ctx.push_overlay(DrawCmd::BoxShadow(DrawBoxShadow {
1253                rect: panel,
1254                radius: self.style.radius,
1255                shadow,
1256            }));
1257        }
1258        paint_popup_shell(ctx, panel, &self.style.popup);
1259        self.paint_input(ctx, self.input_rect(bounds), layout);
1260        self.paint_rows(ctx, self.list_rect(bounds));
1261        paint_popup_border(ctx, panel, &self.style.popup);
1262    }
1263
1264    /// Paints the focused single-line query editor into the overlay layer.
1265    fn paint_input(&self, ctx: &mut PaintCtx<'_>, input: Rect, layout: &LayoutResult) {
1266        let style = self.text_style();
1267        ctx.push_overlay(DrawCmd::RRect(DrawRRect {
1268            rect: input,
1269            radius: style.radius,
1270            color: style.bg,
1271        }));
1272        ctx.push_overlay(DrawCmd::Border(DrawBorder {
1273            rect: input,
1274            radius: Radius::uniform(style.radius),
1275            border: Border::new(1.0, style.border_focused),
1276        }));
1277        paint_overlay_single_line_text(
1278            ctx,
1279            input,
1280            layout,
1281            &self.query,
1282            &self.buffer,
1283            &self.edit,
1284            Some(self.placeholder.read()),
1285            style,
1286            true,
1287        );
1288    }
1289
1290    /// Paints visible filtered rows under a list clip, or the empty-state label.
1291    fn paint_rows(&self, ctx: &mut PaintCtx<'_>, list: Rect) {
1292        let filtered = self.filtered_indices();
1293        ctx.with_overlay_clip(list, |ctx| {
1294            if filtered.is_empty() {
1295                let row = Rect::new(list.x, list.y, list.w, self.style.row_height);
1296                paint_overlay_text_in_rect(
1297                    ctx,
1298                    "No results",
1299                    self.style.no_results_text,
1300                    row.inflate(-self.style.padding, 0.0),
1301                    self.style.disabled_opacity,
1302                );
1303                return;
1304            }
1305
1306            for (row_idx, item_idx) in filtered.iter().copied().enumerate() {
1307                let item = &self.items[item_idx];
1308                let row = Rect::new(
1309                    list.x,
1310                    list.y - self.scroll.read().offset.y + row_idx as f32 * self.style.row_height,
1311                    list.w,
1312                    self.style.row_height,
1313                );
1314                if row.bottom() < list.y || row.y > list.bottom() {
1315                    continue;
1316                }
1317                self.paint_row(ctx, row, item, self.active_index.read() == Some(item_idx));
1318            }
1319        });
1320    }
1321
1322    /// Paints one result row with active and disabled visual state.
1323    fn paint_row(&self, ctx: &mut PaintCtx<'_>, row: Rect, item: &CommandItem<A>, active: bool) {
1324        let disabled = item.disabled.read();
1325        let opacity = if disabled {
1326            self.style.disabled_opacity
1327        } else {
1328            1.0
1329        };
1330        if active {
1331            ctx.push_overlay(DrawCmd::Rect(DrawRect {
1332                rect: row,
1333                color: apply_opacity(self.style.popup.option_active, opacity),
1334            }));
1335        }
1336
1337        let mut x = row.x + self.style.padding;
1338        if let Some(icon) = &item.icon {
1339            ctx.push_overlay(DrawCmd::Image(DrawImage {
1340                rect: Rect::new(
1341                    x,
1342                    row.y + (row.h - self.style.icon_size) * 0.5,
1343                    self.style.icon_size,
1344                    self.style.icon_size,
1345                ),
1346                icon: icon.clone(),
1347                tint: apply_opacity(self.style.icon_tint, opacity),
1348                rotation_rad: 0.0,
1349            }));
1350            x += self.style.icon_size + self.style.gap;
1351        }
1352
1353        let shortcut_w = item
1354            .shortcut
1355            .as_ref()
1356            .map(|s| measure_text(ctx.text_system.as_deref_mut(), s, self.style.shortcut_text).w)
1357            .unwrap_or(0.0);
1358        let text_right = row.right() - self.style.padding - shortcut_w - self.style.gap;
1359        let title_h = if item.subtitle.is_some() { 20.0 } else { row.h };
1360        paint_overlay_text_in_rect(
1361            ctx,
1362            &item.title,
1363            if disabled {
1364                TextStyle {
1365                    color: apply_opacity(self.style.title_text.color, opacity),
1366                    ..self.style.title_text
1367                }
1368            } else {
1369                self.style.title_text
1370            },
1371            Rect::new(x, row.y + 1.0, (text_right - x).max(0.0), title_h),
1372            opacity,
1373        );
1374        if let Some(subtitle) = &item.subtitle {
1375            paint_overlay_text_in_rect(
1376                ctx,
1377                subtitle,
1378                self.style.subtitle_text,
1379                Rect::new(x, row.y + 21.0, (text_right - x).max(0.0), 18.0),
1380                opacity,
1381            );
1382        }
1383        if let Some(shortcut) = &item.shortcut {
1384            paint_overlay_text_in_rect(
1385                ctx,
1386                shortcut,
1387                self.style.shortcut_text,
1388                Rect::new(
1389                    row.right() - self.style.padding - shortcut_w,
1390                    row.y,
1391                    shortcut_w,
1392                    row.h,
1393                ),
1394                opacity,
1395            );
1396        }
1397    }
1398}
1399
1400#[derive(Debug, Clone, Copy)]
1401/// Direction used by wrapping enabled-row navigation.
1402enum Direction {
1403    /// Move forward through filtered item indices.
1404    Next,
1405    /// Move backward through filtered item indices.
1406    Previous,
1407}
1408
1409/// Creates edit state with its caret at the end of `text`.
1410fn edit_at_end(text: &str) -> TextEditState {
1411    let mut edit = TextEditState::new();
1412    let buffer = TextBuffer::from_string(text.to_string());
1413    edit.set_caret(&buffer, text.len(), false);
1414    edit
1415}
1416
1417/// Returns source indices matching the trimmed ASCII-insensitive substring query.
1418fn filtered_indices<A>(query: &str, items: &[CommandItem<A>]) -> Vec<usize> {
1419    let q = query.trim().to_ascii_lowercase();
1420    items
1421        .iter()
1422        .enumerate()
1423        .filter_map(|(idx, item)| {
1424            (q.is_empty()
1425                || item.title.to_ascii_lowercase().contains(&q)
1426                || item
1427                    .subtitle
1428                    .as_ref()
1429                    .is_some_and(|s| s.to_ascii_lowercase().contains(&q))
1430                || item
1431                    .keywords
1432                    .iter()
1433                    .any(|s| s.to_ascii_lowercase().contains(&q)))
1434            .then_some(idx)
1435        })
1436        .collect()
1437}
1438
1439/// Finds the next enabled filtered index with wraparound.
1440fn next_enabled(
1441    filtered: &[usize],
1442    current: Option<usize>,
1443    enabled: impl Fn(usize) -> bool,
1444) -> Option<usize> {
1445    if filtered.is_empty() {
1446        return None;
1447    }
1448    let start = current
1449        .and_then(|current| filtered.iter().position(|idx| *idx == current))
1450        .unwrap_or(filtered.len().saturating_sub(1));
1451    (1..=filtered.len())
1452        .map(|offset| filtered[(start + offset) % filtered.len()])
1453        .find(|idx| enabled(*idx))
1454}
1455
1456/// Finds the previous enabled filtered index with wraparound.
1457fn previous_enabled(
1458    filtered: &[usize],
1459    current: Option<usize>,
1460    enabled: impl Fn(usize) -> bool,
1461) -> Option<usize> {
1462    if filtered.is_empty() {
1463        return None;
1464    }
1465    let start = current
1466        .and_then(|current| filtered.iter().position(|idx| *idx == current))
1467        .unwrap_or(0);
1468    (1..=filtered.len())
1469        .map(|offset| filtered[(start + filtered.len() - offset) % filtered.len()])
1470        .find(|idx| enabled(*idx))
1471}
1472
1473/// Resolves host size from its child or finite constraint maxima.
1474fn host_slot_size<A: 'static>(
1475    engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
1476    ctx: &mut LayoutCtx<'_>,
1477    children: &mut [LayoutChild],
1478    constraints: Constraints,
1479    layout: LayoutStyle,
1480) -> Size {
1481    let intrinsic = if let Some(child) = children.first_mut() {
1482        ctx.with_layout_pass(LayoutPass::Measure, |ctx| {
1483            child.layout(engine, ctx, constraints.loosen()).size
1484        })
1485    } else {
1486        Size::new(
1487            finite_or(constraints.max_w, 0.0),
1488            finite_or(constraints.max_h, 0.0),
1489        )
1490    };
1491    apply_layout_size(intrinsic, layout, constraints)
1492}
1493
1494/// Returns `value` when finite and `fallback` for NaN or either infinity.
1495fn finite_or(value: f32, fallback: f32) -> f32 {
1496    if value.is_finite() {
1497        value
1498    } else {
1499        fallback
1500    }
1501}
1502
1503#[allow(clippy::too_many_arguments)]
1504/// Paints clipped overlay selection, query/placeholder glyphs, and caret.
1505///
1506/// An exact committed text artifact is mandatory. Current query or IME state
1507/// that does not match that artifact is skipped until layout commits a matching
1508/// one; overlay paint never reshapes into stale panel geometry.
1509fn paint_overlay_single_line_text(
1510    ctx: &mut PaintCtx<'_>,
1511    bounds: Rect,
1512    layout: &LayoutResult,
1513    value: &Signal<String>,
1514    buffer: &Signal<TextBuffer>,
1515    edit: &Signal<TextEditState>,
1516    placeholder: Option<String>,
1517    style: TextInputStyle,
1518    focused: bool,
1519) {
1520    let buffer = read_display_buffer(value, buffer);
1521    let value = buffer.as_str();
1522    let is_empty = value.is_empty();
1523    let edit_state = edit.read();
1524    let (display, caret_in_display) = display_text_for_edit(
1525        &value,
1526        edit_state.caret_byte.min(value.len()),
1527        edit_state.preedit.as_ref(),
1528    );
1529    let text = if is_empty && display.is_empty() {
1530        placeholder.unwrap_or_default()
1531    } else {
1532        display
1533    };
1534    let text_color = if is_empty && edit_state.preedit.is_none() {
1535        style.placeholder
1536    } else {
1537        style.text.color
1538    };
1539    let style = TextInputStyle {
1540        text: TextStyle {
1541            color: text_color,
1542            ..style.text
1543        },
1544        ..style
1545    };
1546
1547    let Some(layout_handle) = layout
1548        .artifact
1549        .as_ref()
1550        .and_then(|artifact| match artifact {
1551            LayoutArtifact::Text(layout) if layout.text() == text => Some(layout.clone()),
1552            _ => None,
1553        })
1554    else {
1555        return;
1556    };
1557
1558    let content_rect = text_input_content_rect(bounds, style);
1559    let baseline_x = content_rect.x - edit_state.scroll_x;
1560    let baseline_y = bounds.y + style.pad_y + style.text.px_size as f32;
1561    let px = style.text.px_size as f32;
1562    let y_top = (baseline_y - px).round();
1563    let frame_time_ms = ctx.frame_time_ms() as i64;
1564
1565    ctx.with_overlay_clip(content_rect, |ctx| {
1566        if edit_state.preedit.is_none() {
1567            if let Some(sel) = edit_state.selection {
1568                if !sel.is_collapsed() {
1569                    let (lo, hi) = sel.normalized();
1570                    let lo = lo.min(text.len());
1571                    let hi = hi.min(text.len());
1572                    if hi > lo {
1573                        let x0 = (baseline_x + layout_handle.caret_x_at(lo)).round();
1574                        let x1 = (baseline_x + layout_handle.caret_x_at(hi)).round();
1575                        ctx.push_overlay(DrawCmd::Rect(DrawRect {
1576                            rect: Rect::new(x0, y_top, (x1 - x0).max(1.0), px + 2.0),
1577                            color: style.selection_bg,
1578                        }));
1579                    }
1580                }
1581            }
1582        }
1583
1584        ctx.push_overlay(DrawCmd::Text(DrawText {
1585            pos: [baseline_x, baseline_y],
1586            color: style.text.color,
1587            decoration: ailloli_ui_core::TextDecoration::None,
1588            layout: layout_handle.clone(),
1589        }));
1590
1591        if focused && style.caret_blink_ms > 0 {
1592            let on = ((frame_time_ms / style.caret_blink_ms) % 2) == 0;
1593            if on {
1594                let caret_x = (baseline_x + layout_handle.caret_x_at(caret_in_display)).round();
1595                ctx.push_overlay(DrawCmd::Rect(DrawRect {
1596                    rect: Rect::new(caret_x, y_top, style.caret_w, px + 2.0),
1597                    color: style.caret,
1598                }));
1599            }
1600        }
1601    });
1602}
1603
1604/// Local geometry extension used to pass list viewport dimensions.
1605trait RectExt {
1606    /// Copies rectangle width and height into a [`Size`].
1607    fn size(self) -> Size;
1608}
1609
1610impl RectExt for Rect {
1611    fn size(self) -> Size {
1612        Size::new(self.w, self.h)
1613    }
1614}
1615
1616#[cfg(test)]
1617mod tests {
1618    //! Fail-closed query painting against committed overlay artifacts.
1619
1620    use std::cell::RefCell;
1621
1622    use super::*;
1623    use ailloli_ui_core::Size;
1624    use ailloli_ui_text::{TextLayoutParams, TextSystem, WrapMode};
1625
1626    /// Creates a deterministic standalone signal for direct widget-helper tests.
1627    fn signal<T: 'static>(value: T) -> Signal<T> {
1628        Signal::new(Rc::new(RefCell::new(value)), Rc::new(|| {}))
1629    }
1630
1631    #[test]
1632    fn command_palette_query_paint_skips_a_mismatched_committed_artifact() {
1633        let value = signal("fresh".to_string());
1634        let buffer = signal(TextBuffer::from_string("fresh".to_string()));
1635        let edit = signal(edit_at_end("fresh"));
1636        let style = TextInputStyle::default();
1637        let mut text_system = TextSystem::new();
1638        let stale = text_system.layout_cached(TextLayoutParams {
1639            text: "stale",
1640            style: style.text,
1641            max_width: Some(200.0),
1642            wrap_mode: WrapMode::NoWrap,
1643        });
1644        let layout = LayoutResult {
1645            size: Size::new(200.0, 40.0),
1646            children: Vec::new(),
1647            paint_bounds: Rect::new(0.0, 0.0, 200.0, 40.0),
1648            visual_bounds: Rect::new(0.0, 0.0, 200.0, 40.0),
1649            overlay_hit_bounds: Vec::new(),
1650            clip: None,
1651            is_window_root_clip: false,
1652            artifact: Some(LayoutArtifact::Text(stale)),
1653        };
1654        let mut paint = PaintCtx::with_text_system(&mut text_system);
1655
1656        paint_overlay_single_line_text(
1657            &mut paint,
1658            Rect::new(0.0, 0.0, 200.0, 40.0),
1659            &layout,
1660            &value,
1661            &buffer,
1662            &edit,
1663            None,
1664            style,
1665            true,
1666        );
1667
1668        assert!(paint.overlay_layers.iter().all(|layer| {
1669            layer
1670                .cmds
1671                .iter()
1672                .all(|cmd| !matches!(cmd, DrawCmd::Text(_)))
1673        }));
1674    }
1675}