gpui-material-components 0.2.0

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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
use std::cell::RefCell;
use std::rc::Rc;

use gpui::{
    AccessibleAction, AnyElement, App, Div, ElementId, Entity, Hsla, InteractiveElement,
    IntoElement, ParentElement, Pixels, RenderOnce, SharedString, Stateful,
    StatefulInteractiveElement, Styled, Window, div, prelude::FluentBuilder, px,
};
use gpui_base::{Switch as BaseSwitch, TestSupportExt};
use gpui_material_foundation::{InteractionSource, animate, current_material_theme};
use gpui_material_theme::{ColorRole, Direction, MotionKind, MotionSpec, MotionSpeed, StateLayer};

use crate::action::{Change, FeedbackState, feedback_target, ripple_ink, ripple_state};

use super::{focus_style, row, tone};

/// Optional pigments for one switch state. Omitted fields use the window theme.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct SwitchStateColors {
    pub track: Option<Hsla>,
    pub border: Option<Hsla>,
    pub thumb: Option<Hsla>,
    pub content: Option<Hsla>,
}

/// Per-instance colors for enabled and disabled switches in either checked state.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct SwitchColors {
    pub unchecked: SwitchStateColors,
    pub checked: SwitchStateColors,
    pub disabled_unchecked: SwitchStateColors,
    pub disabled_checked: SwitchStateColors,
}

struct SwitchPalette {
    track: Hsla,
    border: Hsla,
    thumb: Hsla,
    content: Hsla,
}

impl SwitchStateColors {
    fn resolve(self, defaults: SwitchPalette) -> SwitchPalette {
        SwitchPalette {
            track: self.track.unwrap_or(defaults.track),
            border: self.border.unwrap_or(defaults.border),
            thumb: self.thumb.unwrap_or(defaults.thumb),
            content: self.content.unwrap_or(defaults.content),
        }
    }
}

impl SwitchColors {
    fn resolve(
        self,
        checked: bool,
        disabled: bool,
        tint: f32,
        window: &Window,
        cx: &App,
    ) -> SwitchPalette {
        use ColorRole::*;
        let color = |role| tone(role, window, cx);
        if disabled {
            // Compose precomposites disabled pigments over the surface color.
            let muted = |role, opacity| color(Surface).blend(color(role).opacity(opacity));
            return if checked {
                self.disabled_checked.resolve(SwitchPalette {
                    track: muted(OnSurface, 0.12),
                    border: gpui::transparent_black(),
                    thumb: color(Surface),
                    content: muted(OnSurface, 0.38),
                })
            } else {
                self.disabled_unchecked.resolve(SwitchPalette {
                    track: muted(SurfaceContainerHighest, 0.12),
                    border: muted(OnSurface, 0.12),
                    thumb: muted(OnSurface, 0.38),
                    content: muted(SurfaceContainerHighest, 0.38),
                })
            };
        }

        let unchecked = self.unchecked.resolve(SwitchPalette {
            track: color(SurfaceContainerHighest),
            border: color(Outline),
            thumb: color(Outline),
            content: color(SurfaceContainerHighest),
        });
        let on = self.checked.resolve(SwitchPalette {
            track: color(Primary),
            border: unchecked.border.opacity(0.),
            thumb: color(OnPrimary),
            content: color(OnPrimaryContainer),
        });
        let mix = |off, on| match tint {
            0. => off,
            1. => on,
            _ => crate::motion::mix(off, on, tint),
        };
        SwitchPalette {
            track: mix(unchecked.track, on.track),
            border: mix(unchecked.border, on.border),
            thumb: mix(unchecked.thumb, on.thumb),
            content: if checked {
                on.content
            } else {
                unchecked.content
            },
        }
    }
}

/// Material switch. The caller owns the checked state and optional thumb content.
#[derive(IntoElement)]
pub struct Switch {
    id: ElementId,
    label: SharedString,
    checked: bool,
    disabled: bool,
    checked_icon: Option<AnyElement>,
    unchecked_icon: Option<AnyElement>,
    thumb_content: Option<AnyElement>,
    colors: SwitchColors,
    interaction_source: Option<Entity<InteractionSource>>,
    on_change: Option<Change>,
}

