use std::{cell::RefCell, rc::Rc};
use arc_motion::{BlurFallback, CubicBezier, is_reduced_motion, motion_now};
use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, Typography};
use gpui_kit::{
AnyElement, App, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
ParentElement, PathBuilder, RenderOnce, Role, SharedString, Styled, TestSupportExt as _,
Window, base::StyledExt as _, canvas, div, linear_color_stop, linear_gradient, point,
prelude::*, px,
};
pub const EXPANDABLE_TEXT_LINE_HEIGHT: f32 = 21.0;
pub fn expandable_text_open_duration(distance_px: f32) -> f64 {
0.50 + (f64::from(distance_px.max(0.0)) / 1600.0).min(0.10)
}
pub fn expandable_text_close_duration(distance_px: f32) -> f64 {
0.40 + (f64::from(distance_px.max(0.0)) / 2000.0).min(0.05)
}
pub fn expandable_text_ease(t: f32) -> f32 {
CubicBezier::new(0.32, 0.5, 0.2, 1.0).sample(t.clamp(0.0, 1.0))
}
pub fn expandable_text_fade_strength(progress: f32) -> f32 {
let p = progress.clamp(0.0, 1.0);
let fade = (1.0 - p).powf(1.35);
if fade <= 0.002 {
0.0
} else {
(fade * 0.96).clamp(0.0, 0.96)
}
}
pub fn expandable_text_label_sample(progress: f32, reduced: bool) -> (f32, f32, f32, f32) {
let p = progress.clamp(0.0, 1.0);
if reduced {
return if p >= 0.5 {
(0.0, -4.0, 1.0, 0.0)
} else {
(1.0, 0.0, 0.0, 4.0)
};
}
let more_blur = BlurFallback::evaluate(px(p * 2.0), false);
let less_blur = BlurFallback::evaluate(px((1.0 - p) * 2.0), false);
let more_alpha = ((1.0 - p) * more_blur.opacity_multiplier).clamp(0.0, 1.0);
let more_y = -4.0 * p;
let less_alpha = (p * less_blur.opacity_multiplier).clamp(0.0, 1.0);
let less_y = 4.0 * (1.0 - p);
(more_alpha, more_y, less_alpha, less_y)
}
fn paint_rotated_chevron_16(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
let rad = angle_deg.to_radians();
let cos = rad.cos();
let sin = rad.sin();
let rot =
|dx: f32, dy: f32| -> (f32, f32) { (cx + dx * cos - dy * sin, cy + dx * sin + dy * cos) };
let (x1, y1) = rot(-4.0, -1.6);
let (xm, ym) = rot(0.0, 2.4);
let (x2, y2) = rot(4.0, -1.6);
let mut b = PathBuilder::stroke(px(1.75));
b.move_to(point(px(x1), px(y1)));
b.line_to(point(px(xm), px(ym)));
b.line_to(point(px(x2), px(y2)));
if let Ok(path) = b.build() {
window.paint_path(path, color);
}
}
type ExpandChangeCallback = Rc<dyn Fn(&bool, &mut Window, &mut App)>;
#[derive(Clone)]
struct ExpandableTextInternal {
expanded: bool,
from_progress: f32,
target_progress: f32,
anim_started_at: f64,
anim_duration: f64,
hovered: bool,
full_height: Rc<RefCell<f32>>,
focus_handle: FocusHandle,
}
impl ExpandableTextInternal {
fn new(default_expanded: bool, now: f64, focus_handle: FocusHandle) -> Self {
let p = if default_expanded { 1.0 } else { 0.0 };
Self {
expanded: default_expanded,
from_progress: p,
target_progress: p,
anim_started_at: now - 10.0,
anim_duration: 0.5,
hovered: false,
full_height: Rc::new(RefCell::new(168.0)),
focus_handle,
}
}
fn current_progress(&self, now: f64, reduced: bool) -> (f32, bool) {
if reduced || self.anim_duration <= 0.0001 {
return (self.target_progress, false);
}
let elapsed = (now - self.anim_started_at).max(0.0);
if elapsed >= self.anim_duration {
(self.target_progress, false)
} else {
let t = (elapsed / self.anim_duration).clamp(0.0, 1.0) as f32;
let eased = expandable_text_ease(t);
let p = self.from_progress + (self.target_progress - self.from_progress) * eased;
(p.clamp(0.0, 1.0), true)
}
}
}
#[derive(IntoElement)]
pub struct ExpandableText {
id: ElementId,
lines: usize,
default_expanded: bool,
expanded: Option<bool>,
on_expanded_change: Option<ExpandChangeCallback>,
more_label: SharedString,
less_label: SharedString,
fade_bg: Option<Hsla>,
body: Option<AnyElement>,
}
impl ExpandableText {
pub fn new(id: impl Into<ElementId>, content: impl IntoElement) -> Self {
Self {
id: id.into(),
lines: 3,
default_expanded: false,
expanded: None,
on_expanded_change: None,
more_label: "Read more".into(),
less_label: "Show less".into(),
fade_bg: None,
body: Some(content.into_any_element()),
}
}
pub fn lines(mut self, lines: usize) -> Self {
self.lines = lines.max(1);
self
}
pub fn default_expanded(mut self, default_expanded: bool) -> Self {
self.default_expanded = default_expanded;
self
}
pub fn expanded(mut self, expanded: bool) -> Self {
self.expanded = Some(expanded);
self
}
pub fn on_expanded_change(
mut self,
handler: impl Fn(&bool, &mut Window, &mut App) + 'static,
) -> Self {
self.on_expanded_change = Some(Rc::new(handler));
self
}
pub fn more_label(mut self, label: impl Into<SharedString>) -> Self {
self.more_label = label.into();
self
}
pub fn less_label(mut self, label: impl Into<SharedString>) -> Self {
self.less_label = label.into();
self
}
pub fn surface_color(mut self, color: Hsla) -> Self {
self.fade_bg = Some(color);
self
}
}
impl RenderOnce for ExpandableText {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let reduced = is_reduced_motion(cx);
let now = motion_now(cx);
let state_id =
ElementId::NamedChild(self.id.clone().into(), "__arc-expandable-text-state".into());
let internal = window.use_keyed_state(state_id, cx, |_, cx| {
ExpandableTextInternal::new(self.default_expanded, now, cx.focus_handle())
});
let clamp_h = (self.lines as f32) * EXPANDABLE_TEXT_LINE_HEIGHT;
if let Some(controlled) = self.expanded {
let cur_open = internal.read(cx).expanded;
if cur_open != controlled {
internal.update(cx, |s, _| {
let (live_p, _) = s.current_progress(now, reduced);
let full = (*s.full_height.borrow()).max(clamp_h);
let span = (full - clamp_h).max(1.0);
let target = if controlled { 1.0 } else { 0.0 };
let dist = (target - live_p).abs() * span;
s.expanded = controlled;
s.from_progress = live_p;
s.target_progress = target;
s.anim_started_at = now;
s.anim_duration = if controlled {
expandable_text_open_duration(dist)
} else {
expandable_text_close_duration(dist)
};
});
}
}
let snap = internal.read(cx).clone();
let is_expanded = self.expanded.unwrap_or(snap.expanded);
let (progress, animating) = snap.current_progress(now, reduced);
if animating && !reduced {
window.request_animation_frame();
}
let full_h = (*snap.full_height.borrow()).max(clamp_h);
let overflowing = full_h > clamp_h + 1.0;
let visible_h = if !overflowing {
full_h
} else {
clamp_h + (full_h - clamp_h) * progress
};
let fade_alpha = if overflowing {
expandable_text_fade_strength(progress)
} else {
0.0
};
let chevron_deg = progress * 180.0;
let (more_a, more_y, less_a, less_y) = expandable_text_label_sample(progress, reduced);
let full_h_ref = snap.full_height.clone();
let measure_probe = canvas(
move |rect, _, _| {
let h = f32::from(rect.size.height);
if h > 8.0 {
*full_h_ref.borrow_mut() = h;
}
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
let mut inner = div()
.relative()
.w_full()
.text_size(Typography::TEXT_SM)
.text_color(colors.text_secondary)
.child(measure_probe);
if let Some(body) = self.body {
inner = inner.child(body);
}
let fade_color = self.fade_bg.unwrap_or(colors.surface);
let fade_h = (EXPANDABLE_TEXT_LINE_HEIGHT * 1.6).min(visible_h);
let mut content_clip = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"content".into(),
))
.test_support()
.relative()
.w_full()
.h(px(visible_h))
.overflow_hidden()
.child(inner);
if fade_alpha > 0.002 {
content_clip = content_clip.child(
div()
.absolute()
.left_0()
.right_0()
.bottom_0()
.h(px(fade_h))
.bg(linear_gradient(
180.0,
linear_color_stop(fade_color.opacity(0.0), 0.0),
linear_color_stop(fade_color.opacity(fade_alpha), 1.0),
)),
);
}
let max_chars = self
.more_label
.chars()
.count()
.max(self.less_label.chars().count())
.max(4);
let slot_w = (max_chars as f32 * 7.6).max(56.0);
let int_hover = internal.clone();
let int_click = internal.clone();
let on_change_click = self.on_expanded_change.clone();
let focus_click = snap.focus_handle.clone();
let int_key = internal.clone();
let on_change_key = self.on_expanded_change.clone();
let label_color = if snap.hovered {
colors.text_secondary
} else {
colors.foreground
};
let icon_color = colors.text_muted;
let mut root = div()
.id(self.id.clone())
.test_support()
.track_focus(&snap.focus_handle)
.w_full()
.flex()
.flex_col()
.items_start()
.gap(Spacing::S2)
.on_key_down(move |event: &KeyDownEvent, window, cx| {
let key = event.keystroke.key.as_str();
if matches!(key, "enter" | "space" | " ") {
let t = motion_now(cx);
let next = !int_key.read(cx).expanded;
int_key.update(cx, |s, _| {
let (live_p, _) = s.current_progress(t, reduced);
let full = (*s.full_height.borrow()).max(clamp_h);
let span = (full - clamp_h).max(1.0);
let target = if next { 1.0 } else { 0.0 };
let dist = (target - live_p).abs() * span;
s.expanded = next;
s.from_progress = live_p;
s.target_progress = target;
s.anim_started_at = t;
s.anim_duration = if next {
expandable_text_open_duration(dist)
} else {
expandable_text_close_duration(dist)
};
});
if let Some(h) = &on_change_key {
h(&next, window, cx);
}
window.refresh();
}
})
.child(content_clip);
if overflowing {
let toggle = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"toggle".into(),
))
.test_support()
.role(Role::Button)
.aria_expanded(is_expanded)
.min_h(px(28.0))
.px(px(2.0))
.rounded(Radii::CONTROL)
.flex()
.items_center()
.gap(Spacing::S1)
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(label_color)
.cursor_pointer()
.on_hover(move |hovered, window, cx| {
int_hover.update(cx, |s, _| {
s.hovered = *hovered;
});
window.refresh();
})
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
let t = motion_now(cx);
let next = !int_click.read(cx).expanded;
int_click.update(cx, |s, _| {
let (live_p, _) = s.current_progress(t, reduced);
let full = (*s.full_height.borrow()).max(clamp_h);
let span = (full - clamp_h).max(1.0);
let target = if next { 1.0 } else { 0.0 };
let dist = (target - live_p).abs() * span;
s.expanded = next;
s.from_progress = live_p;
s.target_progress = target;
s.anim_started_at = t;
s.anim_duration = if next {
expandable_text_open_duration(dist)
} else {
expandable_text_close_duration(dist)
};
});
focus_click.focus(window, cx);
if let Some(h) = &on_change_click {
h(&next, window, cx);
}
window.refresh();
})
.child(
div()
.relative()
.w(px(slot_w))
.h(px(20.0))
.child(
div()
.absolute()
.left_0()
.top(px(more_y))
.opacity(more_a)
.whitespace_nowrap()
.child(self.more_label),
)
.child(
div()
.absolute()
.left_0()
.top(px(less_y))
.opacity(less_a)
.whitespace_nowrap()
.child(self.less_label),
),
)
.child(
div().w(px(16.0)).h(px(16.0)).flex_none().child(
canvas(
|_, _, _| {},
move |bounds, _, window, _| {
let cx_pt =
f32::from(bounds.origin.x) + f32::from(bounds.size.width) * 0.5;
let cy_pt = f32::from(bounds.origin.y)
+ f32::from(bounds.size.height) * 0.5;
paint_rotated_chevron_16(
cx_pt,
cy_pt,
chevron_deg,
icon_color,
window,
);
},
)
.size_full(),
),
);
root = root.child(toggle);
}
root
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn expandable_text_durations_grow_with_distance_within_caps() {
assert!((expandable_text_open_duration(0.0) - 0.50).abs() < 1e-6);
assert!((expandable_text_open_duration(80.0) - 0.55).abs() < 1e-6);
assert!((expandable_text_open_duration(3200.0) - 0.60).abs() < 1e-6);
assert!((expandable_text_close_duration(0.0) - 0.40).abs() < 1e-6);
assert!((expandable_text_close_duration(50.0) - 0.425).abs() < 1e-6);
assert!((expandable_text_close_duration(5000.0) - 0.45).abs() < 1e-6);
}
#[test]
fn expandable_text_fade_strength_vanishes_when_fully_open() {
assert!((expandable_text_fade_strength(0.0) - 0.96).abs() < 1e-5);
assert!(
expandable_text_fade_strength(0.5) > 0.3 && expandable_text_fade_strength(0.5) < 0.5
);
assert!(expandable_text_fade_strength(1.0).abs() < 1e-5);
}
#[test]
fn expandable_text_label_sample_crossfades_more_and_less() {
let (ma0, my0, la0, ly0) = expandable_text_label_sample(0.0, false);
assert!((ma0 - 1.0).abs() < 1e-5);
assert!(my0.abs() < 1e-5);
assert!(la0.abs() < 1e-5);
assert!((ly0 - 4.0).abs() < 1e-5);
let (ma1, my1, la1, ly1) = expandable_text_label_sample(1.0, false);
assert!(ma1.abs() < 1e-5);
assert!((my1 - (-4.0)).abs() < 1e-5);
assert!((la1 - 1.0).abs() < 1e-5);
assert!(ly1.abs() < 1e-5);
}
}