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