arc-ui 0.4.0

Physics-first native Rust desktop UI component library & charts for GPUI (120+ interactive components ported from Arc).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/expandable-card/expandable-card.tsx` & `.module.css`
//!
//! P3 Component #11: `expandable-card`
//!
//! - Surface card that morphs both width (`width -> expanded_width`) and height (`0 -> auto`) on
//!   the same zero-overshoot spring (`motion.spring.smooth`, `0.35s, bounce 0`) in real pixel
//!   dimensions (no CSS scale), keeping text, border, and corner radius crisp.
//! - Inner details are laid out at their final expanded width (`inner_width - 2px`) throughout the
//!   transition so copy never reflows while the box widens or narrows.
//! - Sequenced choreography:
//!   - On open: box expands immediately (`delay = 0s`); details fade in after `120ms` over
//!     `220ms ease.standard` once room is created.
//!   - On close (when previously settled `> 450ms`): details fade out in `100ms` first while the
//!     box holds for `CLOSE_HOLD_SECS = 0.06s` before shrinking.
//!   - Reversing mid-flight (`<= 450ms` since last toggle) skips the `60ms` close hold so the
//!     spring turns around immediately with its live velocity.
//! - Live `description` changes animate via `swap_text_sample` (changed words rise in from
//!   `+4px` with `BlurFallback`).
//! - Pressing `Escape` while expanded collapses the card and returns focus to the trigger.

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;

/// Delay (`0.06s`) before the card box begins shrinking on a settled close so details fade out first.
pub const CARD_CLOSE_HOLD_SECS: f64 = 0.06;
/// Delay (`0.12s`) before details begin fading in on open so the box makes room first.
pub const CARD_OPEN_CONTENT_DELAY_SECS: f64 = 0.12;
/// Minimum elapsed time (`0.45s`) since the previous toggle for a close to apply [`CARD_CLOSE_HOLD_SECS`].
pub const CARD_SETTLE_TIME_SECS: f64 = 0.45;

/// Computes the effective target (`0.0` or `1.0`) fed to the box width/height/arrow springs given
/// `expanded`, `hold_active`, and `elapsed_since_toggle_secs`.
///
/// When closing from a settled open (`!expanded && hold_active`), the box target remains `1.0` for
/// the first [`CARD_CLOSE_HOLD_SECS`] (`60ms`) while inner content fades out.
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
    }
}

/// Computes the inner detail opacity (`0.0..=1.0`) at `elapsed_since_toggle_secs`.
///
/// - On open (`expanded == true`): waits `120ms`, then eases in over `220ms` (`ease.standard`).
/// - On close (`expanded == false`): eases out immediately over `100ms` (`ease.standard`).
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,
        }
    }
}

/// Arc `ExpandableCard` — width + height morphing disclosure card with fixed-width inner layout,
/// sequenced `60ms` close hold / `120ms` open fade-in, and rolling description swaps.
#[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
    }

    /// Collapsed width cap in `px`. Centered inside its container and clamped to available room.
    pub fn width(mut self, width_px: f32) -> Self {
        self.width = Some(width_px.max(180.0));
        self
    }

    /// Expanded width cap in `px` so the card can grow sideways as well as vertically.
    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);

        // Request another frame while within the 60ms close hold or 340ms content fade window.
        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() {
        // Opening always targets 1.0 immediately
        assert!((expandable_card_box_target(true, true, 0.0) - 1.0).abs() < 1e-5);
        // Settled close holds 1.0 during first 60ms
        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);
        // Mid-flight close skips hold and reverses immediately
        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);
    }
}