Skip to main content

gpui_component/
shimmer.rs

1use gpui::{
2    Animation, AnimationExt as _, App, Bounds, ContentMask, Element, ElementId, GlobalElementId,
3    Hsla, InspectorElementId, IntoElement, LayoutId, ParentElement as _, Pixels, RenderOnce,
4    SharedString, StyleRefinement, Styled, StyledText, Window, div, point, px, size,
5};
6use web_time::Duration;
7
8use crate::{ActiveTheme as _, Colorize as _};
9
10const SHIMMER_LAYER_COUNT: usize = 12;
11const DEFAULT_SHIMMER_SPREAD: f32 = 0.3;
12
13/// The shimmer highlight half-width.
14///
15/// A relative spread follows the text width, keeping short and long labels
16/// proportionally lit. An absolute spread keeps the band the same physical
17/// width across labels, the way a fixed gradient would.
18#[derive(Clone, Copy, Debug, PartialEq)]
19pub enum ShimmerSpread {
20    /// Half-width as a fraction of the text width.
21    Relative(f32),
22    /// Half-width as a fixed length.
23    Absolute(Pixels),
24}
25
26impl Default for ShimmerSpread {
27    fn default() -> Self {
28        Self::Relative(DEFAULT_SHIMMER_SPREAD)
29    }
30}
31
32impl From<f32> for ShimmerSpread {
33    fn from(fraction: f32) -> Self {
34        Self::Relative(fraction)
35    }
36}
37
38impl From<Pixels> for ShimmerSpread {
39    fn from(length: Pixels) -> Self {
40        Self::Absolute(length)
41    }
42}
43
44/// The appearance and timing of a reusable text shimmer.
45///
46/// By default, the highlight's half-width spans 30% of the text width and
47/// completes one left-to-right sweep every two seconds. Its color follows the
48/// current text color and active theme.
49#[derive(Clone, Copy, Debug)]
50pub struct ShimmerStyle {
51    duration: Duration,
52    highlight_color: Option<Hsla>,
53    spread: ShimmerSpread,
54    reverse: bool,
55    once: bool,
56}
57
58impl ShimmerStyle {
59    /// Create a theme-aware shimmer with the default timing and spread.
60    pub fn new() -> Self {
61        Self::default()
62    }
63
64    /// Set the duration of one complete sweep.
65    ///
66    /// A zero duration is clamped to one millisecond.
67    pub fn duration(mut self, duration: Duration) -> Self {
68        self.duration = duration.max(Duration::from_millis(1));
69        self
70    }
71
72    /// Replace the theme-aware highlight with an explicit color.
73    pub fn highlight_color(mut self, color: impl Into<Hsla>) -> Self {
74        self.highlight_color = Some(color.into());
75        self
76    }
77
78    /// Set the highlight half-width.
79    ///
80    /// An `f32` is a fraction of the text width; finite values are clamped to
81    /// the inclusive `0.05..=1.0` range and the default is `0.3`. A [`Pixels`]
82    /// value is an absolute half-width with a one-pixel minimum. Non-finite
83    /// values leave the existing spread unchanged.
84    pub fn spread(mut self, spread: impl Into<ShimmerSpread>) -> Self {
85        match spread.into() {
86            ShimmerSpread::Relative(fraction) if fraction.is_finite() => {
87                self.spread = ShimmerSpread::Relative(fraction.clamp(0.05, 1.));
88            }
89            ShimmerSpread::Absolute(length) if length.as_f32().is_finite() => {
90                self.spread = ShimmerSpread::Absolute(length.max(px(1.)));
91            }
92            _ => {}
93        }
94        self
95    }
96
97    /// Set whether the highlight should move from right to left.
98    pub fn reverse(mut self, reverse: bool) -> Self {
99        self.reverse = reverse;
100        self
101    }
102
103    /// Set whether the highlight should complete one sweep instead of looping.
104    pub fn once(mut self, once: bool) -> Self {
105        self.once = once;
106        self
107    }
108
109    pub(crate) fn animation(self) -> Animation {
110        loading_animation(self.duration, self.once)
111    }
112}
113
114impl Default for ShimmerStyle {
115    fn default() -> Self {
116        Self {
117            duration: Duration::from_secs(2),
118            highlight_color: None,
119            spread: ShimmerSpread::default(),
120            reverse: false,
121            once: false,
122        }
123    }
124}
125
126/// Text with a smooth, theme-aware loading highlight.
127///
128/// Font, color, weight, wrapping, and truncation are inherited from the parent
129/// unless overridden through [`Styled`]. When the system requests reduced
130/// motion, the text stays visible without requesting animation frames.
131///
132/// ```ignore
133/// ShimmerText::new("Thinking…")
134///     .duration(Duration::from_secs(3))
135///     .spread(0.4)
136/// ```
137#[derive(IntoElement)]
138pub struct ShimmerText {
139    text: SharedString,
140    style: StyleRefinement,
141    shimmer_style: ShimmerStyle,
142    id: Option<ElementId>,
143}
144
145impl ShimmerText {
146    /// Create animated text with the default theme-aware shimmer.
147    pub fn new(text: impl Into<SharedString>) -> Self {
148        Self {
149            text: text.into(),
150            style: StyleRefinement::default(),
151            shimmer_style: ShimmerStyle::default(),
152            id: None,
153        }
154    }
155
156    /// Set an explicit animation identity when sibling labels are identical.
157    pub fn id(mut self, id: impl Into<ElementId>) -> Self {
158        self.id = Some(id.into());
159        self
160    }
161
162    /// Apply a reusable shimmer appearance and timing configuration.
163    pub fn with_shimmer_style(mut self, style: ShimmerStyle) -> Self {
164        self.shimmer_style = style;
165        self
166    }
167
168    /// Set the duration of one complete sweep.
169    pub fn duration(mut self, duration: Duration) -> Self {
170        self.shimmer_style = self.shimmer_style.duration(duration);
171        self
172    }
173
174    /// Replace the theme-aware highlight with an explicit color.
175    pub fn highlight_color(mut self, color: impl Into<Hsla>) -> Self {
176        self.shimmer_style = self.shimmer_style.highlight_color(color);
177        self
178    }
179
180    /// Set the relative or absolute highlight half-width; the default is `0.3`.
181    pub fn spread(mut self, spread: impl Into<ShimmerSpread>) -> Self {
182        self.shimmer_style = self.shimmer_style.spread(spread);
183        self
184    }
185
186    /// Set whether the highlight should move from right to left.
187    pub fn reverse(mut self, reverse: bool) -> Self {
188        self.shimmer_style = self.shimmer_style.reverse(reverse);
189        self
190    }
191
192    /// Set whether the highlight should complete one sweep instead of looping.
193    pub fn once(mut self, once: bool) -> Self {
194        self.shimmer_style = self.shimmer_style.once(once);
195        self
196    }
197}
198
199impl Styled for ShimmerText {
200    fn style(&mut self) -> &mut StyleRefinement {
201        &mut self.style
202    }
203}
204
205impl RenderOnce for ShimmerText {
206    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
207        let id = self.id.unwrap_or_else(|| self.text.clone().into());
208        let container = div().min_w_0().refine_style(&self.style);
209
210        if cx.reduce_motion() {
211            return container
212                .child(StyledText::new(self.text))
213                .into_any_element();
214        }
215
216        let tokens = cx.theme().semantic_tokens();
217        let reverse = self.shimmer_style.reverse;
218        let shimmer = ShimmerGlyphs {
219            text: StyledText::new(self.text),
220            highlight_color: self.shimmer_style.highlight_color,
221            background: tokens.colors.background,
222            foreground: tokens.colors.foreground,
223            dark: cx.theme().is_dark(),
224            spread: self.shimmer_style.spread,
225            phase: 0.,
226        }
227        .with_animation(
228            id,
229            self.shimmer_style.animation(),
230            move |mut this, phase| {
231                this.phase = if reverse { 1. - phase } else { phase };
232                this
233            },
234        );
235
236        container.child(shimmer).into_any_element()
237    }
238}
239
240/// Paint an animated highlight over glyphs already laid out by `StyledText`.
241///
242/// Keeping `StyledText` as the layout owner preserves wrapping, truncation,
243/// inherited typography, and GPUI's glyph cache. Nested content masks produce
244/// a soft continuous band without rebuilding text runs on every frame.
245struct ShimmerGlyphs {
246    text: StyledText,
247    highlight_color: Option<Hsla>,
248    background: Hsla,
249    foreground: Hsla,
250    dark: bool,
251    spread: ShimmerSpread,
252    phase: f32,
253}
254
255impl ShimmerGlyphs {
256    fn paint_highlight(&self, bounds: Bounds<Pixels>, window: &mut Window, cx: &mut App) {
257        let masks = std::array::from_fn::<_, SHIMMER_LAYER_COUNT, _>(|layer| {
258            shimmer_band_bounds(bounds, self.phase, self.spread, layer).map(|bounds| ContentMask {
259                fade_out: Default::default(),
260                bounds,
261            })
262        });
263
264        if masks.iter().all(Option::is_none) {
265            return;
266        }
267
268        let color = shimmer_highlight_color(
269            window.text_style().color,
270            self.background,
271            self.foreground,
272            self.dark,
273            self.highlight_color,
274        );
275        let layout = self.text.layout();
276        let line_height = layout.line_height();
277        let mut line_origin = bounds.origin;
278
279        window.paint_layer(bounds, |window| {
280            for wrapped_line in layout.line_layouts() {
281                for (row, visual_line) in wrapped_line.visual_lines().iter().enumerate() {
282                    let baseline = (line_height - wrapped_line.ascent() - wrapped_line.descent())
283                        / 2.
284                        + wrapped_line.ascent();
285                    let origin = point(
286                        line_origin.x + visual_line.offset,
287                        line_origin.y + line_height * row as f32,
288                    );
289                    for fragment in wrapped_line.fragments_for_line(visual_line) {
290                        let glyph_size = cx
291                            .text_system()
292                            .bounding_box(fragment.font_id, fragment.font_size)
293                            .size;
294                        for glyph in fragment.glyphs.iter().filter(|glyph| !glyph.is_emoji) {
295                            let glyph_origin = origin + point(glyph.position.x, px(0.));
296                            let glyph_bounds = Bounds::new(glyph_origin, glyph_size);
297                            let paint_origin = origin + glyph.position + point(px(0.), baseline);
298                            for mask in masks.iter().flatten() {
299                                if !glyph_bounds.intersects(&mask.bounds) {
300                                    continue;
301                                }
302                                window.with_content_mask(Some(*mask), |window| {
303                                    let _ = window.paint_glyph(
304                                        paint_origin,
305                                        fragment.font_id,
306                                        glyph.id,
307                                        fragment.font_size,
308                                        color,
309                                    );
310                                });
311                            }
312                        }
313                    }
314                }
315
316                line_origin.y += wrapped_line.size(line_height).height;
317            }
318        });
319    }
320}
321
322impl IntoElement for ShimmerGlyphs {
323    type Element = Self;
324
325    fn into_element(self) -> Self::Element {
326        self
327    }
328}
329
330impl Element for ShimmerGlyphs {
331    type RequestLayoutState = ();
332    type PrepaintState = ();
333
334    fn id(&self) -> Option<ElementId> {
335        None
336    }
337
338    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
339        None
340    }
341
342    fn request_layout(
343        &mut self,
344        global_id: Option<&GlobalElementId>,
345        inspector_id: Option<&InspectorElementId>,
346        window: &mut Window,
347        cx: &mut App,
348    ) -> (LayoutId, Self::RequestLayoutState) {
349        let (layout_id, ()) = self
350            .text
351            .request_layout(global_id, inspector_id, window, cx);
352        let layout_id = window.request_layout(
353            gpui::Style {
354                display: gpui::Display::Flex,
355                ..Default::default()
356            },
357            [layout_id],
358            cx,
359        );
360        (layout_id, ())
361    }
362
363    fn prepaint(
364        &mut self,
365        global_id: Option<&GlobalElementId>,
366        inspector_id: Option<&InspectorElementId>,
367        bounds: Bounds<Pixels>,
368        layout: &mut Self::RequestLayoutState,
369        window: &mut Window,
370        cx: &mut App,
371    ) -> Self::PrepaintState {
372        self.text
373            .prepaint(global_id, inspector_id, bounds, layout, window, cx);
374    }
375
376    fn paint(
377        &mut self,
378        global_id: Option<&GlobalElementId>,
379        inspector_id: Option<&InspectorElementId>,
380        bounds: Bounds<Pixels>,
381        layout: &mut Self::RequestLayoutState,
382        prepaint: &mut Self::PrepaintState,
383        window: &mut Window,
384        cx: &mut App,
385    ) {
386        self.text.paint(
387            global_id,
388            inspector_id,
389            bounds,
390            layout,
391            prepaint,
392            window,
393            cx,
394        );
395        self.paint_highlight(bounds, window, cx);
396    }
397}
398
399pub(crate) fn loading_animation(duration: Duration, once: bool) -> Animation {
400    if once {
401        Animation::new(duration)
402    } else {
403        Animation::new(duration).repeat()
404    }
405}
406
407fn shimmer_highlight_color(
408    text: Hsla,
409    background: Hsla,
410    foreground: Hsla,
411    dark: bool,
412    override_color: Option<Hsla>,
413) -> Hsla {
414    let highlight = override_color.unwrap_or_else(|| {
415        if dark {
416            text.mix_oklab(foreground, 0.2)
417        } else {
418            text.mix_oklab(background, 0.2)
419        }
420    });
421    let peak_opacity: f32 = if dark { 0.6 } else { 0.75 };
422    let layer_opacity = 1. - (1. - peak_opacity).powf(1. / SHIMMER_LAYER_COUNT as f32);
423
424    highlight.opacity(layer_opacity)
425}
426
427fn shimmer_band_bounds(
428    bounds: Bounds<Pixels>,
429    phase: f32,
430    spread: ShimmerSpread,
431    layer: usize,
432) -> Option<Bounds<Pixels>> {
433    let width = bounds.size.width.as_f32();
434
435    if width <= 0. || bounds.size.height <= px(0.) || layer >= SHIMMER_LAYER_COUNT {
436        return None;
437    }
438
439    let half_width = match spread {
440        ShimmerSpread::Relative(fraction) => width * fraction,
441        ShimmerSpread::Absolute(length) => length.as_f32(),
442    };
443    let padding = half_width / width + 0.05;
444    let center = phase.mul_add(1. + padding * 2., -padding) * width;
445    let radius = half_width * (1. - layer as f32 / SHIMMER_LAYER_COUNT as f32);
446    let left = (center - radius).max(0.);
447    let right = (center + radius).min(width);
448
449    (right > left).then(|| {
450        Bounds::new(
451            point(bounds.origin.x + px(left), bounds.origin.y),
452            size(px(right - left), bounds.size.height),
453        )
454    })
455}
456
457#[cfg(test)]
458mod tests {
459    use super::*;
460
461    #[test]
462    fn test_shimmer_builder() {
463        let color = gpui::white();
464        let style = ShimmerStyle::new()
465            .duration(Duration::from_secs(3))
466            .highlight_color(color)
467            .spread(0.45)
468            .reverse(true)
469            .once(true);
470
471        assert_eq!(style.duration, Duration::from_secs(3));
472        assert_eq!(style.highlight_color, Some(color));
473        assert_eq!(style.spread, ShimmerSpread::Relative(0.45));
474        assert!(style.reverse);
475        assert!(style.once);
476
477        let text = ShimmerText::new("Thinking")
478            .id("thinking")
479            .with_shimmer_style(style)
480            .duration(Duration::from_secs(4))
481            .spread(0.5)
482            .reverse(false)
483            .once(false)
484            .opacity(0.8);
485
486        assert_eq!(text.text.as_ref(), "Thinking");
487        assert_eq!(text.shimmer_style.duration, Duration::from_secs(4));
488        assert_eq!(text.shimmer_style.spread, ShimmerSpread::Relative(0.5));
489        assert!(!text.shimmer_style.reverse);
490        assert!(!text.shimmer_style.once);
491        assert_eq!(text.style.opacity, Some(0.8));
492        assert_eq!(text.id, Some("thinking".into()));
493
494        assert_eq!(
495            ShimmerStyle::new().spread(0.).spread,
496            ShimmerSpread::Relative(0.05)
497        );
498        assert_eq!(
499            ShimmerStyle::new().spread(2.).spread,
500            ShimmerSpread::Relative(1.)
501        );
502        assert_eq!(
503            ShimmerStyle::new().spread(f32::NAN).spread,
504            ShimmerSpread::default()
505        );
506        assert_eq!(
507            ShimmerStyle::new().spread(px(0.)).spread,
508            ShimmerSpread::Absolute(px(1.))
509        );
510        assert_eq!(
511            ShimmerStyle::new().spread(px(48.)).spread,
512            ShimmerSpread::Absolute(px(48.))
513        );
514        assert_eq!(
515            ShimmerStyle::new().spread(px(f32::NAN)).spread,
516            ShimmerSpread::default()
517        );
518        assert_eq!(
519            ShimmerStyle::new().duration(Duration::ZERO).duration,
520            Duration::from_millis(1)
521        );
522    }
523
524    #[test]
525    fn test_shimmer_band_moves_smoothly_across_text() {
526        let bounds = Bounds::new(point(px(10.), px(20.)), size(px(100.), px(18.)));
527        let spread = ShimmerSpread::default();
528
529        assert!(shimmer_band_bounds(bounds, 0., spread, 0).is_none());
530        assert!(shimmer_band_bounds(bounds, 1., spread, 0).is_none());
531
532        let early = shimmer_band_bounds(bounds, 0.35, spread, 0).unwrap();
533        let late = shimmer_band_bounds(bounds, 0.65, spread, 0).unwrap();
534        assert!(early.origin.x < late.origin.x);
535
536        let outer = shimmer_band_bounds(bounds, 0.5, spread, 0).unwrap();
537        let inner = shimmer_band_bounds(bounds, 0.5, spread, SHIMMER_LAYER_COUNT - 1).unwrap();
538        assert!(inner.origin.x > outer.origin.x);
539        assert!(inner.size.width < outer.size.width);
540        assert!(shimmer_band_bounds(bounds, 0.5, spread, SHIMMER_LAYER_COUNT).is_none());
541        assert!(
542            shimmer_band_bounds(
543                Bounds::new(bounds.origin, size(px(0.), px(18.))),
544                0.5,
545                spread,
546                0
547            )
548            .is_none()
549        );
550
551        let narrow = shimmer_band_bounds(bounds, 0.5, ShimmerSpread::Relative(0.1), 0).unwrap();
552        let wide = shimmer_band_bounds(bounds, 0.5, ShimmerSpread::Relative(0.5), 0).unwrap();
553        assert!(narrow.size.width < wide.size.width);
554
555        // An absolute spread keeps the band width constant across text widths.
556        let absolute = ShimmerSpread::Absolute(px(20.));
557        let band = shimmer_band_bounds(bounds, 0.5, absolute, 0).unwrap();
558        assert_eq!(band.size.width, px(40.));
559        let wider_bounds = Bounds::new(bounds.origin, size(px(200.), px(18.)));
560        let wider_band = shimmer_band_bounds(wider_bounds, 0.5, absolute, 0).unwrap();
561        assert_eq!(wider_band.size.width, px(40.));
562    }
563
564    #[test]
565    fn test_shimmer_highlight_stays_bright_in_both_themes() {
566        let black = gpui::black();
567        let white = gpui::white();
568        let muted = white.mix_oklab(black, 0.55);
569        let light = shimmer_highlight_color(black, white, black, false, None);
570        let dark = shimmer_highlight_color(muted, black, white, true, None);
571
572        assert!(light.color.lightness > black.color.lightness);
573        assert!(dark.color.lightness > muted.color.lightness);
574        assert!(light.alpha > dark.alpha);
575        assert!((1. - (1. - light.alpha).powi(SHIMMER_LAYER_COUNT as i32) - 0.75).abs() < 0.001);
576        assert!((1. - (1. - dark.alpha).powi(SHIMMER_LAYER_COUNT as i32) - 0.6).abs() < 0.001);
577
578        let custom = shimmer_highlight_color(black, white, black, false, Some(muted));
579        assert_eq!(custom.color.hue, muted.color.hue);
580        assert_eq!(custom.color.saturation, muted.color.saturation);
581        assert_eq!(custom.color.lightness, muted.color.lightness);
582
583        let animation = loading_animation(Duration::from_secs(3), false);
584        assert_eq!(
585            animation.motion.forward_pass().duration(),
586            Duration::from_secs(3)
587        );
588        assert_eq!(
589            animation.motion.playback().iterations(),
590            gpui::Iterations::Forever
591        );
592
593        let animation = loading_animation(Duration::from_secs(3), true);
594        assert_eq!(
595            animation.motion.forward_pass().duration(),
596            Duration::from_secs(3)
597        );
598        assert_eq!(
599            animation.motion.playback().iterations(),
600            gpui::Iterations::default()
601        );
602    }
603}