arc-ui 0.4.0

Physics-first native Rust desktop UI component library & charts for GPUI (120+ interactive components ported from Arc).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/text-shimmer/text-shimmer.tsx` & `.module.css`
//!
//! P2 Component #33: `text-shimmer`
//!
//! - A calm highlight band sweeps across a short status line while work is ongoing. The band is
//!   the text colour over a muted base (12% current colour mixed into `text-muted` in Oklab).
//! - One sweep takes `duration` (1.8s default) with linear easing, then rests `32%` of that
//!   before the next pass, so the line breathes instead of strobing.
//! - When `active` turns false the base resolves to solid over `0.36s` / `ease.standard`, so the
//!   text never hard-cuts back to grey.
//! - Local design: GPUI has no `background-clip: text`, so the band tints each glyph by its
//!   estimated advance instead of sampling a gradient through the glyphs; per-glyph motion blur,
//!   the label exit half of the swap and the line-width spring are omitted.

use std::cell::Cell;
use std::rc::Rc;

use arc_motion::{
    BlurFallback, CubicBezier, InViewConfig, InViewTracker, arc_transition, is_reduced_motion,
    motion_now,
};
use arc_tokens::{ActiveArcTheme as _, ArcColors, ArcMotionTokens, Typography, oklab_mix};
use gpui_kit::{
    App, Bounds, ElementId, Hsla, IntoElement, ParentElement, Pixels, RenderOnce, Role,
    SharedString, Styled, TestSupportExt as _, Window, div, point, prelude::*, px,
};

/// Half width of the highlight band in em.
pub const BAND_EM: f32 = 2.2;
/// Bell-shaped falloff as `(offset, strength)` stops from Arc.
const FALLOFF: [(f32, f32); 7] = [
    (-1.0, 0.0),
    (-0.5, 0.5),
    (-0.2, 0.9),
    (0.0, 1.0),
    (0.2, 0.9),
    (0.5, 0.5),
    (1.0, 0.0),
];

/// Band strength at normalized distance `d` (`-1..=1`) from the sweep centre.
pub fn bell_strength(d: f32) -> f32 {
    let d = d.clamp(-1.0, 1.0);
    for pair in FALLOFF.windows(2) {
        let (x0, y0) = pair[0];
        let (x1, y1) = pair[1];
        if d >= x0 && d <= x1 {
            let t = if (x1 - x0).abs() < 1e-6 {
                0.0
            } else {
                (d - x0) / (x1 - x0)
            };
            return y0 + (y1 - y0) * t;
        }
    }
    0.0
}

/// Resting base colour: `text-muted` with 12% of the current text colour mixed in (Oklab).
pub fn shimmer_base(colors: ArcColors) -> Hsla {
    oklab_mix(colors.text_muted, colors.foreground, 0.88)
}

/// Colour of a glyph at `strength` between the resting base and the solid highlight.
pub fn shimmer_glyph_color(base: Hsla, highlight: Hsla, settle: f32, strength: f32) -> Hsla {
    let settled = oklab_mix(base, highlight, 1.0 - settle.clamp(0.0, 1.0));
    oklab_mix(settled, highlight, 1.0 - strength.clamp(0.0, 1.0))
}

/// Sweep position `0..=1` for `elapsed` seconds into a looping pass (`duration` + 32% rest).
pub fn sweep_position(elapsed: f64, duration: f64) -> f32 {
    let duration = duration.max(0.05);
    let cycle = duration * 1.32;
    let t = elapsed.rem_euclid(cycle);
    ((t / duration).clamp(0.0, 1.0)) as f32
}

/// Rough advance width in em, used to place each glyph inside the band.
pub fn glyph_advance(ch: char) -> f32 {
    if ch.is_whitespace() {
        0.28
    } else if ch.is_ascii_digit() {
        0.56
    } else if ch.is_ascii_uppercase() {
        0.64
    } else if ch.is_ascii() {
        0.52
    } else {
        1.0
    }
}

struct ShimmerState {
    started_at: f64,
    text: String,
    in_view: Rc<std::cell::RefCell<InViewTracker>>,
    visible: Rc<Cell<bool>>,
    measured: Rc<Cell<bool>>,
}

/// Arc `TextShimmer` — a calm light sweep across a short status line.
#[derive(IntoElement)]
pub struct TextShimmer {
    id: ElementId,
    text: SharedString,
    active: bool,
    duration: f64,
    text_size: Pixels,
    role: Role,
}

impl TextShimmer {
    pub fn new(id: impl Into<ElementId>, text: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            text: text.into(),
            active: true,
            duration: 1.8,
            text_size: Typography::TEXT_SM,
            role: Role::Label,
        }
    }

    /// Sweeps while work is ongoing (`true` by default).
    pub fn active(mut self, active: bool) -> Self {
        self.active = active;
        self
    }

    /// Seconds for one sweep across the text.
    pub fn duration(mut self, duration: f64) -> Self {
        self.duration = duration.max(0.05);
        self
    }

    pub fn text_size(mut self, size: Pixels) -> Self {
        self.text_size = size;
        self
    }

    pub fn role(mut self, role: Role) -> Self {
        self.role = role;
        self
    }
}

impl RenderOnce for TextShimmer {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = cx.arc_theme().clone();
        let colors = theme.colors;
        let motion = theme.motion;
        let reduced = is_reduced_motion(cx);
        let now = motion_now(cx);
        let em = f32::from(self.text_size);

        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-shimmer".into());
        let state = window.use_keyed_state(state_id, cx, |_, _| ShimmerState {
            started_at: now,
            text: String::new(),
            in_view: Rc::new(std::cell::RefCell::new(InViewTracker::new(InViewConfig {
                amount: 0.05,
                once: false,
            }))),
            visible: Rc::new(Cell::new(true)),
            measured: Rc::new(Cell::new(false)),
        });

        let (started_at, in_view, visible, measured) = {
            let read = state.read(cx);
            (
                read.started_at,
                read.in_view.clone(),
                read.visible.clone(),
                read.measured.clone(),
            )
        };
        let label_started = {
            let changed = state.read(cx).text != self.text.as_ref();
            if changed {
                state.update(cx, |s, _| {
                    s.text = self.text.to_string();
                    s.started_at = now;
                });
                now
            } else {
                state.read(cx).started_at
            }
        };

        let visible_now = visible.get() || !measured.get();
        let running = self.active && !reduced && visible_now;
        let settle = if self.active {
            if reduced {
                0.0
            } else {
                arc_transition(
                    (self.id.clone(), "settle"),
                    0.0,
                    motion.duration.standard,
                    motion.ease.standard,
                    window,
                    cx,
                )
            }
        } else if reduced {
            1.0
        } else {
            arc_transition(
                (self.id.clone(), "settle"),
                1.0,
                ArcMotionTokens::DEFAULT.duration.standard.mul_f64(1.5),
                ArcMotionTokens::DEFAULT.ease.standard,
                window,
                cx,
            )
        };

        let sweep = if running {
            window.request_animation_frame();
            sweep_position(now - started_at, self.duration)
        } else if self.active {
            0.0
        } else {
            1.0
        };

        let base = shimmer_base(colors);
        let highlight = colors.foreground;
        let chars: Vec<char> = self.text.chars().collect();
        let total_em: f32 = chars
            .iter()
            .map(|ch| glyph_advance(*ch))
            .sum::<f32>()
            .max(0.1);

        let mut line = div().flex().flex_row().items_baseline().whitespace_nowrap();
        let mut cursor_em = 0.0f32;
        for ch in &chars {
            let advance = glyph_advance(*ch);
            let center = (cursor_em + advance * 0.5) / total_em;
            let normalized = (center - sweep) * total_em / BAND_EM;
            let strength = bell_strength(normalized);
            let color = shimmer_glyph_color(base, highlight, settle, strength);
            cursor_em += advance;
            line = line.child(
                div()
                    .flex_none()
                    .text_color(color)
                    .when(*ch == ' ', |this| this.w(px(0.28 * em)))
                    .child(if *ch == ' ' {
                        SharedString::from("\u{00a0}")
                    } else {
                        SharedString::from(ch.to_string())
                    }),
            );
        }

        // Label swap rise: new copy fades and rises from 0.3em with a soft blur.
        let rise_t = if reduced {
            1.0
        } else {
            (((now - label_started) / motion.duration.standard.as_secs_f64()).clamp(0.0, 1.0))
                as f32
        };
        let rise = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(rise_t);
        let blur = BlurFallback::evaluate(px(f32::from(motion.blur.soft) * (1.0 - rise)), reduced);

        // Viewport probe drives the in-view gate (Arc uses a 64px margin; GPUI tracks ratio only).
        let probe = {
            let in_view = in_view.clone();
            let visible = visible.clone();
            let measured = measured.clone();
            gpui_kit::canvas(
                move |rect: Bounds<Pixels>, window: &mut Window, _| {
                    let viewport = Bounds::new(point(px(0.0), px(0.0)), window.viewport_size());
                    let state = in_view.borrow_mut().evaluate(rect, viewport);
                    let next = state.ratio > 0.0;
                    if measured.get() && visible.get() != next {
                        visible.set(next);
                        window.request_animation_frame();
                    }
                    visible.set(next);
                    measured.set(true);
                },
                |_, _, _, _| {},
            )
            .absolute()
            .inset_0()
        };

        div()
            .id(self.id)
            .test_support()
            .role(self.role)
            .aria_label(self.text.clone())
            .self_start()
            .relative()
            .flex()
            .flex_col()
            .text_size(self.text_size)
            .line_height(self.text_size * 1.4)
            .max_w(px(32.0 * em))
            .child(probe)
            .child(
                div()
                    .opacity((rise * blur.opacity_multiplier).clamp(0.0, 1.0))
                    .mt(px((1.0 - rise) * 0.3 * em))
                    .child(line),
            )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn bell_is_symmetric_and_peaks_at_the_centre() {
        assert!((bell_strength(0.0) - 1.0).abs() < 1e-6);
        assert!((bell_strength(-0.2) - 0.9).abs() < 1e-6);
        assert_eq!(bell_strength(1.0), 0.0);
        assert_eq!(bell_strength(-1.0), 0.0);
        assert!((bell_strength(0.1) - bell_strength(-0.1)).abs() < 1e-6);
        assert_eq!(bell_strength(2.0), 0.0);
    }

    #[test]
    fn sweep_loops_with_a_rest_between_passes() {
        assert_eq!(sweep_position(0.0, 1.8), 0.0);
        assert!((sweep_position(0.9, 1.8) - 0.5).abs() < 1e-6);
        assert_eq!(sweep_position(1.8, 1.8), 1.0);
        // 1.8s sweep + 0.576s rest == 2.376s cycle.
        let cycle = 1.8 * 1.32;
        assert_eq!(sweep_position(cycle * 3.0 + 0.0, 1.8), 0.0);
        assert!(sweep_position(1.8 + 0.2, 1.8) >= 1.0);
    }

    #[test]
    fn settle_and_strength_move_the_colour_towards_the_highlight() {
        let colors =
            arc_tokens::ArcTheme::new(arc_tokens::ThemeMode::Light, arc_tokens::Accent::Neutral)
                .colors;
        let base = shimmer_base(colors);
        let resting = shimmer_glyph_color(base, colors.foreground, 0.0, 0.0);
        let in_band = shimmer_glyph_color(base, colors.foreground, 0.0, 1.0);
        let settled = shimmer_glyph_color(base, colors.foreground, 1.0, 0.0);
        assert!((in_band.l - colors.foreground.l).abs() < 1e-3);
        assert!((settled.l - colors.foreground.l).abs() < 1e-3);
        // The resting base leans towards `text-muted`; the settled colour reaches the highlight.
        assert!(
            (resting.l - colors.foreground.l).abs()
                > (settled.l - colors.foreground.l).abs() + 1e-4
        );
        assert!((in_band.l - colors.foreground.l).abs() <= (resting.l - colors.foreground.l).abs());
    }

    #[test]
    fn advances_are_wider_for_cjk_than_spaces() {
        assert!(glyph_advance('中') > glyph_advance('W'));
        assert!(glyph_advance('W') > glyph_advance('a'));
        assert!(glyph_advance('a') > glyph_advance(' '));
    }

    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
    use gpui_kit::{
        Context, Render, TestAppContext,
        test::{TestQueryExt as _, TestWindowExt as _},
    };

    struct ShimmerHost {
        active: bool,
    }

    impl Render for ShimmerHost {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            div().p(px(24.0)).child(
                TextShimmer::new("status", "正在生成摘要")
                    .active(self.active)
                    .duration(0.6),
            )
        }
    }

    #[gpui_kit::test]
    fn shimmer_renders_busy_line_and_settles_when_idle(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
        });
        let (view, cx) = cx.add_window_view(|_, _| ShimmerHost { active: true });
        cx.update(|window, cx| {
            for _ in 0..4 {
                window.render_frame(cx);
            }
            assert!(f32::from(window.find_by_label("正在生成摘要").bounds().size.width) > 0.0);
        });
        view.update(cx, |host, cx| {
            host.active = false;
            cx.notify();
        });
        cx.update(|window, cx| {
            for _ in 0..8 {
                window.render_frame(cx);
            }
            assert!(f32::from(window.find_by_label("正在生成摘要").bounds().size.width) > 0.0);
        });
    }
}