Skip to main content

gpui_material_components/
skeleton.rs

1use std::f32::consts::TAU;
2
3use gpui::{
4    App, Corners, ElementId, Hsla, InteractiveElement, IntoElement, ParentElement, Pixels,
5    RenderOnce, Rgba, Role, SharedString, StatefulInteractiveElement, Styled, Window, canvas, div,
6    fill, prelude::FluentBuilder, px,
7};
8use gpui_base::TestSupportExt;
9use gpui_material_foundation::{
10    LoopClock, Shape, ShapeFit, ShapePolygon, color, current_material_theme, is_bounds_visible,
11};
12use gpui_material_theme::{ColorRole, CornerRole, CornerShape, TypeRole, TypographyEmphasis};
13use web_time::Instant;
14
15const PULSE_PERIOD_SECS: f32 = 1.4;
16const DEFAULT_TEXT_LINE_HEIGHT: Pixels = px(16.);
17
18/// Optional base and highlight pigments for [`Skeleton`].
19///
20/// Defaults to `SurfaceContainerHigh` and `SurfaceContainerHighest`.
21#[derive(Clone, Copy, Debug, Default, PartialEq)]
22pub struct SkeletonColors {
23    /// Resting fill color of the skeleton placeholder.
24    pub base: Option<Hsla>,
25    /// Peak pulse highlight color interpolated during animation.
26    pub highlight: Option<Hsla>,
27}
28
29enum SkeletonGeometry {
30    Rect {
31        width: Option<Pixels>,
32        height: Pixels,
33        corner: CornerShape,
34    },
35    Shape {
36        width: Pixels,
37        height: Pixels,
38        polygon: ShapePolygon,
39    },
40}
41
42/// An animated Material 3 loading placeholder built on [`LoopClock`] and
43/// [`is_bounds_visible`].
44///
45/// Offscreen or clipped skeletons schedule zero animation frames, and
46/// `reduced_motion` or `.animated(false)` renders the static base color with
47/// zero animation frames.
48#[derive(IntoElement)]
49pub struct Skeleton {
50    id: ElementId,
51    geometry: SkeletonGeometry,
52    text_role: Option<TypeRole>,
53    colors: SkeletonColors,
54    animated: bool,
55    accessible_label: Option<SharedString>,
56}
57
58impl Skeleton {
59    /// Creates a rectangular placeholder with `CornerRole::Small` corners.
60    pub fn rect(id: impl Into<ElementId>, width: Pixels, height: Pixels) -> Self {
61        Self {
62            id: id.into(),
63            geometry: SkeletonGeometry::Rect {
64                width: Some(sanitize_extent(width)),
65                height: sanitize_extent(height),
66                corner: CornerRole::Small.shape(),
67            },
68            text_role: None,
69            colors: SkeletonColors::default(),
70            animated: true,
71            accessible_label: None,
72        }
73    }
74
75    /// Creates a full-width single-line text placeholder (default 16 dp height,
76    /// `CornerRole::Small`).
77    pub fn text_line(id: impl Into<ElementId>) -> Self {
78        Self {
79            id: id.into(),
80            geometry: SkeletonGeometry::Rect {
81                width: None,
82                height: DEFAULT_TEXT_LINE_HEIGHT,
83                corner: CornerRole::Small.shape(),
84            },
85            text_role: None,
86            colors: SkeletonColors::default(),
87            animated: true,
88            accessible_label: None,
89        }
90    }
91
92    /// Creates a circular placeholder (`CornerRole::Full`).
93    pub fn circle(id: impl Into<ElementId>, diameter: Pixels) -> Self {
94        let side = sanitize_extent(diameter);
95        Self {
96            id: id.into(),
97            geometry: SkeletonGeometry::Rect {
98                width: Some(side),
99                height: side,
100                corner: CornerRole::Full.shape(),
101            },
102            text_role: None,
103            colors: SkeletonColors::default(),
104            animated: true,
105            accessible_label: None,
106        }
107    }
108
109    /// Creates a placeholder using any Foundation [`ShapePolygon`] (including
110    /// [`gpui_material_theme::MaterialShape`] presets such as `Cookie7Sided`).
111    pub fn shape(
112        id: impl Into<ElementId>,
113        width: Pixels,
114        height: Pixels,
115        shape: impl Into<ShapePolygon>,
116    ) -> Self {
117        Self {
118            id: id.into(),
119            geometry: SkeletonGeometry::Shape {
120                width: sanitize_extent(width),
121                height: sanitize_extent(height),
122                polygon: shape.into(),
123            },
124            text_role: None,
125            colors: SkeletonColors::default(),
126            animated: true,
127            accessible_label: None,
128        }
129    }
130
131    /// Expands a rectangular or text-line placeholder to fill its parent's width.
132    pub fn full_width(mut self) -> Self {
133        if let SkeletonGeometry::Rect { width, .. } = &mut self.geometry {
134            *width = None;
135        }
136        self
137    }
138
139    /// Sets an explicit width in logical pixels.
140    pub fn width(mut self, width: Pixels) -> Self {
141        let width = sanitize_extent(width);
142        match &mut self.geometry {
143            SkeletonGeometry::Rect { width: slot, .. } => *slot = Some(width),
144            SkeletonGeometry::Shape { width: slot, .. } => *slot = width,
145        }
146        self
147    }
148
149    /// Sets an explicit height in logical pixels, overriding any `.role(...)`.
150    pub fn height(mut self, height: Pixels) -> Self {
151        let height = sanitize_extent(height);
152        self.text_role = None;
153        match &mut self.geometry {
154            SkeletonGeometry::Rect { height: slot, .. } => *slot = height,
155            SkeletonGeometry::Shape { height: slot, .. } => *slot = height,
156        }
157        self
158    }
159
160    /// Sizes a text-line or rectangular placeholder's height to match a Material
161    /// typography role's scaled line height.
162    pub fn role(mut self, role: TypeRole) -> Self {
163        self.text_role = Some(role);
164        self
165    }
166
167    /// Sets custom logical corners on rectangular, text-line, or circular placeholders.
168    pub fn corner(mut self, shape: CornerShape) -> Self {
169        if let SkeletonGeometry::Rect { corner, .. } = &mut self.geometry {
170            *corner = shape;
171        }
172        self
173    }
174
175    /// Sets a Material [`CornerRole`] on rectangular, text-line, or circular placeholders.
176    pub fn corner_role(self, role: CornerRole) -> Self {
177        self.corner(role.shape())
178    }
179
180    /// Overrides the resting base and pulse highlight colors.
181    pub fn colors(mut self, colors: SkeletonColors) -> Self {
182        self.colors = colors;
183        self
184    }
185
186    /// Enables or disables the pulse animation. Defaults to `true`.
187    pub fn animated(mut self, animated: bool) -> Self {
188        self.animated = animated;
189        self
190    }
191
192    /// Exposes an optional `Role::Status` label for assistive technology without
193    /// adding a keyboard Tab stop. Placeholders are decorative by default.
194    pub fn accessible_label(mut self, label: impl Into<SharedString>) -> Self {
195        self.accessible_label = Some(label.into());
196        self
197    }
198}
199
200impl RenderOnce for Skeleton {
201    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
202        let theme = current_material_theme(window, cx);
203        let direction = theme.layout.direction;
204        let base = self
205            .colors
206            .base
207            .unwrap_or_else(|| color(theme.colors.color(ColorRole::SurfaceContainerHigh)));
208        let highlight = self
209            .colors
210            .highlight
211            .unwrap_or_else(|| color(theme.colors.color(ColorRole::SurfaceContainerHighest)));
212        let role_height = self.text_role.map(|role| {
213            let scaled = theme
214                .typography
215                .scale_style(role.style(TypographyEmphasis::Baseline));
216            px(scaled.line_height)
217        });
218
219        let reduced = cx.reduce_motion();
220        let running = self.animated && !reduced && window.is_window_active() && window.is_visible();
221        let motion = self.animated.then(|| {
222            window.use_keyed_state((self.id.clone(), "skeleton-motion"), cx, |_, _| {
223                SkeletonMotion::default()
224            })
225        });
226        let phase = if let Some(motion) = &motion {
227            let now = cx.background_executor().now();
228            motion.update(cx, |state, _| {
229                state.phase(now, running && state.visible, reduced)
230            })
231        } else {
232            0.
233        };
234        let fill_color = if running {
235            mix_color(base, highlight, pulse_fraction(phase))
236        } else {
237            base
238        };
239
240        let (width, height, paint_kind) = match self.geometry {
241            SkeletonGeometry::Rect {
242                width,
243                height,
244                corner,
245            } => (
246                width,
247                role_height.unwrap_or(height),
248                PaintKind::Rect(corner),
249            ),
250            SkeletonGeometry::Shape {
251                width,
252                height,
253                polygon,
254            } => (Some(width), height, PaintKind::Polygon(polygon)),
255        };
256
257        let painter = canvas(
258            |_, _, _| (),
259            move |bounds, (), window, cx| {
260                let visible = is_bounds_visible(bounds, window);
261                if let Some(motion) = &motion {
262                    let now = cx.background_executor().now();
263                    motion.update(cx, |state, _| {
264                        state.set_visible(visible, now);
265                    });
266                }
267                if !visible {
268                    return;
269                }
270                match &paint_kind {
271                    PaintKind::Rect(corner) => {
272                        let [top_left, top_right, bottom_right, bottom_left] = corner
273                            .radii(
274                                f32::from(bounds.size.width),
275                                f32::from(bounds.size.height),
276                                direction,
277                            )
278                            .map(px);
279                        window.paint_quad(fill(bounds, fill_color).corner_radii(Corners {
280                            top_left,
281                            top_right,
282                            bottom_right,
283                            bottom_left,
284                        }));
285                    }
286                    PaintKind::Polygon(polygon) => {
287                        if let Some(shape) = Shape::polygon(bounds, polygon, ShapeFit::Contain) {
288                            window.paint_path(shape.fill_path().clone(), fill_color);
289                        }
290                    }
291                }
292                if running {
293                    window.request_animation_frame();
294                }
295            },
296        )
297        .size_full();
298
299        div()
300            .id(self.id)
301            .test_support()
302            .h(height)
303            .when_some(width, |el, w| el.w(w).flex_none())
304            .when(width.is_none(), Styled::w_full)
305            .when_some(self.accessible_label, |el, label| {
306                el.role(Role::Status).aria_label(label)
307            })
308            .child(painter)
309    }
310}
311
312enum PaintKind {
313    Rect(CornerShape),
314    Polygon(ShapePolygon),
315}
316
317struct SkeletonMotion {
318    clock: LoopClock,
319    visible: bool,
320}
321
322impl Default for SkeletonMotion {
323    fn default() -> Self {
324        Self {
325            clock: LoopClock::default(),
326            visible: true,
327        }
328    }
329}
330
331impl SkeletonMotion {
332    fn set_visible(&mut self, visible: bool, now: Instant) {
333        if self.visible != visible {
334            self.visible = visible;
335            if !visible {
336                self.clock.pause(now);
337            }
338        }
339    }
340
341    fn phase(&mut self, now: Instant, running: bool, reduced: bool) -> f32 {
342        self.clock.advance(now, running, reduced).as_secs_f32() / PULSE_PERIOD_SECS
343    }
344}
345
346fn pulse_fraction(phase: f32) -> f32 {
347    if !phase.is_finite() {
348        return 0.;
349    }
350    (0.5 - 0.5 * (phase.fract() * TAU).cos()).clamp(0., 1.)
351}
352
353fn sanitize_extent(value: Pixels) -> Pixels {
354    let raw = f32::from(value);
355    if raw.is_finite() && raw >= 0. {
356        value
357    } else {
358        px(0.)
359    }
360}
361
362fn mix_color(from: Hsla, to: Hsla, fraction: f32) -> Hsla {
363    let fraction = fraction.clamp(0., 1.);
364    if fraction == 0. {
365        return from;
366    }
367    if fraction == 1. {
368        return to;
369    }
370    let from = Rgba::from(from);
371    let to = Rgba::from(to);
372    let lerp = |a, b| a + (b - a) * fraction;
373    Rgba {
374        r: lerp(from.r, to.r),
375        g: lerp(from.g, to.g),
376        b: lerp(from.b, to.b),
377        a: lerp(from.a, to.a),
378    }
379    .into()
380}
381
382#[cfg(test)]
383mod tests {
384    use std::time::Duration;
385
386    use super::*;
387    use gpui_material_theme::MaterialShape;
388
389    #[test]
390    fn pulse_fraction_starts_and_ends_at_base_and_peaks_at_half_period() {
391        assert!((pulse_fraction(0.) - 0.).abs() < 1e-5);
392        assert!((pulse_fraction(0.5) - 1.).abs() < 1e-5);
393        assert!((pulse_fraction(1.) - 0.).abs() < 1e-5);
394        assert!((pulse_fraction(1.5) - 1.).abs() < 1e-5);
395        assert_eq!(pulse_fraction(f32::NAN), 0.);
396    }
397
398    #[test]
399    fn skeleton_motion_pauses_offscreen_and_resets_under_reduced_motion() {
400        let mut motion = SkeletonMotion::default();
401        let start = Instant::now();
402        let at = |ms| start + Duration::from_millis(ms);
403
404        assert_eq!(motion.phase(start, true, false), 0.);
405        let mid = motion.phase(at(350), true, false);
406        assert!(mid > 0.);
407        motion.set_visible(false, at(350));
408        assert!(!motion.visible);
409        assert_eq!(motion.phase(at(700), false, false), mid);
410        motion.set_visible(true, at(700));
411        assert_eq!(motion.phase(at(700), true, false), mid);
412        assert!(motion.phase(at(1050), true, false) > mid);
413        assert_eq!(motion.phase(at(1100), false, true), 0.);
414    }
415
416    #[test]
417    fn skeleton_constructors_sanitize_dimensions_and_accept_material_shapes() {
418        assert_eq!(sanitize_extent(px(-10.)), px(0.));
419        assert_eq!(sanitize_extent(px(f32::NAN)), px(0.));
420        assert_eq!(sanitize_extent(px(24.)), px(24.));
421        let cookie = Skeleton::shape("cookie", px(48.), px(48.), MaterialShape::Cookie7Sided);
422        assert!(matches!(
423            cookie.geometry,
424            SkeletonGeometry::Shape {
425                width,
426                height,
427                ..
428            } if width == px(48.) && height == px(48.)
429        ));
430    }
431}