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