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;
pub const OPEN_DELAY_SECS: f64 = 0.50;
pub const CLOSE_DELAY_SECS: f64 = 0.14;
pub const OFFSET: f32 = 8.0;
pub const CARD_WIDTH: f32 = 296.0;
pub const TRAVEL_PX: f32 = 4.0;
pub const CARD_FADE_SECS: f64 = 0.16;
pub const CARD_RISE_SECS: f64 = 0.34;
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;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum HoverCardSide {
Top,
#[default]
Bottom,
Left,
Right,
}
#[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,
}
}
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))
}
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>;
#[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)
},
)
}
}
#[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(),
}
}
}
#[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| {
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);
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));
});
}
}