gpui-material-extras 0.4.1

Optional Material 3 Expressive component families for GPUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
use std::rc::Rc;

use gpui::{
    AnyElement, App, ElementId, Entity, FocusHandle, InteractiveElement, IntoElement,
    ParentElement, Pixels, RenderOnce, Role, SharedString, StatefulInteractiveElement, Styled,
    Window, div, prelude::FluentBuilder, px,
};
use gpui_material_components::{
    ButtonVariant, ControlSize, Icon, IconName, Menu, MenuItem, SemanticTone,
    button_composition::{ButtonPart, Segment, label_width, split_trailing_size},
};
use gpui_material_foundation::{InteractionSource, current_material_theme};
use gpui_material_theme::Direction;

use crate::ButtonSegmentStyle;

type Command = Rc<dyn Fn(&mut Window, &mut App)>;
type Change = Rc<dyn Fn(bool, &mut Window, &mut App)>;

enum Leading {
    Label,
    IconAndLabel(AnyElement),
    Icon(AnyElement),
    Content(AnyElement),
}

enum Trailing {
    Arrow,
    Icon(AnyElement),
    Content(AnyElement),
}

enum TrailingAction {
    Menu(Vec<MenuItem>),
    Invoke(Command),
    Toggle { selected: bool, change: Change },
}

#[derive(Default)]
struct Part {
    style: ButtonSegmentStyle,
    source: Option<Entity<InteractionSource>>,
}

impl Part {
    fn apply(self, button: ButtonPart) -> ButtonPart {
        button
            .shapes(self.style.shapes)
            .colors(self.style.colors)
            .elevations(self.style.elevations)
            .when_some(self.style.border, ButtonPart::border)
            .when_some(self.style.padding, ButtonPart::content_padding)
            .when_some(self.source.as_ref(), ButtonPart::interaction_source)
    }
}

/// Two adjoining actions with independent focus, content, and appearance.
#[derive(IntoElement)]
pub struct SplitButton {
    id: ElementId,
    accessible_label: Option<SharedString>,
    leading_name: SharedString,
    trailing_name: SharedString,
    leading_content: Leading,
    trailing_content: Trailing,
    leading_style: Part,
    trailing_style: Part,
    trailing_action: TrailingAction,
    size: ControlSize,
    variant: ButtonVariant,
    leading_tone: SemanticTone,
    trailing_tone: SemanticTone,
    spacing: Pixels,
    disabled: bool,
    trailing_disabled: bool,
    on_activate: Option<Command>,
    focus: Option<(FocusHandle, FocusHandle)>,
}

impl SplitButton {
    /// Creates a split button with a primary `leading_name`, a `trailing_name` for the secondary
    /// control, and default dropdown `menu` items.
    pub fn new(
        id: impl Into<ElementId>,
        leading_name: impl Into<SharedString>,
        trailing_name: impl Into<SharedString>,
        menu: impl IntoIterator<Item = MenuItem>,
    ) -> Self {
        Self {
            id: id.into(),
            accessible_label: None,
            leading_name: leading_name.into(),
            trailing_name: trailing_name.into(),
            leading_content: Leading::Label,
            trailing_content: Trailing::Arrow,
            leading_style: Part::default(),
            trailing_style: Part::default(),
            trailing_action: TrailingAction::Menu(menu.into_iter().collect()),
            size: ControlSize::default(),
            variant: ButtonVariant::default(),
            leading_tone: SemanticTone::Default,
            trailing_tone: SemanticTone::Default,
            spacing: px(2.),
            disabled: false,
            trailing_disabled: false,
            on_activate: None,
            focus: None,
        }
    }

    /// Sets an accessible name for the outer split button group (`Role::Group`).
    pub fn accessible_label(mut self, label: impl Into<SharedString>) -> Self {
        self.accessible_label = Some(label.into());
        self
    }

    /// Sets the [`ControlSize`] shared by both segments.
    pub fn size(mut self, size: ControlSize) -> Self {
        self.size = size;
        self
    }

    /// Sets the [`ButtonVariant`] shared by both segments.
    pub fn variant(mut self, variant: ButtonVariant) -> Self {
        self.variant = variant;
        self
    }

    /// Applies a Material 3 semantic tone to both segments.
    pub fn tone(mut self, tone: SemanticTone) -> Self {
        self.leading_tone = tone;
        self.trailing_tone = tone;
        self
    }

    /// Applies a Material 3 semantic tone to the leading segment.
    pub fn leading_tone(mut self, tone: SemanticTone) -> Self {
        self.leading_tone = tone;
        self
    }

