Skip to main content

arc_ui/text/
text_shimmer.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/text-shimmer/text-shimmer.tsx` & `.module.css`
3//!
4//! P2 Component #33: `text-shimmer`
5//!
6//! - A calm highlight band sweeps across a short status line while work is ongoing. The band is
7//!   the text colour over a muted base (12% current colour mixed into `text-muted` in Oklab).
8//! - One sweep takes `duration` (1.8s default) with linear easing, then rests `32%` of that
9//!   before the next pass, so the line breathes instead of strobing.
10//! - When `active` turns false the base resolves to solid over `0.36s` / `ease.standard`, so the
11//!   text never hard-cuts back to grey.
12//! - Local design: GPUI has no `background-clip: text`, so the band tints each glyph by its
13//!   estimated advance instead of sampling a gradient through the glyphs; per-glyph motion blur,
14//!   the label exit half of the swap and the line-width spring are omitted.
15
16use std::cell::Cell;
17use std::rc::Rc;
18
19use arc_motion::{
20    BlurFallback, CubicBezier, InViewConfig, InViewTracker, arc_transition, is_reduced_motion,
21    motion_now,
22};
23use arc_tokens::{ActiveArcTheme as _, ArcColors, ArcMotionTokens, Typography, oklab_mix};
24use gpui_kit::{
25    App, Bounds, ElementId, Hsla, IntoElement, ParentElement, Pixels, RenderOnce, Role,
26    SharedString, Styled, TestSupportExt as _, Window, div, point, prelude::*, px,
27};
28
29/// Half width of the highlight band in em.
30pub const BAND_EM: f32 = 2.2;
31/// Bell-shaped falloff as `(offset, strength)` stops from Arc.
32const FALLOFF: [(f32, f32); 7] = [
33    (-1.0, 0.0),
34    (-0.5, 0.5),
35    (-0.2, 0.9),
36    (0.0, 1.0),
37    (0.2, 0.9),
38    (0.5, 0.5),
39    (1.0, 0.0),
40];
41
42/// Band strength at normalized distance `d` (`-1..=1`) from the sweep centre.
43pub fn bell_strength(d: f32) -> f32 {
44    let d = d.clamp(-1.0, 1.0);
45    for pair in FALLOFF.windows(2) {
46        let (x0, y0) = pair[0];
47        let (x1, y1) = pair[1];
48        if d >= x0 && d <= x1 {
49            let t = if (x1 - x0).abs() < 1e-6 {
50                0.0
51            } else {
52                (d - x0) / (x1 - x0)
53            };
54            return y0 + (y1 - y0) * t;
55        }
56    }
57    0.0
58}
59
60/// Resting base colour: `text-muted` with 12% of the current text colour mixed in (Oklab).
61pub fn shimmer_base(colors: ArcColors) -> Hsla {
62    oklab_mix(colors.text_muted, colors.foreground, 0.88)
63}
64
65/// Colour of a glyph at `strength` between the resting base and the solid highlight.
66pub fn shimmer_glyph_color(base: Hsla, highlight: Hsla, settle: f32, strength: f32) -> Hsla {
67    let settled = oklab_mix(base, highlight, 1.0 - settle.clamp(0.0, 1.0));
68    oklab_mix(settled, highlight, 1.0 - strength.clamp(0.0, 1.0))
69}
70
71/// Sweep position `0..=1` for `elapsed` seconds into a looping pass (`duration` + 32% rest).
72pub fn sweep_position(elapsed: f64, duration: f64) -> f32 {
73    let duration = duration.max(0.05);
74    let cycle = duration * 1.32;
75    let t = elapsed.rem_euclid(cycle);
76    ((t / duration).clamp(0.0, 1.0)) as f32
77}
78
79/// Rough advance width in em, used to place each glyph inside the band.
80pub fn glyph_advance(ch: char) -> f32 {
81    if ch.is_whitespace() {
82        0.28
83    } else if ch.is_ascii_digit() {
84        0.56
85    } else if ch.is_ascii_uppercase() {
86        0.64
87    } else if ch.is_ascii() {
88        0.52
89    } else {
90        1.0
91    }
92}
93
94struct ShimmerState {
95    started_at: f64,
96    text: String,
97    in_view: Rc<std::cell::RefCell<InViewTracker>>,
98    visible: Rc<Cell<bool>>,
99    measured: Rc<Cell<bool>>,
100}
101
102/// Arc `TextShimmer` — a calm light sweep across a short status line.
103#[derive(IntoElement)]
104pub struct TextShimmer {
105    id: ElementId,
106    text: SharedString,
107    active: bool,
108    duration: f64,
109    text_size: Pixels,
110    role: Role,
111}
112
113impl TextShimmer {
114    pub fn new(id: impl Into<ElementId>, text: impl Into<SharedString>) -> Self {
115        Self {
116            id: id.into(),
117            text: text.into(),
118            active: true,
119            duration: 1.8,
120            text_size: Typography::TEXT_SM,
121            role: Role::Label,
122        }
123    }
124
125    /// Sweeps while work is ongoing (`true` by default).
126    pub fn active(mut self, active: bool) -> Self {
127        self.active = active;
128        self
129    }
130
131    /// Seconds for one sweep across the text.
132    pub fn duration(mut self, duration: f64) -> Self {
133        self.duration = duration.max(0.05);
134        self
135    }
136
137    pub fn text_size(mut self, size: Pixels) -> Self {
138        self.text_size = size;
139        self
140    }
141
142    pub fn role(mut self, role: Role) -> Self {
143        self.role = role;
144        self
145    }
146}
147
148impl RenderOnce for TextShimmer {
149    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
150        let theme = cx.arc_theme().clone();
151        let colors = theme.colors;
152        let motion = theme.motion;
153        let reduced = is_reduced_motion(cx);
154        let now = motion_now(cx);
155        let em = f32::from(self.text_size);
156
157        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-shimmer".into());
158        let state = window.use_keyed_state(state_id, cx, |_, _| ShimmerState {
159            started_at: now,
160            text: String::new(),
161            in_view: Rc::new(std::cell::RefCell::new(InViewTracker::new(InViewConfig {
162                amount: 0.05,
163                once: false,
164            }))),
165            visible: Rc::new(Cell::new(true)),
166            measured: Rc::new(Cell::new(false)),
167        });
168
169        let (started_at, in_view, visible, measured) = {
170            let read = state.read(cx);
171            (
172                read.started_at,
173                read.in_view.clone(),
174                read.visible.clone(),
175                read.measured.clone(),
176            )
177        };
178        let label_started = {
179            let changed = state.read(cx).text != self.text.as_ref();
180            if changed {
181                state.update(cx, |s, _| {
182                    s.text = self.text.to_string();
183                    s.started_at = now;
184                });
185                now
186            } else {
187                state.read(cx).started_at
188            }
189        };
190
191        let visible_now = visible.get() || !measured.get();
192        let running = self.active && !reduced && visible_now;
193        let settle = if self.active {
194            if reduced {
195                0.0
196            } else {
197                arc_transition(
198                    (self.id.clone(), "settle"),
199                    0.0,
200                    motion.duration.standard,
201                    motion.ease.standard,
202                    window,
203                    cx,
204                )
205            }
206        } else if reduced {
207            1.0
208        } else {
209            arc_transition(
210                (self.id.clone(), "settle"),
211                1.0,
212                ArcMotionTokens::DEFAULT.duration.standard.mul_f64(1.5),
213                ArcMotionTokens::DEFAULT.ease.standard,
214                window,
215                cx,
216            )
217        };
218
219        let sweep = if running {
220            window.request_animation_frame();
221            sweep_position(now - started_at, self.duration)
222        } else if self.active {
223            0.0
224        } else {
225            1.0
226        };
227
228        let base = shimmer_base(colors);
229        let highlight = colors.foreground;
230        let chars: Vec<char> = self.text.chars().collect();
231        let total_em: f32 = chars
232            .iter()
233            .map(|ch| glyph_advance(*ch))
234            .sum::<f32>()
235            .max(0.1);
236
237        let mut line = div().flex().flex_row().items_baseline().whitespace_nowrap();
238        let mut cursor_em = 0.0f32;
239        for ch in &chars {
240            let advance = glyph_advance(*ch);
241            let center = (cursor_em + advance * 0.5) / total_em;
242            let normalized = (center - sweep) * total_em / BAND_EM;
243            let strength = bell_strength(normalized);
244            let color = shimmer_glyph_color(base, highlight, settle, strength);
245            cursor_em += advance;
246            line = line.child(
247                div()
248                    .flex_none()
249                    .text_color(color)
250                    .when(*ch == ' ', |this| this.w(px(0.28 * em)))
251                    .child(if *ch == ' ' {
252                        SharedString::from("\u{00a0}")
253                    } else {
254                        SharedString::from(ch.to_string())
255                    }),
256            );
257        }
258
259        // Label swap rise: new copy fades and rises from 0.3em with a soft blur.
260        let rise_t = if reduced {
261            1.0
262        } else {
263            (((now - label_started) / motion.duration.standard.as_secs_f64()).clamp(0.0, 1.0))
264                as f32
265        };
266        let rise = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(rise_t);
267        let blur = BlurFallback::evaluate(px(f32::from(motion.blur.soft) * (1.0 - rise)), reduced);
268
269        // Viewport probe drives the in-view gate (Arc uses a 64px margin; GPUI tracks ratio only).
270        let probe = {
271            let in_view = in_view.clone();
272            let visible = visible.clone();
273            let measured = measured.clone();
274            gpui_kit::canvas(
275                move |rect: Bounds<Pixels>, window: &mut Window, _| {
276                    let viewport = Bounds::new(point(px(0.0), px(0.0)), window.viewport_size());
277                    let state = in_view.borrow_mut().evaluate(rect, viewport);
278                    let next = state.ratio > 0.0;
279                    if measured.get() && visible.get() != next {
280                        visible.set(next);
281                        window.request_animation_frame();
282                    }
283                    visible.set(next);
284                    measured.set(true);
285                },
286                |_, _, _, _| {},
287            )
288            .absolute()
289            .inset_0()
290        };
291
292        div()
293            .id(self.id)
294            .test_support()
295            .role(self.role)
296            .aria_label(self.text.clone())
297            .self_start()
298            .relative()
299            .flex()
300            .flex_col()
301            .text_size(self.text_size)
302            .line_height(self.text_size * 1.4)
303            .max_w(px(32.0 * em))
304            .child(probe)
305            .child(
306                div()
307                    .opacity((rise * blur.opacity_multiplier).clamp(0.0, 1.0))
308                    .mt(px((1.0 - rise) * 0.3 * em))
309                    .child(line),
310            )
311    }
312}
313
314#[cfg(test)]
315mod tests {
316    use super::*;
317
318    #[test]
319    fn bell_is_symmetric_and_peaks_at_the_centre() {
320        assert!((bell_strength(0.0) - 1.0).abs() < 1e-6);
321        assert!((bell_strength(-0.2) - 0.9).abs() < 1e-6);
322        assert_eq!(bell_strength(1.0), 0.0);
323        assert_eq!(bell_strength(-1.0), 0.0);
324        assert!((bell_strength(0.1) - bell_strength(-0.1)).abs() < 1e-6);
325        assert_eq!(bell_strength(2.0), 0.0);
326    }
327
328    #[test]
329    fn sweep_loops_with_a_rest_between_passes() {
330        assert_eq!(sweep_position(0.0, 1.8), 0.0);
331        assert!((sweep_position(0.9, 1.8) - 0.5).abs() < 1e-6);
332        assert_eq!(sweep_position(1.8, 1.8), 1.0);
333        // 1.8s sweep + 0.576s rest == 2.376s cycle.
334        let cycle = 1.8 * 1.32;
335        assert_eq!(sweep_position(cycle * 3.0 + 0.0, 1.8), 0.0);
336        assert!(sweep_position(1.8 + 0.2, 1.8) >= 1.0);
337    }
338
339    #[test]
340    fn settle_and_strength_move_the_colour_towards_the_highlight() {
341        let colors =
342            arc_tokens::ArcTheme::new(arc_tokens::ThemeMode::Light, arc_tokens::Accent::Neutral)
343                .colors;
344        let base = shimmer_base(colors);
345        let resting = shimmer_glyph_color(base, colors.foreground, 0.0, 0.0);
346        let in_band = shimmer_glyph_color(base, colors.foreground, 0.0, 1.0);
347        let settled = shimmer_glyph_color(base, colors.foreground, 1.0, 0.0);
348        assert!((in_band.l - colors.foreground.l).abs() < 1e-3);
349        assert!((settled.l - colors.foreground.l).abs() < 1e-3);
350        // The resting base leans towards `text-muted`; the settled colour reaches the highlight.
351        assert!(
352            (resting.l - colors.foreground.l).abs()
353                > (settled.l - colors.foreground.l).abs() + 1e-4
354        );
355        assert!((in_band.l - colors.foreground.l).abs() <= (resting.l - colors.foreground.l).abs());
356    }
357
358    #[test]
359    fn advances_are_wider_for_cjk_than_spaces() {
360        assert!(glyph_advance('中') > glyph_advance('W'));
361        assert!(glyph_advance('W') > glyph_advance('a'));
362        assert!(glyph_advance('a') > glyph_advance(' '));
363    }
364
365    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
366    use gpui_kit::{
367        Context, Render, TestAppContext,
368        test::{TestQueryExt as _, TestWindowExt as _},
369    };
370
371    struct ShimmerHost {
372        active: bool,
373    }
374
375    impl Render for ShimmerHost {
376        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
377            div().p(px(24.0)).child(
378                TextShimmer::new("status", "正在生成摘要")
379                    .active(self.active)
380                    .duration(0.6),
381            )
382        }
383    }
384
385    #[gpui_kit::test]
386    fn shimmer_renders_busy_line_and_settles_when_idle(cx: &mut TestAppContext) {
387        cx.update(|cx| {
388            gpui_kit::init(cx);
389            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
390        });
391        let (view, cx) = cx.add_window_view(|_, _| ShimmerHost { active: true });
392        cx.update(|window, cx| {
393            for _ in 0..4 {
394                window.render_frame(cx);
395            }
396            assert!(f32::from(window.find_by_label("正在生成摘要").bounds().size.width) > 0.0);
397        });
398        view.update(cx, |host, cx| {
399            host.active = false;
400            cx.notify();
401        });
402        cx.update(|window, cx| {
403            for _ in 0..8 {
404                window.render_frame(cx);
405            }
406            assert!(f32::from(window.find_by_label("正在生成摘要").bounds().size.width) > 0.0);
407        });
408    }
409}