gpui-material-components 0.3.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
use std::f32::consts::TAU;

use gpui::{
    App, Corners, ElementId, Hsla, InteractiveElement, IntoElement, ParentElement, Pixels,
    RenderOnce, Rgba, Role, SharedString, StatefulInteractiveElement, Styled, Window, canvas, div,
    fill, prelude::FluentBuilder, px,
};
use gpui_base::TestSupportExt;
use gpui_material_foundation::{
    LoopClock, Shape, ShapeFit, ShapePolygon, color, current_material_theme, is_bounds_visible,
};
use gpui_material_theme::{ColorRole, CornerRole, CornerShape, TypeRole, TypographyEmphasis};
use web_time::Instant;

const PULSE_PERIOD_SECS: f32 = 1.4;
const DEFAULT_TEXT_LINE_HEIGHT: Pixels = px(16.);

/// Optional base and highlight pigments for [`Skeleton`].
///
/// Defaults to `SurfaceContainerHigh` and `SurfaceContainerHighest`.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct SkeletonColors {
    pub base: Option<Hsla>,
    pub highlight: Option<Hsla>,
}

enum SkeletonGeometry {
    Rect {
        width: Option<Pixels>,
        height: Pixels,
        corner: CornerShape,
    },
    Shape {
        width: Pixels,
        height: Pixels,
        polygon: ShapePolygon,
    },
}

/// An animated Material 3 loading placeholder built on [`LoopClock`] and
/// [`is_bounds_visible`].
///
/// Offscreen or clipped skeletons schedule zero animation frames, and
/// `reduced_motion` or `.animated(false)` renders the static base color with
/// zero animation frames.
#[derive(IntoElement)]
pub struct Skeleton {
    id: ElementId,
    geometry: SkeletonGeometry,
    text_role: Option<TypeRole>,
    colors: SkeletonColors,
    animated: bool,
    accessible_label: Option<SharedString>,
}

impl Skeleton {
    /// Creates a rectangular placeholder with `CornerRole::Small` corners.
    pub fn rect(id: impl Into<ElementId>, width: Pixels, height: Pixels) -> Self {
        Self {
            id: id.into(),
            geometry: SkeletonGeometry::Rect {
                width: Some(sanitize_extent(width)),
                height: sanitize_extent(height),
                corner: CornerRole::Small.shape(),
            },
            text_role: None,
            colors: SkeletonColors::default(),
            animated: true,
            accessible_label: None,
        }
    }