impl Switch {
    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>, checked: bool) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            checked,
            disabled: false,
            checked_icon: None,
            unchecked_icon: None,
            thumb_content: None,
            colors: SwitchColors::default(),
            interaction_source: None,
            on_change: None,
        }
    }

    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    pub fn checked_icon(mut self, icon: impl IntoElement) -> Self {
        self.checked_icon = Some(icon.into_any_element());
        self
    }

    pub fn unchecked_icon(mut self, icon: impl IntoElement) -> Self {
        self.unchecked_icon = Some(icon.into_any_element());
        self
    }

    /// Supplies decorative content in the centered 16 px thumb slot. The
    /// element takes precedence over the icon preset for this render.
    pub fn thumb_content(mut self, content: impl IntoElement) -> Self {
        self.thumb_content = Some(content.into_any_element());
        self
    }

    pub fn colors(mut self, colors: SwitchColors) -> Self {
        self.colors = colors;
        self
    }

    /// Reports presentation state to a caller-owned source.
    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
        self.interaction_source = Some(source.clone());
        self
    }

    pub fn on_change(mut self, handler: impl Fn(bool, &mut Window, &mut App) + 'static) -> Self {
        self.on_change = Some(Rc::new(handler));
        self
    }

    fn thumb_decoration(&mut self) -> Option<AnyElement> {
        let icon = if self.checked {
            self.checked_icon.take()
        } else {
            self.unchecked_icon.take()
        };
        self.thumb_content
            .take()
            .map(|content| {
                div()
                    .id("switch-thumb-content")
                    .role(gpui::Role::Group)
                    .a11y_synthetic_children(|tree| tree.parent_node().set_hidden())
                    .size(px(16.))
                    .overflow_hidden()
                    .flex()
                    .items_center()
                    .justify_center()
                    .child(content)
                    .into_any_element()
            })
            .or(icon)
    }

    fn thumb_geometry(
        &self,
        has_decoration: bool,
        active: bool,
        motion: MotionSpec,
        window: &mut Window,
        cx: &mut App,
    ) -> (f32, Pixels) {
        let normal_size = if self.checked || has_decoration {
            24.
        } else {
            16.
        };
        let diameter = animate(
            (self.id.clone(), "thumb-diameter"),
            if active { 28. } else { normal_size },
            if active { MotionSpec::Instant } else { motion },
            window,
            cx,
        )
        .clamp(16., 28.);
        let offset = animate(
            (self.id.clone(), "thumb-offset"),
            match (active, self.checked) {
                (true, false) => 2.,
                (true, true) => 22.,
                (false, true) => 24.,
                (false, false) => (32. - normal_size) / 2.,
            },
            if active { MotionSpec::Instant } else { motion },
            window,
            cx,
        );
        // Offset and diameter are sampled independently, including a reversal on release.
        (diameter, px(offset.clamp(2., 50. - diameter)))
    }
}

#[allow(clippy::too_many_arguments)]
fn render_state_layer(
    diameter: f32,
    checked: bool,
    disabled: bool,
    active: bool,
    group: &SharedString,
    ink: Rc<RefCell<FeedbackState>>,
    direction: Direction,
    window: &Window,
    cx: &App,
) -> Stateful<Div> {
    use ColorRole::*;
    let accent = tone(if checked { Primary } else { OnSurface }, window, cx);
    div()
        .id("switch-state-layer")
        .absolute()
        .size(px(40.))
        .left(px((diameter - 40.) / 2.))
        .top(px((diameter - 40.) / 2.))
        .rounded_full()
        .when(!disabled, |layer| {
            let static_pressed = active && cx.reduce_motion();
            layer
                .when(static_pressed, |layer| {
                    layer.bg(accent.opacity(StateLayer::Pressed.opacity()))
                })
                .when(!static_pressed, |layer| {
                    layer.group_hover(group.clone(), move |style| {
                        style.bg(accent.opacity(StateLayer::Hover.opacity()))
                    })
                })
                .when(cx.reduce_motion(), |layer| {
                    layer.group_active(group.clone(), move |style| {
                        style.bg(accent.opacity(StateLayer::Pressed.opacity()))
                    })
                })
        })
        .child(ripple_ink(
            ink,
            accent,
            gpui_material_theme::CornerRole::Full.shape(),
            direction,
        ))
}

