use std::{cell::RefCell, rc::Rc};
use arc_motion::{CubicBezier, arc_spring, is_reduced_motion, motion_now};
use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, 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, point, prelude::*, px,
};
use crate::overlay::dialog::swap_text_sample;
pub const CARD_CLOSE_HOLD_SECS: f64 = 0.06;
pub const CARD_OPEN_CONTENT_DELAY_SECS: f64 = 0.12;
pub const CARD_SETTLE_TIME_SECS: f64 = 0.45;
pub fn expandable_card_box_target(
expanded: bool,
hold_active: bool,
elapsed_since_toggle_secs: f64,
) -> f32 {
if expanded || (hold_active && elapsed_since_toggle_secs < CARD_CLOSE_HOLD_SECS) {
1.0
} else {
0.0
}
}
pub fn expandable_card_content_opacity(
expanded: bool,
elapsed_since_toggle_secs: f64,
reduced: bool,
) -> f32 {
if reduced {
return if expanded { 1.0 } else { 0.0 };
}
let ease = CubicBezier::new(0.2, 0.0, 0.0, 1.0);
if expanded {
let t = ((elapsed_since_toggle_secs - CARD_OPEN_CONTENT_DELAY_SECS) / 0.22).clamp(0.0, 1.0)
as f32;
ease.sample(t)
} else {
let t = (elapsed_since_toggle_secs / 0.10).clamp(0.0, 1.0) as f32;
(1.0 - ease.sample(t)).clamp(0.0, 1.0)
}
}
fn paint_rotated_arrow(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.5, -1.8);
let (xm, ym) = rot(0.0, 2.7);
let (x2, y2) = rot(4.5, -1.8);
let mut b = PathBuilder::stroke(px(1.7));
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 ExpandCallback = Rc<dyn Fn(&bool, &mut Window, &mut App)>;
#[derive(Clone)]
struct ExpandableCardInternal {
expanded: bool,
hold: bool,
last_toggle_at: f64,
hovered: bool,
room_width: Rc<RefCell<Option<f32>>>,
panel_height: Rc<RefCell<f32>>,
prev_desc: Option<SharedString>,
curr_desc: SharedString,
desc_changed_at: f64,
focus_handle: FocusHandle,
}
impl ExpandableCardInternal {
fn new(
default_expanded: bool,
desc: SharedString,
now: f64,
focus_handle: FocusHandle,
) -> Self {
Self {
expanded: default_expanded,
hold: true,
last_toggle_at: now - 10.0,
hovered: false,
room_width: Rc::new(RefCell::new(None)),
panel_height: Rc::new(RefCell::new(160.0)),
prev_desc: None,
curr_desc: desc,
desc_changed_at: now - 10.0,
focus_handle,
}
}
}
#[derive(IntoElement)]
pub struct ExpandableCard {
id: ElementId,
title: SharedString,
description: Option<SharedString>,
width: Option<f32>,
expanded_width: Option<f32>,
default_expanded: bool,
expanded: Option<bool>,
on_expanded_change: Option<ExpandCallback>,
body: Option<AnyElement>,
}
impl ExpandableCard {
pub fn new(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
title: title.into(),
description: None,
width: None,
expanded_width: None,
default_expanded: false,
expanded: None,
on_expanded_change: None,
body: None,
}
}
pub fn description(mut self, description: impl Into<SharedString>) -> Self {
self.description = Some(description.into());
self
}
pub fn width(mut self, width_px: f32) -> Self {
self.width = Some(width_px.max(180.0));
self
}
pub fn expanded_width(mut self, width_px: f32) -> Self {
self.expanded_width = Some(width_px.max(180.0));
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 content(mut self, body: impl IntoElement) -> Self {
self.body = Some(body.into_any_element());
self
}
}
impl RenderOnce for ExpandableCard {
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 incoming_desc = self.description.clone().unwrap_or_default();
let state_id =
ElementId::NamedChild(self.id.clone().into(), "__arc-expandable-card-state".into());
let internal = window.use_keyed_state(state_id, cx, |_, cx| {
ExpandableCardInternal::new(
self.default_expanded,
incoming_desc.clone(),
now,
cx.focus_handle(),
)
});
internal.update(cx, |s, _| {
if s.curr_desc != incoming_desc {
s.prev_desc = Some(s.curr_desc.clone());
s.curr_desc = incoming_desc.clone();
s.desc_changed_at = now;
}
if let Some(controlled) = self.expanded
&& s.expanded != controlled
{
s.hold = (now - s.last_toggle_at) > CARD_SETTLE_TIME_SECS;
s.last_toggle_at = now;
s.expanded = controlled;
}
});
let snap = internal.read(cx).clone();
let is_expanded = self.expanded.unwrap_or(snap.expanded);
let elapsed = (now - snap.last_toggle_at).max(0.0);
let box_target = expandable_card_box_target(is_expanded, snap.hold, elapsed);
let content_alpha = expandable_card_content_opacity(is_expanded, elapsed, reduced);
if !reduced
&& ((snap.hold && !is_expanded && elapsed < CARD_CLOSE_HOLD_SECS + 0.02)
|| (is_expanded && elapsed < CARD_OPEN_CONTENT_DELAY_SECS + 0.24)
|| (!is_expanded && elapsed < 0.12))
{
window.request_animation_frame();
}
let room = snap.room_width.borrow().unwrap_or(680.0).max(200.0);
let collapsed_cap = self.width.unwrap_or(room).min(room);
let expanded_cap = self.expanded_width.or(self.width).unwrap_or(room).min(room);
let target_w = if box_target >= 0.5 {
expanded_cap
} else {
collapsed_cap
};
let current_w = if reduced {
if is_expanded {
expanded_cap
} else {
collapsed_cap
}
} else {
arc_spring(
(self.id.clone(), "card-width"),
target_w,
motion.spring.smooth,
window,
cx,
)
};
let progress_h = if reduced {
if is_expanded { 1.0 } else { 0.0 }
} else {
arc_spring(
(self.id.clone(), "card-height-p"),
box_target,
motion.spring.smooth,
window,
cx,
)
};
let arrow_deg = if reduced {
if is_expanded { 180.0 } else { 0.0 }
} else {
arc_spring(
(self.id.clone(), "card-arrow-deg"),
box_target * 180.0,
motion.spring.smooth,
window,
cx,
)
};
let natural_panel_h = (*snap.panel_height.borrow()).max(32.0);
let animated_panel_h = (natural_panel_h * progress_h).max(0.0);
let inner_fixed_w = (expanded_cap - 2.0).max(160.0);
let desc_elapsed = (now - snap.desc_changed_at).max(0.0);
let (desc_old_a, desc_old_y, desc_new_a, desc_new_y) =
swap_text_sample(desc_elapsed, reduced);
if snap.prev_desc.is_some() && desc_elapsed < 0.24 && !reduced {
window.request_animation_frame();
}
let room_ref = snap.room_width.clone();
let track_probe = canvas(
move |rect, _, _| {
let w = f32::from(rect.size.width);
if w > 40.0 {
*room_ref.borrow_mut() = Some(w);
}
},
|_, _, _, _| {},
)
.absolute()
.inset_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 arrow_color = if is_expanded || snap.hovered {
colors.foreground
} else {
colors.text_muted
};
let mut copy_col = div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.gap(px(4.0))
.child(
div()
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(colors.foreground)
.child(self.title),
);
if !snap.curr_desc.is_empty() {
let mut desc_box = div()
.relative()
.w_full()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted);
if let Some(prev) = snap.prev_desc.filter(|_| desc_old_a > 0.01) {
desc_box = desc_box.child(
div()
.absolute()
.left_0()
.top(px(desc_old_y))
.opacity(desc_old_a)
.child(prev),
);
}
desc_box = desc_box.child(
div()
.relative()
.top(px(desc_new_y))
.opacity(desc_new_a)
.child(snap.curr_desc),
);
copy_col = copy_col.child(desc_box);
}
let trigger = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"trigger".into(),
))
.test_support()
.role(Role::Button)
.aria_expanded(is_expanded)
.w_full()
.min_h(px(64.0))
.px(Spacing::S5)
.py(Spacing::S4)
.flex()
.items_center()
.justify_between()
.gap(Spacing::S5)
.bg(if snap.hovered {
colors.surface_muted
} else {
Hsla::transparent_black()
})
.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 = !is_expanded;
int_click.update(cx, |s, _| {
s.hold = (t - s.last_toggle_at) > CARD_SETTLE_TIME_SECS;
s.last_toggle_at = t;
s.expanded = next;
});
focus_click.focus(window, cx);
if let Some(h) = &on_change_click {
h(&next, window, cx);
}
window.refresh();
})
.child(copy_col)
.child(
div().w(px(18.0)).h(px(18.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_arrow(cx_pt, cy_pt, arrow_deg, arrow_color, window);
},
)
.size_full(),
),
);
let mut card = div()
.id(self.id.clone())
.test_support()
.track_focus(&snap.focus_handle)
.w(px(current_w))
.overflow_hidden()
.rounded(Radii::SURFACE)
.border_1()
.border_color(colors.border)
.bg(colors.surface)
.shadow(Shadows::resting(theme.mode))
.flex()
.flex_col()
.on_key_down(move |event: &KeyDownEvent, window, cx| {
if event.keystroke.key == "escape" && is_expanded {
let t = motion_now(cx);
int_key.update(cx, |s, _| {
s.hold = (t - s.last_toggle_at) > CARD_SETTLE_TIME_SECS;
s.last_toggle_at = t;
s.expanded = false;
});
if let Some(h) = &on_change_key {
h(&false, window, cx);
}
window.refresh();
}
})
.child(trigger);
if is_expanded || animated_panel_h > 0.5 {
let panel_h_ref = snap.panel_height.clone();
let measure_probe = canvas(
move |rect, _, _| {
let h = f32::from(rect.size.height);
if h > 8.0 {
*panel_h_ref.borrow_mut() = h;
}
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
let mut panel_inner = div()
.relative()
.w(px(inner_fixed_w))
.px(Spacing::S5)
.pt(Spacing::S4)
.pb(Spacing::S5)
.text_size(Typography::TEXT_SM)
.text_color(colors.text_secondary)
.opacity(content_alpha)
.child(measure_probe);
if let Some(body) = self.body {
panel_inner = panel_inner.child(body);
}
card = card.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"panel".into(),
))
.test_support()
.w_full()
.h(px(animated_panel_h))
.overflow_hidden()
.border_t_1()
.border_color(colors.border)
.bg(colors.surface_muted)
.child(panel_inner),
);
}
div()
.relative()
.w_full()
.flex()
.justify_center()
.child(track_probe)
.child(card)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn expandable_card_box_holds_for_60ms_on_settled_close() {
assert!((expandable_card_box_target(true, true, 0.0) - 1.0).abs() < 1e-5);
assert!((expandable_card_box_target(false, true, 0.02) - 1.0).abs() < 1e-5);
assert!(expandable_card_box_target(false, true, 0.07).abs() < 1e-5);
assert!(expandable_card_box_target(false, false, 0.01).abs() < 1e-5);
}
#[test]
fn expandable_card_content_opacity_waits_120ms_on_open_and_fades_fast_on_close() {
assert!(expandable_card_content_opacity(true, 0.05, false).abs() < 1e-5);
assert!(expandable_card_content_opacity(true, 0.22, false) > 0.3);
assert!((expandable_card_content_opacity(true, 0.40, false) - 1.0).abs() < 1e-5);
assert!(expandable_card_content_opacity(false, 0.05, false) < 0.7);
assert!(expandable_card_content_opacity(false, 0.12, false).abs() < 1e-5);
}
}