    /// Applies a Material 3 semantic tone to the trailing segment.
    pub fn trailing_tone(mut self, tone: SemanticTone) -> Self {
        self.trailing_tone = tone;
        self
    }

    /// Sets the space between segments. Invalid lengths use the default 2 dp.
    pub fn spacing(mut self, spacing: Pixels) -> Self {
        self.spacing = if f32::from(spacing).is_finite() {
            spacing.max(px(0.))
        } else {
            px(2.)
        };
        self
    }

    /// Sets availability for the leading action.
    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    /// Alias for [`Self::trailing_disabled`] when the trailing segment opens a menu.
    pub fn menu_disabled(self, disabled: bool) -> Self {
        self.trailing_disabled(disabled)
    }

    /// Disables the trailing segment (menu trigger, command, or toggle) when `true`.
    pub fn trailing_disabled(mut self, disabled: bool) -> Self {
        self.trailing_disabled = disabled;
        self
    }

    /// Registers a callback invoked when the leading primary segment is activated.
    pub fn on_activate(mut self, callback: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        self.on_activate = Some(Rc::new(callback));
        self
    }

    /// Replaces the trailing menu or toggle with a command.
    pub fn on_trailing_activate(
        mut self,
        callback: impl Fn(&mut Window, &mut App) + 'static,
    ) -> Self {
        self.trailing_action = TrailingAction::Invoke(Rc::new(callback));
        self
    }

    /// Replaces the trailing menu or command with a caller-controlled toggle.
    pub fn trailing_toggle(
        mut self,
        selected: bool,
        callback: impl Fn(bool, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.trailing_action = TrailingAction::Toggle {
            selected,
            change: Rc::new(callback),
        };
        self
    }

    /// Displays an icon before the leading segment's label.
    pub fn leading_icon(mut self, icon: impl IntoElement) -> Self {
        self.leading_content = Leading::IconAndLabel(icon.into_any_element());
        self
    }

    /// Renders the leading segment with an icon only, keeping `leading_name` as its accessible name.
    pub fn leading_icon_only(mut self, icon: impl IntoElement) -> Self {
        self.leading_content = Leading::Icon(icon.into_any_element());
        self
    }

    /// Replaces the leading label's presentation and retains its accessible name.
    pub fn leading_content(mut self, content: impl IntoElement) -> Self {
        self.leading_content = Leading::Content(content.into_any_element());
        self
    }

    /// Replaces the default dropdown arrow icon on the trailing segment.
    pub fn trailing_icon(mut self, icon: impl IntoElement) -> Self {
        self.trailing_content = Trailing::Icon(icon.into_any_element());
        self
    }

    /// Replaces the trailing icon's presentation and retains its accessible name.
    pub fn trailing_content(mut self, content: impl IntoElement) -> Self {
        self.trailing_content = Trailing::Content(content.into_any_element());
        self
    }

    /// Applies appearance overrides to the leading segment.
    pub fn leading_style(mut self, style: ButtonSegmentStyle) -> Self {
        self.leading_style.style = style;
        self
    }

    /// Applies appearance overrides to the trailing segment.
    pub fn trailing_style(mut self, style: ButtonSegmentStyle) -> Self {
        self.trailing_style.style = style;
        self
    }

    /// Connects an [`InteractionSource`] to observe interaction states on the leading segment.
    pub fn leading_interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
        self.leading_style.source = Some(source.clone());
        self
    }

    /// Connects an [`InteractionSource`] to observe interaction states on the trailing segment.
    pub fn trailing_interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
        self.trailing_style.source = Some(source.clone());
        self
    }

    /// Supplies independent focus handles for the leading and trailing segments.
    pub fn track_focus(mut self, primary: &FocusHandle, trailing: &FocusHandle) -> Self {
        self.focus = Some((primary.clone(), trailing.clone()));
        self
    }
}

