use std::{cell::RefCell, rc::Rc};
use arc_motion::{CubicBezier, is_reduced_motion, motion_now};
use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, Typography, oklab_mix};
use gpui_kit::{
AnyElement, App, Bounds, Context, ElementId, IntoElement, ParentElement, Pixels, Render,
RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window,
base::{Placement, TooltipPositioner},
canvas, deferred, div,
prelude::*,
px,
};
use crate::overlay::with_overlay;
pub const SHOW_DELAY_SECS: f64 = 0.25;
pub const SKIP_WINDOW_SECS: f64 = 0.30;
pub const ENTER_SECS: f64 = 0.16;
pub const EXIT_SECS: f64 = 0.12;
pub const OFFSET: f32 = 8.0;
pub const MAX_WIDTH: f32 = 240.0;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum TooltipSide {
#[default]
Top,
Bottom,
Left,
Right,
}
impl TooltipSide {
const fn placement(self) -> Placement {
match self {
Self::Top => Placement::Top,
Self::Bottom => Placement::Bottom,
Self::Left => Placement::Left,
Self::Right => Placement::Right,
}
}
}
#[derive(Clone)]
struct Pending {
id: String,
text: SharedString,
side: TooltipSide,
bounds: Bounds<Pixels>,
due_at: f64,
instant: bool,
}
#[derive(Clone)]
struct Active {
id: String,
text: SharedString,
side: TooltipSide,
bounds: Bounds<Pixels>,
shown_at: f64,
instant: bool,
exit_at: Option<f64>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct TooltipVisual {
pub id: String,
pub text: SharedString,
pub side: TooltipSide,
pub bounds: Bounds<Pixels>,
pub alpha: f32,
pub rise: f32,
}
#[derive(Default)]
pub struct TooltipMachine {
pending: Option<Pending>,
active: Option<Active>,
warm_until: Option<f64>,
}
impl TooltipMachine {
pub fn is_warm(&self, now: f64) -> bool {
self.warm_until.map(|until| now < until).unwrap_or(false)
}
pub fn request(
&mut self,
id: impl Into<String>,
text: impl Into<SharedString>,
side: TooltipSide,
bounds: Bounds<Pixels>,
now: f64,
) {
let id = id.into();
let text = text.into();
if let Some(active) = self.active.as_mut() {
if active.id == id {
self.pending = None;
return;
}
active.id = id;
active.text = text;
active.side = side;
active.bounds = bounds;
active.exit_at = None;
self.pending = None;
return;
}
let instant = self.is_warm(now);
self.pending = Some(Pending {
id,
text,
side,
bounds,
due_at: now + if instant { 0.0 } else { SHOW_DELAY_SECS },
instant,
});
}
pub fn dismiss(&mut self, id: &str, now: f64) {
if self.pending.as_ref().map(|p| p.id == id).unwrap_or(false) {
self.pending = None;
}
if let Some(active) = self.active.as_mut()
&& active.id == id
&& active.exit_at.is_none()
{
active.exit_at = Some(now);
self.warm_until = Some(now + EXIT_SECS + SKIP_WINDOW_SECS);
}
}
pub fn tick(&mut self, now: f64) -> bool {
if let Some(pending) = self.pending.clone()
&& now >= pending.due_at
{
self.pending = None;
self.active = Some(Active {
id: pending.id,
text: pending.text,
side: pending.side,
bounds: pending.bounds,
shown_at: pending.due_at.min(now),
instant: pending.instant,
exit_at: None,
});
}
if let Some(active) = self.active.as_ref()
&& let Some(exit_at) = active.exit_at
&& now >= exit_at + EXIT_SECS
{
self.active = None;
}
let mut needs_frames = self.pending.is_some();
if let Some(active) = self.active.as_ref() {
needs_frames |= match active.exit_at {
Some(exit_at) => now < exit_at + EXIT_SECS,
None => {
let enter_secs = if active.instant {
EXIT_SECS
} else {
ENTER_SECS
};
now < active.shown_at + enter_secs
}
};
}
needs_frames
}
pub fn visual(&self, now: f64, reduced: bool) -> Option<TooltipVisual> {
let active = self.active.as_ref()?;
let enter_secs = if active.instant {
EXIT_SECS
} else {
ENTER_SECS
};
let (alpha, rise) = match active.exit_at {
Some(exit_at) => {
let t = ((now - exit_at) / EXIT_SECS).clamp(0.0, 1.0) as f32;
let eased = CubicBezier::new(0.22, 1.0, 0.36, 1.0).sample(t);
(1.0 - eased, 1.0)
}
None => {
if reduced {
(1.0, 1.0)
} else {
let t = ((now - active.shown_at) / enter_secs).clamp(0.0, 1.0) as f32;
let eased = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t);
(eased, eased)
}
}
};
Some(TooltipVisual {
id: active.id.clone(),
text: active.text.clone(),
side: active.side,
bounds: active.bounds,
alpha,
rise,
})
}
#[cfg(test)]
fn active_id(&self) -> Option<&str> {
self.active.as_ref().map(|a| a.id.as_str())
}
}
pub struct ArcOverlay {
machine: TooltipMachine,
}
impl ArcOverlay {
pub fn new(_window: &mut Window, _cx: &mut Context<Self>) -> Self {
Self {
machine: TooltipMachine::default(),
}
}
pub fn request_tooltip(
&mut self,
id: impl Into<String>,
text: impl Into<SharedString>,
side: TooltipSide,
bounds: Bounds<Pixels>,
cx: &mut Context<Self>,
) {
let now = motion_now(cx);
self.machine.request(id, text, side, bounds, now);
cx.notify();
}
pub fn dismiss_tooltip(&mut self, id: &str, cx: &mut Context<Self>) {
let now = motion_now(cx);
self.machine.dismiss(id, now);
cx.notify();
}
pub fn active_tooltip(&self) -> Option<&str> {
self.machine.active.as_ref().map(|a| a.id.as_str())
}
}
impl gpui_kit::base::RootPlugin for ArcOverlay {}
impl Render for ArcOverlay {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let now = motion_now(cx);
let reduced = is_reduced_motion(cx);
if self.machine.tick(now) {
window.request_animation_frame();
}
let Some(visual) = self.machine.visual(now, reduced) else {
return div().absolute().inset_0().into_any_element();
};
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let direction = match visual.side {
TooltipSide::Top => 1.0,
TooltipSide::Bottom => -1.0,
TooltipSide::Left | TooltipSide::Right => 0.0,
};
let dy = (1.0 - visual.rise) * 3.0 * direction;
let bubble = div()
.id(ElementId::Name(SharedString::from(format!(
"arc-tooltip-{}",
visual.id
))))
.max_w(px(MAX_WIDTH))
.px(Spacing::S4)
.py(Spacing::S3)
.rounded(Radii::CONTROL)
.border_1()
.border_color(oklab_mix(colors.background, colors.foreground, 0.14))
.bg(colors.foreground)
.text_color(colors.background)
.shadow(Shadows::raised(theme.mode))
.text_size(Typography::TEXT_SM)
.line_height(Typography::TEXT_SM * 1.4)
.opacity(visual.alpha.clamp(0.0, 1.0))
.mt(px(dy))
.role(Role::Tooltip)
.test_support()
.aria_label(visual.text.clone())
.child(visual.text.clone());
div()
.absolute()
.inset_0()
.child(deferred(
div()
.absolute()
.inset_0()
.child(
TooltipPositioner::new(visual.bounds)
.placement(visual.side.placement())
.offset(px(OFFSET))
.child(bubble),
)
.into_any_element(),
))
.into_any_element()
}
}
#[derive(IntoElement)]
pub struct ArcTooltip {
id: ElementId,
text: SharedString,
side: TooltipSide,
child: AnyElement,
bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
}
impl ArcTooltip {
pub fn new(id: impl Into<ElementId>, text: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
text: text.into(),
side: TooltipSide::Top,
child: div().into_any_element(),
bounds: Rc::new(RefCell::new(None)),
}
}
pub fn side(mut self, side: TooltipSide) -> Self {
self.side = side;
self
}
pub fn child(mut self, child: impl IntoElement) -> Self {
self.child = child.into_any_element();
self
}
}
impl RenderOnce for ArcTooltip {
fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
let measure = self.bounds.clone();
let hover_bounds = self.bounds.clone();
let probe = canvas(
move |rect, _, _| {
*measure.borrow_mut() = Some(rect);
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
let key = format!("{:?}", self.id);
let text = self.text.clone();
let side = self.side;
div()
.id(self.id)
.relative()
.child(probe)
.child(self.child)
.on_hover(move |hovered, window, cx| {
let Some(bounds) = *hover_bounds.borrow() else {
return;
};
if *hovered {
with_overlay(window, cx, |overlay, cx| {
overlay.request_tooltip(key.clone(), text.clone(), side, bounds, cx);
});
} else {
with_overlay(window, cx, |overlay, cx| {
overlay.dismiss_tooltip(&key, cx);
});
}
})
}
}
#[cfg(test)]
mod tests {
use arc_tokens::{Accent, ThemeMode, install_arc_theme};
use gpui_kit::{
Render, Styled, TestAppContext, bounds, div, point, px, size,
test::{TestQueryExt as _, TestWindowExt as _},
};
use super::*;
fn trigger() -> Bounds<Pixels> {
bounds(point(px(40.0), px(60.0)), size(px(80.0), px(28.0)))
}
#[test]
fn first_tooltip_waits_250ms_then_rises() {
let mut m = TooltipMachine::default();
m.request("a", "保存", TooltipSide::Top, trigger(), 0.0);
assert!(m.tick(0.1), "still waiting, but frames are needed");
assert_eq!(m.active_id(), None);
assert!(m.tick(0.26), "the enter animation needs frames");
assert_eq!(m.active_id(), Some("a"));
let early = m.visual(0.26, false).expect("visible");
assert!(
early.alpha > 0.0 && early.alpha < 0.6,
"fades in from transparent: {}",
early.alpha
);
let settled = m.visual(0.26 + ENTER_SECS, false).expect("visible");
assert!(settled.alpha > 0.99 && settled.rise > 0.99);
}
#[test]
fn warm_window_skips_the_delay_and_the_rise() {
let mut m = TooltipMachine::default();
m.request("a", "保存", TooltipSide::Top, trigger(), 0.0);
m.tick(0.26);
m.dismiss("a", 0.30);
m.tick(0.30 + EXIT_SECS);
assert_eq!(m.active_id(), None);
assert!(m.is_warm(0.50), "warm right after closing");
m.request("b", "删除", TooltipSide::Bottom, trigger(), 0.50);
m.tick(0.50);
assert_eq!(m.active_id(), Some("b"));
let visual = m.visual(0.50, false).expect("visible");
assert_eq!(
visual.rise, 0.0,
"instant shows keep the 3px rise at 0 progress"
);
}
#[test]
fn exit_fades_out_then_expires() {
let mut m = TooltipMachine::default();
m.request("a", "保存", TooltipSide::Top, trigger(), 0.0);
m.tick(0.26);
let shown = m.visual(0.45, false).expect("visible");
assert!(shown.alpha > 0.99);
m.dismiss("a", 0.45);
let fading = m.visual(0.45 + EXIT_SECS * 0.5, false).expect("fading");
assert!(fading.alpha > 0.0 && fading.alpha < 0.3, "{}", fading.alpha);
assert!(!m.tick(0.45 + EXIT_SECS + 0.001));
assert_eq!(m.active_id(), None);
}
#[test]
fn reduced_motion_shows_without_a_rise() {
let mut m = TooltipMachine::default();
m.request("a", "保存", TooltipSide::Top, trigger(), 0.0);
m.tick(0.26);
let visual = m.visual(0.26, true).expect("visible");
assert_eq!(visual.alpha, 1.0);
assert_eq!(visual.rise, 1.0);
}
struct OverlayHost {
overlay: gpui_kit::Entity<ArcOverlay>,
}
impl Render for OverlayHost {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div().size_full().child(self.overlay.clone())
}
}
#[gpui_kit::test]
fn wrapper_hover_fires_when_the_pointer_is_over_a_child_button(cx: &mut TestAppContext) {
use std::cell::Cell;
struct Probe {
hits: std::rc::Rc<Cell<usize>>,
}
impl Render for Probe {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
let hits = self.hits.clone();
div()
.id("wrap")
.w(px(240.0))
.h(px(80.0))
.p(px(8.0))
.on_hover(move |hovered, _, _| {
if *hovered {
hits.set(hits.get() + 1);
}
})
.child(
gpui_kit::base::Button::new("inner")
.w(px(120.0))
.h(px(40.0))
.child("inner"),
)
}
}
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
});
let hits = std::rc::Rc::new(Cell::new(0));
let (_view, cx) = cx.add_window_view(|_, _| Probe { hits: hits.clone() });
cx.update(|window, cx| {
window.render_frame(cx);
window.hover("inner", cx);
window.render_frame(cx);
});
assert!(
hits.get() > 0,
"a wrapper's on_hover must still fire over a child button"
);
}
#[gpui_kit::test]
fn overlay_layer_paints_the_bubble_with_the_tooltip_role(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
});
let overlay = cx.update(|cx| {
cx.new(|_| ArcOverlay {
machine: TooltipMachine::default(),
})
});
let (_view, cx) = cx.add_window_view(|_, _| OverlayHost {
overlay: overlay.clone(),
});
cx.update(|window, cx| {
overlay.update(cx, |overlay, cx| {
overlay.request_tooltip("hit", "保存更改", TooltipSide::Top, trigger(), cx);
});
window.render_frame(cx);
});
cx.executor()
.advance_clock(std::time::Duration::from_millis(400));
cx.update(|window, cx| {
window.render_frame(cx);
window.render_frame(cx);
assert_eq!(window.find_by_label("保存更改").role(), Some(Role::Tooltip));
});
}
}