A preview card shown while the pointer rests on a trigger.
use std::time::Duration;
use gpui::{div, prelude::*, px, App, FontWeight, Window};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::hover_card::HoverCard;
pub fn hover_card_demo(_window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
HoverCard::new("hover-card-demo")
.open_delay(Duration::from_millis(10))
.close_delay(Duration::from_millis(100))
.trigger(
Button::new("hover-card-demo-trigger", "Hover Here")
.variant(ButtonVariant::Link)
.size(ButtonSize::Sm),
)
.child(
div()
.flex()
.flex_col()
.gap_0p5()
.line_height(px(20.0))
.child(div().font_weight(FontWeight::SEMIBOLD).child("@nextjs"))
.child("The React Framework – created and maintained by @vercel.")
.child(
div()
.mt_1()
.text_xs()
.line_height(px(16.0))
.text_color(theme.muted_foreground)
.child("Joined December 2021"),
),
)
}Installation
Copies src/ui/hover_card.rs into your project, along with any components it depends on, and registers the module in src/ui/mod.rs.
Install the theme
Every component reads colors from
crate::theme. Follow the installation guide if you have not added it yet.Copy the source
Paste the code below into
src/ui/hover_card.rs.src/ui/hover_card.rs use std::time::Duration; use gpui::{ anchored, canvas, deferred, div, point, prelude::*, px, AnyElement, App, Bounds, BoxShadow, Context, DispatchPhase, ElementId, HitboxBehavior, Hsla, MouseExitEvent, MouseMoveEvent, Pixels, Point, ScrollEvent, Size, Task, Window, }; use crate::theme::{ActiveTheme, OverlayHost}; use crate::ui::popover::{animate_overlay, animation_clock, ease, placement, Align, Presence, Side, Transition, SLIDE_IN}; /// Radix's defaults: a deliberate hover opens the card, a brief exit doesn't close it. const OPEN_DELAY: Duration = Duration::from_millis(700); const CLOSE_DELAY: Duration = Duration::from_millis(300); /// How long an opening card waits for a host to grow the frame before showing anyway. const HOST_WAIT: Duration = Duration::from_millis(150); /// shadcn's hover card animates in and out over 100ms (`duration-100`), quicker than a popover. const TRANSITION: Transition = Transition { enter: Duration::from_millis(100), exit: Duration::from_millis(100), easing: ease, }; /// How the card itself looks. #[derive(Clone, Copy, Default, PartialEq)] pub enum HoverCardVariant { /// shadcn's default style: 10px corners, 10px padding, a faint ring in place of a border, /// and a medium shadow. #[default] Default, /// shadcn's Rhea style: 22px corners, a faint ring in place of the border, and a large /// shadow, for cards that float over chat. Rhea, } /// A preview card shown while the pointer rests on a link-like trigger. /// It stays open while the pointer travels from the trigger onto the card. #[derive(IntoElement)] pub struct HoverCard { id: ElementId, trigger: Option<AnyElement>, children: Vec<AnyElement>, side: Side, align: Align, width: Pixels, variant: HoverCardVariant, open_delay: Duration, close_delay: Duration, } /// Hover intent with open/close delays needs a cancellable timer per trigger. That is pointer /// state the app has no reason to own (shadcn leaves hover cards uncontrolled too), so it lives here. #[derive(Default)] struct HoverCardState { trigger_hovered: bool, card_hovered: bool, open: bool, trigger_bounds: Option<Bounds<Pixels>>, pending: Option<Task<()>>, /// Copied from the element on every render, so the latest builder values apply. open_delay: Duration, close_delay: Duration, /// Keeps the card up while it animates out. presence: Presence, /// Whether the card was mounted last frame. visible: bool, /// Where the pointer was when the view last scrolled, to re-check the trigger's hover once /// the scrolled layout is in place. scrolled_at: Option<Point<Pixels>>, /// The window size and time when the card last opened, while it waits for the host to /// grow the frame. opened: Option<(Size<Pixels>, Duration)>, } impl HoverCardState { /// Schedules the open state to follow the pointer after the matching delay. fn sync(&mut self, cx: &mut Context<Self>) { let want = self.trigger_hovered || self.card_hovered; if want == self.open { self.pending = None; return; } let delay = if want { self.open_delay } else { self.close_delay }; // Replacing the task drops, and so cancels, any earlier pending change. self.pending = Some(cx.spawn(async move |this, cx| { cx.background_executor().timer(delay).await; this.update(cx, |state, cx| { state.open = want; cx.notify(); }) .ok(); })); } } impl HoverCard { pub fn new(id: impl Into<ElementId>) -> Self { Self { id: id.into(), trigger: None, children: Vec::new(), side: Side::Bottom, align: Align::Center, width: px(256.0), variant: HoverCardVariant::Default, open_delay: OPEN_DELAY, close_delay: CLOSE_DELAY, } } /// The element that opens the card on hover. pub fn trigger(mut self, trigger: impl IntoElement) -> Self { self.trigger = Some(trigger.into_any_element()); self } pub fn side(mut self, side: Side) -> Self { self.side = side; self } pub fn align(mut self, align: Align) -> Self { self.align = align; self } pub fn width(mut self, width: impl Into<Pixels>) -> Self { self.width = width.into(); self } pub fn variant(mut self, variant: HoverCardVariant) -> Self { self.variant = variant; self } /// How long the pointer must rest on the trigger before the card opens. Defaults to 700ms. pub fn open_delay(mut self, delay: Duration) -> Self { self.open_delay = delay; self } /// How long the card stays open after the pointer leaves it and the trigger. Defaults to /// 300ms; too short and the card closes while the pointer crosses the gap onto it. pub fn close_delay(mut self, delay: Duration) -> Self { self.close_delay = delay; self } } impl ParentElement for HoverCard { fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) { self.children.extend(elements); } } impl RenderOnce for HoverCard { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let state = window.use_keyed_state(self.id.clone(), cx, |_, _| HoverCardState::default()); let (trigger_bounds, frame, marked) = state.update(cx, |state, cx| { state.open_delay = self.open_delay; state.close_delay = self.close_delay; // A host that shows the view in a smaller frame, like the docs previews, grows the // frame to the page while an overlay is up. let hosted = cx.has_global::<OverlayHost>(); // The frame grows a few frames after the card asks for it. Placed before that, the // card would flip away from the small frame's edge and then jump back, so an opening // card waits, unplaced and unpainted, until the window has grown (or briefly, in // case it never does). let now = animation_clock(cx); let viewport = window.viewport_size(); if !state.open { state.opened = None; } else if state.opened.is_none() && !state.visible { state.opened = Some((viewport, now)); } let waiting = state.open && hosted && state.opened.is_some_and(|(size, at)| size == viewport && now.saturating_sub(at) < HOST_WAIT); if !waiting { state.opened = None; } else { window.request_animation_frame(); } let frame = state.presence.update(state.open && !waiting, TRANSITION, window, cx); state.visible = frame.visible(); // Counts as an overlay while waiting too, since that is what grows the frame. let marked = state.trigger_bounds.is_some() && (frame.visible() || waiting); (state.trigger_bounds, frame, marked) }); if marked { crate::theme::mark_overlay(cx); } let theme = cx.theme(); let rhea = self.variant == HoverCardVariant::Rhea; // Rhea's `ring-1 ring-foreground/5` (10% in dark mode) and `shadow-lg`. A ring is a // spread-only shadow, painted under the card's opaque fill. // The default style's `ring-1 ring-foreground/10` and `shadow-md`. let shadows = if rhea { let ring = theme.foreground.opacity(if theme.background.l > 0.5 { 0.05 } else { 0.1 }); vec![ shadow(ring, 0.0, 0.0, 1.0), shadow(gpui::black().opacity(0.1), 10.0, 15.0, -3.0), shadow(gpui::black().opacity(0.1), 4.0, 6.0, -4.0), ] } else { vec![ shadow(theme.foreground.opacity(0.1), 0.0, 0.0, 1.0), shadow(gpui::black().opacity(0.1), 4.0, 6.0, -1.0), shadow(gpui::black().opacity(0.1), 2.0, 4.0, -2.0), ] }; let side = self.side; let card = trigger_bounds.filter(|_| frame.visible()).map(|bounds| { let (anchor, corner, offset) = placement(self.side, self.align); let hover_state = state.clone(); deferred( anchored() .attach(bounds, corner) .anchor(anchor) .offset(offset) .snap_to_window_with_margin(px(8.0)) .child(animate_overlay( div() .id("hover-card-content") .when(frame.opening, |this| this.occlude()) .w(self.width) .bg(theme.background) .text_color(theme.foreground) .text_sm() .map(|this| { if rhea { this.p_4().rounded(px(22.0)) } else { // `rounded-lg`, one step above the theme's radius. this.p(px(10.0)).rounded(theme.radius + px(2.0)) } }) .shadow(shadows) // A card animating out would never report the pointer leaving it // once unmounted, so only an open card tracks hover. .when(frame.opening, |this| { this.on_hover(move |hovered, _, cx| { hover_state.update(cx, |state, cx| { state.card_hovered = *hovered; state.sync(cx); }); }) }) .children(self.children), side, frame, SLIDE_IN, )), ) .with_priority(1) }); // The trigger's hover follows the pointer's moves rather than GPUI's hover, which is // also re-checked when the layout changes. The docs preview grows its frame to the // whole page while the card is up, and until the pointer moves again GPUI still has // its position in the small frame's coordinates, which no longer land on the trigger: // hover would drop, the card close and the frame shrink, over and over. let move_state = state.clone(); let exit_state = state.clone(); let scroll_state = state.clone(); // A hitbox over the trigger that blocks nothing, so another open card on top of the // trigger still hides it from the pointer. let pointer = canvas( |bounds, window, _| window.insert_hitbox(bounds, HitboxBehavior::Normal), move |_, hitbox, window, cx| { // Scrolling can carry the trigger out from under (or into) a still pointer. The // wheel event arrives before the scrolled layout, so it only notes where the // pointer was, and this frame, laid out after the scroll, re-checks. let scrolled_at = scroll_state.update(cx, |state, _| state.scrolled_at.take()); if let Some(position) = scrolled_at { let hovered = hitbox.bounds.contains(&position); scroll_state.update(cx, |state, cx| { if hovered != state.trigger_hovered { state.trigger_hovered = hovered; state.sync(cx); } }); } let scroll_state = scroll_state.clone(); window.on_mouse_event(move |event: &ScrollEvent, phase, window, cx| { if phase != DispatchPhase::Bubble { return; } scroll_state.update(cx, |state, _| state.scrolled_at = Some(event.position)); window.refresh(); }); let move_state = move_state.clone(); window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, cx| { if phase != DispatchPhase::Bubble { return; } let hovered = hitbox.is_hovered_at(event.position, window); move_state.update(cx, |state, cx| { if hovered != state.trigger_hovered { state.trigger_hovered = hovered; state.sync(cx); } }); }); let exit_state = exit_state.clone(); window.on_mouse_event(move |_: &MouseExitEvent, phase, _, cx| { if phase != DispatchPhase::Bubble { return; } exit_state.update(cx, |state, cx| { if state.trigger_hovered { state.trigger_hovered = false; state.sync(cx); } }); }); }, ) .absolute() .top_0() .left_0() .size_full(); let trigger = div().id("hover-card-trigger").children(self.trigger); div() .flex() .on_children_prepainted(move |bounds, _, cx| { state.update(cx, |state, cx| { let first = bounds.first().copied(); if state.trigger_bounds != first { state.trigger_bounds = first; cx.notify(); } }); }) .id(self.id) .child(trigger) .child(pointer) .children(card) } } fn shadow(color: Hsla, offset_y: f32, blur: f32, spread: f32) -> BoxShadow { BoxShadow { color, offset: point(px(0.0), px(offset_y)), blur_radius: px(blur), spread_radius: px(spread), inset: false, } }Register the module
// src/ui/mod.rs pub mod hover_card;
Usage
use crate::ui::hover_card::*;Examples
Basic
A link that previews a profile while the pointer rests on it. The card stays open while you move onto it.
use std::time::Duration;
use gpui::{div, prelude::*, px, App, FontWeight, Window};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::hover_card::HoverCard;
pub fn hover_card_basic(_window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
HoverCard::new("hover-card-basic")
.open_delay(Duration::from_millis(10))
.close_delay(Duration::from_millis(100))
.trigger(
Button::new("hover-card-basic-trigger", "Hover Here")
.variant(ButtonVariant::Link)
.size(ButtonSize::Sm),
)
.child(
div()
.flex()
.flex_col()
.gap_0p5()
.line_height(px(20.0))
.child(div().font_weight(FontWeight::SEMIBOLD).child("@nextjs"))
.child("The React Framework – created and maintained by @vercel.")
.child(
div()
.mt_1()
.text_xs()
.line_height(px(16.0))
.text_color(theme.muted_foreground)
.child("Joined December 2021"),
),
)
}Sides
side opens the card to the left, top, bottom (the default) or right of the trigger. Near a window edge it flips to the side with room.
use std::time::Duration;
use gpui::{div, prelude::*, px, App, FontWeight, Window};
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::hover_card::HoverCard;
use crate::ui::popover::Side;
const SIDES: [(&str, Side); 4] = [("left", Side::Left), ("top", Side::Top), ("bottom", Side::Bottom), ("right", Side::Right)];
pub fn hover_card_sides(_window: &mut Window, _cx: &mut App) -> impl IntoElement {
div().flex().flex_wrap().justify_center().gap_2().children(SIDES.into_iter().enumerate().map(|(ix, (side, placement))| {
// The trigger reads "Left", like shadcn's `capitalize`.
let label = format!("{}{}", side[..1].to_uppercase(), &side[1..]);
HoverCard::new(("hover-card-side", ix))
.side(placement)
.open_delay(Duration::from_millis(100))
.close_delay(Duration::from_millis(100))
.trigger(
Button::new(("hover-card-side-trigger", ix), label)
.variant(ButtonVariant::Outline)
.size(ButtonSize::Sm),
)
.child(
div()
.flex()
.flex_col()
.gap_1()
.line_height(px(20.0))
.child(div().font_weight(FontWeight::MEDIUM).child("Hover Card"))
.child(format!("This hover card appears on the {side} side of the trigger.")),
)
}))
}API Reference
HoverCardVariant
How the card itself looks.
HoverCardVariant::Defaultshadcn's default style: 10px corners, 10px padding, a faint ring in place of a border, and a medium shadow.
HoverCardVariant::Rheashadcn's Rhea style: 22px corners, a faint ring in place of the border, and a large shadow, for cards that float over chat.
HoverCard
A preview card shown while the pointer rests on a link-like trigger. It stays open while the pointer travels from the trigger onto the card.
HoverCard::new(id: impl Into<ElementId>) -> Self.trigger(trigger: impl IntoElement)The element that opens the card on hover.
.side(side: Side).align(align: Align).width(width: impl Into<Pixels>).variant(variant: HoverCardVariant).open_delay(delay: Duration)How long the pointer must rest on the trigger before the card opens. Defaults to 700ms.
.close_delay(delay: Duration)How long the card stays open after the pointer leaves it and the trigger. Defaults to 300ms; too short and the card closes while the pointer crosses the gap onto it.