1use std::cell::{Cell, RefCell};
18
19use arc_motion::{BlurFallback, CubicBezier, arc_spring, is_reduced_motion, motion_now};
20use arc_tokens::{ActiveArcTheme as _, Typography};
21use gpui_kit::{
22 App, ElementId, IntoElement, ParentElement, Pixels, RenderOnce, Role, SharedString, Styled,
23 TestSupportExt as _, Window, div, prelude::*, px,
24};
25
26const HANDOFF: f64 = 0.05;
28const ENTER_SECS: f64 = 0.28;
30const EXIT_SECS: f64 = 0.18;
31
32pub fn glyph_keys(text: &str) -> Vec<(char, String)> {
34 let mut seen: std::collections::HashMap<char, usize> = std::collections::HashMap::new();
35 text.chars()
36 .map(|ch| {
37 let count = *seen.get(&ch).unwrap_or(&0);
38 seen.insert(ch, count + 1);
39 (ch, format!("{ch}-{count}"))
40 })
41 .collect()
42}
43
44pub fn entry_delay(order: usize, stagger_secs: f64) -> f64 {
46 HANDOFF + order.min(8) as f64 * stagger_secs * 2.0
47}
48
49pub fn glyph_positions(text: &str, em: f32) -> Vec<(String, char, f32, f32)> {
51 let mut cursor = 0.0;
52 glyph_keys(text)
53 .into_iter()
54 .map(|(ch, key)| {
55 let advance = crate::text::text_shimmer::glyph_advance(ch) * em;
56 let entry = (key, ch, cursor, advance);
57 cursor += advance;
58 entry
59 })
60 .collect()
61}
62
63pub fn estimated_width(text: &str, em: f32) -> f32 {
65 text.chars()
66 .map(|ch| crate::text::text_shimmer::glyph_advance(ch) * em)
67 .sum::<f32>()
68 .max(1.0)
69}
70
71struct MorphState {
72 text: String,
73 prev_text: String,
74 exiting: RefCell<Vec<(String, char, f32)>>,
75 changed_at: Cell<f64>,
76}
77
78#[derive(IntoElement)]
80pub struct TextMorph {
81 id: ElementId,
82 text: SharedString,
83 text_size: Pixels,
84 role: Role,
85}
86
87impl TextMorph {
88 pub fn new(id: impl Into<ElementId>, text: impl Into<SharedString>) -> Self {
89 Self {
90 id: id.into(),
91 text: text.into(),
92 text_size: Typography::TEXT_BASE,
93 role: Role::Label,
94 }
95 }
96
97 pub fn text_size(mut self, size: Pixels) -> Self {
98 self.text_size = size;
99 self
100 }
101
102 pub fn role(mut self, role: Role) -> Self {
103 self.role = role;
104 self
105 }
106}
107
108impl RenderOnce for TextMorph {
109 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
110 let theme = cx.arc_theme().clone();
111 let colors = theme.colors;
112 let motion = theme.motion;
113 let reduced = is_reduced_motion(cx);
114 let now = motion_now(cx);
115 let em = f32::from(self.text_size);
116
117 let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-text-morph".into());
118 let state = window.use_keyed_state(state_id, cx, |_, _| MorphState {
119 text: String::new(),
120 prev_text: String::new(),
121 exiting: RefCell::new(Vec::new()),
122 changed_at: Cell::new(now),
123 });
124
125 let current = state.read(cx).text.clone();
126 if current != self.text.as_ref() {
127 let prev = current.clone();
128 let previous_layout = glyph_positions(&prev, em)
129 .into_iter()
130 .map(|(key, ch, x, _)| (key, ch, x))
131 .collect::<Vec<_>>();
132 state.update(cx, |s, _| {
133 s.text = self.text.to_string();
134 s.prev_text = prev;
135 s.exiting = RefCell::new(previous_layout);
136 s.changed_at = Cell::new(now);
137 });
138 }
139
140 let (changed_at, exiting) = {
141 let read = state.read(cx);
142 (read.changed_at.get(), read.exiting.borrow().clone())
143 };
144 let prev_keys: std::collections::HashSet<String> = glyph_keys(&state.read(cx).prev_text)
145 .into_iter()
146 .map(|(_, key)| key)
147 .collect();
148
149 let glyphs = glyph_positions(&self.text, em);
150 let width_target = estimated_width(&self.text, em);
151 let width = if reduced {
152 width_target
153 } else {
154 arc_spring(
155 (self.id.clone(), "width"),
156 width_target,
157 motion.spring.morph,
158 window,
159 cx,
160 )
161 };
162
163 let mut entering_order = 0usize;
164 let mut layers = div().absolute().inset_0();
165 let mut animating = false;
166
167 for (key, ch, x, advance) in &glyphs {
168 let kept = prev_keys.contains(key);
169 let order = if kept {
170 0
171 } else {
172 entering_order += 1;
173 entering_order - 1
174 };
175 let delay = entry_delay(order, motion.stagger.char.as_secs_f64());
176 let elapsed = (now - changed_at - delay).max(0.0);
177 let progress = if reduced || kept {
178 1.0
179 } else {
180 CubicBezier::new(0.16, 1.0, 0.3, 1.0)
181 .sample((elapsed / ENTER_SECS).clamp(0.0, 1.0) as f32)
182 };
183 if progress < 0.999 {
184 animating = true;
185 }
186 let blur =
187 BlurFallback::evaluate(px(f32::from(motion.blur.soft) * (1.0 - progress)), reduced);
188 layers = layers.child(
189 div()
190 .absolute()
191 .left(px(*x))
192 .top(px((1.0 - progress) * 0.14 * em))
193 .w(px(*advance))
194 .opacity((progress * blur.opacity_multiplier).clamp(0.0, 1.0))
195 .child(if *ch == ' ' {
196 SharedString::from("\u{00a0}")
197 } else {
198 SharedString::from(ch.to_string())
199 }),
200 );
201 }
202
203 if !exiting.is_empty() {
204 let elapsed = now - changed_at;
205 let progress = if reduced {
206 1.0
207 } else {
208 CubicBezier::new(0.22, 1.0, 0.36, 1.0)
209 .sample((elapsed / EXIT_SECS).clamp(0.0, 1.0) as f32)
210 };
211 if progress < 0.999 {
212 animating = true;
213 }
214 if progress >= 0.999 {
215 state.update(cx, |s, _| s.exiting.borrow_mut().clear());
216 }
217 for (_key, ch, x) in &exiting {
218 let alpha = (1.0 - progress).clamp(0.0, 1.0);
219 layers = layers.child(
220 div()
221 .absolute()
222 .left(px(*x))
223 .top(px(-progress * 0.1 * em))
224 .w(px(crate::text::text_shimmer::glyph_advance(*ch) * em))
225 .opacity(alpha)
226 .child(if *ch == ' ' {
227 SharedString::from("\u{00a0}")
228 } else {
229 SharedString::from(ch.to_string())
230 }),
231 );
232 }
233 }
234
235 if animating {
236 window.request_animation_frame();
237 }
238
239 div()
240 .id(self.id)
241 .test_support()
242 .role(self.role)
243 .aria_label(self.text.clone())
244 .self_start()
245 .relative()
246 .h(self.text_size * 1.4)
247 .w(px(width.max(1.0)))
248 .overflow_hidden()
249 .text_size(self.text_size)
250 .line_height(self.text_size * 1.4)
251 .text_color(colors.foreground)
252 .child(layers)
253 }
254}
255
256#[cfg(test)]
257mod tests {
258 use arc_tokens::{Accent, ArcMotionTokens, ThemeMode, install_arc_theme};
259 use gpui_kit::{
260 Context, Render, TestAppContext, div,
261 test::{TestQueryExt as _, TestWindowExt as _},
262 };
263
264 use super::*;
265
266 #[test]
267 fn glyphs_pair_by_character_and_occurrence() {
268 let publish = glyph_keys("Publish");
269 let publishing = glyph_keys("Publishing");
270 let keys: Vec<&str> = publish.iter().map(|(_, key)| key.as_str()).collect();
271 assert_eq!(keys, vec!["P-0", "u-0", "b-0", "l-0", "i-0", "s-0", "h-0"]);
272 let next: Vec<&str> = publishing.iter().map(|(_, key)| key.as_str()).collect();
273 assert!(next.starts_with(&keys));
274 assert_eq!(&next[7..], ["i-1", "n-0", "g-0"]);
275 let second = glyph_keys("bubbles");
277 assert_eq!(second[2].1, "b-1");
278 }
279
280 #[test]
281 fn width_estimate_grows_with_new_letters() {
282 let small = estimated_width("Publish", 16.0);
283 let big = estimated_width("Publishing", 16.0);
284 assert!(big > small);
285 assert!(estimated_width("", 16.0) >= 1.0);
286 let positions = glyph_positions("abc", 16.0);
287 assert_eq!(positions.len(), 3);
288 assert_eq!(positions[0].2, 0.0);
289 assert!(positions[1].2 > 0.0);
290 }
291
292 #[test]
293 fn entry_stagger_is_capped_after_eight_letters() {
294 let stagger = ArcMotionTokens::DEFAULT.stagger.char.as_secs_f64();
295 assert!((entry_delay(0, stagger) - 0.05).abs() < 1e-9);
296 assert!((entry_delay(3, stagger) - 0.05 - 0.096).abs() < 1e-9);
297 assert!((entry_delay(12, stagger) - 0.05 - 0.256).abs() < 1e-9);
299 }
300
301 struct MorphHost {
302 label: &'static str,
303 }
304
305 impl Render for MorphHost {
306 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
307 div().p(px(24.0)).child(TextMorph::new("morph", self.label))
308 }
309 }
310
311 #[gpui_kit::test]
312 fn text_morph_swaps_labels_and_reads_the_plain_text(cx: &mut TestAppContext) {
313 cx.update(|cx| {
314 gpui_kit::init(cx);
315 install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
316 });
317 let (view, cx) = cx.add_window_view(|_, _| MorphHost { label: "Publish" });
318 cx.update(|window, cx| {
319 for _ in 0..4 {
320 window.render_frame(cx);
321 }
322 assert!(f32::from(window.find_by_label("Publish").bounds().size.width) > 0.0);
323 });
324 view.update(cx, |host, cx| {
325 host.label = "Publishing";
326 cx.notify();
327 });
328 cx.update(|window, cx| {
329 for _ in 0..12 {
330 window.render_frame(cx);
331 }
332 assert!(f32::from(window.find_by_label("Publishing").bounds().size.width) > 0.0);
333 });
334 }
335}