use std::cell::{Cell, RefCell};
use std::rc::Rc;
use arc_motion::{
BlurFallback, CubicBezier, InViewConfig, InViewTracker, is_reduced_motion, motion_now,
};
use arc_tokens::{ActiveArcTheme as _, Typography};
use gpui_kit::{
App, Bounds, ElementId, IntoElement, ParentElement, Pixels, RenderOnce, SharedString, Styled,
TestSupportExt as _, Window, div, point, prelude::*, px,
};
const TRACK_EM: f32 = 0.06;
const WIPE_EDGE: f32 = 0.12;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum InViewTitleVariant {
Word,
Line,
#[default]
Blur,
Tracking,
Wipe,
}
impl InViewTitleVariant {
pub const fn settle(self) -> f64 {
match self {
Self::Word | Self::Blur => 0.80,
Self::Line => 0.86,
Self::Tracking => 1.00,
Self::Wipe => 0.90,
}
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum InViewTitleLevel {
H1,
#[default]
H2,
H3,
}
impl InViewTitleLevel {
pub const fn default_size(self) -> Pixels {
match self {
Self::H1 => Typography::TEXT_5XL,
Self::H2 => Typography::TEXT_3XL,
Self::H3 => Typography::TEXT_2XL,
}
}
}
pub fn word_step(word_count: usize) -> f64 {
0.06_f64.min(0.4 / (word_count.max(1) as f64))
}
pub fn track_progress(elapsed: f64, duration: f64, delay: f64, enter: bool) -> f32 {
if duration <= 0.0 {
return 1.0;
}
let t = ((elapsed - delay) / duration).clamp(0.0, 1.0) as f32;
let curve = if enter {
CubicBezier::new(0.16, 1.0, 0.3, 1.0)
} else {
CubicBezier::new(0.22, 1.0, 0.36, 1.0)
};
curve.sample(t)
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TitleTracks {
pub opacity: f32,
pub filter: f32,
pub transform: f32,
}
impl TitleTracks {
pub fn at(elapsed: f64, delay: f64, settle: f64) -> Self {
Self {
opacity: track_progress(elapsed, settle * 0.56, delay, false),
filter: track_progress(elapsed, settle * 0.78, delay, true),
transform: track_progress(elapsed, settle, delay, true),
}
}
pub fn settled(self) -> bool {
self.opacity >= 0.999 && self.filter >= 0.999 && self.transform >= 0.999
}
}
#[cfg(test)]
pub(crate) static PROBE_RUNS: std::sync::atomic::AtomicUsize =
std::sync::atomic::AtomicUsize::new(0);
#[cfg(test)]
pub(crate) static FLIPS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
#[cfg(test)]
pub(crate) static STATE_CREATIONS: std::sync::atomic::AtomicUsize =
std::sync::atomic::AtomicUsize::new(0);
#[cfg(test)]
pub(crate) static LAST_TRANSFORM: std::sync::atomic::AtomicU32 =
std::sync::atomic::AtomicU32::new(0);
struct TitleState {
visible: Rc<Cell<bool>>,
revealed_at: Rc<Cell<f64>>,
tracker: Rc<RefCell<InViewTracker>>,
}
#[derive(IntoElement)]
pub struct InViewTitle {
id: ElementId,
text: SharedString,
variant: InViewTitleVariant,
level: InViewTitleLevel,
lines: Vec<SharedString>,
once: bool,
text_size: Option<Pixels>,
}
impl InViewTitle {
pub fn new(id: impl Into<ElementId>, text: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
text: text.into(),
variant: InViewTitleVariant::Blur,
level: InViewTitleLevel::H2,
lines: Vec::new(),
once: true,
text_size: None,
}
}
pub fn variant(mut self, variant: InViewTitleVariant) -> Self {
self.variant = variant;
self
}
pub fn level(mut self, level: InViewTitleLevel) -> Self {
self.level = level;
self
}
pub fn lines(mut self, lines: impl IntoIterator<Item = impl Into<SharedString>>) -> Self {
self.lines = lines.into_iter().map(Into::into).collect();
self
}
pub fn once(mut self, once: bool) -> Self {
self.once = once;
self
}
pub fn text_size(mut self, size: Pixels) -> Self {
self.text_size = Some(size);
self
}
}
impl RenderOnce for InViewTitle {
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 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-in-view-title".into());
let state = window.use_keyed_state(state_id, cx, |_, _| {
#[cfg(test)]
STATE_CREATIONS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
TitleState {
visible: Rc::new(Cell::new(false)),
revealed_at: Rc::new(Cell::new(0.0)),
tracker: Rc::new(RefCell::new(InViewTracker::new(InViewConfig {
amount: 0.45,
once: true,
}))),
}
});
if !self.once {
*state.read(cx).tracker.borrow_mut() = InViewTracker::new(InViewConfig {
amount: 0.45,
once: false,
});
}
let probe = {
let visible = state.read(cx).visible.clone();
let revealed_at = state.read(cx).revealed_at.clone();
let tracker = state.read(cx).tracker.clone();
gpui_kit::canvas(
move |rect: Bounds<Pixels>, window: &mut Window, _| {
#[cfg(test)]
PROBE_RUNS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let viewport = Bounds::new(point(px(0.0), px(0.0)), window.viewport_size());
let evaluated = tracker.borrow_mut().evaluate(rect, viewport);
let passed = f32::from(rect.origin.y) < f32::from(viewport.origin.y);
let next = evaluated.in_view || passed;
if visible.get() != next {
#[cfg(test)]
FLIPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
visible.set(next);
if next {
revealed_at.set(now);
}
window.request_animation_frame();
}
},
|_, _, _, _| {},
)
.absolute()
.inset_0()
};
let visible = state.read(cx).visible.get();
let revealed_at = state.read(cx).revealed_at.get();
let elapsed = (now - revealed_at).max(0.0);
let settle = self.variant.settle();
let words: Vec<String> = self
.text
.split_whitespace()
.map(ToString::to_string)
.collect();
let step = word_step(words.len());
let mut animating = false;
let part = |elapsed: f64, delay: f64, settle: f64, animating: &mut bool| -> TitleTracks {
if reduced || !visible {
return if visible {
TitleTracks {
opacity: 1.0,
filter: 1.0,
transform: 1.0,
}
} else {
TitleTracks {
opacity: 0.0,
filter: 0.0,
transform: 0.0,
}
};
}
let tracks = TitleTracks::at(elapsed, delay, settle);
if !tracks.settled() {
*animating = true;
}
tracks
};
let mut wrapper = div()
.flex()
.flex_col()
.items_start()
.text_size(size)
.line_height(size * 1.15)
.text_color(colors.foreground);
match self.variant {
InViewTitleVariant::Word => {
let mut row = div()
.flex()
.flex_row()
.flex_wrap()
.items_start()
.gap(px(0.26 * em));
for (index, word) in words.iter().enumerate() {
let tracks = part(elapsed, index as f64 * step, settle, &mut animating);
row = row.child(
div().overflow_hidden().child(
div()
.whitespace_nowrap()
.opacity(tracks.opacity)
.mt(px((1.0 - tracks.transform) * 0.9 * em))
.child(word.clone()),
),
);
}
wrapper = wrapper.child(row);
}
InViewTitleVariant::Line => {
let lines: Vec<SharedString> = if self.lines.is_empty() {
vec![self.text.clone()]
} else {
self.lines.clone()
};
for (index, line) in lines.iter().enumerate() {
let tracks = part(
elapsed,
index as f64 * motion.stagger.line.as_secs_f64(),
settle,
&mut animating,
);
wrapper = wrapper.child(
div().w_full().overflow_hidden().child(
div()
.whitespace_nowrap()
.opacity(tracks.opacity)
.mt(px((1.0 - tracks.transform) * 1.12 * em))
.child(line.clone()),
),
);
}
}
InViewTitleVariant::Blur => {
let mut row = div()
.flex()
.flex_row()
.flex_wrap()
.items_start()
.gap(px(0.26 * em));
for (index, word) in words.iter().enumerate() {
let tracks = part(elapsed, index as f64 * step, settle, &mut animating);
#[cfg(test)]
if index == 0 {
LAST_TRANSFORM.store(
tracks.transform.to_bits(),
std::sync::atomic::Ordering::Relaxed,
);
}
let blur = BlurFallback::evaluate(
px(f32::from(motion.blur.text) * (1.0 - tracks.filter)),
reduced,
);
row = row.child(
div()
.flex_none()
.opacity((tracks.opacity * blur.opacity_multiplier).clamp(0.0, 1.0))
.mt(px((1.0 - tracks.transform) * 0.2 * em))
.child(word.clone()),
);
}
wrapper = wrapper.child(row);
}
InViewTitleVariant::Tracking => {
let mut row = div()
.flex()
.flex_row()
.flex_wrap()
.items_start()
.gap(px(0.26 * em));
for (index, word) in words.iter().enumerate() {
let letters: Vec<char> = word.chars().collect();
let center = (letters.len().saturating_sub(1)) as f32 / 2.0;
let delay = index as f64 * motion.stagger.char.as_secs_f64() * 2.0;
let tracks = part(elapsed, delay, settle, &mut animating);
let blur = BlurFallback::evaluate(
px(f32::from(motion.blur.soft) * (1.0 - tracks.filter)),
reduced,
);
let mut word_row = div()
.flex()
.flex_row()
.whitespace_nowrap()
.opacity((tracks.opacity * blur.opacity_multiplier).clamp(0.0, 1.0));
for (letter_index, letter) in letters.iter().enumerate() {
let offset = (center - letter_index as f32)
* TRACK_EM
* em
* (1.0 - tracks.transform);
word_row = word_row.child(
div()
.flex_none()
.ml(px(offset))
.child(SharedString::from(letter.to_string())),
);
}
row = row.child(word_row);
}
wrapper = wrapper.child(row);
}
InViewTitleVariant::Wipe => {
let chars: Vec<char> = self.text.chars().collect();
let total = chars.len().max(1) as f32;
let tracks = part(elapsed, 0.0, settle, &mut animating);
let mut row = div()
.flex()
.flex_row()
.whitespace_nowrap()
.ml(px(-0.12 * em * (1.0 - tracks.transform)));
for (index, ch) in chars.iter().enumerate() {
let unit = (index as f32 + 0.5) / total;
let swept = tracks.transform * (1.0 + WIPE_EDGE);
let edge = ((swept - unit) / WIPE_EDGE).clamp(0.0, 1.0);
row = row.child(
div()
.flex_none()
.opacity((tracks.opacity * edge).clamp(0.0, 1.0))
.child(if *ch == ' ' {
SharedString::from("\u{00a0}")
} else {
SharedString::from(ch.to_string())
}),
);
}
wrapper = wrapper.child(row);
}
}
if animating {
window.request_animation_frame();
}
div()
.id(self.id)
.test_support()
.role(gpui_kit::Role::Heading)
.aria_label(self.text.clone())
.self_start()
.w_full()
.relative()
.child(probe)
.child(wrapper)
}
}
#[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::*;
static COUNTER_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
#[test]
fn word_stagger_is_capped_for_long_titles() {
assert!((word_step(2) - 0.06).abs() < 1e-9);
assert!((word_step(10) - 0.04).abs() < 1e-9);
assert!((word_step(20) - 0.02).abs() < 1e-9);
assert!(word_step(20) * 20.0 <= 0.40 + 1e-9);
assert!(word_step(0) > 0.0);
}
#[test]
fn tracks_lead_with_opacity_and_settle_with_transform() {
let settle = InViewTitleVariant::Blur.settle();
let early = TitleTracks::at(0.15, 0.0, settle);
assert!(early.opacity > early.transform, "opacity leads");
assert!(
early.filter > early.transform,
"filter clears before the transform settles"
);
let done = TitleTracks::at(settle + 0.05, 0.0, settle);
assert!(done.settled());
let delayed = TitleTracks::at(0.10, 0.20, settle);
assert_eq!(delayed.opacity, 0.0);
assert_eq!(track_progress(1.0, 0.0, 0.5, true), 1.0);
}
#[test]
fn variants_ship_arc_settle_durations() {
assert_eq!(InViewTitleVariant::Blur.settle(), 0.80);
assert_eq!(InViewTitleVariant::Line.settle(), 0.86);
assert_eq!(InViewTitleVariant::Tracking.settle(), 1.00);
assert_eq!(InViewTitleVariant::Wipe.settle(), 0.90);
}
struct TitleHost {
variant: InViewTitleVariant,
}
impl Render for TitleHost {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div().p(px(24.0)).w_full().child(
InViewTitle::new("title", "更快地构建桌面界面")
.variant(self.variant)
.level(InViewTitleLevel::H2),
)
}
}
#[gpui_kit::test]
fn probe_runs_and_flips_visible(cx: &mut TestAppContext) {
let _guard = COUNTER_LOCK.lock().unwrap_or_else(|e| e.into_inner());
PROBE_RUNS.store(0, std::sync::atomic::Ordering::Relaxed);
FLIPS.store(0, std::sync::atomic::Ordering::Relaxed);
STATE_CREATIONS.store(0, std::sync::atomic::Ordering::Relaxed);
LAST_TRANSFORM.store(0, std::sync::atomic::Ordering::Relaxed);
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
});
let (_view, cx) = cx.add_window_view(|_, _| TitleHost {
variant: InViewTitleVariant::Blur,
});
cx.update(|window, cx| {
for _ in 0..6 {
window.render_frame(cx);
}
});
let flips = FLIPS.load(std::sync::atomic::Ordering::Relaxed);
let probes = PROBE_RUNS.load(std::sync::atomic::Ordering::Relaxed);
assert!(probes > 1, "probe must run every frame, ran {probes}");
assert_eq!(
flips, 1,
"the reveal must latch once (probes={probes}); more flips means the visibility state is not shared with the paint closure"
);
assert_eq!(
STATE_CREATIONS.load(std::sync::atomic::Ordering::Relaxed),
1
);
}
#[gpui_kit::test]
fn in_view_title_reveals_and_can_replay(cx: &mut TestAppContext) {
let _guard = COUNTER_LOCK.lock().unwrap_or_else(|e| e.into_inner());
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
});
let (view, cx) = cx.add_window_view(|_, _| TitleHost {
variant: InViewTitleVariant::Blur,
});
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.variant = InViewTitleVariant::Wipe;
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
);
});
}
}