    /// Creates a full-width single-line text placeholder (default 16 dp height,
    /// `CornerRole::Small`).
    pub fn text_line(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            geometry: SkeletonGeometry::Rect {
                width: None,
                height: DEFAULT_TEXT_LINE_HEIGHT,
                corner: CornerRole::Small.shape(),
            },
            text_role: None,
            colors: SkeletonColors::default(),
            animated: true,
            accessible_label: None,
        }
    }

    /// Creates a circular placeholder (`CornerRole::Full`).
    pub fn circle(id: impl Into<ElementId>, diameter: Pixels) -> Self {
        let side = sanitize_extent(diameter);
        Self {
            id: id.into(),
            geometry: SkeletonGeometry::Rect {
                width: Some(side),
                height: side,
                corner: CornerRole::Full.shape(),
            },
            text_role: None,
            colors: SkeletonColors::default(),
            animated: true,
            accessible_label: None,
        }
    }

    /// Creates a placeholder using any Foundation [`ShapePolygon`] (including
    /// [`gpui_material_theme::MaterialShape`] presets such as `Cookie7Sided`).
    pub fn shape(
        id: impl Into<ElementId>,
        width: Pixels,
        height: Pixels,
        shape: impl Into<ShapePolygon>,
    ) -> Self {
        Self {
            id: id.into(),
            geometry: SkeletonGeometry::Shape {
                width: sanitize_extent(width),
                height: sanitize_extent(height),
                polygon: shape.into(),
            },
            text_role: None,
            colors: SkeletonColors::default(),
            animated: true,
            accessible_label: None,
        }
    }

    /// Expands a rectangular or text-line placeholder to fill its parent's width.
    pub fn full_width(mut self) -> Self {
        if let SkeletonGeometry::Rect { width, .. } = &mut self.geometry {
            *width = None;
        }
        self
    }

    /// Sets an explicit width in logical pixels.
    pub fn width(mut self, width: Pixels) -> Self {
        let width = sanitize_extent(width);
        match &mut self.geometry {
            SkeletonGeometry::Rect { width: slot, .. } => *slot = Some(width),
            SkeletonGeometry::Shape { width: slot, .. } => *slot = width,
        }
        self
    }

    /// Sets an explicit height in logical pixels, overriding any `.role(...)`.
    pub fn height(mut self, height: Pixels) -> Self {
        let height = sanitize_extent(height);
        self.text_role = None;
        match &mut self.geometry {
            SkeletonGeometry::Rect { height: slot, .. } => *slot = height,
            SkeletonGeometry::Shape { height: slot, .. } => *slot = height,
        }
        self
    }

    /// Sizes a text-line or rectangular placeholder's height to match a Material
    /// typography role's scaled line height.
    pub fn role(mut self, role: TypeRole) -> Self {
        self.text_role = Some(role);
        self
    }

    /// Sets custom logical corners on rectangular, text-line, or circular placeholders.
    pub fn corner(mut self, shape: CornerShape) -> Self {
        if let SkeletonGeometry::Rect { corner, .. } = &mut self.geometry {
            *corner = shape;
        }
        self
    }

    /// Sets a Material [`CornerRole`] on rectangular, text-line, or circular placeholders.
    pub fn corner_role(self, role: CornerRole) -> Self {
        self.corner(role.shape())
    }

    /// Overrides the resting base and pulse highlight colors.
    pub fn colors(mut self, colors: SkeletonColors) -> Self {
        self.colors = colors;
        self
    }

    /// Enables or disables the pulse animation. Defaults to `true`.
    pub fn animated(mut self, animated: bool) -> Self {
        self.animated = animated;
        self
    }

    /// Exposes an optional `Role::Status` label for assistive technology without
    /// adding a keyboard Tab stop. Placeholders are decorative by default.
    pub fn accessible_label(mut self, label: impl Into<SharedString>) -> Self {
        self.accessible_label = Some(label.into());
        self
    }
}

impl RenderOnce for Skeleton {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = current_material_theme(window, cx);
        let direction = theme.layout.direction;
        let base = self
            .colors
            .base
            .unwrap_or_else(|| color(theme.colors.color(ColorRole::SurfaceContainerHigh)));
        let highlight = self
            .colors
            .highlight
            .unwrap_or_else(|| color(theme.colors.color(ColorRole::SurfaceContainerHighest)));
        let role_height = self.text_role.map(|role| {
            let scaled = theme
                .typography
                .scale_style(role.style(TypographyEmphasis::Baseline));
            px(scaled.line_height)
        });

        let reduced = cx.reduce_motion();
        let running = self.animated && !reduced && window.is_window_active() && window.is_visible();
        let motion = self.animated.then(|| {
            window.use_keyed_state((self.id.clone(), "skeleton-motion"), cx, |_, _| {
                SkeletonMotion::default()
            })
        });
        let phase = if let Some(motion) = &motion {
            let now = cx.background_executor().now();
            motion.update(cx, |state, _| {
                state.phase(now, running && state.visible, reduced)
            })
        } else {
            0.
        };
        let fill_color = if running {
            mix_color(base, highlight, pulse_fraction(phase))
        } else {
            base
        };

        let (width, height, paint_kind) = match self.geometry {
            SkeletonGeometry::Rect {
                width,
                height,
                corner,
            } => (
                width,
                role_height.unwrap_or(height),
                PaintKind::Rect(corner),
            ),
            SkeletonGeometry::Shape {
                width,
                height,
                polygon,
            } => (Some(width), height, PaintKind::Polygon(polygon)),
        };

        let painter = canvas(
            |_, _, _| (),
            move |bounds, (), window, cx| {
                let visible = is_bounds_visible(bounds, window);
                if let Some(motion) = &motion {
                    let now = cx.background_executor().now();
                    motion.update(cx, |state, _| {
                        state.set_visible(visible, now);
                    });
                }
                if !visible {
                    return;
                }
                match &paint_kind {
                    PaintKind::Rect(corner) => {
                        let [top_left, top_right, bottom_right, bottom_left] = corner
                            .radii(
                                f32::from(bounds.size.width),
                                f32::from(bounds.size.height),
                                direction,
                            )
                            .map(px);
                        window.paint_quad(fill(bounds, fill_color).corner_radii(Corners {
                            top_left,
                            top_right,
                            bottom_right,
                            bottom_left,
                        }));
                    }
                    PaintKind::Polygon(polygon) => {
                        if let Some(shape) = Shape::polygon(bounds, polygon, ShapeFit::Contain) {
                            window.paint_path(shape.fill_path().clone(), fill_color);
                        }
                    }
                }
                if running {
                    window.request_animation_frame();
                }
            },
        )
        .size_full();

