Skip to main content

arc_ui/inputs/
combobox.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/combobox/combobox.tsx` & `.module.css`
3//!
4//! P4 Component #2: `combobox`
5//!
6//! - Searchable single-value selector (`ControlHeights::MD` 44px, `Radii::CONTROL`, `1px border`,
7//!   leading `16px Search` icon, inline text input, animated `22×22px` clear button, and rotating
8//!   `ChevronDown`).
9//! - While searching (`open = true`), the currently selected label remains visible as muted
10//!   placeholder copy instead of vanishing.
11//! - Settling animation: committing an option closes the popover and settles the chosen label from
12//!   `y = +0.35em (4.9px)` with `blur.soft (4px) -> 0` over `duration.standard` (`240ms`,
13//!   `ease.enter`); clearing fades the placeholder in over `duration.fast` (`160ms`, `ease.enter`).
14//! - Clear button (`22×22px`): enters/exits between `scale(0.6)` and `1.0` on `motion.spring.snappy`
15//!   with `blur.subtle (2px)` and presses to `scale(0.96)`.
16//! - Floating popover (`top: calc(100% + 8px)`, `Radii::PANEL` 26px, `5px` padding): enters from
17//!   `y = -6px` on `motion.spring.snappy` with `duration.fast` opacity (`ease.enter`) and exits
18//!   toward `y = -4px` over `duration.instant` (`120ms`).
19//! - `AutoHeight`: the listbox container tracks its filtered height with `motion.spring.smooth` so
20//!   typing never snaps the menu box.
21
22use std::{cell::RefCell, rc::Rc, time::Duration};
23
24use arc_motion::{
25    ArcPresence, ArcPresenceConfig, BlurFallback, CubicBezier, arc_spring, arc_spring_with_options,
26    arc_transition, is_reduced_motion, motion_now, spring::SpringOptions,
27};
28use arc_tokens::{
29    ActiveArcTheme as _, ControlHeights, Radii, Shadows, Spacing, Typography, oklab_mix,
30};
31use gpui_kit::{
32    App, Bounds, ElementId, Entity, Focusable as _, Hsla, IntoElement, KeyDownEvent, MouseButton,
33    MouseDownEvent, ParentElement, PathBuilder, Pixels, RenderOnce, Role, SharedString, Styled,
34    TestSupportExt as _, Window,
35    assets::IconName,
36    base::{Button as BaseButton, StyledExt as _},
37    canvas,
38    component::{
39        Icon,
40        input::{Input as KitInput, InputState},
41    },
42    deferred, div, point,
43    prelude::*,
44    px,
45};
46
47type ComboboxChangeHandler = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
48
49/// Base font size (`14px`, `--text-sm`) used for the `0.35em` settled value rise.
50pub const COMBOBOX_TEXT_EM_PX: f32 = 14.0;
51/// Row height (`32px`) for each option inside the combobox listbox.
52pub const COMBOBOX_OPTION_HEIGHT_PX: f32 = 32.0;
53/// Empty-state row height (`38px`) when no options match the query.
54pub const COMBOBOX_EMPTY_HEIGHT_PX: f32 = 38.0;
55/// Maximum viewport height (`260px`) of the scrollable listbox.
56pub const COMBOBOX_MAX_LISTBOX_HEIGHT_PX: f32 = 260.0;
57
58/// Filters `options` by matching `query` (case-insensitive, trimmed) against `option.label` and
59/// `option.keywords`. Returns the matching indices into `options`.
60pub fn filter_combobox_options(options: &[ComboboxOption], query: &str) -> Vec<usize> {
61    let norm = query.trim().to_lowercase();
62    if norm.is_empty() {
63        return (0..options.len()).collect();
64    }
65    options
66        .iter()
67        .enumerate()
68        .filter_map(|(idx, opt)| {
69            let label_match = opt.label.to_lowercase().contains(&norm);
70            let kw_match = opt
71                .keywords
72                .iter()
73                .any(|kw| kw.to_lowercase().contains(&norm));
74            if label_match || kw_match {
75                Some(idx)
76            } else {
77                None
78            }
79        })
80        .collect()
81}
82
83/// Computes the target inner height of the listbox for `filtered_count` matching options,
84/// clamped to [`COMBOBOX_MAX_LISTBOX_HEIGHT_PX`].
85pub fn combobox_target_height(filtered_count: usize) -> f32 {
86    if filtered_count == 0 {
87        COMBOBOX_EMPTY_HEIGHT_PX
88    } else {
89        (filtered_count as f32 * COMBOBOX_OPTION_HEIGHT_PX).min(COMBOBOX_MAX_LISTBOX_HEIGHT_PX)
90    }
91}
92
93/// Sampled `(opacity, y_offset_px)` for the settled value text after selecting (`has_value = true`,
94/// `240ms`, `+0.35em -> 0`, `blur 4px -> 0`) or clearing (`has_value = false`, `160ms` fade).
95pub fn combobox_settle_sample(elapsed: f64, has_value: bool, reduced: bool) -> (f32, f32) {
96    if reduced {
97        return (1.0, 0.0);
98    }
99    if has_value {
100        let t = (elapsed / 0.24).clamp(0.0, 1.0) as f32;
101        let e = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t);
102        let blur = BlurFallback::evaluate(px(4.0 * (1.0 - e)), false);
103        let op = (e * blur.opacity_multiplier).clamp(0.0, 1.0);
104        let y = 0.35 * COMBOBOX_TEXT_EM_PX * (1.0 - e);
105        (op, y)
106    } else {
107        let t = (elapsed / 0.16).clamp(0.0, 1.0) as f32;
108        let e = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t);
109        (e.clamp(0.0, 1.0), 0.0)
110    }
111}
112
113/// Sampled `(opacity, y_offset_px)` for the empty-state message (`240ms`, `ease.enter`, `y: 4 -> 0`,
114/// `blur: 4px -> 0`).
115pub fn combobox_empty_sample(elapsed: f64, reduced: bool) -> (f32, f32) {
116    if reduced {
117        return (1.0, 0.0);
118    }
119    let t = (elapsed / 0.24).clamp(0.0, 1.0) as f32;
120    let e = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t);
121    let blur = BlurFallback::evaluate(px(4.0 * (1.0 - e)), false);
122    (
123        (e * blur.opacity_multiplier).clamp(0.0, 1.0),
124        4.0 * (1.0 - e),
125    )
126}
127
128/// Loops forward (`step = 1`) or backward (`step = -1`) among enabled indices in `filtered`.
129pub fn next_enabled_combobox_match(
130    options: &[ComboboxOption],
131    filtered: &[usize],
132    current_filtered_pos: Option<usize>,
133    step: isize,
134) -> Option<usize> {
135    let enabled_positions: Vec<usize> = filtered
136        .iter()
137        .enumerate()
138        .filter_map(|(pos, &opt_idx)| (!options[opt_idx].disabled).then_some(pos))
139        .collect();
140    if enabled_positions.is_empty() {
141        return None;
142    }
143    let len = enabled_positions.len() as isize;
144    let cur_slot =
145        current_filtered_pos.and_then(|p| enabled_positions.iter().position(|&ep| ep == p));
146    let next_slot = match cur_slot {
147        Some(slot) => (slot as isize + step).rem_euclid(len) as usize,
148        None => {
149            if step >= 0 {
150                0
151            } else {
152                (len - 1) as usize
153            }
154        }
155    };
156    Some(enabled_positions[next_slot])
157}
158
159/// One searchable option inside [`Combobox`].
160#[derive(Clone, Debug, PartialEq, Eq)]
161pub struct ComboboxOption {
162    pub value: SharedString,
163    pub label: SharedString,
164    pub disabled: bool,
165    pub keywords: Vec<SharedString>,
166}
167
168impl ComboboxOption {
169    pub fn new(value: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
170        Self {
171            value: value.into(),
172            label: label.into(),
173            disabled: false,
174            keywords: Vec::new(),
175        }
176    }
177
178    pub fn disabled(mut self, disabled: bool) -> Self {
179        self.disabled = disabled;
180        self
181    }
182
183    pub fn keyword(mut self, keyword: impl Into<SharedString>) -> Self {
184        self.keywords.push(keyword.into());
185        self
186    }
187
188    pub fn keywords<I, S>(mut self, keywords: I) -> Self
189    where
190        I: IntoIterator<Item = S>,
191        S: Into<SharedString>,
192    {
193        self.keywords.extend(keywords.into_iter().map(Into::into));
194        self
195    }
196}
197
198#[derive(Clone)]
199struct ComboboxInternal {
200    open: bool,
201    opened_at_secs: f64,
202    uncontrolled_value: SharedString,
203    settled_value: SharedString,
204    settle_started_at_secs: f64,
205    empty_entered_at_secs: Option<f64>,
206    last_query: SharedString,
207    active_filtered_pos: Option<usize>,
208    control_hovered: bool,
209    clear_pressed: bool,
210    query_input: Entity<InputState>,
211    control_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
212    popover_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
213}
214
215impl ComboboxInternal {
216    fn new(
217        default_value: SharedString,
218        placeholder: SharedString,
219        now: f64,
220        window: &mut Window,
221        cx: &mut App,
222    ) -> Self {
223        let query_input = cx.new(|cx| InputState::new(window, cx).placeholder(placeholder));
224        Self {
225            open: false,
226            opened_at_secs: now - 10.0,
227            uncontrolled_value: default_value.clone(),
228            settled_value: default_value,
229            settle_started_at_secs: now - 10.0,
230            empty_entered_at_secs: None,
231            last_query: "".into(),
232            active_filtered_pos: None,
233            control_hovered: false,
234            clear_pressed: false,
235            query_input,
236            control_bounds: Rc::new(RefCell::new(None)),
237            popover_bounds: Rc::new(RefCell::new(None)),
238        }
239    }
240}
241
242fn paint_rotated_chevron(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
243    let rad = angle_deg.to_radians();
244    let cos_a = rad.cos();
245    let sin_a = rad.sin();
246    let pts = [(-4.0_f32, -2.0_f32), (0.0, 2.0), (4.0, -2.0)];
247    let mut builder = PathBuilder::stroke(px(1.75));
248    for (i, (lx, ly)) in pts.iter().enumerate() {
249        let rx = cx + lx * cos_a - ly * sin_a;
250        let ry = cy + lx * sin_a + ly * cos_a;
251        let p = point(px(rx), px(ry));
252        if i == 0 {
253            builder.move_to(p);
254        } else {
255            builder.line_to(p);
256        }
257    }
258    if let Ok(path) = builder.build() {
259        window.paint_path(path, color);
260    }
261}
262
263fn paint_check(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
264    let pts = [(-4.5_f32, 0.2_f32), (-1.4, 3.3), (4.8, -3.2)];
265    let mut builder = PathBuilder::stroke(px(1.75));
266    for (i, (lx, ly)) in pts.iter().enumerate() {
267        let p = point(px(cx + lx), px(cy + ly));
268        if i == 0 {
269            builder.move_to(p);
270        } else {
271            builder.line_to(p);
272        }
273    }
274    if let Ok(path) = builder.build() {
275        window.paint_path(path, color);
276    }
277}
278
279/// Arc `Combobox` — searchable single-value dropdown with `AutoHeight` spring listbox,
280/// muted selected-label placeholder while typing, animated clear button, and settled label rise.
281#[derive(IntoElement)]
282pub struct Combobox {
283    id: ElementId,
284    label: SharedString,
285    options: Vec<ComboboxOption>,
286    value: Option<SharedString>,
287    default_value: Option<SharedString>,
288    description: Option<SharedString>,
289    placeholder: SharedString,
290    empty_message: SharedString,
291    disabled: bool,
292    width: Option<Pixels>,
293    on_value_change: Option<ComboboxChangeHandler>,
294}
295
296impl Combobox {
297    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
298        Self {
299            id: id.into(),
300            label: label.into(),
301            options: Vec::new(),
302            value: None,
303            default_value: None,
304            description: None,
305            placeholder: "Search or select…".into(),
306            empty_message: "No matches found".into(),
307            disabled: false,
308            width: None,
309            on_value_change: None,
310        }
311    }
312
313    pub fn option(mut self, option: ComboboxOption) -> Self {
314        self.options.push(option);
315        self
316    }
317
318    pub fn options(mut self, options: impl IntoIterator<Item = ComboboxOption>) -> Self {
319        self.options.extend(options);
320        self
321    }
322
323    pub fn value(mut self, value: impl Into<SharedString>) -> Self {
324        self.value = Some(value.into());
325        self
326    }
327
328    pub fn default_value(mut self, value: impl Into<SharedString>) -> Self {
329        self.default_value = Some(value.into());
330        self
331    }
332
333    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
334        self.description = Some(description.into());
335        self
336    }
337
338    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
339        self.placeholder = placeholder.into();
340        self
341    }
342
343    pub fn empty_message(mut self, message: impl Into<SharedString>) -> Self {
344        self.empty_message = message.into();
345        self
346    }
347
348    pub fn disabled(mut self, disabled: bool) -> Self {
349        self.disabled = disabled;
350        self
351    }
352
353    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
354        self.width = Some(width.into());
355        self
356    }
357
358    pub fn on_value_change(
359        mut self,
360        handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
361    ) -> Self {
362        self.on_value_change = Some(Rc::new(handler));
363        self
364    }
365}
366
367impl RenderOnce for Combobox {
368    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
369        let theme = cx.arc_theme().clone();
370        let colors = theme.colors;
371        let motion = theme.motion;
372        let reduced = is_reduced_motion(cx);
373        let now = motion_now(cx);
374
375        let initial_val = self
376            .value
377            .clone()
378            .or_else(|| self.default_value.clone())
379            .unwrap_or_default();
380        let placeholder_init = self.placeholder.clone();
381
382        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-combobox-state".into());
383        let internal = window.use_keyed_state(state_id, cx, |window, cx| {
384            ComboboxInternal::new(initial_val.clone(), placeholder_init, now, window, cx)
385        });
386
387        let selected_value = self
388            .value
389            .clone()
390            .unwrap_or_else(|| internal.read(cx).uncontrolled_value.clone());
391        let selected_option = self
392            .options
393            .iter()
394            .find(|opt| opt.value == selected_value)
395            .cloned();
396        let has_selected = selected_option.is_some();
397
398        // Keep the inner InputState's placeholder synced to `selectedOption?.label ?? placeholder`.
399        let effective_placeholder = selected_option
400            .as_ref()
401            .map(|opt| opt.label.clone())
402            .unwrap_or_else(|| self.placeholder.clone());
403        {
404            let q_entity = internal.read(cx).query_input.clone();
405            q_entity.update(cx, |s, cx| {
406                s.set_placeholder(effective_placeholder.clone(), window, cx);
407            });
408        }
409
410        // Detect value change to trigger the settle animation (`0.35em -> 0`, `blur 4px -> 0`).
411        {
412            let prev_settled = internal.read(cx).settled_value.clone();
413            if prev_settled != selected_value {
414                internal.update(cx, |s, _| {
415                    s.settled_value = selected_value.clone();
416                    s.settle_started_at_secs = now;
417                });
418            }
419        }
420
421        // If the query input gained focus, open the menu; if query text changed while typing,
422        // reset `active_filtered_pos` and make sure `open = true`.
423        {
424            let q_entity = internal.read(cx).query_input.clone();
425            let q_val: SharedString = q_entity.read(cx).value().clone();
426            let is_input_focused = q_entity.read(cx).focus_handle(cx).is_focused(window);
427            let last_q = internal.read(cx).last_query.clone();
428            let was_open = internal.read(cx).open;
429            if !self.disabled
430                && (q_val != last_q || (is_input_focused && !was_open && !q_val.is_empty()))
431            {
432                internal.update(cx, |s, _| {
433                    if q_val != last_q {
434                        s.last_query = q_val.clone();
435                        s.active_filtered_pos = None;
436                        if !q_val.is_empty() && !s.open {
437                            s.open = true;
438                            s.opened_at_secs = now;
439                        }
440                    }
441                });
442            }
443        }
444
445        let snap = internal.read(cx).clone();
446        let is_open = snap.open && !self.disabled;
447        let query_str = if is_open {
448            snap.query_input.read(cx).value().to_string()
449        } else {
450            String::new()
451        };
452        let filtered_indices = filter_combobox_options(&self.options, &query_str);
453
454        // Track when the filtered list enters the empty state so the empty row fades/rises in.
455        {
456            let is_empty = is_open && filtered_indices.is_empty();
457            let cur_empty_at = internal.read(cx).empty_entered_at_secs;
458            if is_empty && cur_empty_at.is_none() {
459                internal.update(cx, |s, _| {
460                    s.empty_entered_at_secs = Some(now);
461                });
462            } else if !is_empty && cur_empty_at.is_some() {
463                internal.update(cx, |s, _| {
464                    s.empty_entered_at_secs = None;
465                });
466            }
467        }
468        let empty_started_at = internal.read(cx).empty_entered_at_secs.unwrap_or(now);
469
470        let is_input_focused = snap
471            .query_input
472            .read(cx)
473            .focus_handle(cx)
474            .is_focused(window);
475
476        // Settled label animation (`duration.standard` 240ms when chosen, `duration.fast` 160ms when cleared).
477        let settle_elapsed = (now - snap.settle_started_at_secs).max(0.0);
478        let settle_dur = if has_selected { 0.24 } else { 0.16 };
479        let (settle_op, settle_y) = if !is_open && settle_elapsed < settle_dur {
480            window.request_animation_frame();
481            combobox_settle_sample(settle_elapsed, has_selected, reduced)
482        } else {
483            (1.0, 0.0)
484        };
485
486        // Chevron rotation `0 -> 180` on `motion.spring.snappy`.
487        let chevron_deg = if reduced {
488            if is_open { 180.0 } else { 0.0 }
489        } else {
490            arc_spring(
491                (self.id.clone(), "chevron-deg"),
492                if is_open { 180.0 } else { 0.0 },
493                motion.spring.snappy,
494                window,
495                cx,
496            )
497        };
498
499        // Clear button (`22×22px`) presence, scale (`0.6 -> 1.0`, press `0.96`), and blur fallback.
500        let show_clear_target = has_selected && !self.disabled;
501        let clear_target_scale = if !show_clear_target {
502            0.6
503        } else if snap.clear_pressed && !reduced {
504            0.96
505        } else {
506            1.0
507        };
508        let clear_scale = if reduced {
509            if show_clear_target { 1.0 } else { 0.6 }
510        } else {
511            arc_spring(
512                (self.id.clone(), "clear-scale"),
513                clear_target_scale,
514                motion.spring.snappy,
515                window,
516                cx,
517            )
518        };
519        let clear_op = arc_transition(
520            (self.id.clone(), "clear-op"),
521            if show_clear_target { 1.0 } else { 0.0 },
522            if reduced {
523                motion.duration.instant
524            } else if show_clear_target {
525                motion.duration.fast
526            } else {
527                motion.duration.instant
528            },
529            motion.ease.standard,
530            window,
531            cx,
532        );
533        let clear_blur = BlurFallback::evaluate(motion.blur.subtle * (1.0 - clear_op), reduced);
534        let render_clear = show_clear_target || clear_op > 0.02;
535
536        // Control surface & border transitions.
537        let hover_p = arc_transition(
538            (self.id.clone(), "control-hover"),
539            if !self.disabled && (is_open || snap.control_hovered) {
540                1.0
541            } else {
542                0.0
543            },
544            if reduced {
545                Duration::ZERO
546            } else {
547                motion.duration.fast
548            },
549            motion.ease.standard,
550            window,
551            cx,
552        );
553        let control_bg = oklab_mix(colors.surface_muted, colors.surface, hover_p);
554        let control_border = if !self.disabled && is_input_focused {
555            colors.accent
556        } else {
557            oklab_mix(colors.border_strong, colors.border, hover_p)
558        };
559
560        // Floating popover presence (`duration.fast` 160ms enter / `duration.instant` 120ms exit).
561        let popover_presence = ArcPresence::new((self.id.clone(), "popover-presence"), is_open)
562            .animate_initial(false)
563            .config(ArcPresenceConfig {
564                enter_duration: motion.duration.fast,
565                exit_duration: motion.duration.instant,
566                enter_ease: motion.ease.enter,
567                exit_ease: motion.ease.standard,
568                fade_on_reduced_motion: true,
569            })
570            .sample(window, cx);
571
572        let popover_y = if reduced {
573            0.0
574        } else {
575            arc_spring(
576                (self.id.clone(), "popover-y"),
577                if is_open { 0.0 } else { -6.0 },
578                motion.spring.snappy,
579                window,
580                cx,
581            )
582        };
583
584        // `AutoHeight`: follow filtered listbox height with `motion.spring.smooth`.
585        let target_h = combobox_target_height(filtered_indices.len());
586        let auto_h = if reduced {
587            target_h
588        } else {
589            arc_spring_with_options(
590                (self.id.clone(), "auto-height"),
591                target_h,
592                SpringOptions::new(motion.spring.smooth),
593                window,
594                cx,
595            )
596            .value
597            .max(24.0)
598        };
599
600        let control_bounds_ref = snap.control_bounds.clone();
601        let control_bounds_outside = snap.control_bounds.clone();
602        let popover_bounds_outside = snap.popover_bounds.clone();
603        let internal_outside = internal.clone();
604        let control_probe = canvas(
605            move |rect, _, _| {
606                *control_bounds_ref.borrow_mut() = Some(rect);
607            },
608            move |_, _, window, _| {
609                if is_open {
610                    let c_ref = control_bounds_outside.clone();
611                    let p_ref = popover_bounds_outside.clone();
612                    let st = internal_outside.clone();
613                    window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
614                        if !phase.bubble() {
615                            return;
616                        }
617                        let in_control =
618                            c_ref.borrow().is_some_and(|b| b.contains(&event.position));
619                        let in_popover =
620                            p_ref.borrow().is_some_and(|b| b.contains(&event.position));
621                        if !in_control && !in_popover {
622                            let q_in = st.read(cx).query_input.clone();
623                            q_in.update(cx, |s, cx| s.set_value("", window, cx));
624                            st.update(cx, |s, _| {
625                                s.open = false;
626                                s.last_query = "".into();
627                                s.active_filtered_pos = None;
628                            });
629                            window.refresh();
630                        }
631                    });
632                }
633            },
634        )
635        .absolute()
636        .inset_0();
637
638        let disabled = self.disabled;
639        let int_hover = internal.clone();
640        let int_open = internal.clone();
641        let int_key = internal.clone();
642        let options_for_key = self.options.clone();
643        let filtered_for_key = filtered_indices.clone();
644        let on_change_key = self.on_value_change.clone();
645
646        // Clear button (`22×22px`).
647        let int_clear_click = internal.clone();
648        let int_clear_down = internal.clone();
649        let int_clear_up = internal.clone();
650        let int_clear_out = internal.clone();
651        let on_change_clear = self.on_value_change.clone();
652        let clear_hover_bg = colors.surface_muted;
653        let clear_hover_fg = colors.foreground;
654
655        let clear_el = if render_clear {
656            let btn_sz = (22.0 * clear_scale).clamp(13.0, 24.0);
657            let icon_sz = (14.0 * clear_scale).clamp(9.0, 16.0);
658            Some(
659                BaseButton::new(ElementId::NamedChild(
660                    self.id.clone().into(),
661                    "clear".into(),
662                ))
663                .accessibility_label("Clear selection")
664                .on_click(move |_, window, cx| {
665                    let t_now = motion_now(cx);
666                    let q_in = int_clear_click.read(cx).query_input.clone();
667                    q_in.update(cx, |s, cx| {
668                        s.set_value("", window, cx);
669                        s.focus(window, cx);
670                    });
671                    int_clear_click.update(cx, |s, _| {
672                        s.uncontrolled_value = "".into();
673                        s.settled_value = "".into();
674                        s.settle_started_at_secs = t_now;
675                        s.last_query = "".into();
676                        s.open = true;
677                        s.opened_at_secs = t_now;
678                        s.active_filtered_pos = None;
679                        s.clear_pressed = false;
680                    });
681                    if let Some(cb) = &on_change_clear {
682                        let empty: SharedString = "".into();
683                        cb(&empty, window, cx);
684                    }
685                    window.refresh();
686                })
687                .w(px(btn_sz))
688                .h(px(btn_sz))
689                .flex_none()
690                .flex()
691                .items_center()
692                .justify_center()
693                .rounded(Radii::CONTROL)
694                .opacity((clear_op * clear_blur.opacity_multiplier).clamp(0.0, 1.0))
695                .text_color(colors.text_muted)
696                .cursor_pointer()
697                .hover(move |s| s.bg(clear_hover_bg).text_color(clear_hover_fg))
698                .on_mouse_down(MouseButton::Left, move |_, window, cx| {
699                    int_clear_down.update(cx, |s, _| s.clear_pressed = true);
700                    window.refresh();
701                })
702                .on_mouse_up(MouseButton::Left, move |_, window, cx| {
703                    int_clear_up.update(cx, |s, _| s.clear_pressed = false);
704                    window.refresh();
705                })
706                .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
707                    int_clear_out.update(cx, |s, _| s.clear_pressed = false);
708                    window.refresh();
709                })
710                .child(Icon::new(IconName::X).text_size(px(icon_sz))),
711            )
712        } else {
713            None
714        };
715
716        // Middle display / input area:
717        // - When `is_open == true`: renders live `KitInput` so user can type to filter while
718        //   the selected label remains as muted placeholder copy.
719        // - When `is_open == false`: renders the settled label (or placeholder) with the `0.35em`
720        //   settle rise animation; clicking anywhere on the control opens the popover and focuses
721        //   `query_input`.
722        let middle_slot = if is_open {
723            div()
724                .flex_1()
725                .min_w_0()
726                .text_size(Typography::TEXT_SM)
727                .text_color(colors.foreground)
728                .child(
729                    KitInput::new(&snap.query_input)
730                        .appearance(false)
731                        .disabled(disabled)
732                        .w_full(),
733                )
734                .into_any_element()
735        } else {
736            let display_text = selected_option
737                .as_ref()
738                .map(|opt| opt.label.clone())
739                .unwrap_or_else(|| self.placeholder.clone());
740            let text_fg = if has_selected {
741                colors.foreground
742            } else {
743                colors.text_muted
744            };
745            div()
746                .flex_1()
747                .min_w_0()
748                .h(px(20.0))
749                .overflow_hidden()
750                .flex()
751                .items_center()
752                .child(
753                    div()
754                        .w_full()
755                        .mt(px(settle_y))
756                        .opacity(settle_op)
757                        .text_size(Typography::TEXT_SM)
758                        .text_color(text_fg)
759                        .truncate()
760                        .child(display_text),
761                )
762                .into_any_element()
763        };
764
765        let chevron_color = colors.text_muted;
766        let control_id = ElementId::NamedChild(self.id.clone().into(), "control".into());
767        let int_chevron_toggle = internal.clone();
768
769        let control = div()
770            .id(control_id)
771            .test_support()
772            .role(Role::ComboBox)
773            .aria_label(self.label.clone())
774            .relative()
775            .w_full()
776            .min_h(ControlHeights::MD)
777            .px(Spacing::S3)
778            .flex()
779            .flex_row()
780            .items_center()
781            .gap(Spacing::S2)
782            .rounded(Radii::CONTROL)
783            .border_1()
784            .border_color(control_border)
785            .bg(control_bg)
786            .opacity(if disabled { 0.5 } else { 1.0 })
787            .when(!disabled, |this| this.cursor_pointer())
788            .on_hover(move |hovered, window, cx| {
789                int_hover.update(cx, |s, _| {
790                    s.control_hovered = *hovered;
791                });
792                window.refresh();
793            })
794            .on_click(move |_, window, cx| {
795                if disabled {
796                    return;
797                }
798                let t_now = motion_now(cx);
799                let q_in = int_open.read(cx).query_input.clone();
800                let already_open = int_open.read(cx).open;
801                if !already_open {
802                    q_in.update(cx, |s, cx| {
803                        s.set_value("", window, cx);
804                        s.focus(window, cx);
805                    });
806                    int_open.update(cx, |s, _| {
807                        s.open = true;
808                        s.opened_at_secs = t_now;
809                        s.last_query = "".into();
810                        s.active_filtered_pos = None;
811                    });
812                } else {
813                    q_in.update(cx, |s, cx| s.set_value("", window, cx));
814                    int_open.update(cx, |s, _| {
815                        s.open = false;
816                        s.last_query = "".into();
817                        s.active_filtered_pos = None;
818                    });
819                }
820                window.refresh();
821            })
822            .on_key_down(move |event: &KeyDownEvent, window, cx| {
823                if disabled {
824                    return;
825                }
826                match event.keystroke.key.as_str() {
827                    "down" | "arrowdown" => {
828                        let currently_open = int_key.read(cx).open;
829                        if !currently_open {
830                            let t_now = motion_now(cx);
831                            let q_in = int_key.read(cx).query_input.clone();
832                            q_in.update(cx, |s, cx| s.set_value("", window, cx));
833                            int_key.update(cx, |s, _| {
834                                s.open = true;
835                                s.opened_at_secs = t_now;
836                                s.last_query = "".into();
837                                s.active_filtered_pos = None;
838                            });
839                        } else {
840                            let cur = int_key.read(cx).active_filtered_pos;
841                            if let Some(next_pos) = next_enabled_combobox_match(
842                                &options_for_key,
843                                &filtered_for_key,
844                                cur,
845                                1,
846                            ) {
847                                int_key.update(cx, |s, _| {
848                                    s.active_filtered_pos = Some(next_pos);
849                                });
850                            }
851                        }
852                        window.refresh();
853                    }
854                    "up" | "arrowup" => {
855                        let currently_open = int_key.read(cx).open;
856                        if !currently_open {
857                            let t_now = motion_now(cx);
858                            let q_in = int_key.read(cx).query_input.clone();
859                            q_in.update(cx, |s, cx| s.set_value("", window, cx));
860                            int_key.update(cx, |s, _| {
861                                s.open = true;
862                                s.opened_at_secs = t_now;
863                                s.last_query = "".into();
864                                s.active_filtered_pos = None;
865                            });
866                        } else {
867                            let cur = int_key.read(cx).active_filtered_pos;
868                            if let Some(prev_pos) = next_enabled_combobox_match(
869                                &options_for_key,
870                                &filtered_for_key,
871                                cur,
872                                -1,
873                            ) {
874                                int_key.update(cx, |s, _| {
875                                    s.active_filtered_pos = Some(prev_pos);
876                                });
877                            }
878                        }
879                        window.refresh();
880                    }
881                    "enter" => {
882                        let (currently_open, active_pos) = {
883                            let s = int_key.read(cx);
884                            (s.open, s.active_filtered_pos)
885                        };
886                        if currently_open
887                            && let Some(pos) = active_pos
888                            && let Some(&opt_idx) = filtered_for_key.get(pos)
889                            && let Some(opt) = options_for_key.get(opt_idx)
890                            && !opt.disabled
891                        {
892                            let chosen_val = opt.value.clone();
893                            let t_now = motion_now(cx);
894                            let q_in = int_key.read(cx).query_input.clone();
895                            q_in.update(cx, |s, cx| s.set_value("", window, cx));
896                            int_key.update(cx, |s, _| {
897                                s.uncontrolled_value = chosen_val.clone();
898                                s.settled_value = chosen_val.clone();
899                                s.settle_started_at_secs = t_now;
900                                s.last_query = "".into();
901                                s.open = false;
902                                s.active_filtered_pos = None;
903                            });
904                            if let Some(cb) = &on_change_key {
905                                cb(&chosen_val, window, cx);
906                            }
907                            window.refresh();
908                        }
909                    }
910                    "escape" => {
911                        let currently_open = int_key.read(cx).open;
912                        if currently_open {
913                            let q_in = int_key.read(cx).query_input.clone();
914                            q_in.update(cx, |s, cx| s.set_value("", window, cx));
915                            int_key.update(cx, |s, _| {
916                                s.open = false;
917                                s.last_query = "".into();
918                                s.active_filtered_pos = None;
919                            });
920                            window.refresh();
921                        }
922                    }
923                    _ => {}
924                }
925            })
926            .child(control_probe)
927            .child(
928                Icon::new(IconName::Search)
929                    .text_size(px(16.0))
930                    .text_color(colors.text_muted),
931            )
932            .child(middle_slot)
933            .when_some(clear_el, |this, btn| this.child(btn))
934            .child(
935                BaseButton::new(ElementId::NamedChild(
936                    self.id.clone().into(),
937                    "chevron-toggle".into(),
938                ))
939                .accessibility_label("Toggle options")
940                .disabled(disabled)
941                .on_click(move |_, window, cx| {
942                    if disabled {
943                        return;
944                    }
945                    let t_now = motion_now(cx);
946                    let q_in = int_chevron_toggle.read(cx).query_input.clone();
947                    let next_open = !int_chevron_toggle.read(cx).open;
948                    q_in.update(cx, |s, cx| {
949                        s.set_value("", window, cx);
950                        if next_open {
951                            s.focus(window, cx);
952                        }
953                    });
954                    int_chevron_toggle.update(cx, |s, _| {
955                        s.open = next_open;
956                        if next_open {
957                            s.opened_at_secs = t_now;
958                        }
959                        s.last_query = "".into();
960                        s.active_filtered_pos = None;
961                    });
962                    window.refresh();
963                })
964                .size(px(22.0))
965                .flex_none()
966                .flex()
967                .items_center()
968                .justify_center()
969                .rounded(Radii::CONTROL)
970                .cursor_pointer()
971                .child(
972                    canvas(
973                        |_, _, _| {},
974                        move |rect, _, window, _| {
975                            let cx_pt = f32::from(rect.origin.x + rect.size.width * 0.5);
976                            let cy_pt = f32::from(rect.origin.y + rect.size.height * 0.5);
977                            paint_rotated_chevron(cx_pt, cy_pt, chevron_deg, chevron_color, window);
978                        },
979                    )
980                    .size(px(16.0))
981                    .flex_none(),
982                ),
983            );
984
985        // Floating popover (`top: calc(100% + 8px)`, `Radii::PANEL` 26px, `padding: 5px`).
986        let popover_el = if popover_presence.should_render() {
987            let p = popover_presence.progress.clamp(0.0, 1.0);
988            let popover_bounds_ref = snap.popover_bounds.clone();
989            let popover_probe = canvas(
990                move |rect, _, _| {
991                    *popover_bounds_ref.borrow_mut() = Some(rect);
992                },
993                |_, _, _, _| {},
994            )
995            .absolute()
996            .inset_0();
997
998            let listbox_content = if filtered_indices.is_empty() {
999                let empty_elapsed = (now - empty_started_at).max(0.0);
1000                let (emp_op, emp_y) = combobox_empty_sample(empty_elapsed, reduced);
1001                if is_open && !reduced && empty_elapsed < 0.24 {
1002                    window.request_animation_frame();
1003                }
1004                div()
1005                    .w_full()
1006                    .p(Spacing::S3)
1007                    .mt(px(emp_y))
1008                    .opacity(emp_op)
1009                    .text_size(Typography::TEXT_SM)
1010                    .text_color(colors.text_muted)
1011                    .child(self.empty_message)
1012                    .into_any_element()
1013            } else {
1014                let option_rows = filtered_indices
1015                    .iter()
1016                    .copied()
1017                    .enumerate()
1018                    .map(|(pos, opt_idx)| {
1019                        let option = &self.options[opt_idx];
1020                        let item_id = ElementId::NamedChild(
1021                            self.id.clone().into(),
1022                            SharedString::from(format!("option-{}", option.value)),
1023                        );
1024                        let is_active = snap.active_filtered_pos == Some(pos) && !option.disabled;
1025                        let is_selected = option.value == selected_value;
1026                        let row_bg = if is_active {
1027                            colors.surface_muted
1028                        } else {
1029                            Hsla::transparent_black()
1030                        };
1031                        let int_hi = internal.clone();
1032                        let int_choose = internal.clone();
1033                        let on_change = self.on_value_change.clone();
1034                        let opt_val = option.value.clone();
1035                        let opt_label = option.label.clone();
1036                        let opt_disabled = option.disabled;
1037                        let check_color = colors.foreground;
1038
1039                        div()
1040                            .id(item_id)
1041                            .test_support()
1042                            .role(Role::ListBoxOption)
1043                            .aria_label(opt_label.clone())
1044                            .w_full()
1045                            .min_h(px(COMBOBOX_OPTION_HEIGHT_PX))
1046                            .px(px(12.0))
1047                            .flex()
1048                            .flex_row()
1049                            .items_center()
1050                            .justify_between()
1051                            .gap(Spacing::S3)
1052                            .rounded((Radii::PANEL - px(4.0)).max(px(4.0)))
1053                            .bg(row_bg)
1054                            .text_size(Typography::TEXT_SM)
1055                            .text_color(colors.foreground)
1056                            .opacity(if opt_disabled { 0.42 } else { 1.0 })
1057                            .when(!opt_disabled, |this| this.cursor_pointer())
1058                            .on_hover(move |hovered, window, cx| {
1059                                if opt_disabled {
1060                                    return;
1061                                }
1062                                int_hi.update(cx, |s, _| {
1063                                    if *hovered {
1064                                        s.active_filtered_pos = Some(pos);
1065                                    }
1066                                });
1067                                window.refresh();
1068                            })
1069                            .on_click(move |_, window, cx| {
1070                                if opt_disabled {
1071                                    return;
1072                                }
1073                                let t_now = motion_now(cx);
1074                                let q_in = int_choose.read(cx).query_input.clone();
1075                                q_in.update(cx, |s, cx| s.set_value("", window, cx));
1076                                int_choose.update(cx, |s, _| {
1077                                    s.uncontrolled_value = opt_val.clone();
1078                                    s.settled_value = opt_val.clone();
1079                                    s.settle_started_at_secs = t_now;
1080                                    s.last_query = "".into();
1081                                    s.open = false;
1082                                    s.active_filtered_pos = None;
1083                                });
1084                                if let Some(cb) = &on_change {
1085                                    cb(&opt_val, window, cx);
1086                                }
1087                                window.refresh();
1088                            })
1089                            .child(div().flex_1().min_w_0().truncate().child(opt_label))
1090                            .when(is_selected, |this| {
1091                                this.child(
1092                                    canvas(
1093                                        |_, _, _| {},
1094                                        move |rect, _, window, _| {
1095                                            let cx_pt =
1096                                                f32::from(rect.origin.x + rect.size.width * 0.5);
1097                                            let cy_pt =
1098                                                f32::from(rect.origin.y + rect.size.height * 0.5);
1099                                            paint_check(cx_pt, cy_pt, check_color, window);
1100                                        },
1101                                    )
1102                                    .size(px(16.0))
1103                                    .flex_none(),
1104                                )
1105                            })
1106                            .into_any_element()
1107                    })
1108                    .collect::<Vec<_>>();
1109
1110                div()
1111                    .id(ElementId::NamedChild(
1112                        self.id.clone().into(),
1113                        "listbox".into(),
1114                    ))
1115                    .role(Role::ListBox)
1116                    .w_full()
1117                    .max_h(px(COMBOBOX_MAX_LISTBOX_HEIGHT_PX))
1118                    .overflow_y_scroll()
1119                    .flex()
1120                    .flex_col()
1121                    .children(option_rows)
1122                    .into_any_element()
1123            };
1124
1125            Some(
1126                deferred(
1127                    div()
1128                        .id(ElementId::NamedChild(
1129                            self.id.clone().into(),
1130                            "popover".into(),
1131                        ))
1132                        .test_support()
1133                        .absolute()
1134                        .top_full()
1135                        .left_0()
1136                        .right_0()
1137                        .mt(px(8.0 + popover_y))
1138                        .p(px(5.0))
1139                        .rounded(Radii::PANEL)
1140                        .border_1()
1141                        .border_color(colors.border)
1142                        .bg(colors.surface_raised)
1143                        .shadow(Shadows::floating(theme.mode))
1144                        .opacity(p)
1145                        .overflow_hidden()
1146                        .child(popover_probe)
1147                        .child(
1148                            div()
1149                                .w_full()
1150                                .h(px(auto_h))
1151                                .overflow_hidden()
1152                                .child(listbox_content),
1153                        ),
1154                )
1155                .with_priority(20),
1156            )
1157        } else {
1158            None
1159        };
1160
1161        div()
1162            .id(self.id)
1163            .test_support()
1164            .when_some(self.width, |this, w| this.w(w))
1165            .when(self.width.is_none(), |this| this.w_full())
1166            .flex()
1167            .flex_col()
1168            .gap(Spacing::S2)
1169            .child(
1170                div()
1171                    .text_size(Typography::TEXT_SM)
1172                    .font_medium()
1173                    .text_color(colors.foreground)
1174                    .child(self.label),
1175            )
1176            .child(
1177                div()
1178                    .relative()
1179                    .w_full()
1180                    .child(control)
1181                    .when_some(popover_el, |this, pop| this.child(pop)),
1182            )
1183            .when_some(self.description, |this, desc| {
1184                this.child(
1185                    div()
1186                        .text_size(Typography::TEXT_XS)
1187                        .text_color(colors.text_muted)
1188                        .child(desc),
1189                )
1190            })
1191    }
1192}
1193
1194#[cfg(test)]
1195mod tests {
1196    use super::*;
1197
1198    #[test]
1199    fn filter_combobox_options_matches_labels_and_keywords_case_insensitively() {
1200        let options = vec![
1201            ComboboxOption::new("rust", "Rust").keywords(["cargo", "systems"]),
1202            ComboboxOption::new("ts", "TypeScript").keywords(["node", "web"]),
1203            ComboboxOption::new("py", "Python").keywords(["ml", "data"]),
1204        ];
1205
1206        assert_eq!(filter_combobox_options(&options, "  "), vec![0, 1, 2]);
1207        assert_eq!(filter_combobox_options(&options, "CARGO"), vec![0]);
1208        assert_eq!(filter_combobox_options(&options, "script"), vec![1]);
1209        assert!(filter_combobox_options(&options, "kotlin").is_empty());
1210    }
1211
1212    #[test]
1213    fn combobox_settle_and_empty_samples_progress_cleanly() {
1214        let (op0, y0) = combobox_settle_sample(0.0, true, false);
1215        assert!(op0 < 0.01);
1216        assert!(y0 > 4.5);
1217
1218        let (op1, y1) = combobox_settle_sample(0.26, true, false);
1219        assert!((op1 - 1.0).abs() < 1e-4);
1220        assert!(y1.abs() < 1e-4);
1221
1222        let (emp_op0, emp_y0) = combobox_empty_sample(0.0, false);
1223        assert!(emp_op0 < 0.01);
1224        assert!((emp_y0 - 4.0).abs() < 1e-4);
1225
1226        let (emp_op_red, emp_y_red) = combobox_empty_sample(0.01, true);
1227        assert!((emp_op_red - 1.0).abs() < 1e-4);
1228        assert!(emp_y_red.abs() < 1e-4);
1229    }
1230
1231    #[test]
1232    fn next_enabled_combobox_match_skips_disabled_items() {
1233        let options = vec![
1234            ComboboxOption::new("a", "Alpha"),
1235            ComboboxOption::new("b", "Beta").disabled(true),
1236            ComboboxOption::new("c", "Gamma"),
1237        ];
1238        let filtered = vec![0, 1, 2];
1239        assert_eq!(
1240            next_enabled_combobox_match(&options, &filtered, None, 1),
1241            Some(0)
1242        );
1243        assert_eq!(
1244            next_enabled_combobox_match(&options, &filtered, Some(0), 1),
1245            Some(2)
1246        );
1247        assert_eq!(
1248            next_enabled_combobox_match(&options, &filtered, Some(2), 1),
1249            Some(0)
1250        );
1251    }
1252}