Skip to main content

gpui_material_components/
skeleton.rs

1use std::f32::consts::TAU;
2
3use gpui::{
4    App, Bounds, Corners, ElementId, Entity, Hsla, InteractiveElement, IntoElement, ParentElement,
5    Path, Pixels, RenderOnce, Rgba, Role, SharedString, StatefulInteractiveElement, Styled, Window,
6    canvas, div, 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            } => {
255                let cache = window.use_keyed_state(
256                    (self.id.clone(), "skeleton-polygon-cache"),
257                    cx,
258                    |_, _| PolygonPathCache::default(),
259                );
260                (Some(width), height, PaintKind::Polygon(polygon, cache))
261            }
262        };
263
264        let painter = canvas(
265            |_, _, _| (),
266            move |bounds, (), window, cx| {
267                let visible = is_bounds_visible(bounds, window);
268                if let Some(motion) = &motion {
269                    let now = cx.background_executor().now();
270                    motion.update(cx, |state, _| {
271                        state.set_visible(visible, now);
272                    });
273                }
274                if !visible {
275                    return;
276                }
277                match &paint_kind {
278                    PaintKind::Rect(corner) => {
279                        let [top_left, top_right, bottom_right, bottom_left] = corner
280                            .radii(
281                                f32::from(bounds.size.width),
282                                f32::from(bounds.size.height),
283                                direction,
284                            )
285                            .map(px);
286                        window.paint_quad(fill(bounds, fill_color).corner_radii(Corners {
287                            top_left,
288                            top_right,
289                            bottom_right,
290                            bottom_left,
291                        }));
292                    }
293                    PaintKind::Polygon(polygon, cache) => {
294                        let path = cache.update(cx, |state, _| state.get_or_build(bounds, polygon));
295                        if let Some(path) = path {
296                            window.paint_path(path, fill_color);
297                        }
298                    }
299                }
300                if running {
301                    window.request_animation_frame();
302                }
303            },
304        )
305        .size_full();
306
307        div()
308            .id(self.id)
309            .test_support()
310            .h(height)
311            .when_some(width, |el, w| el.w(w).flex_none())
312            .when(width.is_none(), Styled::w_full)
313            .when_some(self.accessible_label, |el, label| {
314                el.role(Role::Status).aria_label(label)
315            })
316            .child(painter)
317    }
318}
319
320enum PaintKind {
321    Rect(CornerShape),
322    Polygon(ShapePolygon, Entity<PolygonPathCache>),
323}
324
325#[derive(Default)]
326struct PolygonPathCache {
327    key: Option<(Bounds<Pixels>, ShapePolygon)>,
328    path: Option<Path>,
329}
330
331impl PolygonPathCache {
332    fn get_or_build(&mut self, bounds: Bounds<Pixels>, polygon: &ShapePolygon) -> Option<Path> {
333        let matches = self
334            .key
335            .as_ref()
336            .is_some_and(|(cached_bounds, cached_polygon)| {
337                *cached_bounds == bounds && cached_polygon == polygon
338            });
339        if !matches {
340            self.key = Some((bounds, polygon.clone()));
341            self.path = Shape::polygon(bounds, polygon, ShapeFit::Contain)
342                .map(|shape| shape.fill_path().clone());
343        }
344        self.path.clone()
345    }
346}
347
348struct SkeletonMotion {
349    clock: LoopClock,
350    visible: bool,
351}
352
353impl Default for SkeletonMotion {
354    fn default() -> Self {
355        Self {
356            clock: LoopClock::default(),
357            visible: true,
358        }
359    }
360}
361
362impl SkeletonMotion {
363    fn set_visible(&mut self, visible: bool, now: Instant) {
364        if self.visible != visible {
365            self.visible = visible;
366            if !visible {
367                self.clock.pause(now);
368            }
369        }
370    }
371
372    fn phase(&mut self, now: Instant, running: bool, reduced: bool) -> f32 {
373        self.clock.advance(now, running, reduced).as_secs_f32() / PULSE_PERIOD_SECS
374    }
375}
376
377fn pulse_fraction(phase: f32) -> f32 {
378    if !phase.is_finite() {
379        return 0.;
380    }
381    (0.5 - 0.5 * (phase.fract() * TAU).cos()).clamp(0., 1.)
382}
383
384fn sanitize_extent(value: Pixels) -> Pixels {
385    let raw = f32::from(value);
386    if raw.is_finite() && raw >= 0. {
387        value
388    } else {
389        px(0.)
390    }
391}
392
393fn mix_color(from: Hsla, to: Hsla, fraction: f32) -> Hsla {
394    let fraction = fraction.clamp(0., 1.);
395    if fraction == 0. {
396        return from;
397    }
398    if fraction == 1. {
399        return to;
400    }
401    let from = Rgba::from(from);
402    let to = Rgba::from(to);
403    let lerp = |a, b| a + (b - a) * fraction;
404    Rgba {
405        r: lerp(from.r, to.r),
406        g: lerp(from.g, to.g),
407        b: lerp(from.b, to.b),
408        a: lerp(from.a, to.a),
409    }
410    .into()
411}
412
413#[cfg(test)]
414mod tests {
415    use std::time::Duration;
416
417    use super::*;
418    use gpui_material_theme::MaterialShape;
419
420    #[test]
421    fn pulse_fraction_starts_and_ends_at_base_and_peaks_at_half_period() {
422        assert!((pulse_fraction(0.) - 0.).abs() < 1e-5);
423        assert!((pulse_fraction(0.5) - 1.).abs() < 1e-5);
424        assert!((pulse_fraction(1.) - 0.).abs() < 1e-5);
425        assert!((pulse_fraction(1.5) - 1.).abs() < 1e-5);
426        assert_eq!(pulse_fraction(f32::NAN), 0.);
427    }
428
429    #[test]
430    fn skeleton_motion_pauses_offscreen_and_resets_under_reduced_motion() {
431        let mut motion = SkeletonMotion::default();
432        let start = Instant::now();
433        let at = |ms| start + Duration::from_millis(ms);
434
435        assert_eq!(motion.phase(start, true, false), 0.);
436        let mid = motion.phase(at(350), true, false);
437        assert!(mid > 0.);
438        motion.set_visible(false, at(350));
439        assert!(!motion.visible);
440        assert_eq!(motion.phase(at(700), false, false), mid);
441        motion.set_visible(true, at(700));
442        assert_eq!(motion.phase(at(700), true, false), mid);
443        assert!(motion.phase(at(1050), true, false) > mid);
444        assert_eq!(motion.phase(at(1100), false, true), 0.);
445    }
446
447    #[test]
448    fn skeleton_constructors_sanitize_dimensions_and_accept_material_shapes() {
449        assert_eq!(sanitize_extent(px(-10.)), px(0.));
450        assert_eq!(sanitize_extent(px(f32::NAN)), px(0.));
451        assert_eq!(sanitize_extent(px(24.)), px(24.));
452        let cookie = Skeleton::shape("cookie", px(48.), px(48.), MaterialShape::Cookie7Sided);
453        assert!(matches!(
454            cookie.geometry,
455            SkeletonGeometry::Shape {
456                width,
457                height,
458                ..
459            } if width == px(48.) && height == px(48.)
460        ));
461    }
462
463    #[test]
464    fn polygon_path_cache_reuses_and_invalidates_on_bounds_or_polygon_change() {
465        let mut cache = PolygonPathCache::default();
466        let bounds_a = Bounds::new(gpui::point(px(0.), px(0.)), gpui::size(px(48.), px(48.)));
467        let bounds_b = Bounds::new(gpui::point(px(0.), px(0.)), gpui::size(px(64.), px(64.)));
468        let cookie = ShapePolygon::from(MaterialShape::Cookie7Sided);
469        let other = ShapePolygon::from(MaterialShape::Cookie9Sided);
470
471        assert!(cache.get_or_build(bounds_a, &cookie).is_some());
472        assert_eq!(cache.key, Some((bounds_a, cookie.clone())));
473        // Same key reuses cached path.
474        assert!(cache.get_or_build(bounds_a, &cookie).is_some());
475        assert_eq!(cache.key, Some((bounds_a, cookie.clone())));
476        // Changed bounds updates key.
477        assert!(cache.get_or_build(bounds_b, &cookie).is_some());
478        assert_eq!(cache.key, Some((bounds_b, cookie.clone())));
479        // Changed polygon updates key.
480        assert!(cache.get_or_build(bounds_b, &other).is_some());
481        assert_eq!(cache.key, Some((bounds_b, other)));
482    }
483}