Skip to main content

arc_ui/text/
in_view_title.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/in-view-title/in-view-title.tsx` & `.module.css`
3//!
4//! P2 Component #34: `in-view-title`
5//!
6//! - A section title reveals itself once it scrolls into view (45% visible). Five variants:
7//!   `Blur` sharpens word by word (the default), `Word` and `Line` rise out of a clip,
8//!   `Tracking` opens tight letter spacing and `Wipe` uncovers from left to right.
9//! - Three overlapping tracks per part: opacity leads (`settle × 0.56`, `ease.standard`), the
10//!   filter clears sooner (`settle × 0.78`) and transform settles longest (`settle`, `ease.enter`),
11//!   so text is readable before it fully arrives.
12//! - Titles already above the viewport show immediately; `once(false)` replays on every entry.
13//! - Local design: no `mask-image` (clip edges are hard and the wipe edge is emulated per glyph),
14//!   no server-render fallback timer, and hiding is an instant reset because the trigger is
15//!   off-screen anyway.
16
17use std::cell::{Cell, RefCell};
18use std::rc::Rc;
19
20use arc_motion::{
21    BlurFallback, CubicBezier, InViewConfig, InViewTracker, is_reduced_motion, motion_now,
22};
23use arc_tokens::{ActiveArcTheme as _, Typography};
24use gpui_kit::{
25    App, Bounds, ElementId, IntoElement, ParentElement, Pixels, RenderOnce, SharedString, Styled,
26    TestSupportExt as _, Window, div, point, prelude::*, px,
27};
28
29/// Horizontal distance each letter travels per step from its word centre (`tracking`).
30const TRACK_EM: f32 = 0.06;
31/// Soft edge width of the wipe, as a fraction of the title width.
32const WIPE_EDGE: f32 = 0.12;
33
34/// Reveal style of an [`InViewTitle`].
35#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
36pub enum InViewTitleVariant {
37    Word,
38    Line,
39    #[default]
40    Blur,
41    Tracking,
42    Wipe,
43}
44
45impl InViewTitleVariant {
46    /// Longest transform track in seconds (`settle` in Arc's stylesheet).
47    pub const fn settle(self) -> f64 {
48        match self {
49            Self::Word | Self::Blur => 0.80,
50            Self::Line => 0.86,
51            Self::Tracking => 1.00,
52            Self::Wipe => 0.90,
53        }
54    }
55}
56
57/// Semantic level (sets the default size and role).
58#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
59pub enum InViewTitleLevel {
60    H1,
61    #[default]
62    H2,
63    H3,
64}
65
66impl InViewTitleLevel {
67    pub const fn default_size(self) -> Pixels {
68        match self {
69            Self::H1 => Typography::TEXT_5XL,
70            Self::H2 => Typography::TEXT_3XL,
71            Self::H3 => Typography::TEXT_2XL,
72        }
73    }
74}
75
76/// Per-word stagger: `min(stagger.word × 1.5, 0.4s / words)`.
77pub fn word_step(word_count: usize) -> f64 {
78    0.06_f64.min(0.4 / (word_count.max(1) as f64))
79}
80
81/// One track's progress at `elapsed` seconds after its delay.
82pub fn track_progress(elapsed: f64, duration: f64, delay: f64, enter: bool) -> f32 {
83    if duration <= 0.0 {
84        return 1.0;
85    }
86    let t = ((elapsed - delay) / duration).clamp(0.0, 1.0) as f32;
87    let curve = if enter {
88        CubicBezier::new(0.16, 1.0, 0.3, 1.0)
89    } else {
90        CubicBezier::new(0.22, 1.0, 0.36, 1.0)
91    };
92    curve.sample(t)
93}
94
95/// Three track progresses for one part.
96#[derive(Clone, Copy, Debug, PartialEq)]
97pub struct TitleTracks {
98    pub opacity: f32,
99    pub filter: f32,
100    pub transform: f32,
101}
102
103impl TitleTracks {
104    pub fn at(elapsed: f64, delay: f64, settle: f64) -> Self {
105        Self {
106            opacity: track_progress(elapsed, settle * 0.56, delay, false),
107            filter: track_progress(elapsed, settle * 0.78, delay, true),
108            transform: track_progress(elapsed, settle, delay, true),
109        }
110    }
111
112    pub fn settled(self) -> bool {
113        self.opacity >= 0.999 && self.filter >= 0.999 && self.transform >= 0.999
114    }
115}
116
117#[cfg(test)]
118pub(crate) static PROBE_RUNS: std::sync::atomic::AtomicUsize =
119    std::sync::atomic::AtomicUsize::new(0);
120#[cfg(test)]
121pub(crate) static FLIPS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
122#[cfg(test)]
123pub(crate) static STATE_CREATIONS: std::sync::atomic::AtomicUsize =
124    std::sync::atomic::AtomicUsize::new(0);
125#[cfg(test)]
126pub(crate) static LAST_TRANSFORM: std::sync::atomic::AtomicU32 =
127    std::sync::atomic::AtomicU32::new(0);
128
129struct TitleState {
130    // `Cell` is `Copy`, so these must be `Rc`-shared with the paint closure: cloning a bare
131    // `Cell<bool>` would give the probe its own copy and the reveal could never stick.
132    visible: Rc<Cell<bool>>,
133    revealed_at: Rc<Cell<f64>>,
134    tracker: Rc<RefCell<InViewTracker>>,
135}
136
137/// Arc `InViewTitle` — a section title that reveals itself when it scrolls into view.
138#[derive(IntoElement)]
139pub struct InViewTitle {
140    id: ElementId,
141    text: SharedString,
142    variant: InViewTitleVariant,
143    level: InViewTitleLevel,
144    lines: Vec<SharedString>,
145    once: bool,
146    text_size: Option<Pixels>,
147}
148
149impl InViewTitle {
150    pub fn new(id: impl Into<ElementId>, text: impl Into<SharedString>) -> Self {
151        Self {
152            id: id.into(),
153            text: text.into(),
154            variant: InViewTitleVariant::Blur,
155            level: InViewTitleLevel::H2,
156            lines: Vec::new(),
157            once: true,
158            text_size: None,
159        }
160    }
161
162    pub fn variant(mut self, variant: InViewTitleVariant) -> Self {
163        self.variant = variant;
164        self
165    }
166
167    pub fn level(mut self, level: InViewTitleLevel) -> Self {
168        self.level = level;
169        self
170    }
171
172    /// Explicit line breaks for the `Line` variant.
173    pub fn lines(mut self, lines: impl IntoIterator<Item = impl Into<SharedString>>) -> Self {
174        self.lines = lines.into_iter().map(Into::into).collect();
175        self
176    }
177
178    /// Replays the reveal on every entry (`true` by default: reveal once).
179    pub fn once(mut self, once: bool) -> Self {
180        self.once = once;
181        self
182    }
183
184    pub fn text_size(mut self, size: Pixels) -> Self {
185        self.text_size = Some(size);
186        self
187    }
188}
189
190impl RenderOnce for InViewTitle {
191    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
192        let theme = cx.arc_theme().clone();
193        let colors = theme.colors;
194        let motion = theme.motion;
195        let reduced = is_reduced_motion(cx);
196        let now = motion_now(cx);
197        let size = self.text_size.unwrap_or_else(|| self.level.default_size());
198        let em = f32::from(size);
199
200        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-in-view-title".into());
201        let state = window.use_keyed_state(state_id, cx, |_, _| {
202            #[cfg(test)]
203            STATE_CREATIONS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
204            TitleState {
205                visible: Rc::new(Cell::new(false)),
206                revealed_at: Rc::new(Cell::new(0.0)),
207                tracker: Rc::new(RefCell::new(InViewTracker::new(InViewConfig {
208                    amount: 0.45,
209                    once: true,
210                }))),
211            }
212        });
213        if !self.once {
214            *state.read(cx).tracker.borrow_mut() = InViewTracker::new(InViewConfig {
215                amount: 0.45,
216                once: false,
217            });
218        }
219
220        // Viewport probe: enters at 45% visible, also treats a title already above the viewport
221        // (scrolled past) as visible so it never stays hidden.
222        let probe = {
223            let visible = state.read(cx).visible.clone();
224            let revealed_at = state.read(cx).revealed_at.clone();
225            let tracker = state.read(cx).tracker.clone();
226            gpui_kit::canvas(
227                move |rect: Bounds<Pixels>, window: &mut Window, _| {
228                    #[cfg(test)]
229                    PROBE_RUNS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
230                    let viewport = Bounds::new(point(px(0.0), px(0.0)), window.viewport_size());
231                    let evaluated = tracker.borrow_mut().evaluate(rect, viewport);
232                    // A title that has scrolled past the top counts as visible.
233                    let passed = f32::from(rect.origin.y) < f32::from(viewport.origin.y);
234                    let next = evaluated.in_view || passed;
235                    if visible.get() != next {
236                        #[cfg(test)]
237                        FLIPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
238                        visible.set(next);
239                        if next {
240                            revealed_at.set(now);
241                        }
242                        window.request_animation_frame();
243                    }
244                },
245                |_, _, _, _| {},
246            )
247            .absolute()
248            .inset_0()
249        };
250
251        let visible = state.read(cx).visible.get();
252        let revealed_at = state.read(cx).revealed_at.get();
253        let elapsed = (now - revealed_at).max(0.0);
254        let settle = self.variant.settle();
255
256        let words: Vec<String> = self
257            .text
258            .split_whitespace()
259            .map(ToString::to_string)
260            .collect();
261        let step = word_step(words.len());
262        let mut animating = false;
263
264        let part = |elapsed: f64, delay: f64, settle: f64, animating: &mut bool| -> TitleTracks {
265            if reduced || !visible {
266                return if visible {
267                    TitleTracks {
268                        opacity: 1.0,
269                        filter: 1.0,
270                        transform: 1.0,
271                    }
272                } else {
273                    TitleTracks {
274                        opacity: 0.0,
275                        filter: 0.0,
276                        transform: 0.0,
277                    }
278                };
279            }
280            let tracks = TitleTracks::at(elapsed, delay, settle);
281            if !tracks.settled() {
282                *animating = true;
283            }
284            tracks
285        };
286
287        let mut wrapper = div()
288            .flex()
289            .flex_col()
290            .items_start()
291            .text_size(size)
292            .line_height(size * 1.15)
293            .text_color(colors.foreground);
294
295        match self.variant {
296            InViewTitleVariant::Word => {
297                let mut row = div()
298                    .flex()
299                    .flex_row()
300                    .flex_wrap()
301                    .items_start()
302                    .gap(px(0.26 * em));
303                for (index, word) in words.iter().enumerate() {
304                    let tracks = part(elapsed, index as f64 * step, settle, &mut animating);
305                    row = row.child(
306                        div().overflow_hidden().child(
307                            div()
308                                .whitespace_nowrap()
309                                .opacity(tracks.opacity)
310                                .mt(px((1.0 - tracks.transform) * 0.9 * em))
311                                .child(word.clone()),
312                        ),
313                    );
314                }
315                wrapper = wrapper.child(row);
316            }
317            InViewTitleVariant::Line => {
318                let lines: Vec<SharedString> = if self.lines.is_empty() {
319                    vec![self.text.clone()]
320                } else {
321                    self.lines.clone()
322                };
323                for (index, line) in lines.iter().enumerate() {
324                    let tracks = part(
325                        elapsed,
326                        index as f64 * motion.stagger.line.as_secs_f64(),
327                        settle,
328                        &mut animating,
329                    );
330                    wrapper = wrapper.child(
331                        div().w_full().overflow_hidden().child(
332                            div()
333                                .whitespace_nowrap()
334                                .opacity(tracks.opacity)
335                                .mt(px((1.0 - tracks.transform) * 1.12 * em))
336                                .child(line.clone()),
337                        ),
338                    );
339                }
340            }
341            InViewTitleVariant::Blur => {
342                let mut row = div()
343                    .flex()
344                    .flex_row()
345                    .flex_wrap()
346                    .items_start()
347                    .gap(px(0.26 * em));
348                for (index, word) in words.iter().enumerate() {
349                    let tracks = part(elapsed, index as f64 * step, settle, &mut animating);
350                    #[cfg(test)]
351                    if index == 0 {
352                        LAST_TRANSFORM.store(
353                            tracks.transform.to_bits(),
354                            std::sync::atomic::Ordering::Relaxed,
355                        );
356                    }
357                    let blur = BlurFallback::evaluate(
358                        px(f32::from(motion.blur.text) * (1.0 - tracks.filter)),
359                        reduced,
360                    );
361                    row = row.child(
362                        div()
363                            .flex_none()
364                            .opacity((tracks.opacity * blur.opacity_multiplier).clamp(0.0, 1.0))
365                            .mt(px((1.0 - tracks.transform) * 0.2 * em))
366                            .child(word.clone()),
367                    );
368                }
369                wrapper = wrapper.child(row);
370            }
371            InViewTitleVariant::Tracking => {
372                let mut row = div()
373                    .flex()
374                    .flex_row()
375                    .flex_wrap()
376                    .items_start()
377                    .gap(px(0.26 * em));
378                for (index, word) in words.iter().enumerate() {
379                    let letters: Vec<char> = word.chars().collect();
380                    let center = (letters.len().saturating_sub(1)) as f32 / 2.0;
381                    let delay = index as f64 * motion.stagger.char.as_secs_f64() * 2.0;
382                    let tracks = part(elapsed, delay, settle, &mut animating);
383                    let blur = BlurFallback::evaluate(
384                        px(f32::from(motion.blur.soft) * (1.0 - tracks.filter)),
385                        reduced,
386                    );
387                    let mut word_row = div()
388                        .flex()
389                        .flex_row()
390                        .whitespace_nowrap()
391                        .opacity((tracks.opacity * blur.opacity_multiplier).clamp(0.0, 1.0));
392                    for (letter_index, letter) in letters.iter().enumerate() {
393                        let offset = (center - letter_index as f32)
394                            * TRACK_EM
395                            * em
396                            * (1.0 - tracks.transform);
397                        word_row = word_row.child(
398                            div()
399                                .flex_none()
400                                .ml(px(offset))
401                                .child(SharedString::from(letter.to_string())),
402                        );
403                    }
404                    row = row.child(word_row);
405                }
406                wrapper = wrapper.child(row);
407            }
408            InViewTitleVariant::Wipe => {
409                let chars: Vec<char> = self.text.chars().collect();
410                let total = chars.len().max(1) as f32;
411                let tracks = part(elapsed, 0.0, settle, &mut animating);
412                let mut row = div()
413                    .flex()
414                    .flex_row()
415                    .whitespace_nowrap()
416                    .ml(px(-0.12 * em * (1.0 - tracks.transform)));
417                for (index, ch) in chars.iter().enumerate() {
418                    let unit = (index as f32 + 0.5) / total;
419                    let swept = tracks.transform * (1.0 + WIPE_EDGE);
420                    let edge = ((swept - unit) / WIPE_EDGE).clamp(0.0, 1.0);
421                    row = row.child(
422                        div()
423                            .flex_none()
424                            .opacity((tracks.opacity * edge).clamp(0.0, 1.0))
425                            .child(if *ch == ' ' {
426                                SharedString::from("\u{00a0}")
427                            } else {
428                                SharedString::from(ch.to_string())
429                            }),
430                    );
431                }
432                wrapper = wrapper.child(row);
433            }
434        }
435
436        if animating {
437            window.request_animation_frame();
438        }
439
440        div()
441            .id(self.id)
442            .test_support()
443            .role(gpui_kit::Role::Heading)
444            .aria_label(self.text.clone())
445            .self_start()
446            .w_full()
447            .relative()
448            .child(probe)
449            .child(wrapper)
450    }
451}
452
453#[cfg(test)]
454mod tests {
455    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
456    use gpui_kit::{
457        Context, Render, TestAppContext, div,
458        test::{TestQueryExt as _, TestWindowExt as _},
459    };
460
461    use super::*;
462
463    /// Serializes tests that read the module-level render counters, so the numbers are
464    /// deterministic while the harness runs test functions in parallel threads.
465    static COUNTER_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
466
467    #[test]
468    fn word_stagger_is_capped_for_long_titles() {
469        assert!((word_step(2) - 0.06).abs() < 1e-9);
470        assert!((word_step(10) - 0.04).abs() < 1e-9);
471        assert!((word_step(20) - 0.02).abs() < 1e-9);
472        assert!(word_step(20) * 20.0 <= 0.40 + 1e-9);
473        assert!(word_step(0) > 0.0);
474    }
475
476    #[test]
477    fn tracks_lead_with_opacity_and_settle_with_transform() {
478        let settle = InViewTitleVariant::Blur.settle();
479        let early = TitleTracks::at(0.15, 0.0, settle);
480        assert!(early.opacity > early.transform, "opacity leads");
481        assert!(
482            early.filter > early.transform,
483            "filter clears before the transform settles"
484        );
485        let done = TitleTracks::at(settle + 0.05, 0.0, settle);
486        assert!(done.settled());
487        let delayed = TitleTracks::at(0.10, 0.20, settle);
488        assert_eq!(delayed.opacity, 0.0);
489        assert_eq!(track_progress(1.0, 0.0, 0.5, true), 1.0);
490    }
491
492    #[test]
493    fn variants_ship_arc_settle_durations() {
494        assert_eq!(InViewTitleVariant::Blur.settle(), 0.80);
495        assert_eq!(InViewTitleVariant::Line.settle(), 0.86);
496        assert_eq!(InViewTitleVariant::Tracking.settle(), 1.00);
497        assert_eq!(InViewTitleVariant::Wipe.settle(), 0.90);
498    }
499
500    struct TitleHost {
501        variant: InViewTitleVariant,
502    }
503
504    impl Render for TitleHost {
505        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
506            div().p(px(24.0)).w_full().child(
507                InViewTitle::new("title", "更快地构建桌面界面")
508                    .variant(self.variant)
509                    .level(InViewTitleLevel::H2),
510            )
511        }
512    }
513
514    #[gpui_kit::test]
515    fn probe_runs_and_flips_visible(cx: &mut TestAppContext) {
516        let _guard = COUNTER_LOCK.lock().unwrap_or_else(|e| e.into_inner());
517        PROBE_RUNS.store(0, std::sync::atomic::Ordering::Relaxed);
518        FLIPS.store(0, std::sync::atomic::Ordering::Relaxed);
519        STATE_CREATIONS.store(0, std::sync::atomic::Ordering::Relaxed);
520        LAST_TRANSFORM.store(0, std::sync::atomic::Ordering::Relaxed);
521        cx.update(|cx| {
522            gpui_kit::init(cx);
523            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
524        });
525        let (_view, cx) = cx.add_window_view(|_, _| TitleHost {
526            variant: InViewTitleVariant::Blur,
527        });
528        cx.update(|window, cx| {
529            for _ in 0..6 {
530                window.render_frame(cx);
531            }
532        });
533        let flips = FLIPS.load(std::sync::atomic::Ordering::Relaxed);
534        let probes = PROBE_RUNS.load(std::sync::atomic::Ordering::Relaxed);
535        assert!(probes > 1, "probe must run every frame, ran {probes}");
536        assert_eq!(
537            flips, 1,
538            "the reveal must latch once (probes={probes}); more flips means the visibility              state is not shared with the paint closure"
539        );
540        assert_eq!(
541            STATE_CREATIONS.load(std::sync::atomic::Ordering::Relaxed),
542            1
543        );
544    }
545
546    #[gpui_kit::test]
547    fn in_view_title_reveals_and_can_replay(cx: &mut TestAppContext) {
548        let _guard = COUNTER_LOCK.lock().unwrap_or_else(|e| e.into_inner());
549        cx.update(|cx| {
550            gpui_kit::init(cx);
551            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
552        });
553        let (view, cx) = cx.add_window_view(|_, _| TitleHost {
554            variant: InViewTitleVariant::Blur,
555        });
556        cx.update(|window, cx| {
557            for _ in 0..20 {
558                window.render_frame(cx);
559            }
560            assert!(
561                f32::from(
562                    window
563                        .find_by_label("更快地构建桌面界面")
564                        .bounds()
565                        .size
566                        .width
567                ) > 0.0
568            );
569        });
570        view.update(cx, |host, cx| {
571            host.variant = InViewTitleVariant::Wipe;
572            cx.notify();
573        });
574        cx.update(|window, cx| {
575            for _ in 0..20 {
576                window.render_frame(cx);
577            }
578            assert!(
579                f32::from(
580                    window
581                        .find_by_label("更快地构建桌面界面")
582                        .bounds()
583                        .size
584                        .width
585                ) > 0.0
586            );
587        });
588    }
589}