gpui-material-components 0.3.2

Material 3 Expressive desktop components 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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
use std::{cell::RefCell, rc::Rc};

use gpui::{
    AccessibleAction, AnyElement, App, Axis, ElementId, Entity, FocusHandle, Hsla,
    InteractiveElement, IntoElement, ParentElement, RenderOnce, SharedString,
    StatefulInteractiveElement, Styled, Window, div, prelude::FluentBuilder, px,
};
use gpui_base::{Radio as BaseRadio, RadioGroup as BaseRadioGroup, TestSupportExt};
use gpui_material_foundation::{
    InteractionSource, ThemeScope, animate, current_material_theme, move_roving_focus,
};
use gpui_material_theme::{ColorRole, Direction, MotionKind, MotionSpeed};

use crate::action::{feedback_target, ripple_state, ripple_target};

use super::{focus_style, row, selection_label, selection_target, selection_tone, tone};

type RadioChange = Rc<dyn Fn(&ElementId, &mut Window, &mut App)>;

/// Radio indicator pigments. Omitted values use the current window theme.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct RadioColors {
    /// Ring and inner dot color when enabled and selected.
    pub selected: Option<Hsla>,
    /// Ring color when enabled and unselected.
    pub unselected: Option<Hsla>,
    /// Ring and inner dot color when disabled and selected.
    pub disabled_selected: Option<Hsla>,
    /// Ring color when disabled and unselected.
    pub disabled_unselected: Option<Hsla>,
}

impl RadioColors {
    fn resolve(self, selected: bool, disabled: bool, window: &Window, cx: &App) -> Hsla {
        match (selected, disabled) {
            (true, false) => self.selected,
            (false, false) => self.unselected,
            (true, true) => self.disabled_selected,
            (false, true) => self.disabled_unselected,
        }
        .unwrap_or_else(|| selection_tone(selected, disabled, window, cx))
    }
}

/// A radio option. A group owns the tab stop and the caller owns selection.
#[derive(IntoElement)]
pub struct Radio {
    id: ElementId,
    label: SharedString,
    show_label: bool,
    label_content: Option<AnyElement>,
    selected: bool,
    disabled: bool,
    on_select: Option<crate::action::Activate>,
    colors: RadioColors,
    focus: Option<FocusHandle>,
    interaction_source: Option<Entity<InteractionSource>>,
    decorative: bool,
}

