use std::cell::{Cell, RefCell};
use arc_motion::{BlurFallback, CubicBezier, arc_spring, is_reduced_motion, motion_now};
use arc_tokens::{ActiveArcTheme as _, Typography};
use gpui_kit::{
App, ElementId, IntoElement, ParentElement, Pixels, RenderOnce, Role, SharedString, Styled,
TestSupportExt as _, Window, div, prelude::*, px,
};
const HANDOFF: f64 = 0.05;
const ENTER_SECS: f64 = 0.28;
const EXIT_SECS: f64 = 0.18;
pub fn glyph_keys(text: &str) -> Vec<(char, String)> {
let mut seen: std::collections::HashMap<char, usize> = std::collections::HashMap::new();
text.chars()
.map(|ch| {
let count = *seen.get(&ch).unwrap_or(&0);
seen.insert(ch, count + 1);
(ch, format!("{ch}-{count}"))
})
.collect()
}
pub fn entry_delay(order: usize, stagger_secs: f64) -> f64 {
HANDOFF + order.min(8) as f64 * stagger_secs * 2.0
}
pub fn glyph_positions(text: &str, em: f32) -> Vec<(String, char, f32, f32)> {
let mut cursor = 0.0;
glyph_keys(text)
.into_iter()
.map(|(ch, key)| {
let advance = crate::text::text_shimmer::glyph_advance(ch) * em;
let entry = (key, ch, cursor, advance);
cursor += advance;
entry
})
.collect()
}
pub fn estimated_width(text: &str, em: f32) -> f32 {
text.chars()
.map(|ch| crate::text::text_shimmer::glyph_advance(ch) * em)
.sum::<f32>()
.max(1.0)
}
struct MorphState {
text: String,
prev_text: String,
exiting: RefCell<Vec<(String, char, f32)>>,
changed_at: Cell<f64>,
}
#[derive(IntoElement)]
pub struct TextMorph {
id: ElementId,
text: SharedString,
text_size: Pixels,
role: Role,
}
impl TextMorph {
pub fn new(id: impl Into<ElementId>, text: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
text: text.into(),
text_size: Typography::TEXT_BASE,
role: Role::Label,
}
}
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 TextMorph {
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-text-morph".into());
let state = window.use_keyed_state(state_id, cx, |_, _| MorphState {
text: String::new(),
prev_text: String::new(),
exiting: RefCell::new(Vec::new()),
changed_at: Cell::new(now),
});
let current = state.read(cx).text.clone();
if current != self.text.as_ref() {
let prev = current.clone();
let previous_layout = glyph_positions(&prev, em)
.into_iter()
.map(|(key, ch, x, _)| (key, ch, x))
.collect::<Vec<_>>();
state.update(cx, |s, _| {
s.text = self.text.to_string();
s.prev_text = prev;
s.exiting = RefCell::new(previous_layout);
s.changed_at = Cell::new(now);
});
}
let (changed_at, exiting) = {
let read = state.read(cx);
(read.changed_at.get(), read.exiting.borrow().clone())
};
let prev_keys: std::collections::HashSet<String> = glyph_keys(&state.read(cx).prev_text)
.into_iter()
.map(|(_, key)| key)
.collect();
let glyphs = glyph_positions(&self.text, em);
let width_target = estimated_width(&self.text, em);
let width = if reduced {
width_target
} else {
arc_spring(
(self.id.clone(), "width"),
width_target,
motion.spring.morph,
window,
cx,
)
};
let mut entering_order = 0usize;
let mut layers = div().absolute().inset_0();
let mut animating = false;
for (key, ch, x, advance) in &glyphs {
let kept = prev_keys.contains(key);
let order = if kept {
0
} else {
entering_order += 1;
entering_order - 1
};
let delay = entry_delay(order, motion.stagger.char.as_secs_f64());
let elapsed = (now - changed_at - delay).max(0.0);
let progress = if reduced || kept {
1.0
} else {
CubicBezier::new(0.16, 1.0, 0.3, 1.0)
.sample((elapsed / ENTER_SECS).clamp(0.0, 1.0) as f32)
};
if progress < 0.999 {
animating = true;
}
let blur =
BlurFallback::evaluate(px(f32::from(motion.blur.soft) * (1.0 - progress)), reduced);
layers = layers.child(
div()
.absolute()
.left(px(*x))
.top(px((1.0 - progress) * 0.14 * em))
.w(px(*advance))
.opacity((progress * blur.opacity_multiplier).clamp(0.0, 1.0))
.child(if *ch == ' ' {
SharedString::from("\u{00a0}")
} else {
SharedString::from(ch.to_string())
}),
);
}
if !exiting.is_empty() {
let elapsed = now - changed_at;
let progress = if reduced {
1.0
} else {
CubicBezier::new(0.22, 1.0, 0.36, 1.0)
.sample((elapsed / EXIT_SECS).clamp(0.0, 1.0) as f32)
};
if progress < 0.999 {
animating = true;
}
if progress >= 0.999 {
state.update(cx, |s, _| s.exiting.borrow_mut().clear());
}
for (_key, ch, x) in &exiting {
let alpha = (1.0 - progress).clamp(0.0, 1.0);
layers = layers.child(
div()
.absolute()
.left(px(*x))
.top(px(-progress * 0.1 * em))
.w(px(crate::text::text_shimmer::glyph_advance(*ch) * em))
.opacity(alpha)
.child(if *ch == ' ' {
SharedString::from("\u{00a0}")
} else {
SharedString::from(ch.to_string())
}),
);
}
}
if animating {
window.request_animation_frame();
}
div()
.id(self.id)
.test_support()
.role(self.role)
.aria_label(self.text.clone())
.self_start()
.relative()
.h(self.text_size * 1.4)
.w(px(width.max(1.0)))
.overflow_hidden()
.text_size(self.text_size)
.line_height(self.text_size * 1.4)
.text_color(colors.foreground)
.child(layers)
}
}
#[cfg(test)]
mod tests {
use arc_tokens::{Accent, ArcMotionTokens, ThemeMode, install_arc_theme};
use gpui_kit::{
Context, Render, TestAppContext, div,
test::{TestQueryExt as _, TestWindowExt as _},
};
use super::*;
#[test]
fn glyphs_pair_by_character_and_occurrence() {
let publish = glyph_keys("Publish");
let publishing = glyph_keys("Publishing");
let keys: Vec<&str> = publish.iter().map(|(_, key)| key.as_str()).collect();
assert_eq!(keys, vec!["P-0", "u-0", "b-0", "l-0", "i-0", "s-0", "h-0"]);
let next: Vec<&str> = publishing.iter().map(|(_, key)| key.as_str()).collect();
assert!(next.starts_with(&keys));
assert_eq!(&next[7..], ["i-1", "n-0", "g-0"]);
let second = glyph_keys("bubbles");
assert_eq!(second[2].1, "b-1");
}
#[test]
fn width_estimate_grows_with_new_letters() {
let small = estimated_width("Publish", 16.0);
let big = estimated_width("Publishing", 16.0);
assert!(big > small);
assert!(estimated_width("", 16.0) >= 1.0);
let positions = glyph_positions("abc", 16.0);
assert_eq!(positions.len(), 3);
assert_eq!(positions[0].2, 0.0);
assert!(positions[1].2 > 0.0);
}
#[test]
fn entry_stagger_is_capped_after_eight_letters() {
let stagger = ArcMotionTokens::DEFAULT.stagger.char.as_secs_f64();
assert!((entry_delay(0, stagger) - 0.05).abs() < 1e-9);
assert!((entry_delay(3, stagger) - 0.05 - 0.096).abs() < 1e-9);
assert!((entry_delay(12, stagger) - 0.05 - 0.256).abs() < 1e-9);
}
struct MorphHost {
label: &'static str,
}
impl Render for MorphHost {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div().p(px(24.0)).child(TextMorph::new("morph", self.label))
}
}
#[gpui_kit::test]
fn text_morph_swaps_labels_and_reads_the_plain_text(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(|_, _| MorphHost { label: "Publish" });
cx.update(|window, cx| {
for _ in 0..4 {
window.render_frame(cx);
}
assert!(f32::from(window.find_by_label("Publish").bounds().size.width) > 0.0);
});
view.update(cx, |host, cx| {
host.label = "Publishing";
cx.notify();
});
cx.update(|window, cx| {
for _ in 0..12 {
window.render_frame(cx);
}
assert!(f32::from(window.find_by_label("Publishing").bounds().size.width) > 0.0);
});
}
}