1use std::time::Instant;
14
15use arc_motion::{arc_transition, is_reduced_motion};
16use arc_tokens::{ActiveArcTheme as _, ControlHeights, Radii, Spacing, oklab_mix};
17use gpui_kit::{
18 AnyElement, App, ElementId, IntoElement, ParentElement, RenderOnce, SharedString, Styled,
19 Window, div, prelude::*, px,
20};
21
22const PULSE_SECS: f32 = 1.8;
23const PULSE_CYCLES: f32 = 11.0;
24const STAGGER_SECS: f32 = 0.09;
25
26pub fn pulse_opacity(elapsed: f32, index: usize, ease: impl Fn(f32) -> f32) -> f32 {
28 let t = elapsed - index as f32 * STAGGER_SECS;
29 if t <= 0.0 || t >= PULSE_SECS * PULSE_CYCLES {
30 return 1.0;
31 }
32 let phase = (t % PULSE_SECS) / PULSE_SECS;
33 let half = if phase < 0.5 {
34 phase * 2.0
35 } else {
36 (1.0 - phase) * 2.0
37 };
38 1.0 - 0.48 * ease(half)
39}
40
41struct SkeletonInternal {
42 started: Instant,
43}
44
45#[derive(IntoElement)]
47pub struct Skeleton {
48 id: ElementId,
49 label: SharedString,
50 lines: usize,
51 avatar: bool,
52 loading: bool,
53 content: Option<AnyElement>,
54}
55
56impl Skeleton {
57 pub fn new(id: impl Into<ElementId>) -> Self {
58 Self {
59 id: id.into(),
60 label: "Loading content".into(),
61 lines: 3,
62 avatar: false,
63 loading: true,
64 content: None,
65 }
66 }
67
68 pub fn label(mut self, label: impl Into<SharedString>) -> Self {
69 self.label = label.into();
70 self
71 }
72
73 pub fn lines(mut self, lines: usize) -> Self {
74 self.lines = lines.clamp(1, 6);
75 self
76 }
77
78 pub fn avatar(mut self, avatar: bool) -> Self {
79 self.avatar = avatar;
80 self
81 }
82
83 pub fn loading(mut self, loading: bool) -> Self {
84 self.loading = loading;
85 self
86 }
87
88 pub fn content(mut self, content: impl IntoElement) -> Self {
90 self.content = Some(content.into_any_element());
91 self
92 }
93}
94
95impl RenderOnce for Skeleton {
96 fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
97 let theme = cx.arc_theme().clone();
98 let colors = theme.colors;
99 let motion = theme.motion;
100 let reduced = is_reduced_motion(cx);
101
102 let show_placeholder = self.content.is_none() || self.loading;
103
104 if !show_placeholder {
105 let p = arc_transition(
106 (self.id.clone(), "skeleton-content"),
107 1.0,
108 if reduced {
109 motion.duration.instant
110 } else {
111 motion.duration.standard
112 },
113 motion.ease.enter,
114 window,
115 cx,
116 );
117 let rise = if reduced { 0.0 } else { (1.0 - p) * 4.0 };
118 return div()
119 .id(self.id)
120 .w_full()
121 .mt(px(rise))
122 .opacity(p.clamp(0.0, 1.0))
123 .children(self.content.take())
124 .into_any_element();
125 }
126
127 let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-skeleton".into());
128 let internal = window.use_keyed_state(state_id, cx, |_, _| SkeletonInternal {
129 started: Instant::now(),
130 });
131 let elapsed = internal.read(cx).started.elapsed().as_secs_f32();
132 let animating = !reduced && elapsed < PULSE_SECS * PULSE_CYCLES + 1.0;
133 if animating {
134 window.request_animation_frame();
135 }
136
137 let easing = motion.ease.in_out.to_base_easing();
138 let opacity_for = |index: usize| {
139 if reduced {
140 1.0
141 } else {
142 pulse_opacity(elapsed, index, |t| easing.sample(t))
143 }
144 };
145
146 let block_color = oklab_mix(colors.border_strong, colors.surface, 0.38);
147 let offset = usize::from(self.avatar);
148 let widths = |i: usize, n: usize| -> f32 {
149 if i == 0 && n > 1 {
150 0.48
151 } else if i + 1 == n {
152 0.72
153 } else {
154 1.0
155 }
156 };
157
158 let mut lines = div()
159 .flex_1()
160 .min_w_0()
161 .pt(Spacing::S1)
162 .flex()
163 .flex_col()
164 .gap(Spacing::S3);
165 for i in 0..self.lines {
166 let h = if i == 0 && self.lines > 1 {
167 px(16.0)
168 } else {
169 px(12.0)
170 };
171 let frac = widths(i, self.lines);
172 lines = lines.child(
173 div()
174 .w(gpui_kit::relative(frac))
175 .h(h)
176 .rounded(Radii::CONTROL)
177 .bg(block_color)
178 .opacity(opacity_for(i + offset)),
179 );
180 }
181
182 div()
183 .id(self.id)
184 .w_full()
185 .min_w_0()
186 .flex()
187 .items_start()
188 .gap(Spacing::S4)
189 .when(self.avatar, |this| {
190 this.child(
191 div()
192 .flex_none()
193 .w(ControlHeights::MD)
194 .h(ControlHeights::MD)
195 .rounded(Radii::PILL)
196 .bg(block_color)
197 .opacity(opacity_for(0)),
198 )
199 })
200 .child(lines)
201 .into_any_element()
202 }
203}
204
205#[cfg(test)]
206mod tests {
207 use arc_tokens::{Accent, ThemeMode, install_arc_theme};
208 use gpui_kit::{Context, Render, TestAppContext, div, px, test::TestWindowExt as _};
209
210 use super::*;
211
212 struct SkeletonHost {
213 loading: bool,
214 }
215
216 impl Render for SkeletonHost {
217 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
218 div().w(px(360.0)).p(Spacing::S4).child(
219 Skeleton::new("sk")
220 .avatar(true)
221 .lines(3)
222 .loading(self.loading)
223 .content(div().child("Loaded content")),
224 )
225 }
226 }
227
228 #[test]
229 fn pulse_dims_then_recovers_and_rests() {
230 let lin = |t: f32| t;
231 assert_eq!(pulse_opacity(0.0, 0, lin), 1.0);
232 let mid = pulse_opacity(PULSE_SECS * 0.5, 0, lin);
233 assert!((mid - 0.52).abs() < 1e-4);
234 assert!(pulse_opacity(PULSE_SECS * 0.5 + 0.09, 1, lin) < 0.53);
235 assert_eq!(pulse_opacity(PULSE_SECS * PULSE_CYCLES + 1.0, 0, lin), 1.0);
236 assert_eq!(pulse_opacity(0.02, 3, lin), 1.0);
237 }
238
239 #[gpui_kit::test]
240 fn skeleton_swaps_placeholder_for_content(cx: &mut TestAppContext) {
241 cx.update(|cx| {
242 gpui_kit::init(cx);
243 install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
244 });
245 let (view, cx) = cx.add_window_view(|_, _| SkeletonHost { loading: true });
246 cx.update(|window, cx| {
247 window.render_frame(cx);
248 view.update(cx, |h, cx| {
249 h.loading = false;
250 cx.notify();
251 });
252 window.render_frame(cx);
253 view.update(cx, |h, cx| {
254 h.loading = true;
255 cx.notify();
256 });
257 window.render_frame(cx);
258 });
259 }
260}