arc-ui 0.4.0

Physics-first native Rust desktop UI component library & charts for GPUI (120+ interactive components ported from Arc).
Documentation
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/text-reveal/text-reveal.tsx` & `.module.css`
//!
//! P2 Component #31: `text-reveal`
//!
//! - Each word rises out of its own clip, fades in and sharpens from a soft blur, once, on mount.
//! - Three tracks share one delay: rise `0.76s` / `ease.enter`, fade `0.44s` / `ease.standard`,
//!   focus `0.58s` / `ease.enter`. The stagger is `min(stagger.word, 480ms / word count)` so long
//!   headlines never drift apart.
//! - `\n` starts a deliberate line; changing the text replays the entrance.
//! - Local design: no `mask-image` feather on the clip (hard clip edge), no `text-wrap: balance`,
//!   and the blur clears through the unified opacity fallback instead of a glyph shader.

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

/// Semantic level of a [`TextReveal`] headline.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum TextRevealLevel {
    H1,
    #[default]
    H2,
    H3,
    Paragraph,
}

impl TextRevealLevel {
    pub const fn role(self) -> Role {
        match self {
            Self::H1 | Self::H2 | Self::H3 => Role::Heading,
            Self::Paragraph => Role::Paragraph,
        }
    }

    pub const fn default_size(self) -> Pixels {
        match self {
            Self::H1 => Typography::TEXT_5XL,
            Self::H2 => Typography::TEXT_3XL,
            Self::H3 => Typography::TEXT_2XL,
            Self::Paragraph => Typography::TEXT_BASE,
        }
    }

    pub const fn blur(self) -> Pixels {
        match self {
            Self::Paragraph => ArcMotionTokens::DEFAULT.blur.soft,
            _ => ArcMotionTokens::DEFAULT.blur.text,
        }
    }
}

struct RevealState {
    text: String,
    started_at: f64,
}

/// Per-word stagger, capped so the last word never waits longer than `considered` (480ms).
pub fn stagger_step(word_count: usize) -> f64 {
    ArcMotionTokens::DEFAULT.stagger.word.as_secs_f64().min(
        ArcMotionTokens::DEFAULT.duration.considered.as_secs_f64() / (word_count.max(1) as f64),
    )
}

/// Delay (seconds) before word `index` rises.
pub fn word_delay(index: usize, word_count: usize, delay: f64) -> f64 {
    delay + index as f64 * stagger_step(word_count)
}

/// One word's three overlapping tracks at `elapsed` seconds after its own delay started.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RevealSample {
    /// `0..=1` on the `0.76s` rise track.
    pub rise: f32,
    /// `0..=1` on the `0.44s` fade track.
    pub fade: f32,
    /// `0..=1` on the `0.58s` blur-clear track.
    pub focus: f32,
}

impl RevealSample {
    pub fn at(elapsed: f64) -> Self {
        let rise =
            CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample((elapsed / 0.76).clamp(0.0, 1.0) as f32);
        let fade =
            CubicBezier::new(0.22, 1.0, 0.36, 1.0).sample((elapsed / 0.44).clamp(0.0, 1.0) as f32);
        let focus =
            CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample((elapsed / 0.58).clamp(0.0, 1.0) as f32);
        Self { rise, fade, focus }
    }

    pub fn settled(self) -> bool {
        self.rise >= 0.999 && self.fade >= 0.999 && self.focus >= 0.999
    }
}

/// Arc `TextReveal` — a headline whose words rise out of their clips as it mounts.
#[derive(IntoElement)]
pub struct TextReveal {
    id: ElementId,
    text: SharedString,
    level: TextRevealLevel,
    delay: f64,
    text_size: Option<Pixels>,
}

impl TextReveal {
    pub fn new(id: impl Into<ElementId>, text: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            text: text.into(),
            level: TextRevealLevel::H2,
            delay: 0.0,
            text_size: None,
        }
    }

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

    /// Seconds to wait before the first word rises.
    pub fn delay(mut self, delay: f64) -> Self {
        self.delay = delay.max(0.0);
        self
    }

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

impl RenderOnce for TextReveal {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let colors = cx.arc_theme().colors;
        let reduced = is_reduced_motion(cx);
        let size = self.text_size.unwrap_or_else(|| self.level.default_size());
        let em = f32::from(size);

        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-text-reveal".into());
        let now = motion_now(cx);
        let state = window.use_keyed_state(state_id, cx, |_, _| RevealState {
            text: self.text.to_string(),
            started_at: now,
        });
        let current = state.read(cx).text.clone();
        if current != self.text.as_ref() {
            state.update(cx, |s, _| {
                s.text = self.text.to_string();
                s.started_at = now;
            });
        }
        let started_at = state.read(cx).started_at;

        let lines: Vec<Vec<&str>> = self
            .text
            .split('\n')
            .map(|line| line.split_whitespace().collect())
            .collect();
        let word_count: usize = lines.iter().map(Vec::len).sum();
        let spoken = self.text.replace('\n', " ");
        let blur_token = self.level.blur();

        let mut column = div()
            .flex()
            .flex_col()
            .items_start()
            .text_size(size)
            .line_height(size * 1.15)
            .text_color(colors.foreground)
            // 24ch at roughly 0.5em per character.
            .max_w(px(12.0 * em));

        let mut index = 0usize;
        let mut animating = false;
        for (line_index, words) in lines.iter().enumerate() {
            let mut row = div()
                .flex()
                .flex_row()
                .flex_wrap()
                .items_start()
                .gap(px(0.26 * em));
            for word in words {
                let delay = word_delay(index, word_count, self.delay)
                    + line_index as f64 * stagger_step(word_count);
                index += 1;
                let elapsed = (now - started_at - delay).max(0.0);
                let sample = if reduced {
                    // Reduced motion keeps only the fade, over `duration.fast`.
                    let fade = CubicBezier::new(0.22, 1.0, 0.36, 1.0)
                        .sample((elapsed / 0.16).clamp(0.0, 1.0) as f32);
                    RevealSample {
                        rise: 1.0,
                        fade,
                        focus: 1.0,
                    }
                } else {
                    RevealSample::at(elapsed)
                };
                if !sample.settled() {
                    animating = true;
                }

                let blur = BlurFallback::evaluate(
                    px(f32::from(blur_token) * (1.0 - sample.focus)),
                    reduced,
                );
                let inner = div()
                    .whitespace_nowrap()
                    .opacity((sample.fade * blur.opacity_multiplier).clamp(0.0, 1.0))
                    .mt(px((1.0 - sample.rise) * 0.62 * em))
                    .child(word.to_string());
                row = row.child(div().overflow_hidden().child(inner));
            }
            column = column.child(row);
        }
        if animating {
            window.request_animation_frame();
        }

        div()
            .id(self.id)
            .test_support()
            .role(self.level.role())
            .aria_label(spoken)
            .self_start()
            .child(column)
    }
}

#[cfg(test)]
mod tests {
    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
    use gpui_kit::{
        Context, Render, TestAppContext, div,
        test::{TestQueryExt as _, TestWindowExt as _},
    };

    use super::*;

    #[test]
    fn stagger_is_capped_by_the_considered_duration() {
        // 40ms per word for short copy.
        assert!((word_delay(3, 5, 0.0) - 0.12).abs() < 1e-9);
        // Long copy compresses so the whole entrance stays under 480ms of stagger.
        let count = 40;
        let step = word_delay(1, count, 0.0);
        assert!((step - 0.012).abs() < 1e-9);
        assert!(word_delay(count - 1, count, 0.0) <= 0.48 + 1e-9);
        assert!((word_delay(0, 5, 0.2) - 0.2).abs() < 1e-9);
    }

    #[test]
    fn reveal_tracks_settle_in_under_a_second() {
        let early = RevealSample::at(0.0);
        assert!(early.rise < 1e-4 && early.fade < 1e-4 && early.focus < 1e-4);
        let fading = RevealSample::at(0.22);
        assert!(fading.fade > fading.rise);
        let settled = RevealSample::at(0.80);
        assert!(settled.settled(), "all tracks should finish by 0.80s");
        // Monotonic, never overshooting.
        let mut last = 0.0;
        for step in 0..=16 {
            let value = RevealSample::at(step as f64 * 0.05).rise;
            assert!(value >= last - 1e-4 && value <= 1.0 + 1e-4);
            last = value;
        }
    }

    struct RevealHost {
        text: &'static str,
    }

    impl Render for RevealHost {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            div().p(px(24.0)).child(
                TextReveal::new("headline", self.text)
                    .level(TextRevealLevel::H2)
                    .delay(0.0),
            )
        }
    }

    #[gpui_kit::test]
    fn text_reveal_animates_then_settles_and_replays_on_change(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(|_, _| RevealHost {
            text: "动效是界面的语气",
        });
        cx.update(|window, cx| {
            for _ in 0..20 {
                window.render_frame(cx);
            }
            assert!(f32::from(window.find_by_label("动效是界面的语气").bounds().size.width) > 0.0);
        });
        view.update(cx, |host, cx| {
            host.text = "动效是界面的语气。";
            cx.notify();
        });
        cx.update(|window, cx| {
            for _ in 0..20 {
                window.render_frame(cx);
            }
            assert!(
                f32::from(
                    window
                        .find_by_label("动效是界面的语气。")
                        .bounds()
                        .size
                        .width
                ) > 0.0
            );
        });
    }
}