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,
};
pub const BAND_EM: f32 = 2.2;
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),
];
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
}
pub fn shimmer_base(colors: ArcColors) -> Hsla {
oklab_mix(colors.text_muted, colors.foreground, 0.88)
}
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))
}
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
}
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>>,
}
#[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,
}
}
pub fn active(mut self, active: bool) -> Self {
self.active = active;
self
}
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())
}),
);
}
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);
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);
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);
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);
});
}
}