impl RenderOnce for SplitButton {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = current_material_theme(window, cx);
        let direction = theme.layout.direction;
        let density = theme.layout.density;
        let (primary_focus, trailing_focus) = self.focus.unwrap_or_else(|| {
            window
                .use_keyed_state((self.id.clone(), "split-focus"), cx, |_, cx| {
                    (cx.focus_handle(), cx.focus_handle())
                })
                .read(cx)
                .clone()
        });
        let primary_id = ElementId::from((self.id.clone(), "primary"));
        let primary = if matches!(self.leading_content, Leading::Label)
            && self.leading_style.style.padding.is_none()
        {
            let width = label_width(self.size, self.leading_name.clone(), window, cx);
            ButtonPart::new(primary_id, self.leading_name, width)
        } else {
            ButtonPart::intrinsic(primary_id, self.leading_name)
        };
        let primary = match self.leading_content {
            Leading::Label => primary,
            Leading::IconAndLabel(icon) => primary.leading_icon(icon),
            Leading::Icon(icon) => primary.icon(icon),
            Leading::Content(content) => primary.content(content),
        };
        let primary = self
            .leading_style
            .apply(primary)
            .size(self.size)
            .variant(self.variant)
            .tone(self.leading_tone)
            .segment(Some(Segment::SplitLeading))
            .track_focus(&primary_focus)
            .disabled(self.disabled)
            .when_some(self.on_activate, |button, action| {
                button.on_activate(move |window, cx| action(window, cx))
            });

        let trailing_id = ElementId::from((self.id.clone(), "secondary"));
        let restore = trailing_focus.clone();
        let trailing = move |active| {
            let part = if matches!(self.trailing_content, Trailing::Content(_))
                || self.trailing_style.style.padding.is_some()
            {
                ButtonPart::intrinsic(trailing_id, self.trailing_name)
            } else {
                ButtonPart::new(
                    trailing_id,
                    self.trailing_name,
                    px(density.interactive_size(split_trailing_size(self.size).1)),
                )
            };
            let part = match self.trailing_content {
                Trailing::Arrow => part.icon(Icon::new(IconName::ArrowDropDown).rotate(
                    gpui::Radians(if active { std::f32::consts::PI } else { 0. }),
                )),
                Trailing::Icon(icon) => part.icon(icon),
                Trailing::Content(content) => part.content(content),
            };
            self.trailing_style
                .apply(part)
                .size(self.size)
                .variant(self.variant)
                .tone(self.trailing_tone)
                .segment(Some(Segment::SplitTrailing))
                .track_focus(&trailing_focus)
                .disabled(self.trailing_disabled)
        };
        let trailing = match self.trailing_action {
            TrailingAction::Menu(items) if self.trailing_disabled || items.is_empty() => {
                trailing(false).disabled(true).into_any_element()
            }
            TrailingAction::Menu(items) => {
                Menu::composed((self.id.clone(), "menu"), items, move |open, toggle| {
                    trailing(open)
                        .presentation_selected(open)
                        .on_accessible_activate(move |window, cx| {
                            restore.focus(window, cx);
                            toggle(window, cx);
                        })
                        .into_any_element()
                })
                .into_any_element()
            }
            TrailingAction::Invoke(command) => trailing(false)
                .on_activate(move |window, cx| command(window, cx))
                .into_any_element(),
            TrailingAction::Toggle { selected, change } => trailing(selected)
                .selected(Some(selected))
                .on_change(move |next, window, cx| change(next, window, cx))
                .into_any_element(),
        };
        div()
            .id(self.id)
            .role(Role::Group)
            .when_some(self.accessible_label, |group, label| {
                group.aria_label(label)
            })
            .flex()
            .items_center()
            .min_w_0()
            .max_w_full()
            .gap(self.spacing)
            .when(direction == Direction::Rtl, Styled::flex_row_reverse)
            .child(primary)
            .child(trailing)
    }
}

#[cfg(test)]
mod tests {
    use gpui_material_components::{ButtonColors, ControlElevations};
    use gpui_material_theme::{Elevation, LogicalEdges};

    use super::*;

    #[test]
    fn split_button_sets_outer_group_accessible_label_and_unified_segment_styles() {
        let leading = ButtonSegmentStyle {
            colors: ButtonColors {
                container: Some(gpui::hsla(0.2, 0.5, 0.5, 1.)),
                ..Default::default()
            },
            padding: Some(LogicalEdges::symmetric(14., 4.)),
            ..Default::default()
        };
        let trailing = ButtonSegmentStyle {
            elevations: ControlElevations {
                resting: Some(Elevation::Level2),
                ..Default::default()
            },
            ..Default::default()
        };
        let button = SplitButton::new("send", "Send", "More send options", [])
            .accessible_label("Send actions")
            .leading_style(leading)
            .trailing_style(trailing);

        assert_eq!(button.accessible_label.as_deref(), Some("Send actions"));
        assert_eq!(button.leading_style.style, leading);
        assert_eq!(button.trailing_style.style, trailing);
    }
}