#[allow(clippy::too_many_arguments)]
fn render_track(
    id: &ElementId,
    palette: SwitchPalette,
    diameter: f32,
    offset: Pixels,
    direction: Direction,
    state_layer: Stateful<Div>,
    decoration: Option<AnyElement>,
) -> impl IntoElement + use<> {
    let handle = div()
        .absolute()
        .top_0()
        .h_full()
        .w(px(diameter))
        .flex()
        .items_center()
        .justify_center()
        .when(direction == Direction::Ltr, |handle| handle.left(offset))
        .when(direction == Direction::Rtl, |handle| handle.right(offset))
        .child(
            div()
                .id((id.clone(), "switch-thumb"))
                .relative()
                .test_support()
                .size(px(diameter))
                .rounded_full()
                .bg(palette.thumb)
                .text_color(palette.content)
                .text_size(px(16.))
                .flex()
                .items_center()
                .justify_center()
                .child(state_layer)
                .children(decoration),
        );
    div()
        .id((id.clone(), "switch-track"))
        .test_support()
        .relative()
        .w(px(52.))
        .h(px(32.))
        .rounded_full()
        .bg(palette.track)
        .when(palette.border.a > 0., |track| {
            track.child(
                div()
                    .absolute()
                    .inset_0()
                    .rounded_full()
                    .border_2()
                    .border_color(palette.border),
            )
        })
        .child(handle)
}

impl RenderOnce for Switch {
    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = current_material_theme(window, cx);
        let direction = theme.layout.direction;
        let reduced = self.disabled || cx.reduce_motion();
        let motion = theme
            .motion
            .spec(MotionKind::Spatial, MotionSpeed::Fast, reduced);
        let effects = theme
            .motion
            .spec(MotionKind::Effects, MotionSpeed::Fast, reduced);
        let tint = animate(
            (self.id.clone(), "switch-color"),
            f32::from(self.checked),
            effects,
            window,
            cx,
        )
        .clamp(0., 1.);
        let palette = self
            .colors
            .resolve(self.checked, self.disabled, tint, window, cx);
        let decoration = self.thumb_decoration();
        let ripple = ripple_state(&self.id, !self.disabled, window, cx);
        let 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 observes_input = tracker.is_some();
        ripple
            .borrow_mut()
            .track(!self.disabled, &focus, tracker, window, cx);
        let active = ripple.borrow().pressed();
        let (diameter, offset) =
            self.thumb_geometry(decoration.is_some(), active, motion, window, cx);
        let group: SharedString = format!("material-switch/{}", self.id).into();
        let state_layer = render_state_layer(
            diameter,
            self.checked,
            self.disabled,
            active,
            &group,
            ripple.clone(),
            direction,
            window,
            cx,
        );
        let track = render_track(
            &self.id,
            palette,
            diameter,
            offset,
            direction,
            state_layer,
            decoration,
        );
        let control = BaseSwitch::new(self.id)
            .checked(self.checked)
            .disabled(self.disabled)
            .track_focus(&focus)
            .group(group)
            .accessibility_label(self.label.clone())
            .when(!self.disabled, |control| {
                feedback_target(
                    control,
                    ripple,
                    observes_input,
                    observes_input.then_some(focus),
                )
            })
            .border_2()
            .border_color(gpui::transparent_black())
            .rounded_md()
            .focus_visible(focus_style(tone(ColorRole::Secondary, window, cx)))
            .child(
                row(direction)
                    .id("switch-row")
                    .min_h(px(48.))
                    .px_1()
                    .child(track)
                    .child(self.label),
            );
        match self.on_change {
            Some(handler) if !self.disabled => {
                let change = handler.clone();
                control
                    .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
                        change(!self.checked, window, cx)
                    })
                    .on_change(move |checked, _, window, cx| handler(checked, window, cx))
            }
            _ => control,
        }
    }
}