Skip to main content

gpui_material_components/input/
exposed_dropdown.rs

1use std::rc::Rc;
2
3use crate::MenuSurfaceStyle;
4use gpui::{
5    AnyElement, App, ElementId, Entity, Hsla, IntoElement, Pixels, SharedString, Window, px,
6};
7
8use super::TextField;
9
10mod interaction;
11mod option_row;
12mod popup;
13mod render;
14mod state;
15
16pub use state::ExposedDropdownState;
17use state::Visibility;
18
19/// A selectable dropdown value. IDs remain stable when options are reordered.
20#[derive(Clone, PartialEq, Eq)]
21pub struct DropdownOption {
22    /// Stable option identifier used for selection tracking and list reconciliation.
23    pub id: ElementId,
24    /// Visible and searchable option label.
25    pub label: SharedString,
26}
27
28impl DropdownOption {
29    /// Creates a dropdown option with a stable ID and visible label.
30    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
31        Self {
32            id: id.into(),
33            label: label.into(),
34        }
35    }
36}
37
38/// Focus and activation behavior for the primary dropdown anchor.
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub enum DropdownAnchor {
41    /// Allows typing and keeps focus in the field when the menu opens.
42    PrimaryEditable,
43    /// Moves focus to the list when the read-only field opens the menu.
44    PrimaryNotEditable,
45}
46
47type OpenChange = Rc<dyn Fn(bool, &mut Window, &mut App)>;
48type Dismiss = Rc<dyn Fn(&mut Window, &mut App)>;
49type Select = Rc<dyn Fn(&DropdownOption, &mut Window, &mut App)>;
50type Editor = Box<dyn FnOnce(TextField) -> AnyElement>;
51type AnchorContent = Box<dyn FnOnce(bool) -> AnyElement>;
52type OptionContent = Rc<dyn Fn(&DropdownOption, bool, &mut Window, &mut App) -> AnyElement>;
53
54/// A Material field and anchored list in editable and selection-only modes.
55/// Typing filters the list, while only selecting an option calls the owner.
56#[derive(IntoElement)]
57pub struct ExposedDropdown {
58    id: ElementId,
59    label: SharedString,
60    state: Entity<ExposedDropdownState>,
61    options: Rc<[DropdownOption]>,
62    primary: Option<DropdownAnchor>,
63    disabled: bool,
64    primary_enabled: bool,
65    secondary_enabled: bool,
66    secondary: Option<(SharedString, AnchorContent)>,
67    editor: Option<Editor>,
68    option_content: Option<OptionContent>,
69    visibility: Visibility,
70    match_anchor_width: bool,
71    popup_width: Pixels,
72    appearance: MenuSurfaceStyle,
73    container_color: Option<Hsla>,
74    on_select: Option<Select>,
75}
76
77impl ExposedDropdown {
78    /// Creates an exposed dropdown bound to `state` and populated from an iterator of [`DropdownOption`]s.
79    pub fn new(
80        id: impl Into<ElementId>,
81        label: impl Into<SharedString>,
82        state: &Entity<ExposedDropdownState>,
83        options: impl IntoIterator<Item = DropdownOption>,
84    ) -> Self {
85        Self::with_shared_options(id, label, state, options.into_iter().collect::<Vec<_>>())
86    }
87
88    /// Uses a caller-retained option slice to avoid per-render collection and
89    /// linear slice equality comparisons.
90    pub fn with_shared_options(
91        id: impl Into<ElementId>,
92        label: impl Into<SharedString>,
93        state: &Entity<ExposedDropdownState>,
94        options: impl Into<Rc<[DropdownOption]>>,
95    ) -> Self {
96        Self {
97            id: id.into(),
98            label: label.into(),
99            state: state.clone(),
100            options: options.into(),
101            primary: None,
102            disabled: false,
103            primary_enabled: true,
104            secondary_enabled: true,
105            secondary: None,
106            editor: None,
107            option_content: None,
108            visibility: Visibility::default(),
109            match_anchor_width: true,
110            popup_width: px(240.),
111            appearance: MenuSurfaceStyle::default(),
112            container_color: None,
113            on_select: None,
114        }
115    }
116
117    /// Controls primary activation and focus. Pair the anchor with the state's editing mode.
118    pub fn primary_anchor(mut self, anchor: DropdownAnchor) -> Self {
119        self.primary = Some(anchor);
120        self
121    }
122
123    /// Disables the dropdown, its inner text field, and both primary and secondary triggers.
124    ///
125    /// If the popup menu is currently open, it is closed immediately.
126    pub fn disabled(mut self, disabled: bool) -> Self {
127        self.disabled = disabled;
128        self
129    }
130
131    /// Enables or disables opening the popup menu from the primary text field anchor. Defaults to `true`.
132    pub fn primary_anchor_enabled(mut self, enabled: bool) -> Self {
133        self.primary_enabled = enabled;
134        self
135    }
136
137    /// Supplies the name and decorative content of the secondary anchor.
138    pub fn secondary_anchor<E: IntoElement>(
139        mut self,
140        label: impl Into<SharedString>,
141        content: impl FnOnce(bool) -> E + 'static,
142    ) -> Self {
143        self.secondary = Some((
144            label.into(),
145            Box::new(move |open| content(open).into_any_element()),
146        ));
147        self
148    }
149
150    /// Enables or disables the secondary toggle anchor button. Defaults to `true`.
151    pub fn secondary_anchor_enabled(mut self, enabled: bool) -> Self {
152        self.secondary_enabled = enabled;
153        self
154    }
155
156    /// Styles or wraps the field carrying the dropdown's retained editor and semantics.
157    pub fn editor<E: IntoElement>(mut self, render: impl FnOnce(TextField) -> E + 'static) -> Self {
158        self.editor = Some(Box::new(move |field| render(field).into_any_element()));
159        self
160    }
161
162    /// Supplies repeatable decorative content for each visible option.
163    pub fn option_content<E: IntoElement>(
164        mut self,
165        render: impl Fn(&DropdownOption, bool, &mut Window, &mut App) -> E + 'static,
166    ) -> Self {
167        self.option_content = Some(Rc::new(move |option, highlighted, window, cx| {
168            render(option, highlighted, window, cx).into_any_element()
169        }));
170        self
171    }
172
173    /// Controls popup visibility externally instead of letting [`ExposedDropdownState`] toggle it automatically.
174    pub fn open(mut self, open: bool) -> Self {
175        self.visibility.controlled = Some(open);
176        self
177    }
178
179    /// Invoked whenever the dropdown requests opening (`true`) or closing (`false`).
180    pub fn on_open_change(
181        mut self,
182        callback: impl Fn(bool, &mut Window, &mut App) + 'static,
183    ) -> Self {
184        self.visibility.change = Some(Rc::new(callback));
185        self
186    }
187
188    /// Invoked when the open popup menu is dismissed without selecting an option.
189    pub fn on_dismiss(mut self, callback: impl Fn(&mut Window, &mut App) + 'static) -> Self {
190        self.visibility.dismiss = Some(Rc::new(callback));
191        self
192    }
193
194    /// Sizes the popup menu to match the anchor field's width when `true` (default), or uses [`Self::popup_width`] when `false`.
195    pub fn match_anchor_width(mut self, matches: bool) -> Self {
196        self.match_anchor_width = matches;
197        self
198    }
199
200    /// Sets the independent width used with match_anchor_width(false).
201    pub fn popup_width(mut self, width: Pixels) -> Self {
202        if f32::from(width).is_finite() && width > px(0.) {
203            self.popup_width = width;
204        }
205        self
206    }
207
208    /// Overrides the popup menu surface shape, elevation, padding, and border styling.
209    pub fn appearance(mut self, appearance: MenuSurfaceStyle) -> Self {
210        self.appearance = appearance;
211        self
212    }
213
214    /// Overrides the popup menu container background color directly.
215    pub fn container_color(mut self, color: Hsla) -> Self {
216        self.container_color = Some(color);
217        self
218    }
219
220    /// Invoked when the user commits an option via pointer click or keyboard Enter.
221    pub fn on_select(
222        mut self,
223        on_select: impl Fn(&DropdownOption, &mut Window, &mut App) + 'static,
224    ) -> Self {
225        self.on_select = Some(Rc::new(on_select));
226        self
227    }
228}