impl Radio {
    /// Creates a radio option with an element ID and visible/accessible label.
    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            show_label: true,
            label_content: None,
            selected: false,
            disabled: false,
            on_select: None,
            colors: RadioColors::default(),
            focus: None,
            interaction_source: None,
            decorative: false,
        }
    }

    #[cfg(feature = "surfaces")]
    pub(crate) fn decorative(mut self, decorative: bool) -> Self {
        self.decorative = decorative;
        self
    }

    /// Controls whether the visible label is rendered. Defaults to `true`.
    /// When `false`, the constructor's label remains the accessible name and the trailing gap is omitted.
    pub fn show_label(mut self, show: bool) -> Self {
        self.show_label = show;
        self
    }

    /// Replaces the visible label while keeping the constructor's label as the accessible name.
    pub fn label_content(mut self, content: impl IntoElement) -> Self {
        self.label_content = Some(content.into_any_element());
        self
    }

    /// Sets the controlled selected state of a standalone radio button.
    pub fn selected(mut self, selected: bool) -> Self {
        self.selected = selected;
        self
    }

    /// Disables selection and keyboard focus for this option when `true`.
    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    /// Invoked when this standalone radio option is selected.
    pub fn on_select(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        self.on_select = Some(Rc::new(handler));
        self
    }

    /// Overrides indicator colors for the four enabled and selected combinations.
    pub fn colors(mut self, colors: RadioColors) -> Self {
        self.colors = colors;
        self
    }

    /// Uses the caller's focus handle instead of an internal keyed handle, both standalone and
    /// inside a [`RadioGroup`].
    pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
        self.focus = Some(focus.clone());
        self
    }

    /// Observes hover, press, keyboard focus, and disabled state.
    /// Group options are observed under their rendered, group-scoped IDs.
    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
        self.interaction_source = Some(source.clone());
        self
    }

    fn render_indicator(&self, window: &mut Window, cx: &mut App) -> (Hsla, gpui::Div) {
        let motion = current_material_theme(window, cx).motion;
        let reduced = self.disabled || cx.reduce_motion();
        let dot = animate(
            (self.id.clone(), "radio-dot"),
            f32::from(self.selected),
            motion.spec(MotionKind::Spatial, MotionSpeed::Fast, reduced),
            window,
            cx,
        )
        .clamp(0., 1.);
        let tint = animate(
            (self.id.clone(), "radio-color"),
            f32::from(self.selected),
            motion.spec(MotionKind::Effects, MotionSpeed::Fast, reduced),
            window,
            cx,
        )
        .clamp(0., 1.);
        let accent = crate::motion::mix(
            self.colors.resolve(false, self.disabled, window, cx),
            self.colors.resolve(true, self.disabled, window, cx),
            tint,
        );
        let indicator = div()
            .size(px(20.))
            .rounded_full()
            .border_2()
            .border_color(accent)
            .flex()
            .items_center()
            .justify_center()
            .child(div().size(px(10. * dot)).rounded_full().bg(accent));
        (accent, indicator)
    }

    fn render_control(
        self,
        focus: Option<FocusHandle>,
        position: Option<(usize, usize)>,
        tab_stop: bool,
        window: &mut Window,
        cx: &mut App,
    ) -> BaseRadio {
        let (accent, indicator) = self.render_indicator(window, cx);
        let direction = current_material_theme(window, cx).layout.direction;
        let ripple = ripple_state(&self.id, !self.disabled, window, cx);
        let focus = focus.or(self.focus).unwrap_or_else(|| {
            // Match Base's standalone focus ID so changing the source retains focus.
            window
                .use_keyed_state(self.id.clone(), cx, |_, cx| cx.focus_handle())
                .read(cx)
                .clone()
        });
        let tracker = self
            .interaction_source
            .as_ref()
            .map(|source| InteractionSource::track(source, &self.id, window, cx));
        let observed = tracker.is_some();
        ripple
            .borrow_mut()
            .track(!self.disabled, &focus, tracker, window, cx);
        let group: SharedString = format!("material-radio/{}", self.id).into();
        let radio = BaseRadio::new(self.id)
            .when(!self.disabled, |control| {
                if observed {
                    feedback_target(control, ripple.clone(), true, Some(focus.clone()))
                } else {
                    ripple_target(control, ripple.clone())
                }
            })
            .checked(self.selected)
            .disabled(self.disabled)
            .tab_stop(tab_stop)
            .accessibility_label(self.label.clone())
            .group(group.clone())
            .border_2()
            .border_color(gpui::transparent_black())
            .rounded_md()
            .focus_visible(focus_style(tone(ColorRole::Secondary, window, cx)))
            .child(
                row(direction, self.show_label)
                    .child(selection_target(
                        group,
                        indicator,
                        accent,
                        !self.disabled,
                        ripple,
                        direction,
                        cx.reduce_motion(),
                    ))
                    .children(self.show_label.then(|| {
                        selection_label(self.label, self.label_content, self.disabled, window, cx)
                    })),
            )
            .track_focus(&focus)
            .when_some(position, |radio, (position, size)| {
                radio.set_position(position, size)
            });
        match self.on_select {
            Some(handler) if !self.disabled => {
                let handler = Rc::new(ThemeScope::bind_action(
                    move |window, cx| handler(window, cx),
                    window,
                    cx,
                ));
                let select = handler.clone();
                radio
                    .when(!self.selected, |radio| {
                        radio.on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
                            select(window, cx)
                        })
                    })
                    .on_change(move |_, _, window, cx| handler(window, cx))
            }
            _ => radio,
        }
    }
}

impl RenderOnce for Radio {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        if self.decorative {
            let (_, indicator) = self.render_indicator(window, cx);
            return div()
                .id(self.id)
                .test_support()
                .flex_none()
                .size(px(24.))
                .flex()
                .items_center()
                .justify_center()
                .child(indicator)
                .into_any_element();
        }
        self.render_control(None, None, true, window, cx)
            .into_any_element()
    }
}

/// A controlled single-selection group with one Tab stop and directional navigation.
#[derive(IntoElement)]
pub struct RadioGroup {
    id: ElementId,
    label: SharedString,
    selected: Option<ElementId>,
    options: Vec<Radio>,
    axis: Axis,
    on_select: Option<RadioChange>,
}

