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
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/hover-card/hover-card.tsx` & `.module.css`
//!
//! P3 Component #3: `hover-card`
//!
//! - Behaviour comes from `gpui_kit::base::HoverCard` (with an [`OFFSET`] of 8px): hovering the
//!   trigger waits `500ms` (`OPEN_DELAY_SECS`), moving into the card keeps it open, and leaving
//!   both closes after `140ms` (`CLOSE_DELAY_SECS`).
//! - Card: `18.5rem` (296px) wide, `surface_raised`, `1px border`, `panel` radius, `floating`
//!   shadow, 16px padding.
//! - Enter: fades in over `160ms` / `ease.enter` while rising `4px` from the trigger edge on a
//!   smooth ease; [`HoverCardProfile`] staggers its four rows (`head`, `bio`, `stats`, `meta`) by
//!   `40ms` (`stagger.item`) after a `40ms` base delay (`240ms` / `ease.enter`, `4px` y rise).
//! - Local design: the `0.96 -> 1.0` scale and the page-wide warm skip window are omitted (the
//!   base hover card manages each trigger's delay and unmounts on close).

use std::{cell::Cell, rc::Rc, time::Duration};

use arc_motion::{CubicBezier, is_reduced_motion, motion_now};
use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, Typography};
use gpui_kit::{
    Anchor, AnyElement, App, ElementId, IntoElement, ObjectFit, ParentElement, RenderOnce, Role,
    SharedString, Styled, TestSupportExt as _, Window,
    base::{HoverCard as BaseHoverCard, HoverCardState, StyledExt as _},
    div, img,
    prelude::*,
    px,
};

use crate::data::avatar::initials_for;

/// Default hover time before the card opens (`500ms`).
pub const OPEN_DELAY_SECS: f64 = 0.50;
/// Grace time after leaving trigger/card before it closes (`140ms`).
pub const CLOSE_DELAY_SECS: f64 = 0.14;
/// Gap between trigger and card (`sideOffset = 8`).
pub const OFFSET: f32 = 8.0;
/// `18.5rem` card width.
pub const CARD_WIDTH: f32 = 296.0;
/// Travel distance from the trigger edge (`4px`).
pub const TRAVEL_PX: f32 = 4.0;
/// Card fade (`duration.fast = 160ms`) and smooth rise (`340ms`).
pub const CARD_FADE_SECS: f64 = 0.16;
pub const CARD_RISE_SECS: f64 = 0.34;
/// Profile row stagger: `40ms` lead + `40ms` per row (`stagger.item`), `240ms` (`duration.standard`).
pub const ROW_LEAD_SECS: f64 = 0.04;
pub const ROW_STEP_SECS: f64 = 0.04;
pub const ROW_DURATION_SECS: f64 = 0.24;
pub const ROW_RISE_PX: f32 = 4.0;

/// Side of the trigger the card prefers (default `Bottom`).
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum HoverCardSide {
    Top,
    #[default]
    Bottom,
    Left,
    Right,
}

/// Alignment along the trigger edge (default `Start`).
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum HoverCardAlign {
    #[default]
    Start,
    Center,
    End,
}

fn anchor_for(side: HoverCardSide, align: HoverCardAlign) -> Anchor {
    match (side, align) {
        (HoverCardSide::Bottom, HoverCardAlign::Start) => Anchor::TopLeft,
        (HoverCardSide::Bottom, HoverCardAlign::Center) => Anchor::TopCenter,
        (HoverCardSide::Bottom, HoverCardAlign::End) => Anchor::TopRight,
        (HoverCardSide::Top, HoverCardAlign::Start) => Anchor::BottomLeft,
        (HoverCardSide::Top, HoverCardAlign::Center) => Anchor::BottomCenter,
        (HoverCardSide::Top, HoverCardAlign::End) => Anchor::BottomRight,
        (HoverCardSide::Right, _) => Anchor::LeftCenter,
        (HoverCardSide::Left, _) => Anchor::RightCenter,
    }
}

fn travel_sign(side: HoverCardSide) -> f32 {
    match side {
        HoverCardSide::Bottom => -1.0,
        HoverCardSide::Top => 1.0,
        HoverCardSide::Left | HoverCardSide::Right => 0.0,
    }
}

/// `(fade, rise)` in `0..=1` for a card opened `elapsed` seconds ago.
pub fn card_progress(elapsed: f64, reduced: bool) -> (f32, f32) {
    if reduced {
        return (1.0, 1.0);
    }
    let ease = CubicBezier::new(0.16, 1.0, 0.3, 1.0);
    let fade_t = (elapsed / CARD_FADE_SECS).clamp(0.0, 1.0) as f32;
    let rise_t = (elapsed / CARD_RISE_SECS).clamp(0.0, 1.0) as f32;
    (ease.sample(fade_t), ease.sample(rise_t))
}

/// `0..=1` settle progress for a profile row at index `order` (`0..=3`).
pub fn row_progress(elapsed: f64, order: usize, reduced: bool) -> f32 {
    if reduced {
        return 1.0;
    }
    let delay = ROW_LEAD_SECS + (order as f64) * ROW_STEP_SECS;
    let t = ((elapsed - delay) / ROW_DURATION_SECS).clamp(0.0, 1.0) as f32;
    CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t)
}

type ContentBuilder = Rc<dyn Fn(f64, &mut Window, &mut App) -> AnyElement>;

/// Arc `HoverCard` — rich preview anchored to a trigger after a short hover delay.
#[derive(IntoElement)]
pub struct ArcHoverCard {
    id: ElementId,
    side: HoverCardSide,
    align: HoverCardAlign,
    open_delay: Duration,
    close_delay: Duration,
    trigger: AnyElement,
    content: Option<ContentBuilder>,
    opened_at: Rc<Cell<f64>>,
}

impl ArcHoverCard {
    pub fn new(
        id: impl Into<ElementId>,
        content: impl Fn(f64, &mut Window, &mut App) -> AnyElement + 'static,
    ) -> Self {
        Self {
            id: id.into(),
            side: HoverCardSide::Bottom,
            align: HoverCardAlign::Start,
            open_delay: Duration::from_secs_f64(OPEN_DELAY_SECS),
            close_delay: Duration::from_secs_f64(CLOSE_DELAY_SECS),
            trigger: div().into_any_element(),
            content: Some(Rc::new(content)),
            opened_at: Rc::new(Cell::new(f64::NEG_INFINITY)),
        }
    }

    pub fn side(mut self, side: HoverCardSide) -> Self {
        self.side = side;
        self
    }

    pub fn align(mut self, align: HoverCardAlign) -> Self {
        self.align = align;
        self
    }

    pub fn open_delay(mut self, duration: Duration) -> Self {
        self.open_delay = duration;
        self
    }

    pub fn close_delay(mut self, duration: Duration) -> Self {
        self.close_delay = duration;
        self
    }

    pub fn trigger(mut self, trigger: impl IntoElement) -> Self {
        self.trigger = trigger.into_any_element();
        self
    }
}

impl RenderOnce for ArcHoverCard {
    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 opened_at = self.opened_at.clone();
        let opened_for_change = self.opened_at.clone();
        let content = self.content.clone();
        let side = self.side;
        let align = self.align;
        let id = self.id.clone();
        let card_id = id.clone();

        BaseHoverCard::new(id)
            .anchor(anchor_for(side, align))
            .open_delay(self.open_delay)
            .close_delay(self.close_delay)
            .trigger(self.trigger)
            .on_open_change(move |open, _window, cx| {
                if *open {
                    opened_for_change.set(motion_now(cx));
                }
            })
            .content(
                move |_state: &mut HoverCardState,
                      window: &mut Window,
                      cx: &mut gpui_kit::Context<'_, HoverCardState>| {
                    let cx: &mut App = cx;
                    let elapsed = (motion_now(cx) - opened_at.get()).max(0.0);
                    let (fade, rise) = card_progress(elapsed, reduced);
                    let tail_settled = row_progress(elapsed, 3, reduced) >= 0.999;
                    if fade < 0.999 || rise < 0.999 || !tail_settled {
                        window.request_animation_frame();
                    }
                    let dy = (1.0 - rise) * TRAVEL_PX * travel_sign(side);
                    let gap_top = if matches!(side, HoverCardSide::Bottom) {
                        OFFSET + dy
                    } else {
                        dy
                    };
                    let gap_bottom = if matches!(side, HoverCardSide::Top) {
                        OFFSET
                    } else {
                        0.0
                    };
                    let inner = content
                        .as_ref()
                        .map(|build| build(elapsed, window, cx))
                        .unwrap_or_else(|| div().into_any_element());

                    let card = div()
                        .id(ElementId::NamedChild(card_id.clone().into(), "card".into()))
                        .role(Role::Tooltip)
                        .test_support()
                        .w(px(CARD_WIDTH))
                        .p(Spacing::S4)
                        .rounded(Radii::PANEL)
                        .border_1()
                        .border_color(colors.border)
                        .bg(colors.surface_raised)
                        .text_color(colors.foreground)
                        .text_size(Typography::TEXT_SM)
                        .shadow(Shadows::floating(theme.mode))
                        .opacity(fade.clamp(0.0, 1.0))
                        .child(inner);

                    div()
                        .id(ElementId::NamedChild(
                            card_id.clone().into(),
                            "card-host".into(),
                        ))
                        .mt(px(gap_top))
                        .mb(px(gap_bottom))
                        .child(card)
                },
            )
    }
}

/// One label/value metric inside [`HoverCardProfile`].
#[derive(Clone, Debug)]
pub struct HoverCardStat {
    pub label: SharedString,
    pub value: SharedString,
}

impl HoverCardStat {
    pub fn new(label: impl Into<SharedString>, value: impl Into<SharedString>) -> Self {
        Self {
            label: label.into(),
            value: value.into(),
        }
    }
}

/// Arc `HoverCardProfile` — person preview (48px avatar, name, role, bio, stats, meta) with
/// staggered row entrance.
#[derive(IntoElement)]
pub struct HoverCardProfile {
    name: SharedString,
    role: Option<SharedString>,
    avatar_src: Option<SharedString>,
    bio: Option<SharedString>,
    stats: Vec<HoverCardStat>,
    meta: Option<SharedString>,
    elapsed: f64,
}

impl HoverCardProfile {
    pub fn new(name: impl Into<SharedString>, elapsed: f64) -> Self {
        Self {
            name: name.into(),
            role: None,
            avatar_src: None,
            bio: None,
            stats: Vec::new(),
            meta: None,
            elapsed,
        }
    }

    pub fn role(mut self, role: impl Into<SharedString>) -> Self {
        self.role = Some(role.into());
        self
    }

    pub fn avatar_src(mut self, src: impl Into<SharedString>) -> Self {
        self.avatar_src = Some(src.into());
        self
    }

    pub fn bio(mut self, bio: impl Into<SharedString>) -> Self {
        self.bio = Some(bio.into());
        self
    }

    pub fn stats(mut self, stats: impl IntoIterator<Item = HoverCardStat>) -> Self {
        self.stats = stats.into_iter().collect();
        self
    }

    pub fn meta(mut self, meta: impl Into<SharedString>) -> Self {
        self.meta = Some(meta.into());
        self
    }
}

impl RenderOnce for HoverCardProfile {
    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
        let colors = cx.arc_theme().colors;
        let reduced = is_reduced_motion(cx);
        let initials = initials_for(&self.name);

        let settle = |order: usize| -> (f32, f32) {
            let p = row_progress(self.elapsed, order, reduced);
            (p.clamp(0.0, 1.0), (1.0 - p) * ROW_RISE_PX)
        };

        let (head_op, head_dy) = settle(0);
        let (bio_op, bio_dy) = settle(1);
        let (stats_op, stats_dy) = settle(2);
        let (meta_op, meta_dy) = settle(3);

        let avatar = div()
            .flex_none()
            .w(px(48.0))
            .h(px(48.0))
            .rounded(Radii::PILL)
            .border_1()
            .border_color(colors.border)
            .bg(colors.surface_muted)
            .text_color(colors.foreground)
            .text_size(Typography::TEXT_SM)
            .font_medium()
            .overflow_hidden()
            .flex()
            .items_center()
            .justify_center()
            .child(if let Some(src) = self.avatar_src {
                img(src)
                    .size_full()
                    .object_fit(ObjectFit::Cover)
                    .into_any_element()
            } else {
                div().child(initials).into_any_element()
            });

        let identity = div()
            .flex()
            .flex_col()
            .min_w_0()
            .child(
                div()
                    .text_size(Typography::TEXT_BASE)
                    .font_medium()
                    .text_color(colors.foreground)
                    .truncate()
                    .child(self.name),
            )
            .when_some(self.role, |this, role| {
                this.child(
                    div()
                        .text_size(Typography::TEXT_SM)
                        .text_color(colors.text_secondary)
                        .truncate()
                        .child(role),
                )
            });

        let head = div()
            .flex()
            .items_center()
            .gap(Spacing::S3)
            .min_w_0()
            .opacity(head_op)
            .mt(px(head_dy))
            .child(avatar)
            .child(identity);

        div()
            .flex()
            .flex_col()
            .gap(Spacing::S3)
            .child(head)
            .when_some(self.bio, |this, bio| {
                this.child(
                    div()
                        .text_size(Typography::TEXT_SM)
                        .line_height(Typography::TEXT_SM * 1.45)
                        .text_color(colors.text_secondary)
                        .opacity(bio_op)
                        .mt(px(bio_dy))
                        .child(bio),
                )
            })
            .when(!self.stats.is_empty(), |this| {
                this.child(
                    div()
                        .pt(Spacing::S3)
                        .border_t_1()
                        .border_color(colors.border_subtle)
                        .flex()
                        .flex_wrap()
                        .gap_x(Spacing::S6)
                        .gap_y(Spacing::S2)
                        .opacity(stats_op)
                        .mt(px(stats_dy))
                        .children(self.stats.into_iter().map(|stat| {
                            // Numbers lead and labels follow, matching `.stat { flex-direction: column-reverse }`.
                            div()
                                .flex()
                                .flex_col()
                                .child(
                                    div()
                                        .text_size(Typography::TEXT_BASE)
                                        .font_medium()
                                        .text_color(colors.foreground)
                                        .child(stat.value),
                                )
                                .child(
                                    div()
                                        .text_size(Typography::TEXT_XS)
                                        .text_color(colors.text_muted)
                                        .child(stat.label),
                                )
                        })),
                )
            })
            .when_some(self.meta, |this, meta| {
                this.child(
                    div()
                        .flex()
                        .items_center()
                        .gap(px(6.0))
                        .text_size(Typography::TEXT_XS)
                        .text_color(colors.text_muted)
                        .opacity(meta_op)
                        .mt(px(meta_dy))
                        .child(meta),
                )
            })
    }
}

#[cfg(test)]
mod tests {
    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
    use gpui_kit::{Context, Render, TestAppContext, div, point, test::TestWindowExt as _};

    use super::*;

    #[test]
    fn card_fade_leads_rise_and_rows_stagger_in_order() {
        let (fade0, rise0) = card_progress(0.0, false);
        assert!(fade0 < 1e-4 && rise0 < 1e-4);

        let (fade_done, rise_mid) = card_progress(CARD_FADE_SECS, false);
        assert!(fade_done > 0.99);
        assert!(rise_mid < 0.99);

        // At t = 90ms row 0 is well underway while row 3 has not started yet (starts at 160ms).
        let r0 = row_progress(0.09, 0, false);
        let r1 = row_progress(0.09, 1, false);
        let r3 = row_progress(0.09, 3, false);
        assert!(r0 > r1 && r1 > 0.0, "r0={r0} r1={r1}");
        assert_eq!(r3, 0.0);

        assert_eq!(card_progress(0.0, true), (1.0, 1.0));
        assert_eq!(row_progress(0.0, 3, true), 1.0);
    }

    struct Host;

    impl Render for Host {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            div().size_full().p(px(40.0)).child(
                ArcHoverCard::new("demo-hover-card", |elapsed, _, _| {
                    HoverCardProfile::new("Elia Kuratli", elapsed)
                        .role("设计系统负责人")
                        .bio("构建 Arc 视觉与动效体系。")
                        .stats([HoverCardStat::new("组件", "129")])
                        .meta("苏黎世 · UTC+1")
                        .into_any_element()
                })
                .open_delay(Duration::from_millis(80))
                .close_delay(Duration::from_millis(60))
                .trigger(
                    div()
                        .id("hover-trigger")
                        .w(px(120.0))
                        .h(px(32.0))
                        .child("@elia"),
                ),
            )
        }
    }

    #[gpui_kit::test]
    fn hover_card_opens_after_delay_with_tooltip_role(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
        });
        let (_view, cx) = cx.add_window_view(|_, _| Host);
        cx.update(|window, cx| {
            window.render_frame(cx);
        });
        cx.simulate_mouse_move(point(px(60.0), px(50.0)), None, Default::default());
        cx.executor().advance_clock(Duration::from_millis(120));
        cx.run_until_parked();
        cx.update(|window, cx| {
            window.render_frame(cx);
            window.render_frame(cx);
            let root: std::sync::Arc<ElementId> = ElementId::from("demo-hover-card").into();
            let card = window.find(ElementId::NamedChild(root, "card".into()));
            assert_eq!(card.role(), Some(Role::Tooltip));
        });
    }
}