        div()
            .id(self.id)
            .test_support()
            .h(height)
            .when_some(width, |el, w| el.w(w).flex_none())
            .when(width.is_none(), Styled::w_full)
            .when_some(self.accessible_label, |el, label| {
                el.role(Role::Status).aria_label(label)
            })
            .child(painter)
    }
}

enum PaintKind {
    Rect(CornerShape),
    Polygon(ShapePolygon),
}

struct SkeletonMotion {
    clock: LoopClock,
    visible: bool,
}

impl Default for SkeletonMotion {
    fn default() -> Self {
        Self {
            clock: LoopClock::default(),
            visible: true,
        }
    }
}

impl SkeletonMotion {
    fn set_visible(&mut self, visible: bool, now: Instant) {
        if self.visible != visible {
            self.visible = visible;
            if !visible {
                self.clock.pause(now);
            }
        }
    }

    fn phase(&mut self, now: Instant, running: bool, reduced: bool) -> f32 {
        self.clock.advance(now, running, reduced).as_secs_f32() / PULSE_PERIOD_SECS
    }
}

fn pulse_fraction(phase: f32) -> f32 {
    if !phase.is_finite() {
        return 0.;
    }
    (0.5 - 0.5 * (phase.fract() * TAU).cos()).clamp(0., 1.)
}

fn sanitize_extent(value: Pixels) -> Pixels {
    let raw = f32::from(value);
    if raw.is_finite() && raw >= 0. {
        value
    } else {
        px(0.)
    }
}

fn mix_color(from: Hsla, to: Hsla, fraction: f32) -> Hsla {
    let fraction = fraction.clamp(0., 1.);
    if fraction == 0. {
        return from;
    }
    if fraction == 1. {
        return to;
    }
    let from = Rgba::from(from);
    let to = Rgba::from(to);
    let lerp = |a, b| a + (b - a) * fraction;
    Rgba {
        r: lerp(from.r, to.r),
        g: lerp(from.g, to.g),
        b: lerp(from.b, to.b),
        a: lerp(from.a, to.a),
    }
    .into()
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use super::*;
    use gpui_material_theme::MaterialShape;

    #[test]
    fn pulse_fraction_starts_and_ends_at_base_and_peaks_at_half_period() {
        assert!((pulse_fraction(0.) - 0.).abs() < 1e-5);
        assert!((pulse_fraction(0.5) - 1.).abs() < 1e-5);
        assert!((pulse_fraction(1.) - 0.).abs() < 1e-5);
        assert!((pulse_fraction(1.5) - 1.).abs() < 1e-5);
        assert_eq!(pulse_fraction(f32::NAN), 0.);
    }

    #[test]
    fn skeleton_motion_pauses_offscreen_and_resets_under_reduced_motion() {
        let mut motion = SkeletonMotion::default();
        let start = Instant::now();
        let at = |ms| start + Duration::from_millis(ms);

        assert_eq!(motion.phase(start, true, false), 0.);
        let mid = motion.phase(at(350), true, false);
        assert!(mid > 0.);
        motion.set_visible(false, at(350));
        assert!(!motion.visible);
        assert_eq!(motion.phase(at(700), false, false), mid);
        motion.set_visible(true, at(700));
        assert_eq!(motion.phase(at(700), true, false), mid);
        assert!(motion.phase(at(1050), true, false) > mid);
        assert_eq!(motion.phase(at(1100), false, true), 0.);
    }

    #[test]
    fn skeleton_constructors_sanitize_dimensions_and_accept_material_shapes() {
        assert_eq!(sanitize_extent(px(-10.)), px(0.));
        assert_eq!(sanitize_extent(px(f32::NAN)), px(0.));
        assert_eq!(sanitize_extent(px(24.)), px(24.));
        let cookie = Skeleton::shape("cookie", px(48.), px(48.), MaterialShape::Cookie7Sided);
        assert!(matches!(
            cookie.geometry,
            SkeletonGeometry::Shape {
                width,
                height,
                ..
            } if width == px(48.) && height == px(48.)
        ));
    }
}