Skip to main content

gpui_material_extras/
split_button.rs

1use std::rc::Rc;
2
3use gpui::{
4    AnyElement, App, ElementId, Entity, FocusHandle, InteractiveElement, IntoElement,
5    ParentElement, Pixels, RenderOnce, Role, SharedString, StatefulInteractiveElement, Styled,
6    Window, div, prelude::FluentBuilder, px,
7};
8use gpui_material_components::{
9    ButtonVariant, ControlSize, Icon, IconName, Menu, MenuItem, SemanticTone,
10    button_composition::{ButtonPart, Segment, label_width, split_trailing_size},
11};
12use gpui_material_foundation::{InteractionSource, current_material_theme};
13use gpui_material_theme::Direction;
14
15use crate::ButtonSegmentStyle;
16
17type Command = Rc<dyn Fn(&mut Window, &mut App)>;
18type Change = Rc<dyn Fn(bool, &mut Window, &mut App)>;
19
20enum Leading {
21    Label,
22    IconAndLabel(AnyElement),
23    Icon(AnyElement),
24    Content(AnyElement),
25}
26
27enum Trailing {
28    Arrow,
29    Icon(AnyElement),
30    Content(AnyElement),
31}
32
33enum TrailingAction {
34    Menu(Vec<MenuItem>),
35    Invoke(Command),
36    Toggle { selected: bool, change: Change },
37}
38
39#[derive(Default)]
40struct Part {
41    style: ButtonSegmentStyle,
42    source: Option<Entity<InteractionSource>>,
43}
44
45impl Part {
46    fn apply(self, button: ButtonPart) -> ButtonPart {
47        button
48            .shapes(self.style.shapes)
49            .colors(self.style.colors)
50            .elevations(self.style.elevations)
51            .when_some(self.style.border, ButtonPart::border)
52            .when_some(self.style.padding, ButtonPart::content_padding)
53            .when_some(self.source.as_ref(), ButtonPart::interaction_source)
54    }
55}
56
57/// Two adjoining actions with independent focus, content, and appearance.
58#[derive(IntoElement)]
59pub struct SplitButton {
60    id: ElementId,
61    accessible_label: Option<SharedString>,
62    leading_name: SharedString,
63    trailing_name: SharedString,
64    leading_content: Leading,
65    trailing_content: Trailing,
66    leading_style: Part,
67    trailing_style: Part,
68    trailing_action: TrailingAction,
69    size: ControlSize,
70    variant: ButtonVariant,
71    leading_tone: SemanticTone,
72    trailing_tone: SemanticTone,
73    spacing: Pixels,
74    disabled: bool,
75    trailing_disabled: bool,
76    on_activate: Option<Command>,
77    focus: Option<(FocusHandle, FocusHandle)>,
78}
79
80impl SplitButton {
81    /// Creates a split button with a primary `leading_name`, a `trailing_name` for the secondary
82    /// control, and default dropdown `menu` items.
83    pub fn new(
84        id: impl Into<ElementId>,
85        leading_name: impl Into<SharedString>,
86        trailing_name: impl Into<SharedString>,
87        menu: impl IntoIterator<Item = MenuItem>,
88    ) -> Self {
89        Self {
90            id: id.into(),
91            accessible_label: None,
92            leading_name: leading_name.into(),
93            trailing_name: trailing_name.into(),
94            leading_content: Leading::Label,
95            trailing_content: Trailing::Arrow,
96            leading_style: Part::default(),
97            trailing_style: Part::default(),
98            trailing_action: TrailingAction::Menu(menu.into_iter().collect()),
99            size: ControlSize::default(),
100            variant: ButtonVariant::default(),
101            leading_tone: SemanticTone::Default,
102            trailing_tone: SemanticTone::Default,
103            spacing: px(2.),
104            disabled: false,
105            trailing_disabled: false,
106            on_activate: None,
107            focus: None,
108        }
109    }
110
111    /// Sets an accessible name for the outer split button group (`Role::Group`).
112    pub fn accessible_label(mut self, label: impl Into<SharedString>) -> Self {
113        self.accessible_label = Some(label.into());
114        self
115    }
116
117    /// Sets the [`ControlSize`] shared by both segments.
118    pub fn size(mut self, size: ControlSize) -> Self {
119        self.size = size;
120        self
121    }
122
123    /// Sets the [`ButtonVariant`] shared by both segments.
124    pub fn variant(mut self, variant: ButtonVariant) -> Self {
125        self.variant = variant;
126        self
127    }
128
129    /// Applies a Material 3 semantic tone to both segments.
130    pub fn tone(mut self, tone: SemanticTone) -> Self {
131        self.leading_tone = tone;
132        self.trailing_tone = tone;
133        self
134    }
135
136    /// Applies a Material 3 semantic tone to the leading segment.
137    pub fn leading_tone(mut self, tone: SemanticTone) -> Self {
138        self.leading_tone = tone;
139        self
140    }
141
142    /// Applies a Material 3 semantic tone to the trailing segment.
143    pub fn trailing_tone(mut self, tone: SemanticTone) -> Self {
144        self.trailing_tone = tone;
145        self
146    }
147
148    /// Sets the space between segments. Invalid lengths use the default 2 dp.
149    pub fn spacing(mut self, spacing: Pixels) -> Self {
150        self.spacing = if f32::from(spacing).is_finite() {
151            spacing.max(px(0.))
152        } else {
153            px(2.)
154        };
155        self
156    }
157
158    /// Sets availability for the leading action.
159    pub fn disabled(mut self, disabled: bool) -> Self {
160        self.disabled = disabled;
161        self
162    }
163
164    /// Alias for [`Self::trailing_disabled`] when the trailing segment opens a menu.
165    pub fn menu_disabled(self, disabled: bool) -> Self {
166        self.trailing_disabled(disabled)
167    }
168
169    /// Disables the trailing segment (menu trigger, command, or toggle) when `true`.
170    pub fn trailing_disabled(mut self, disabled: bool) -> Self {
171        self.trailing_disabled = disabled;
172        self
173    }
174
175    /// Registers a callback invoked when the leading primary segment is activated.
176    pub fn on_activate(mut self, callback: impl Fn(&mut Window, &mut App) + 'static) -> Self {
177        self.on_activate = Some(Rc::new(callback));
178        self
179    }
180
181    /// Replaces the trailing menu or toggle with a command.
182    pub fn on_trailing_activate(
183        mut self,
184        callback: impl Fn(&mut Window, &mut App) + 'static,
185    ) -> Self {
186        self.trailing_action = TrailingAction::Invoke(Rc::new(callback));
187        self
188    }
189
190    /// Replaces the trailing menu or command with a caller-controlled toggle.
191    pub fn trailing_toggle(
192        mut self,
193        selected: bool,
194        callback: impl Fn(bool, &mut Window, &mut App) + 'static,
195    ) -> Self {
196        self.trailing_action = TrailingAction::Toggle {
197            selected,
198            change: Rc::new(callback),
199        };
200        self
201    }
202
203    /// Displays an icon before the leading segment's label.
204    pub fn leading_icon(mut self, icon: impl IntoElement) -> Self {
205        self.leading_content = Leading::IconAndLabel(icon.into_any_element());
206        self
207    }
208
209    /// Renders the leading segment with an icon only, keeping `leading_name` as its accessible name.
210    pub fn leading_icon_only(mut self, icon: impl IntoElement) -> Self {
211        self.leading_content = Leading::Icon(icon.into_any_element());
212        self
213    }
214
215    /// Replaces the leading label's presentation and retains its accessible name.
216    pub fn leading_content(mut self, content: impl IntoElement) -> Self {
217        self.leading_content = Leading::Content(content.into_any_element());
218        self
219    }
220
221    /// Replaces the default dropdown arrow icon on the trailing segment.
222    pub fn trailing_icon(mut self, icon: impl IntoElement) -> Self {
223        self.trailing_content = Trailing::Icon(icon.into_any_element());
224        self
225    }
226
227    /// Replaces the trailing icon's presentation and retains its accessible name.
228    pub fn trailing_content(mut self, content: impl IntoElement) -> Self {
229        self.trailing_content = Trailing::Content(content.into_any_element());
230        self
231    }
232
233    /// Applies appearance overrides to the leading segment.
234    pub fn leading_style(mut self, style: ButtonSegmentStyle) -> Self {
235        self.leading_style.style = style;
236        self
237    }
238
239    /// Applies appearance overrides to the trailing segment.
240    pub fn trailing_style(mut self, style: ButtonSegmentStyle) -> Self {
241        self.trailing_style.style = style;
242        self
243    }
244
245    /// Connects an [`InteractionSource`] to observe interaction states on the leading segment.
246    pub fn leading_interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
247        self.leading_style.source = Some(source.clone());
248        self
249    }
250
251    /// Connects an [`InteractionSource`] to observe interaction states on the trailing segment.
252    pub fn trailing_interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
253        self.trailing_style.source = Some(source.clone());
254        self
255    }
256
257    /// Supplies independent focus handles for the leading and trailing segments.
258    pub fn track_focus(mut self, primary: &FocusHandle, trailing: &FocusHandle) -> Self {
259        self.focus = Some((primary.clone(), trailing.clone()));
260        self
261    }
262}
263
264impl RenderOnce for SplitButton {
265    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
266        let theme = current_material_theme(window, cx);
267        let direction = theme.layout.direction;
268        let density = theme.layout.density;
269        let (primary_focus, trailing_focus) = self.focus.unwrap_or_else(|| {
270            window
271                .use_keyed_state((self.id.clone(), "split-focus"), cx, |_, cx| {
272                    (cx.focus_handle(), cx.focus_handle())
273                })
274                .read(cx)
275                .clone()
276        });
277        let primary_id = ElementId::from((self.id.clone(), "primary"));
278        let primary = if matches!(self.leading_content, Leading::Label)
279            && self.leading_style.style.padding.is_none()
280        {
281            let width = label_width(self.size, self.leading_name.clone(), window, cx);
282            ButtonPart::new(primary_id, self.leading_name, width)
283        } else {
284            ButtonPart::intrinsic(primary_id, self.leading_name)
285        };
286        let primary = match self.leading_content {
287            Leading::Label => primary,
288            Leading::IconAndLabel(icon) => primary.leading_icon(icon),
289            Leading::Icon(icon) => primary.icon(icon),
290            Leading::Content(content) => primary.content(content),
291        };
292        let primary = self
293            .leading_style
294            .apply(primary)
295            .size(self.size)
296            .variant(self.variant)
297            .tone(self.leading_tone)
298            .segment(Some(Segment::SplitLeading))
299            .track_focus(&primary_focus)
300            .disabled(self.disabled)
301            .when_some(self.on_activate, |button, action| {
302                button.on_activate(move |window, cx| action(window, cx))
303            });
304
305        let trailing_id = ElementId::from((self.id.clone(), "secondary"));
306        let restore = trailing_focus.clone();
307        let trailing = move |active| {
308            let part = if matches!(self.trailing_content, Trailing::Content(_))
309                || self.trailing_style.style.padding.is_some()
310            {
311                ButtonPart::intrinsic(trailing_id, self.trailing_name)
312            } else {
313                ButtonPart::new(
314                    trailing_id,
315                    self.trailing_name,
316                    px(density.interactive_size(split_trailing_size(self.size).1)),
317                )
318            };
319            let part = match self.trailing_content {
320                Trailing::Arrow => part.icon(Icon::new(IconName::ArrowDropDown).rotate(
321                    gpui::Radians(if active { std::f32::consts::PI } else { 0. }),
322                )),
323                Trailing::Icon(icon) => part.icon(icon),
324                Trailing::Content(content) => part.content(content),
325            };
326            self.trailing_style
327                .apply(part)
328                .size(self.size)
329                .variant(self.variant)
330                .tone(self.trailing_tone)
331                .segment(Some(Segment::SplitTrailing))
332                .track_focus(&trailing_focus)
333                .disabled(self.trailing_disabled)
334        };
335        let trailing = match self.trailing_action {
336            TrailingAction::Menu(items) if self.trailing_disabled || items.is_empty() => {
337                trailing(false).disabled(true).into_any_element()
338            }
339            TrailingAction::Menu(items) => {
340                Menu::composed((self.id.clone(), "menu"), items, move |open, toggle| {
341                    trailing(open)
342                        .presentation_selected(open)
343                        .on_accessible_activate(move |window, cx| {
344                            restore.focus(window, cx);
345                            toggle(window, cx);
346                        })
347                        .into_any_element()
348                })
349                .into_any_element()
350            }
351            TrailingAction::Invoke(command) => trailing(false)
352                .on_activate(move |window, cx| command(window, cx))
353                .into_any_element(),
354            TrailingAction::Toggle { selected, change } => trailing(selected)
355                .selected(Some(selected))
356                .on_change(move |next, window, cx| change(next, window, cx))
357                .into_any_element(),
358        };
359        div()
360            .id(self.id)
361            .role(Role::Group)
362            .when_some(self.accessible_label, |group, label| {
363                group.aria_label(label)
364            })
365            .flex()
366            .items_center()
367            .min_w_0()
368            .max_w_full()
369            .gap(self.spacing)
370            .when(direction == Direction::Rtl, Styled::flex_row_reverse)
371            .child(primary)
372            .child(trailing)
373    }
374}
375
376#[cfg(test)]
377mod tests {
378    use gpui_material_components::{ButtonColors, ControlElevations};
379    use gpui_material_theme::{Elevation, LogicalEdges};
380
381    use super::*;
382
383    #[test]
384    fn split_button_sets_outer_group_accessible_label_and_unified_segment_styles() {
385        let leading = ButtonSegmentStyle {
386            colors: ButtonColors {
387                container: Some(gpui::hsla(0.2, 0.5, 0.5, 1.)),
388                ..Default::default()
389            },
390            padding: Some(LogicalEdges::symmetric(14., 4.)),
391            ..Default::default()
392        };
393        let trailing = ButtonSegmentStyle {
394            elevations: ControlElevations {
395                resting: Some(Elevation::Level2),
396                ..Default::default()
397            },
398            ..Default::default()
399        };
400        let button = SplitButton::new("send", "Send", "More send options", [])
401            .accessible_label("Send actions")
402            .leading_style(leading)
403            .trailing_style(trailing);
404
405        assert_eq!(button.accessible_label.as_deref(), Some("Send actions"));
406        assert_eq!(button.leading_style.style, leading);
407        assert_eq!(button.trailing_style.style, trailing);
408    }
409}