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