Skip to main content

gpui_component/button/
dropdown_button.rs

1use gpui::Corners;
2use gpui::{
3    Anchor, App, Context, Edges, ElementId, InteractiveElement as _, IntoElement, ParentElement,
4    RenderOnce, SharedString, StyleRefinement, Styled, Window, div, prelude::FluentBuilder,
5};
6use gpui_base::LogicalStyledExt as _;
7use rust_i18n::t;
8
9use crate::{
10    Disableable, Selectable, Sizable, Size, StyledExt as _,
11    menu::{DropdownMenu, PopupMenu},
12};
13
14use super::{Button, ButtonVariant, ButtonVariants};
15
16/// Group name shared by both halves, so hovering one can style the other.
17const HALVES_GROUP: &str = "dropdown-button";
18
19/// A split button: an action button with an attached menu trigger.
20///
21/// The two halves stay visually joined. A `ghost` split is transparent at
22/// rest; hovering either half surfaces the whole control with the hovered half
23/// emphasized, and it stays surfaced while the menu is open, so the pair reads
24/// as one control rather than two buttons.
25///
26#[derive(IntoElement)]
27pub struct DropdownButton {
28    id: ElementId,
29    style: StyleRefinement,
30    button: Option<Button>,
31    menu:
32        Option<Box<dyn Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static>>,
33    selected: bool,
34    disabled: bool,
35    menu_accessibility_label: Option<SharedString>,
36    // The button props, applied to both halves. Unset means the inner
37    // [`Button`] keeps whatever it was given.
38    outline: bool,
39    variant: Option<ButtonVariant>,
40    size: Option<Size>,
41    anchor: Anchor,
42}
43
44impl DropdownButton {
45    /// Create a new DropdownButton.
46    pub fn new(id: impl Into<ElementId>) -> Self {
47        Self {
48            id: id.into(),
49            style: StyleRefinement::default(),
50            button: None,
51            menu: None,
52            selected: false,
53            disabled: false,
54            menu_accessibility_label: None,
55            outline: false,
56            variant: None,
57            size: None,
58            anchor: Anchor::TopRight,
59        }
60    }
61
62    fn effective_variant(&self) -> ButtonVariant {
63        self.variant
64            .or_else(|| self.button.as_ref().map(Button::variant))
65            .unwrap_or_default()
66    }
67
68    fn effective_size(&self) -> Size {
69        self.size
70            .or_else(|| self.button.as_ref().map(Button::button_size))
71            .unwrap_or_default()
72    }
73
74    /// Set the left button of the dropdown button.
75    ///
76    /// The button keeps its own label, icon, tooltip and click handler. A
77    /// variant or size set on the [`DropdownButton`] applies to both halves and
78    /// overrides the one set here. When either outer value is unset, this
79    /// button's value becomes the shared value for both halves.
80    pub fn button(mut self, button: Button) -> Self {
81        self.button = Some(button);
82        self
83    }
84
85    /// Set the dropdown menu of the button.
86    pub fn dropdown_menu(
87        mut self,
88        menu: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static,
89    ) -> Self {
90        self.menu = Some(Box::new(menu));
91        self
92    }
93
94    /// Set the dropdown menu of the button with anchor corner.
95    pub fn dropdown_menu_with_anchor(
96        mut self,
97        anchor: impl Into<Anchor>,
98        menu: impl Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu + 'static,
99    ) -> Self {
100        self.menu = Some(Box::new(menu));
101        self.anchor = anchor.into();
102        self
103    }
104
105    /// Set the name a screen reader announces for the menu trigger. Defaults
106    /// to the localized "More options".
107    ///
108    /// The trigger shows only a caret, so it has no visible label to read.
109    /// The inner [`Button`] names the action half.
110    pub fn menu_accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
111        self.menu_accessibility_label = Some(label.into());
112        self
113    }
114
115    /// Set the button to outline style.
116    ///
117    /// See also: [`Button::outline`]
118    pub fn outline(mut self) -> Self {
119        self.outline = true;
120        self
121    }
122}
123
124impl Disableable for DropdownButton {
125    fn disabled(mut self, disabled: bool) -> Self {
126        self.disabled = disabled;
127        self
128    }
129}
130
131impl Styled for DropdownButton {
132    fn style(&mut self) -> &mut gpui::StyleRefinement {
133        &mut self.style
134    }
135}
136
137impl Sizable for DropdownButton {
138    fn with_size(mut self, size: impl Into<Size>) -> Self {
139        self.size = Some(size.into());
140        self
141    }
142}
143
144impl ButtonVariants for DropdownButton {
145    fn with_variant(mut self, variant: ButtonVariant) -> Self {
146        self.variant = Some(variant);
147        self
148    }
149}
150
151impl Selectable for DropdownButton {
152    fn selected(mut self, selected: bool) -> Self {
153        self.selected = selected;
154        self
155    }
156
157    fn is_selected(&self) -> bool {
158        self.selected
159    }
160}
161
162impl RenderOnce for DropdownButton {
163    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
164        debug_assert!(
165            self.button.is_some() || self.menu.is_some(),
166            "a DropdownButton needs a `button`, a `dropdown_menu`, or both"
167        );
168
169        let variant = self.effective_variant();
170        let size = self.effective_size();
171        let selected = self.selected || self.button.as_ref().is_some_and(Selectable::is_selected);
172        // Only a ghost split has no surface at rest, so only it needs hovering
173        // one half to reveal the other, and the action half to stay revealed
174        // while the menu holds the trigger pressed.
175        let is_ghost = variant.is_ghost();
176        let menu_open = window.use_keyed_state(self.id.clone(), cx, |_, _| false);
177        let is_menu_open = *menu_open.read(cx);
178
179        div()
180            .id(self.id)
181            .when(is_ghost, |this| this.group(HALVES_GROUP))
182            .h_flex()
183            .flex_row_dir(cx)
184            .refine_style(&self.style)
185            .when_some(self.button, |this, button| {
186                let disabled = self.disabled || button.is_disabled();
187                this.child(
188                    button
189                        .border_corners(Corners {
190                            top_left: true,
191                            top_right: false,
192                            bottom_left: true,
193                            bottom_right: false,
194                        })
195                        .border_edges(Edges::all(true))
196                        .selected(selected)
197                        .disabled(disabled)
198                        .when(self.outline, |this| this.outline())
199                        .with_size(size)
200                        .with_variant(variant)
201                        .when(is_ghost, |this| {
202                            this.hover_group(HALVES_GROUP)
203                                .hover_group_held(is_menu_open)
204                        }),
205                )
206            })
207            .when_some(self.menu, |this, menu| {
208                this.child(
209                    Button::new("popup")
210                        .dropdown_caret(true)
211                        .accessibility_label(
212                            self.menu_accessibility_label
213                                .unwrap_or_else(|| t!("DropdownButton.more_options").into()),
214                        )
215                        .border_corners(Corners {
216                            top_left: false,
217                            top_right: true,
218                            bottom_left: false,
219                            bottom_right: true,
220                        })
221                        .border_edges(Edges {
222                            left: false,
223                            top: true,
224                            right: true,
225                            bottom: true,
226                        })
227                        .selected(selected)
228                        .disabled(self.disabled)
229                        .when(self.outline, |this| this.outline())
230                        .with_size(size)
231                        .with_variant(variant)
232                        .when(is_ghost, |this| this.hover_group(HALVES_GROUP))
233                        .dropdown_menu_with_anchor(self.anchor, menu)
234                        .on_open_change(move |open, _, cx| {
235                            menu_open.update(cx, |state, cx| {
236                                *state = *open;
237                                cx.notify();
238                            })
239                        }),
240                )
241            })
242    }
243}
244
245#[cfg(test)]
246mod tests {
247    use super::*;
248
249    #[gpui::test]
250    fn test_dropdown_button_builder(_cx: &mut gpui::TestAppContext) {
251        let button = Button::new("inner").label("Action");
252        let dropdown = DropdownButton::new("complex-dropdown")
253            .button(button)
254            .primary()
255            .outline()
256            .large()
257            .disabled(false)
258            .selected(false)
259            .dropdown_menu_with_anchor(Anchor::BottomLeft, |menu, _, _| menu);
260
261        assert!(dropdown.button.is_some());
262        assert_eq!(dropdown.variant, Some(ButtonVariant::Primary));
263        assert!(dropdown.outline);
264        assert_eq!(dropdown.size, Some(Size::Large));
265        assert!(!dropdown.disabled);
266        assert!(!dropdown.selected);
267        assert!(dropdown.menu.is_some());
268        assert_eq!(dropdown.anchor, Anchor::BottomLeft);
269    }
270
271    /// An unset variant or size leaves the inner button's own to survive, so a
272    /// caller can style the halves from either level.
273    #[gpui::test]
274    fn inner_button_keeps_its_own_variant_and_size(_cx: &mut gpui::TestAppContext) {
275        let dropdown = DropdownButton::new("dropdown")
276            .button(Button::new("inner").label("Action").danger().small())
277            .dropdown_menu(|menu, _, _| menu);
278
279        assert_eq!(dropdown.variant, None);
280        assert_eq!(dropdown.size, None);
281    }
282
283    #[gpui::test]
284    fn inner_ghost_becomes_the_split_variant(_cx: &mut gpui::TestAppContext) {
285        let dropdown = DropdownButton::new("dropdown")
286            .button(Button::new("inner").label("Action").ghost())
287            .dropdown_menu(|menu, _, _| menu);
288
289        assert_eq!(dropdown.effective_variant(), ButtonVariant::Ghost);
290    }
291
292    #[gpui::test]
293    fn inner_size_becomes_the_split_size(_cx: &mut gpui::TestAppContext) {
294        let dropdown = DropdownButton::new("dropdown")
295            .button(Button::new("inner").label("Action").small())
296            .dropdown_menu(|menu, _, _| menu);
297
298        assert_eq!(dropdown.effective_size(), Size::Small);
299    }
300}