Skip to main content

arc_ui/text/
text_reveal.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/text-reveal/text-reveal.tsx` & `.module.css`
3//!
4//! P2 Component #31: `text-reveal`
5//!
6//! - Each word rises out of its own clip, fades in and sharpens from a soft blur, once, on mount.
7//! - Three tracks share one delay: rise `0.76s` / `ease.enter`, fade `0.44s` / `ease.standard`,
8//!   focus `0.58s` / `ease.enter`. The stagger is `min(stagger.word, 480ms / word count)` so long
9//!   headlines never drift apart.
10//! - `\n` starts a deliberate line; changing the text replays the entrance.
11//! - Local design: no `mask-image` feather on the clip (hard clip edge), no `text-wrap: balance`,
12//!   and the blur clears through the unified opacity fallback instead of a glyph shader.
13
14use arc_motion::{BlurFallback, CubicBezier, is_reduced_motion, motion_now};
15use arc_tokens::{ActiveArcTheme as _, ArcMotionTokens, Typography};
16use gpui_kit::{
17    App, ElementId, IntoElement, ParentElement, Pixels, RenderOnce, Role, SharedString, Styled,
18    TestSupportExt as _, Window, div, prelude::*, px,
19};
20
21/// Semantic level of a [`TextReveal`] headline.
22#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
23pub enum TextRevealLevel {
24    H1,
25    #[default]
26    H2,
27    H3,
28    Paragraph,
29}
30
31impl TextRevealLevel {
32    pub const fn role(self) -> Role {
33        match self {
34            Self::H1 | Self::H2 | Self::H3 => Role::Heading,
35            Self::Paragraph => Role::Paragraph,
36        }
37    }
38
39    pub const fn default_size(self) -> Pixels {
40        match self {
41            Self::H1 => Typography::TEXT_5XL,
42            Self::H2 => Typography::TEXT_3XL,
43            Self::H3 => Typography::TEXT_2XL,
44            Self::Paragraph => Typography::TEXT_BASE,
45        }
46    }
47
48    pub const fn blur(self) -> Pixels {
49        match self {
50            Self::Paragraph => ArcMotionTokens::DEFAULT.blur.soft,
51            _ => ArcMotionTokens::DEFAULT.blur.text,
52        }
53    }
54}
55
56struct RevealState {
57    text: String,
58    started_at: f64,
59}
60
61/// Per-word stagger, capped so the last word never waits longer than `considered` (480ms).
62pub fn stagger_step(word_count: usize) -> f64 {
63    ArcMotionTokens::DEFAULT.stagger.word.as_secs_f64().min(
64        ArcMotionTokens::DEFAULT.duration.considered.as_secs_f64() / (word_count.max(1) as f64),
65    )
66}
67
68/// Delay (seconds) before word `index` rises.
69pub fn word_delay(index: usize, word_count: usize, delay: f64) -> f64 {
70    delay + index as f64 * stagger_step(word_count)
71}
72
73/// One word's three overlapping tracks at `elapsed` seconds after its own delay started.
74#[derive(Clone, Copy, Debug, PartialEq)]
75pub struct RevealSample {
76    /// `0..=1` on the `0.76s` rise track.
77    pub rise: f32,
78    /// `0..=1` on the `0.44s` fade track.
79    pub fade: f32,
80    /// `0..=1` on the `0.58s` blur-clear track.
81    pub focus: f32,
82}
83
84impl RevealSample {
85    pub fn at(elapsed: f64) -> Self {
86        let rise =
87            CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample((elapsed / 0.76).clamp(0.0, 1.0) as f32);
88        let fade =
89            CubicBezier::new(0.22, 1.0, 0.36, 1.0).sample((elapsed / 0.44).clamp(0.0, 1.0) as f32);
90        let focus =
91            CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample((elapsed / 0.58).clamp(0.0, 1.0) as f32);
92        Self { rise, fade, focus }
93    }
94
95    pub fn settled(self) -> bool {
96        self.rise >= 0.999 && self.fade >= 0.999 && self.focus >= 0.999
97    }
98}
99
100/// Arc `TextReveal` — a headline whose words rise out of their clips as it mounts.
101#[derive(IntoElement)]
102pub struct TextReveal {
103    id: ElementId,
104    text: SharedString,
105    level: TextRevealLevel,
106    delay: f64,
107    text_size: Option<Pixels>,
108}
109
110impl TextReveal {
111    pub fn new(id: impl Into<ElementId>, text: impl Into<SharedString>) -> Self {
112        Self {
113            id: id.into(),
114            text: text.into(),
115            level: TextRevealLevel::H2,
116            delay: 0.0,
117            text_size: None,
118        }
119    }
120
121    pub fn level(mut self, level: TextRevealLevel) -> Self {
122        self.level = level;
123        self
124    }
125
126    /// Seconds to wait before the first word rises.
127    pub fn delay(mut self, delay: f64) -> Self {
128        self.delay = delay.max(0.0);
129        self
130    }
131
132    pub fn text_size(mut self, size: Pixels) -> Self {
133        self.text_size = Some(size);
134        self
135    }
136}
137
138impl RenderOnce for TextReveal {
139    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
140        let colors = cx.arc_theme().colors;
141        let reduced = is_reduced_motion(cx);
142        let size = self.text_size.unwrap_or_else(|| self.level.default_size());
143        let em = f32::from(size);
144
145        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-text-reveal".into());
146        let now = motion_now(cx);
147        let state = window.use_keyed_state(state_id, cx, |_, _| RevealState {
148            text: self.text.to_string(),
149            started_at: now,
150        });
151        let current = state.read(cx).text.clone();
152        if current != self.text.as_ref() {
153            state.update(cx, |s, _| {
154                s.text = self.text.to_string();
155                s.started_at = now;
156            });
157        }
158        let started_at = state.read(cx).started_at;
159
160        let lines: Vec<Vec<&str>> = self
161            .text
162            .split('\n')
163            .map(|line| line.split_whitespace().collect())
164            .collect();
165        let word_count: usize = lines.iter().map(Vec::len).sum();
166        let spoken = self.text.replace('\n', " ");
167        let blur_token = self.level.blur();
168
169        let mut column = div()
170            .flex()
171            .flex_col()
172            .items_start()
173            .text_size(size)
174            .line_height(size * 1.15)
175            .text_color(colors.foreground)
176            // 24ch at roughly 0.5em per character.
177            .max_w(px(12.0 * em));
178
179        let mut index = 0usize;
180        let mut animating = false;
181        for (line_index, words) in lines.iter().enumerate() {
182            let mut row = div()
183                .flex()
184                .flex_row()
185                .flex_wrap()
186                .items_start()
187                .gap(px(0.26 * em));
188            for word in words {
189                let delay = word_delay(index, word_count, self.delay)
190                    + line_index as f64 * stagger_step(word_count);
191                index += 1;
192                let elapsed = (now - started_at - delay).max(0.0);
193                let sample = if reduced {
194                    // Reduced motion keeps only the fade, over `duration.fast`.
195                    let fade = CubicBezier::new(0.22, 1.0, 0.36, 1.0)
196                        .sample((elapsed / 0.16).clamp(0.0, 1.0) as f32);
197                    RevealSample {
198                        rise: 1.0,
199                        fade,
200                        focus: 1.0,
201                    }
202                } else {
203                    RevealSample::at(elapsed)
204                };
205                if !sample.settled() {
206                    animating = true;
207                }
208
209                let blur = BlurFallback::evaluate(
210                    px(f32::from(blur_token) * (1.0 - sample.focus)),
211                    reduced,
212                );
213                let inner = div()
214                    .whitespace_nowrap()
215                    .opacity((sample.fade * blur.opacity_multiplier).clamp(0.0, 1.0))
216                    .mt(px((1.0 - sample.rise) * 0.62 * em))
217                    .child(word.to_string());
218                row = row.child(div().overflow_hidden().child(inner));
219            }
220            column = column.child(row);
221        }
222        if animating {
223            window.request_animation_frame();
224        }
225
226        div()
227            .id(self.id)
228            .test_support()
229            .role(self.level.role())
230            .aria_label(spoken)
231            .self_start()
232            .child(column)
233    }
234}
235
236#[cfg(test)]
237mod tests {
238    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
239    use gpui_kit::{
240        Context, Render, TestAppContext, div,
241        test::{TestQueryExt as _, TestWindowExt as _},
242    };
243
244    use super::*;
245
246    #[test]
247    fn stagger_is_capped_by_the_considered_duration() {
248        // 40ms per word for short copy.
249        assert!((word_delay(3, 5, 0.0) - 0.12).abs() < 1e-9);
250        // Long copy compresses so the whole entrance stays under 480ms of stagger.
251        let count = 40;
252        let step = word_delay(1, count, 0.0);
253        assert!((step - 0.012).abs() < 1e-9);
254        assert!(word_delay(count - 1, count, 0.0) <= 0.48 + 1e-9);
255        assert!((word_delay(0, 5, 0.2) - 0.2).abs() < 1e-9);
256    }
257
258    #[test]
259    fn reveal_tracks_settle_in_under_a_second() {
260        let early = RevealSample::at(0.0);
261        assert!(early.rise < 1e-4 && early.fade < 1e-4 && early.focus < 1e-4);
262        let fading = RevealSample::at(0.22);
263        assert!(fading.fade > fading.rise);
264        let settled = RevealSample::at(0.80);
265        assert!(settled.settled(), "all tracks should finish by 0.80s");
266        // Monotonic, never overshooting.
267        let mut last = 0.0;
268        for step in 0..=16 {
269            let value = RevealSample::at(step as f64 * 0.05).rise;
270            assert!(value >= last - 1e-4 && value <= 1.0 + 1e-4);
271            last = value;
272        }
273    }
274
275    struct RevealHost {
276        text: &'static str,
277    }
278
279    impl Render for RevealHost {
280        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
281            div().p(px(24.0)).child(
282                TextReveal::new("headline", self.text)
283                    .level(TextRevealLevel::H2)
284                    .delay(0.0),
285            )
286        }
287    }
288
289    #[gpui_kit::test]
290    fn text_reveal_animates_then_settles_and_replays_on_change(cx: &mut TestAppContext) {
291        cx.update(|cx| {
292            gpui_kit::init(cx);
293            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
294        });
295        let (view, cx) = cx.add_window_view(|_, _| RevealHost {
296            text: "动效是界面的语气",
297        });
298        cx.update(|window, cx| {
299            for _ in 0..20 {
300                window.render_frame(cx);
301            }
302            assert!(f32::from(window.find_by_label("动效是界面的语气").bounds().size.width) > 0.0);
303        });
304        view.update(cx, |host, cx| {
305            host.text = "动效是界面的语气。";
306            cx.notify();
307        });
308        cx.update(|window, cx| {
309            for _ in 0..20 {
310                window.render_frame(cx);
311            }
312            assert!(
313                f32::from(
314                    window
315                        .find_by_label("动效是界面的语气。")
316                        .bounds()
317                        .size
318                        .width
319                ) > 0.0
320            );
321        });
322    }
323}