Skip to main content

arc_ui/disclosure/
expandable_card.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/expandable-card/expandable-card.tsx` & `.module.css`
3//!
4//! P3 Component #11: `expandable-card`
5//!
6//! - Surface card that morphs both width (`width -> expanded_width`) and height (`0 -> auto`) on
7//!   the same zero-overshoot spring (`motion.spring.smooth`, `0.35s, bounce 0`) in real pixel
8//!   dimensions (no CSS scale), keeping text, border, and corner radius crisp.
9//! - Inner details are laid out at their final expanded width (`inner_width - 2px`) throughout the
10//!   transition so copy never reflows while the box widens or narrows.
11//! - Sequenced choreography:
12//!   - On open: box expands immediately (`delay = 0s`); details fade in after `120ms` over
13//!     `220ms ease.standard` once room is created.
14//!   - On close (when previously settled `> 450ms`): details fade out in `100ms` first while the
15//!     box holds for `CLOSE_HOLD_SECS = 0.06s` before shrinking.
16//!   - Reversing mid-flight (`<= 450ms` since last toggle) skips the `60ms` close hold so the
17//!     spring turns around immediately with its live velocity.
18//! - Live `description` changes animate via `swap_text_sample` (changed words rise in from
19//!   `+4px` with `BlurFallback`).
20//! - Pressing `Escape` while expanded collapses the card and returns focus to the trigger.
21
22use std::{cell::RefCell, rc::Rc};
23
24use arc_motion::{CubicBezier, arc_spring, is_reduced_motion, motion_now};
25use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, Typography};
26use gpui_kit::{
27    AnyElement, App, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
28    ParentElement, PathBuilder, RenderOnce, Role, SharedString, Styled, TestSupportExt as _,
29    Window, base::StyledExt as _, canvas, div, point, prelude::*, px,
30};
31
32use crate::overlay::dialog::swap_text_sample;
33
34/// Delay (`0.06s`) before the card box begins shrinking on a settled close so details fade out first.
35pub const CARD_CLOSE_HOLD_SECS: f64 = 0.06;
36/// Delay (`0.12s`) before details begin fading in on open so the box makes room first.
37pub const CARD_OPEN_CONTENT_DELAY_SECS: f64 = 0.12;
38/// Minimum elapsed time (`0.45s`) since the previous toggle for a close to apply [`CARD_CLOSE_HOLD_SECS`].
39pub const CARD_SETTLE_TIME_SECS: f64 = 0.45;
40
41/// Computes the effective target (`0.0` or `1.0`) fed to the box width/height/arrow springs given
42/// `expanded`, `hold_active`, and `elapsed_since_toggle_secs`.
43///
44/// When closing from a settled open (`!expanded && hold_active`), the box target remains `1.0` for
45/// the first [`CARD_CLOSE_HOLD_SECS`] (`60ms`) while inner content fades out.
46pub fn expandable_card_box_target(
47    expanded: bool,
48    hold_active: bool,
49    elapsed_since_toggle_secs: f64,
50) -> f32 {
51    if expanded || (hold_active && elapsed_since_toggle_secs < CARD_CLOSE_HOLD_SECS) {
52        1.0
53    } else {
54        0.0
55    }
56}
57
58/// Computes the inner detail opacity (`0.0..=1.0`) at `elapsed_since_toggle_secs`.
59///
60/// - On open (`expanded == true`): waits `120ms`, then eases in over `220ms` (`ease.standard`).
61/// - On close (`expanded == false`): eases out immediately over `100ms` (`ease.standard`).
62pub fn expandable_card_content_opacity(
63    expanded: bool,
64    elapsed_since_toggle_secs: f64,
65    reduced: bool,
66) -> f32 {
67    if reduced {
68        return if expanded { 1.0 } else { 0.0 };
69    }
70    let ease = CubicBezier::new(0.2, 0.0, 0.0, 1.0);
71    if expanded {
72        let t = ((elapsed_since_toggle_secs - CARD_OPEN_CONTENT_DELAY_SECS) / 0.22).clamp(0.0, 1.0)
73            as f32;
74        ease.sample(t)
75    } else {
76        let t = (elapsed_since_toggle_secs / 0.10).clamp(0.0, 1.0) as f32;
77        (1.0 - ease.sample(t)).clamp(0.0, 1.0)
78    }
79}
80
81fn paint_rotated_arrow(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
82    let rad = angle_deg.to_radians();
83    let cos = rad.cos();
84    let sin = rad.sin();
85    let rot =
86        |dx: f32, dy: f32| -> (f32, f32) { (cx + dx * cos - dy * sin, cy + dx * sin + dy * cos) };
87    let (x1, y1) = rot(-4.5, -1.8);
88    let (xm, ym) = rot(0.0, 2.7);
89    let (x2, y2) = rot(4.5, -1.8);
90
91    let mut b = PathBuilder::stroke(px(1.7));
92    b.move_to(point(px(x1), px(y1)));
93    b.line_to(point(px(xm), px(ym)));
94    b.line_to(point(px(x2), px(y2)));
95    if let Ok(path) = b.build() {
96        window.paint_path(path, color);
97    }
98}
99
100type ExpandCallback = Rc<dyn Fn(&bool, &mut Window, &mut App)>;
101
102#[derive(Clone)]
103struct ExpandableCardInternal {
104    expanded: bool,
105    hold: bool,
106    last_toggle_at: f64,
107    hovered: bool,
108    room_width: Rc<RefCell<Option<f32>>>,
109    panel_height: Rc<RefCell<f32>>,
110    prev_desc: Option<SharedString>,
111    curr_desc: SharedString,
112    desc_changed_at: f64,
113    focus_handle: FocusHandle,
114}
115
116impl ExpandableCardInternal {
117    fn new(
118        default_expanded: bool,
119        desc: SharedString,
120        now: f64,
121        focus_handle: FocusHandle,
122    ) -> Self {
123        Self {
124            expanded: default_expanded,
125            hold: true,
126            last_toggle_at: now - 10.0,
127            hovered: false,
128            room_width: Rc::new(RefCell::new(None)),
129            panel_height: Rc::new(RefCell::new(160.0)),
130            prev_desc: None,
131            curr_desc: desc,
132            desc_changed_at: now - 10.0,
133            focus_handle,
134        }
135    }
136}
137
138/// Arc `ExpandableCard` — width + height morphing disclosure card with fixed-width inner layout,
139/// sequenced `60ms` close hold / `120ms` open fade-in, and rolling description swaps.
140#[derive(IntoElement)]
141pub struct ExpandableCard {
142    id: ElementId,
143    title: SharedString,
144    description: Option<SharedString>,
145    width: Option<f32>,
146    expanded_width: Option<f32>,
147    default_expanded: bool,
148    expanded: Option<bool>,
149    on_expanded_change: Option<ExpandCallback>,
150    body: Option<AnyElement>,
151}
152
153impl ExpandableCard {
154    pub fn new(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self {
155        Self {
156            id: id.into(),
157            title: title.into(),
158            description: None,
159            width: None,
160            expanded_width: None,
161            default_expanded: false,
162            expanded: None,
163            on_expanded_change: None,
164            body: None,
165        }
166    }
167
168    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
169        self.description = Some(description.into());
170        self
171    }
172
173    /// Collapsed width cap in `px`. Centered inside its container and clamped to available room.
174    pub fn width(mut self, width_px: f32) -> Self {
175        self.width = Some(width_px.max(180.0));
176        self
177    }
178
179    /// Expanded width cap in `px` so the card can grow sideways as well as vertically.
180    pub fn expanded_width(mut self, width_px: f32) -> Self {
181        self.expanded_width = Some(width_px.max(180.0));
182        self
183    }
184
185    pub fn default_expanded(mut self, default_expanded: bool) -> Self {
186        self.default_expanded = default_expanded;
187        self
188    }
189
190    pub fn expanded(mut self, expanded: bool) -> Self {
191        self.expanded = Some(expanded);
192        self
193    }
194
195    pub fn on_expanded_change(
196        mut self,
197        handler: impl Fn(&bool, &mut Window, &mut App) + 'static,
198    ) -> Self {
199        self.on_expanded_change = Some(Rc::new(handler));
200        self
201    }
202
203    pub fn content(mut self, body: impl IntoElement) -> Self {
204        self.body = Some(body.into_any_element());
205        self
206    }
207}
208
209impl RenderOnce for ExpandableCard {
210    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
211        let theme = cx.arc_theme().clone();
212        let colors = theme.colors;
213        let motion = theme.motion;
214        let reduced = is_reduced_motion(cx);
215        let now = motion_now(cx);
216        let incoming_desc = self.description.clone().unwrap_or_default();
217
218        let state_id =
219            ElementId::NamedChild(self.id.clone().into(), "__arc-expandable-card-state".into());
220        let internal = window.use_keyed_state(state_id, cx, |_, cx| {
221            ExpandableCardInternal::new(
222                self.default_expanded,
223                incoming_desc.clone(),
224                now,
225                cx.focus_handle(),
226            )
227        });
228
229        internal.update(cx, |s, _| {
230            if s.curr_desc != incoming_desc {
231                s.prev_desc = Some(s.curr_desc.clone());
232                s.curr_desc = incoming_desc.clone();
233                s.desc_changed_at = now;
234            }
235            if let Some(controlled) = self.expanded
236                && s.expanded != controlled
237            {
238                s.hold = (now - s.last_toggle_at) > CARD_SETTLE_TIME_SECS;
239                s.last_toggle_at = now;
240                s.expanded = controlled;
241            }
242        });
243
244        let snap = internal.read(cx).clone();
245        let is_expanded = self.expanded.unwrap_or(snap.expanded);
246        let elapsed = (now - snap.last_toggle_at).max(0.0);
247
248        let box_target = expandable_card_box_target(is_expanded, snap.hold, elapsed);
249        let content_alpha = expandable_card_content_opacity(is_expanded, elapsed, reduced);
250
251        // Request another frame while within the 60ms close hold or 340ms content fade window.
252        if !reduced
253            && ((snap.hold && !is_expanded && elapsed < CARD_CLOSE_HOLD_SECS + 0.02)
254                || (is_expanded && elapsed < CARD_OPEN_CONTENT_DELAY_SECS + 0.24)
255                || (!is_expanded && elapsed < 0.12))
256        {
257            window.request_animation_frame();
258        }
259
260        let room = snap.room_width.borrow().unwrap_or(680.0).max(200.0);
261        let collapsed_cap = self.width.unwrap_or(room).min(room);
262        let expanded_cap = self.expanded_width.or(self.width).unwrap_or(room).min(room);
263
264        let target_w = if box_target >= 0.5 {
265            expanded_cap
266        } else {
267            collapsed_cap
268        };
269        let current_w = if reduced {
270            if is_expanded {
271                expanded_cap
272            } else {
273                collapsed_cap
274            }
275        } else {
276            arc_spring(
277                (self.id.clone(), "card-width"),
278                target_w,
279                motion.spring.smooth,
280                window,
281                cx,
282            )
283        };
284
285        let progress_h = if reduced {
286            if is_expanded { 1.0 } else { 0.0 }
287        } else {
288            arc_spring(
289                (self.id.clone(), "card-height-p"),
290                box_target,
291                motion.spring.smooth,
292                window,
293                cx,
294            )
295        };
296        let arrow_deg = if reduced {
297            if is_expanded { 180.0 } else { 0.0 }
298        } else {
299            arc_spring(
300                (self.id.clone(), "card-arrow-deg"),
301                box_target * 180.0,
302                motion.spring.smooth,
303                window,
304                cx,
305            )
306        };
307
308        let natural_panel_h = (*snap.panel_height.borrow()).max(32.0);
309        let animated_panel_h = (natural_panel_h * progress_h).max(0.0);
310        let inner_fixed_w = (expanded_cap - 2.0).max(160.0);
311
312        let desc_elapsed = (now - snap.desc_changed_at).max(0.0);
313        let (desc_old_a, desc_old_y, desc_new_a, desc_new_y) =
314            swap_text_sample(desc_elapsed, reduced);
315        if snap.prev_desc.is_some() && desc_elapsed < 0.24 && !reduced {
316            window.request_animation_frame();
317        }
318
319        let room_ref = snap.room_width.clone();
320        let track_probe = canvas(
321            move |rect, _, _| {
322                let w = f32::from(rect.size.width);
323                if w > 40.0 {
324                    *room_ref.borrow_mut() = Some(w);
325                }
326            },
327            |_, _, _, _| {},
328        )
329        .absolute()
330        .inset_0();
331
332        let int_hover = internal.clone();
333        let int_click = internal.clone();
334        let on_change_click = self.on_expanded_change.clone();
335        let focus_click = snap.focus_handle.clone();
336        let int_key = internal.clone();
337        let on_change_key = self.on_expanded_change.clone();
338
339        let arrow_color = if is_expanded || snap.hovered {
340            colors.foreground
341        } else {
342            colors.text_muted
343        };
344
345        let mut copy_col = div()
346            .flex_1()
347            .min_w_0()
348            .flex()
349            .flex_col()
350            .gap(px(4.0))
351            .child(
352                div()
353                    .text_size(Typography::TEXT_SM)
354                    .font_medium()
355                    .text_color(colors.foreground)
356                    .child(self.title),
357            );
358
359        if !snap.curr_desc.is_empty() {
360            let mut desc_box = div()
361                .relative()
362                .w_full()
363                .text_size(Typography::TEXT_XS)
364                .text_color(colors.text_muted);
365            if let Some(prev) = snap.prev_desc.filter(|_| desc_old_a > 0.01) {
366                desc_box = desc_box.child(
367                    div()
368                        .absolute()
369                        .left_0()
370                        .top(px(desc_old_y))
371                        .opacity(desc_old_a)
372                        .child(prev),
373                );
374            }
375            desc_box = desc_box.child(
376                div()
377                    .relative()
378                    .top(px(desc_new_y))
379                    .opacity(desc_new_a)
380                    .child(snap.curr_desc),
381            );
382            copy_col = copy_col.child(desc_box);
383        }
384
385        let trigger = div()
386            .id(ElementId::NamedChild(
387                self.id.clone().into(),
388                "trigger".into(),
389            ))
390            .test_support()
391            .role(Role::Button)
392            .aria_expanded(is_expanded)
393            .w_full()
394            .min_h(px(64.0))
395            .px(Spacing::S5)
396            .py(Spacing::S4)
397            .flex()
398            .items_center()
399            .justify_between()
400            .gap(Spacing::S5)
401            .bg(if snap.hovered {
402                colors.surface_muted
403            } else {
404                Hsla::transparent_black()
405            })
406            .cursor_pointer()
407            .on_hover(move |hovered, window, cx| {
408                int_hover.update(cx, |s, _| {
409                    s.hovered = *hovered;
410                });
411                window.refresh();
412            })
413            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
414                let t = motion_now(cx);
415                let next = !is_expanded;
416                int_click.update(cx, |s, _| {
417                    s.hold = (t - s.last_toggle_at) > CARD_SETTLE_TIME_SECS;
418                    s.last_toggle_at = t;
419                    s.expanded = next;
420                });
421                focus_click.focus(window, cx);
422                if let Some(h) = &on_change_click {
423                    h(&next, window, cx);
424                }
425                window.refresh();
426            })
427            .child(copy_col)
428            .child(
429                div().w(px(18.0)).h(px(18.0)).flex_none().child(
430                    canvas(
431                        |_, _, _| {},
432                        move |bounds, _, window, _| {
433                            let cx_pt =
434                                f32::from(bounds.origin.x) + f32::from(bounds.size.width) * 0.5;
435                            let cy_pt =
436                                f32::from(bounds.origin.y) + f32::from(bounds.size.height) * 0.5;
437                            paint_rotated_arrow(cx_pt, cy_pt, arrow_deg, arrow_color, window);
438                        },
439                    )
440                    .size_full(),
441                ),
442            );
443
444        let mut card = div()
445            .id(self.id.clone())
446            .test_support()
447            .track_focus(&snap.focus_handle)
448            .w(px(current_w))
449            .overflow_hidden()
450            .rounded(Radii::SURFACE)
451            .border_1()
452            .border_color(colors.border)
453            .bg(colors.surface)
454            .shadow(Shadows::resting(theme.mode))
455            .flex()
456            .flex_col()
457            .on_key_down(move |event: &KeyDownEvent, window, cx| {
458                if event.keystroke.key == "escape" && is_expanded {
459                    let t = motion_now(cx);
460                    int_key.update(cx, |s, _| {
461                        s.hold = (t - s.last_toggle_at) > CARD_SETTLE_TIME_SECS;
462                        s.last_toggle_at = t;
463                        s.expanded = false;
464                    });
465                    if let Some(h) = &on_change_key {
466                        h(&false, window, cx);
467                    }
468                    window.refresh();
469                }
470            })
471            .child(trigger);
472
473        if is_expanded || animated_panel_h > 0.5 {
474            let panel_h_ref = snap.panel_height.clone();
475            let measure_probe = canvas(
476                move |rect, _, _| {
477                    let h = f32::from(rect.size.height);
478                    if h > 8.0 {
479                        *panel_h_ref.borrow_mut() = h;
480                    }
481                },
482                |_, _, _, _| {},
483            )
484            .absolute()
485            .inset_0();
486
487            let mut panel_inner = div()
488                .relative()
489                .w(px(inner_fixed_w))
490                .px(Spacing::S5)
491                .pt(Spacing::S4)
492                .pb(Spacing::S5)
493                .text_size(Typography::TEXT_SM)
494                .text_color(colors.text_secondary)
495                .opacity(content_alpha)
496                .child(measure_probe);
497
498            if let Some(body) = self.body {
499                panel_inner = panel_inner.child(body);
500            }
501
502            card = card.child(
503                div()
504                    .id(ElementId::NamedChild(
505                        self.id.clone().into(),
506                        "panel".into(),
507                    ))
508                    .test_support()
509                    .w_full()
510                    .h(px(animated_panel_h))
511                    .overflow_hidden()
512                    .border_t_1()
513                    .border_color(colors.border)
514                    .bg(colors.surface_muted)
515                    .child(panel_inner),
516            );
517        }
518
519        div()
520            .relative()
521            .w_full()
522            .flex()
523            .justify_center()
524            .child(track_probe)
525            .child(card)
526    }
527}
528
529#[cfg(test)]
530mod tests {
531    use super::*;
532
533    #[test]
534    fn expandable_card_box_holds_for_60ms_on_settled_close() {
535        // Opening always targets 1.0 immediately
536        assert!((expandable_card_box_target(true, true, 0.0) - 1.0).abs() < 1e-5);
537        // Settled close holds 1.0 during first 60ms
538        assert!((expandable_card_box_target(false, true, 0.02) - 1.0).abs() < 1e-5);
539        assert!(expandable_card_box_target(false, true, 0.07).abs() < 1e-5);
540        // Mid-flight close skips hold and reverses immediately
541        assert!(expandable_card_box_target(false, false, 0.01).abs() < 1e-5);
542    }
543
544    #[test]
545    fn expandable_card_content_opacity_waits_120ms_on_open_and_fades_fast_on_close() {
546        assert!(expandable_card_content_opacity(true, 0.05, false).abs() < 1e-5);
547        assert!(expandable_card_content_opacity(true, 0.22, false) > 0.3);
548        assert!((expandable_card_content_opacity(true, 0.40, false) - 1.0).abs() < 1e-5);
549
550        assert!(expandable_card_content_opacity(false, 0.05, false) < 0.7);
551        assert!(expandable_card_content_opacity(false, 0.12, false).abs() < 1e-5);
552    }
553}