impl RadioGroup {
    /// Creates an empty vertical radio group with an element ID and accessible group label.
    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            selected: None,
            options: Vec::new(),
            axis: Axis::Vertical,
            on_select: None,
        }
    }

    /// Sets the ID of the currently selected option.
    pub fn selected(mut self, selected: impl Into<ElementId>) -> Self {
        self.selected = Some(selected.into());
        self
    }

    /// Appends [`Radio`] options to the group.
    pub fn options(mut self, options: impl IntoIterator<Item = Radio>) -> Self {
        self.options.extend(options);
        self
    }

    /// Sets the layout and arrow-key navigation axis (`Axis::Vertical` by default).
    pub fn axis(mut self, axis: Axis) -> Self {
        self.axis = axis;
        self
    }

    /// Invoked with the selected option's ID when selection changes via click or arrow keys.
    pub fn on_select(
        mut self,
        handler: impl Fn(&ElementId, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_select = Some(Rc::new(handler));
        self
    }
}

impl RenderOnce for RadioGroup {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let direction = current_material_theme(window, cx).layout.direction;
        let current = self
            .options
            .iter()
            .position(|item| !item.disabled && Some(&item.id) == self.selected.as_ref());
        let tab_stop = current.or_else(|| self.options.iter().position(|item| !item.disabled));
        let size = self.options.len();
        let focus: Vec<_> = self
            .options
            .iter()
            .map(|item| {
                if let Some(focus) = &item.focus {
                    focus.clone()
                } else {
                    let id = ElementId::from((self.id.clone(), "radio-focus"));
                    window.with_id(id, |window| {
                        window
                            .use_keyed_state(item.id.clone(), cx, |_, cx| cx.focus_handle())
                            .read(cx)
                            .clone()
                    })
                }
            })
            .collect();
        let navigation: Vec<_> = self
            .options
            .iter()
            .zip(&focus)
            .map(|(item, focus)| (item.id.clone(), focus.clone(), !item.disabled))
            .collect();
        let change = self.on_select.clone().map(|change| {
            let pending = Rc::new(RefCell::new(None::<ElementId>));
            let pending_arg = pending.clone();
            let bound = ThemeScope::bind_action(
                move |window, cx| {
                    if let Some(id) = pending_arg.borrow_mut().take() {
                        change(&id, window, cx);
                    }
                },
                window,
                cx,
            );
            move |id: &ElementId, window: &mut Window, cx: &mut App| {
                *pending.borrow_mut() = Some(id.clone());
                bound(window, cx);
            }
        });
        let selected = self.selected.clone();
        let axis = self.axis;
        let group = BaseRadioGroup::new(self.id.clone())
            .axis(axis)
            .aria_label(self.label)
            .flex()
            .gap_1()
            .when(axis == Axis::Vertical, Styled::flex_col)
            .when(axis == Axis::Horizontal, Styled::flex_wrap)
            .when(
                axis == Axis::Horizontal && direction == Direction::Rtl,
                Styled::flex_row_reverse,
            )
            .on_key_down(move |event, window, cx| {
                let items: Vec<_> = navigation
                    .iter()
                    .map(|(_, focus, enabled)| (focus, *enabled))
                    .collect();
                let Some(ix) =
                    move_roving_focus(&items, &event.keystroke.key, axis, direction, window, cx)
                else {
                    return;
                };
                cx.stop_propagation();
                if let Some(change) = &change
                    && Some(&navigation[ix].0) != selected.as_ref()
                {
                    change(&navigation[ix].0, window, cx);
                }
            });

        group.children(self.options.into_iter().zip(focus).enumerate().map(
            |(ix, (mut radio, focus))| {
                let option_id = radio.id.clone();
                radio.id = ElementId::from((self.id.clone(), option_id.to_string()));
                radio.selected = Some(&option_id) == self.selected.as_ref();
                let handler = self.on_select.clone();
                radio.on_select = handler.map(|handler| {
                    let callback: crate::action::Activate =
                        Rc::new(move |window, cx| handler(&option_id, window, cx));
                    callback
                });
                radio.render_control(
                    Some(focus),
                    Some((ix + 1, size)),
                    Some(ix) == tab_stop,
                    window,
                    cx,
                )
            },
        ))
    }
}