1use std::{cell::RefCell, rc::Rc};
19
20use arc_motion::{BlurFallback, CubicBezier, is_reduced_motion, motion_now};
21use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, Typography};
22use gpui_kit::{
23 AnyElement, App, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
24 ParentElement, PathBuilder, RenderOnce, Role, SharedString, Styled, TestSupportExt as _,
25 Window, base::StyledExt as _, canvas, div, linear_color_stop, linear_gradient, point,
26 prelude::*, px,
27};
28
29pub const EXPANDABLE_TEXT_LINE_HEIGHT: f32 = 21.0;
31
32pub fn expandable_text_open_duration(distance_px: f32) -> f64 {
34 0.50 + (f64::from(distance_px.max(0.0)) / 1600.0).min(0.10)
35}
36
37pub fn expandable_text_close_duration(distance_px: f32) -> f64 {
39 0.40 + (f64::from(distance_px.max(0.0)) / 2000.0).min(0.05)
40}
41
42pub fn expandable_text_ease(t: f32) -> f32 {
44 CubicBezier::new(0.32, 0.5, 0.2, 1.0).sample(t.clamp(0.0, 1.0))
45}
46
47pub fn expandable_text_fade_strength(progress: f32) -> f32 {
50 let p = progress.clamp(0.0, 1.0);
51 let fade = (1.0 - p).powf(1.35);
52 if fade <= 0.002 {
53 0.0
54 } else {
55 (fade * 0.96).clamp(0.0, 0.96)
56 }
57}
58
59pub fn expandable_text_label_sample(progress: f32, reduced: bool) -> (f32, f32, f32, f32) {
65 let p = progress.clamp(0.0, 1.0);
66 if reduced {
67 return if p >= 0.5 {
68 (0.0, -4.0, 1.0, 0.0)
69 } else {
70 (1.0, 0.0, 0.0, 4.0)
71 };
72 }
73 let more_blur = BlurFallback::evaluate(px(p * 2.0), false);
74 let less_blur = BlurFallback::evaluate(px((1.0 - p) * 2.0), false);
75 let more_alpha = ((1.0 - p) * more_blur.opacity_multiplier).clamp(0.0, 1.0);
76 let more_y = -4.0 * p;
77 let less_alpha = (p * less_blur.opacity_multiplier).clamp(0.0, 1.0);
78 let less_y = 4.0 * (1.0 - p);
79 (more_alpha, more_y, less_alpha, less_y)
80}
81
82fn paint_rotated_chevron_16(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
83 let rad = angle_deg.to_radians();
84 let cos = rad.cos();
85 let sin = rad.sin();
86 let rot =
87 |dx: f32, dy: f32| -> (f32, f32) { (cx + dx * cos - dy * sin, cy + dx * sin + dy * cos) };
88 let (x1, y1) = rot(-4.0, -1.6);
89 let (xm, ym) = rot(0.0, 2.4);
90 let (x2, y2) = rot(4.0, -1.6);
91
92 let mut b = PathBuilder::stroke(px(1.75));
93 b.move_to(point(px(x1), px(y1)));
94 b.line_to(point(px(xm), px(ym)));
95 b.line_to(point(px(x2), px(y2)));
96 if let Ok(path) = b.build() {
97 window.paint_path(path, color);
98 }
99}
100
101type ExpandChangeCallback = Rc<dyn Fn(&bool, &mut Window, &mut App)>;
102
103#[derive(Clone)]
104struct ExpandableTextInternal {
105 expanded: bool,
106 from_progress: f32,
107 target_progress: f32,
108 anim_started_at: f64,
109 anim_duration: f64,
110 hovered: bool,
111 full_height: Rc<RefCell<f32>>,
112 focus_handle: FocusHandle,
113}
114
115impl ExpandableTextInternal {
116 fn new(default_expanded: bool, now: f64, focus_handle: FocusHandle) -> Self {
117 let p = if default_expanded { 1.0 } else { 0.0 };
118 Self {
119 expanded: default_expanded,
120 from_progress: p,
121 target_progress: p,
122 anim_started_at: now - 10.0,
123 anim_duration: 0.5,
124 hovered: false,
125 full_height: Rc::new(RefCell::new(168.0)),
126 focus_handle,
127 }
128 }
129
130 fn current_progress(&self, now: f64, reduced: bool) -> (f32, bool) {
131 if reduced || self.anim_duration <= 0.0001 {
132 return (self.target_progress, false);
133 }
134 let elapsed = (now - self.anim_started_at).max(0.0);
135 if elapsed >= self.anim_duration {
136 (self.target_progress, false)
137 } else {
138 let t = (elapsed / self.anim_duration).clamp(0.0, 1.0) as f32;
139 let eased = expandable_text_ease(t);
140 let p = self.from_progress + (self.target_progress - self.from_progress) * eased;
141 (p.clamp(0.0, 1.0), true)
142 }
143 }
144}
145
146#[derive(IntoElement)]
149pub struct ExpandableText {
150 id: ElementId,
151 lines: usize,
152 default_expanded: bool,
153 expanded: Option<bool>,
154 on_expanded_change: Option<ExpandChangeCallback>,
155 more_label: SharedString,
156 less_label: SharedString,
157 fade_bg: Option<Hsla>,
158 body: Option<AnyElement>,
159}
160
161impl ExpandableText {
162 pub fn new(id: impl Into<ElementId>, content: impl IntoElement) -> Self {
163 Self {
164 id: id.into(),
165 lines: 3,
166 default_expanded: false,
167 expanded: None,
168 on_expanded_change: None,
169 more_label: "Read more".into(),
170 less_label: "Show less".into(),
171 fade_bg: None,
172 body: Some(content.into_any_element()),
173 }
174 }
175
176 pub fn lines(mut self, lines: usize) -> Self {
178 self.lines = lines.max(1);
179 self
180 }
181
182 pub fn default_expanded(mut self, default_expanded: bool) -> Self {
183 self.default_expanded = default_expanded;
184 self
185 }
186
187 pub fn expanded(mut self, expanded: bool) -> Self {
188 self.expanded = Some(expanded);
189 self
190 }
191
192 pub fn on_expanded_change(
193 mut self,
194 handler: impl Fn(&bool, &mut Window, &mut App) + 'static,
195 ) -> Self {
196 self.on_expanded_change = Some(Rc::new(handler));
197 self
198 }
199
200 pub fn more_label(mut self, label: impl Into<SharedString>) -> Self {
201 self.more_label = label.into();
202 self
203 }
204
205 pub fn less_label(mut self, label: impl Into<SharedString>) -> Self {
206 self.less_label = label.into();
207 self
208 }
209
210 pub fn surface_color(mut self, color: Hsla) -> Self {
212 self.fade_bg = Some(color);
213 self
214 }
215}
216
217impl RenderOnce for ExpandableText {
218 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
219 let theme = cx.arc_theme().clone();
220 let colors = theme.colors;
221 let reduced = is_reduced_motion(cx);
222 let now = motion_now(cx);
223
224 let state_id =
225 ElementId::NamedChild(self.id.clone().into(), "__arc-expandable-text-state".into());
226 let internal = window.use_keyed_state(state_id, cx, |_, cx| {
227 ExpandableTextInternal::new(self.default_expanded, now, cx.focus_handle())
228 });
229
230 let clamp_h = (self.lines as f32) * EXPANDABLE_TEXT_LINE_HEIGHT;
231
232 if let Some(controlled) = self.expanded {
233 let cur_open = internal.read(cx).expanded;
234 if cur_open != controlled {
235 internal.update(cx, |s, _| {
236 let (live_p, _) = s.current_progress(now, reduced);
237 let full = (*s.full_height.borrow()).max(clamp_h);
238 let span = (full - clamp_h).max(1.0);
239 let target = if controlled { 1.0 } else { 0.0 };
240 let dist = (target - live_p).abs() * span;
241 s.expanded = controlled;
242 s.from_progress = live_p;
243 s.target_progress = target;
244 s.anim_started_at = now;
245 s.anim_duration = if controlled {
246 expandable_text_open_duration(dist)
247 } else {
248 expandable_text_close_duration(dist)
249 };
250 });
251 }
252 }
253
254 let snap = internal.read(cx).clone();
255 let is_expanded = self.expanded.unwrap_or(snap.expanded);
256 let (progress, animating) = snap.current_progress(now, reduced);
257 if animating && !reduced {
258 window.request_animation_frame();
259 }
260
261 let full_h = (*snap.full_height.borrow()).max(clamp_h);
262 let overflowing = full_h > clamp_h + 1.0;
263 let visible_h = if !overflowing {
264 full_h
265 } else {
266 clamp_h + (full_h - clamp_h) * progress
267 };
268
269 let fade_alpha = if overflowing {
270 expandable_text_fade_strength(progress)
271 } else {
272 0.0
273 };
274 let chevron_deg = progress * 180.0;
275 let (more_a, more_y, less_a, less_y) = expandable_text_label_sample(progress, reduced);
276
277 let full_h_ref = snap.full_height.clone();
278 let measure_probe = canvas(
279 move |rect, _, _| {
280 let h = f32::from(rect.size.height);
281 if h > 8.0 {
282 *full_h_ref.borrow_mut() = h;
283 }
284 },
285 |_, _, _, _| {},
286 )
287 .absolute()
288 .inset_0();
289
290 let mut inner = div()
291 .relative()
292 .w_full()
293 .text_size(Typography::TEXT_SM)
294 .text_color(colors.text_secondary)
295 .child(measure_probe);
296 if let Some(body) = self.body {
297 inner = inner.child(body);
298 }
299
300 let fade_color = self.fade_bg.unwrap_or(colors.surface);
301 let fade_h = (EXPANDABLE_TEXT_LINE_HEIGHT * 1.6).min(visible_h);
302
303 let mut content_clip = div()
304 .id(ElementId::NamedChild(
305 self.id.clone().into(),
306 "content".into(),
307 ))
308 .test_support()
309 .relative()
310 .w_full()
311 .h(px(visible_h))
312 .overflow_hidden()
313 .child(inner);
314
315 if fade_alpha > 0.002 {
316 content_clip = content_clip.child(
317 div()
318 .absolute()
319 .left_0()
320 .right_0()
321 .bottom_0()
322 .h(px(fade_h))
323 .bg(linear_gradient(
324 180.0,
325 linear_color_stop(fade_color.opacity(0.0), 0.0),
326 linear_color_stop(fade_color.opacity(fade_alpha), 1.0),
327 )),
328 );
329 }
330
331 let max_chars = self
333 .more_label
334 .chars()
335 .count()
336 .max(self.less_label.chars().count())
337 .max(4);
338 let slot_w = (max_chars as f32 * 7.6).max(56.0);
339
340 let int_hover = internal.clone();
341 let int_click = internal.clone();
342 let on_change_click = self.on_expanded_change.clone();
343 let focus_click = snap.focus_handle.clone();
344 let int_key = internal.clone();
345 let on_change_key = self.on_expanded_change.clone();
346
347 let label_color = if snap.hovered {
348 colors.text_secondary
349 } else {
350 colors.foreground
351 };
352 let icon_color = colors.text_muted;
353
354 let mut root = div()
355 .id(self.id.clone())
356 .test_support()
357 .track_focus(&snap.focus_handle)
358 .w_full()
359 .flex()
360 .flex_col()
361 .items_start()
362 .gap(Spacing::S2)
363 .on_key_down(move |event: &KeyDownEvent, window, cx| {
364 let key = event.keystroke.key.as_str();
365 if matches!(key, "enter" | "space" | " ") {
366 let t = motion_now(cx);
367 let next = !int_key.read(cx).expanded;
368 int_key.update(cx, |s, _| {
369 let (live_p, _) = s.current_progress(t, reduced);
370 let full = (*s.full_height.borrow()).max(clamp_h);
371 let span = (full - clamp_h).max(1.0);
372 let target = if next { 1.0 } else { 0.0 };
373 let dist = (target - live_p).abs() * span;
374 s.expanded = next;
375 s.from_progress = live_p;
376 s.target_progress = target;
377 s.anim_started_at = t;
378 s.anim_duration = if next {
379 expandable_text_open_duration(dist)
380 } else {
381 expandable_text_close_duration(dist)
382 };
383 });
384 if let Some(h) = &on_change_key {
385 h(&next, window, cx);
386 }
387 window.refresh();
388 }
389 })
390 .child(content_clip);
391
392 if overflowing {
393 let toggle = div()
394 .id(ElementId::NamedChild(
395 self.id.clone().into(),
396 "toggle".into(),
397 ))
398 .test_support()
399 .role(Role::Button)
400 .aria_expanded(is_expanded)
401 .min_h(px(28.0))
402 .px(px(2.0))
403 .rounded(Radii::CONTROL)
404 .flex()
405 .items_center()
406 .gap(Spacing::S1)
407 .text_size(Typography::TEXT_SM)
408 .font_medium()
409 .text_color(label_color)
410 .cursor_pointer()
411 .on_hover(move |hovered, window, cx| {
412 int_hover.update(cx, |s, _| {
413 s.hovered = *hovered;
414 });
415 window.refresh();
416 })
417 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
418 let t = motion_now(cx);
419 let next = !int_click.read(cx).expanded;
420 int_click.update(cx, |s, _| {
421 let (live_p, _) = s.current_progress(t, reduced);
422 let full = (*s.full_height.borrow()).max(clamp_h);
423 let span = (full - clamp_h).max(1.0);
424 let target = if next { 1.0 } else { 0.0 };
425 let dist = (target - live_p).abs() * span;
426 s.expanded = next;
427 s.from_progress = live_p;
428 s.target_progress = target;
429 s.anim_started_at = t;
430 s.anim_duration = if next {
431 expandable_text_open_duration(dist)
432 } else {
433 expandable_text_close_duration(dist)
434 };
435 });
436 focus_click.focus(window, cx);
437 if let Some(h) = &on_change_click {
438 h(&next, window, cx);
439 }
440 window.refresh();
441 })
442 .child(
443 div()
444 .relative()
445 .w(px(slot_w))
446 .h(px(20.0))
447 .child(
448 div()
449 .absolute()
450 .left_0()
451 .top(px(more_y))
452 .opacity(more_a)
453 .whitespace_nowrap()
454 .child(self.more_label),
455 )
456 .child(
457 div()
458 .absolute()
459 .left_0()
460 .top(px(less_y))
461 .opacity(less_a)
462 .whitespace_nowrap()
463 .child(self.less_label),
464 ),
465 )
466 .child(
467 div().w(px(16.0)).h(px(16.0)).flex_none().child(
468 canvas(
469 |_, _, _| {},
470 move |bounds, _, window, _| {
471 let cx_pt =
472 f32::from(bounds.origin.x) + f32::from(bounds.size.width) * 0.5;
473 let cy_pt = f32::from(bounds.origin.y)
474 + f32::from(bounds.size.height) * 0.5;
475 paint_rotated_chevron_16(
476 cx_pt,
477 cy_pt,
478 chevron_deg,
479 icon_color,
480 window,
481 );
482 },
483 )
484 .size_full(),
485 ),
486 );
487 root = root.child(toggle);
488 }
489
490 root
491 }
492}
493
494#[cfg(test)]
495mod tests {
496 use super::*;
497
498 #[test]
499 fn expandable_text_durations_grow_with_distance_within_caps() {
500 assert!((expandable_text_open_duration(0.0) - 0.50).abs() < 1e-6);
501 assert!((expandable_text_open_duration(80.0) - 0.55).abs() < 1e-6);
502 assert!((expandable_text_open_duration(3200.0) - 0.60).abs() < 1e-6);
503
504 assert!((expandable_text_close_duration(0.0) - 0.40).abs() < 1e-6);
505 assert!((expandable_text_close_duration(50.0) - 0.425).abs() < 1e-6);
506 assert!((expandable_text_close_duration(5000.0) - 0.45).abs() < 1e-6);
507 }
508
509 #[test]
510 fn expandable_text_fade_strength_vanishes_when_fully_open() {
511 assert!((expandable_text_fade_strength(0.0) - 0.96).abs() < 1e-5);
512 assert!(
513 expandable_text_fade_strength(0.5) > 0.3 && expandable_text_fade_strength(0.5) < 0.5
514 );
515 assert!(expandable_text_fade_strength(1.0).abs() < 1e-5);
516 }
517
518 #[test]
519 fn expandable_text_label_sample_crossfades_more_and_less() {
520 let (ma0, my0, la0, ly0) = expandable_text_label_sample(0.0, false);
521 assert!((ma0 - 1.0).abs() < 1e-5);
522 assert!(my0.abs() < 1e-5);
523 assert!(la0.abs() < 1e-5);
524 assert!((ly0 - 4.0).abs() < 1e-5);
525
526 let (ma1, my1, la1, ly1) = expandable_text_label_sample(1.0, false);
527 assert!(ma1.abs() < 1e-5);
528 assert!((my1 - (-4.0)).abs() < 1e-5);
529 assert!((la1 - 1.0).abs() < 1e-5);
530 assert!(ly1.abs() < 1e-5);
531 }
532}