Skip to main content

arc_ui/overlay/
tooltip.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/tooltip/tooltip.tsx` & `.module.css`
3//!
4//! P3 Component #1: `tooltip`
5//!
6//! - Hovering a trigger for `250ms` opens the bubble; while any tooltip is open, and for `300ms`
7//!   after the last one closes, the next one opens without the wait or the rise (Arc's "warm"
8//!   skip window).
9//! - Enter: `160ms` / `ease.enter` fade with a `3px` rise from the trigger; exit: `120ms` /
10//!   `ease.standard` fade. Instant (warm) shows drop the rise.
11//! - Bubble: `foreground` fill, `background` text, `1px` border mixed 14% toward foreground,
12//!   `control` radius, `raised` shadow, 12/16 padding, 15rem max width.
13//! - Local design: the scale `0.97 → 1` of the enter is dropped (no element transform for
14//!   non-SVG content), the text-swap width spring is omitted, and the delay runs on the motion
15//!   clock so the gallery's 0.25x slow-mo also slows the wait.
16
17use std::{cell::RefCell, rc::Rc};
18
19use arc_motion::{CubicBezier, is_reduced_motion, motion_now};
20use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, Typography, oklab_mix};
21use gpui_kit::{
22    AnyElement, App, Bounds, Context, ElementId, IntoElement, ParentElement, Pixels, Render,
23    RenderOnce, Role, SharedString, Styled, TestSupportExt as _, Window,
24    base::{Placement, TooltipPositioner},
25    canvas, deferred, div,
26    prelude::*,
27    px,
28};
29
30use crate::overlay::with_overlay;
31
32/// Hover time before a cold tooltip appears.
33pub const SHOW_DELAY_SECS: f64 = 0.25;
34/// How long a closed tooltip keeps the next one instant.
35pub const SKIP_WINDOW_SECS: f64 = 0.30;
36/// Enter fade (`duration.fast`) and exit fade (`duration.instant`).
37pub const ENTER_SECS: f64 = 0.16;
38pub const EXIT_SECS: f64 = 0.12;
39/// Gap between trigger and bubble.
40pub const OFFSET: f32 = 8.0;
41/// `15rem` max bubble width.
42pub const MAX_WIDTH: f32 = 240.0;
43
44/// Side of the trigger the bubble prefers (placement flips when it does not fit).
45#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
46pub enum TooltipSide {
47    #[default]
48    Top,
49    Bottom,
50    Left,
51    Right,
52}
53
54impl TooltipSide {
55    const fn placement(self) -> Placement {
56        match self {
57            Self::Top => Placement::Top,
58            Self::Bottom => Placement::Bottom,
59            Self::Left => Placement::Left,
60            Self::Right => Placement::Right,
61        }
62    }
63}
64
65#[derive(Clone)]
66struct Pending {
67    id: String,
68    text: SharedString,
69    side: TooltipSide,
70    bounds: Bounds<Pixels>,
71    due_at: f64,
72    instant: bool,
73}
74
75#[derive(Clone)]
76struct Active {
77    id: String,
78    text: SharedString,
79    side: TooltipSide,
80    bounds: Bounds<Pixels>,
81    shown_at: f64,
82    instant: bool,
83    exit_at: Option<f64>,
84}
85
86/// One visible tooltip as the layer needs to paint it.
87#[derive(Clone, Debug, PartialEq)]
88pub struct TooltipVisual {
89    pub id: String,
90    pub text: SharedString,
91    pub side: TooltipSide,
92    pub bounds: Bounds<Pixels>,
93    /// `0..=1` fade alpha (enter from `shown_at`, exit from `exit_at`).
94    pub alpha: f32,
95    /// `0..=1` rise progress (`1` = settled, no offset).
96    pub rise: f32,
97}
98
99/// Show/hide state machine for the tooltip layer, driven by the motion clock.
100#[derive(Default)]
101pub struct TooltipMachine {
102    pending: Option<Pending>,
103    active: Option<Active>,
104    warm_until: Option<f64>,
105}
106
107impl TooltipMachine {
108    pub fn is_warm(&self, now: f64) -> bool {
109        self.warm_until.map(|until| now < until).unwrap_or(false)
110    }
111
112    /// Pointer entered a trigger.
113    pub fn request(
114        &mut self,
115        id: impl Into<String>,
116        text: impl Into<SharedString>,
117        side: TooltipSide,
118        bounds: Bounds<Pixels>,
119        now: f64,
120    ) {
121        let id = id.into();
122        let text = text.into();
123
124        // Switching between triggers while one is open: swap content in place, no re-rise.
125        if let Some(active) = self.active.as_mut() {
126            if active.id == id {
127                self.pending = None;
128                return;
129            }
130            active.id = id;
131            active.text = text;
132            active.side = side;
133            active.bounds = bounds;
134            active.exit_at = None;
135            self.pending = None;
136            return;
137        }
138
139        let instant = self.is_warm(now);
140        self.pending = Some(Pending {
141            id,
142            text,
143            side,
144            bounds,
145            due_at: now + if instant { 0.0 } else { SHOW_DELAY_SECS },
146            instant,
147        });
148    }
149
150    /// Pointer left the trigger (or the trigger went away).
151    pub fn dismiss(&mut self, id: &str, now: f64) {
152        if self.pending.as_ref().map(|p| p.id == id).unwrap_or(false) {
153            self.pending = None;
154        }
155        if let Some(active) = self.active.as_mut()
156            && active.id == id
157            && active.exit_at.is_none()
158        {
159            active.exit_at = Some(now);
160            self.warm_until = Some(now + EXIT_SECS + SKIP_WINDOW_SECS);
161        }
162    }
163
164    /// Advances deadlines; returns `true` while more frames are needed.
165    pub fn tick(&mut self, now: f64) -> bool {
166        if let Some(pending) = self.pending.clone()
167            && now >= pending.due_at
168        {
169            self.pending = None;
170            self.active = Some(Active {
171                id: pending.id,
172                text: pending.text,
173                side: pending.side,
174                bounds: pending.bounds,
175                shown_at: pending.due_at.min(now),
176                instant: pending.instant,
177                exit_at: None,
178            });
179        }
180
181        if let Some(active) = self.active.as_ref()
182            && let Some(exit_at) = active.exit_at
183            && now >= exit_at + EXIT_SECS
184        {
185            self.active = None;
186        }
187
188        let mut needs_frames = self.pending.is_some();
189        if let Some(active) = self.active.as_ref() {
190            needs_frames |= match active.exit_at {
191                Some(exit_at) => now < exit_at + EXIT_SECS,
192                None => {
193                    let enter_secs = if active.instant {
194                        EXIT_SECS
195                    } else {
196                        ENTER_SECS
197                    };
198                    now < active.shown_at + enter_secs
199                }
200            };
201        }
202        needs_frames
203    }
204
205    /// Current paint state, if any.
206    pub fn visual(&self, now: f64, reduced: bool) -> Option<TooltipVisual> {
207        let active = self.active.as_ref()?;
208        let enter_secs = if active.instant {
209            EXIT_SECS
210        } else {
211            ENTER_SECS
212        };
213        let (alpha, rise) = match active.exit_at {
214            Some(exit_at) => {
215                let t = ((now - exit_at) / EXIT_SECS).clamp(0.0, 1.0) as f32;
216                let eased = CubicBezier::new(0.22, 1.0, 0.36, 1.0).sample(t);
217                (1.0 - eased, 1.0)
218            }
219            None => {
220                if reduced {
221                    (1.0, 1.0)
222                } else {
223                    let t = ((now - active.shown_at) / enter_secs).clamp(0.0, 1.0) as f32;
224                    let eased = CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(t);
225                    (eased, eased)
226                }
227            }
228        };
229        Some(TooltipVisual {
230            id: active.id.clone(),
231            text: active.text.clone(),
232            side: active.side,
233            bounds: active.bounds,
234            alpha,
235            rise,
236        })
237    }
238
239    #[cfg(test)]
240    fn active_id(&self) -> Option<&str> {
241        self.active.as_ref().map(|a| a.id.as_str())
242    }
243}
244
245/// Window-level layer that draws every Arc tooltip (registered as a root plugin).
246pub struct ArcOverlay {
247    machine: TooltipMachine,
248}
249
250impl ArcOverlay {
251    pub fn new(_window: &mut Window, _cx: &mut Context<Self>) -> Self {
252        Self {
253            machine: TooltipMachine::default(),
254        }
255    }
256
257    pub fn request_tooltip(
258        &mut self,
259        id: impl Into<String>,
260        text: impl Into<SharedString>,
261        side: TooltipSide,
262        bounds: Bounds<Pixels>,
263        cx: &mut Context<Self>,
264    ) {
265        let now = motion_now(cx);
266        self.machine.request(id, text, side, bounds, now);
267        cx.notify();
268    }
269
270    pub fn dismiss_tooltip(&mut self, id: &str, cx: &mut Context<Self>) {
271        let now = motion_now(cx);
272        self.machine.dismiss(id, now);
273        cx.notify();
274    }
275
276    /// Test/diagnostic hook: the id of the tooltip currently painted.
277    pub fn active_tooltip(&self) -> Option<&str> {
278        self.machine.active.as_ref().map(|a| a.id.as_str())
279    }
280}
281
282impl gpui_kit::base::RootPlugin for ArcOverlay {}
283
284impl Render for ArcOverlay {
285    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
286        let now = motion_now(cx);
287        let reduced = is_reduced_motion(cx);
288        if self.machine.tick(now) {
289            window.request_animation_frame();
290        }
291
292        let Some(visual) = self.machine.visual(now, reduced) else {
293            return div().absolute().inset_0().into_any_element();
294        };
295
296        let theme = cx.arc_theme().clone();
297        let colors = theme.colors;
298        let direction = match visual.side {
299            TooltipSide::Top => 1.0,
300            TooltipSide::Bottom => -1.0,
301            TooltipSide::Left | TooltipSide::Right => 0.0,
302        };
303        let dy = (1.0 - visual.rise) * 3.0 * direction;
304
305        let bubble = div()
306            .id(ElementId::Name(SharedString::from(format!(
307                "arc-tooltip-{}",
308                visual.id
309            ))))
310            .max_w(px(MAX_WIDTH))
311            .px(Spacing::S4)
312            .py(Spacing::S3)
313            .rounded(Radii::CONTROL)
314            .border_1()
315            .border_color(oklab_mix(colors.background, colors.foreground, 0.14))
316            .bg(colors.foreground)
317            .text_color(colors.background)
318            .shadow(Shadows::raised(theme.mode))
319            .text_size(Typography::TEXT_SM)
320            .line_height(Typography::TEXT_SM * 1.4)
321            .opacity(visual.alpha.clamp(0.0, 1.0))
322            .mt(px(dy))
323            .role(Role::Tooltip)
324            .test_support()
325            .aria_label(visual.text.clone())
326            .child(visual.text.clone());
327
328        div()
329            .absolute()
330            .inset_0()
331            .child(deferred(
332                div()
333                    .absolute()
334                    .inset_0()
335                    .child(
336                        TooltipPositioner::new(visual.bounds)
337                            .placement(visual.side.placement())
338                            .offset(px(OFFSET))
339                            .child(bubble),
340                    )
341                    .into_any_element(),
342            ))
343            .into_any_element()
344    }
345}
346
347/// Hover target for [`ArcOverlay`]'s tooltip.
348#[derive(IntoElement)]
349pub struct ArcTooltip {
350    id: ElementId,
351    text: SharedString,
352    side: TooltipSide,
353    child: AnyElement,
354    bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
355}
356
357impl ArcTooltip {
358    pub fn new(id: impl Into<ElementId>, text: impl Into<SharedString>) -> Self {
359        Self {
360            id: id.into(),
361            text: text.into(),
362            side: TooltipSide::Top,
363            child: div().into_any_element(),
364            bounds: Rc::new(RefCell::new(None)),
365        }
366    }
367
368    pub fn side(mut self, side: TooltipSide) -> Self {
369        self.side = side;
370        self
371    }
372
373    pub fn child(mut self, child: impl IntoElement) -> Self {
374        self.child = child.into_any_element();
375        self
376    }
377}
378
379impl RenderOnce for ArcTooltip {
380    fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
381        let measure = self.bounds.clone();
382        let hover_bounds = self.bounds.clone();
383        let probe = canvas(
384            move |rect, _, _| {
385                *measure.borrow_mut() = Some(rect);
386            },
387            |_, _, _, _| {},
388        )
389        .absolute()
390        .inset_0();
391
392        let key = format!("{:?}", self.id);
393        let text = self.text.clone();
394        let side = self.side;
395
396        div()
397            .id(self.id)
398            .relative()
399            .child(probe)
400            .child(self.child)
401            .on_hover(move |hovered, window, cx| {
402                let Some(bounds) = *hover_bounds.borrow() else {
403                    return;
404                };
405                if *hovered {
406                    with_overlay(window, cx, |overlay, cx| {
407                        overlay.request_tooltip(key.clone(), text.clone(), side, bounds, cx);
408                    });
409                } else {
410                    with_overlay(window, cx, |overlay, cx| {
411                        overlay.dismiss_tooltip(&key, cx);
412                    });
413                }
414            })
415    }
416}
417
418#[cfg(test)]
419mod tests {
420    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
421    use gpui_kit::{
422        Render, Styled, TestAppContext, bounds, div, point, px, size,
423        test::{TestQueryExt as _, TestWindowExt as _},
424    };
425
426    use super::*;
427
428    fn trigger() -> Bounds<Pixels> {
429        bounds(point(px(40.0), px(60.0)), size(px(80.0), px(28.0)))
430    }
431
432    #[test]
433    fn first_tooltip_waits_250ms_then_rises() {
434        let mut m = TooltipMachine::default();
435        m.request("a", "保存", TooltipSide::Top, trigger(), 0.0);
436
437        assert!(m.tick(0.1), "still waiting, but frames are needed");
438        assert_eq!(m.active_id(), None);
439        assert!(m.tick(0.26), "the enter animation needs frames");
440        assert_eq!(m.active_id(), Some("a"));
441
442        let early = m.visual(0.26, false).expect("visible");
443        assert!(
444            early.alpha > 0.0 && early.alpha < 0.6,
445            "fades in from transparent: {}",
446            early.alpha
447        );
448        let settled = m.visual(0.26 + ENTER_SECS, false).expect("visible");
449        assert!(settled.alpha > 0.99 && settled.rise > 0.99);
450    }
451
452    #[test]
453    fn warm_window_skips_the_delay_and_the_rise() {
454        let mut m = TooltipMachine::default();
455        m.request("a", "保存", TooltipSide::Top, trigger(), 0.0);
456        m.tick(0.26);
457        m.dismiss("a", 0.30);
458        m.tick(0.30 + EXIT_SECS);
459        assert_eq!(m.active_id(), None);
460        assert!(m.is_warm(0.50), "warm right after closing");
461
462        // A second trigger inside the skip window appears on the same tick.
463        m.request("b", "删除", TooltipSide::Bottom, trigger(), 0.50);
464        m.tick(0.50);
465        assert_eq!(m.active_id(), Some("b"));
466        let visual = m.visual(0.50, false).expect("visible");
467        assert_eq!(
468            visual.rise, 0.0,
469            "instant shows keep the 3px rise at 0 progress"
470        );
471    }
472
473    #[test]
474    fn exit_fades_out_then_expires() {
475        let mut m = TooltipMachine::default();
476        m.request("a", "保存", TooltipSide::Top, trigger(), 0.0);
477        m.tick(0.26);
478        let shown = m.visual(0.45, false).expect("visible");
479        assert!(shown.alpha > 0.99);
480
481        m.dismiss("a", 0.45);
482        // `ease.standard` is front-loaded, so the bubble is mostly gone halfway through the exit.
483        let fading = m.visual(0.45 + EXIT_SECS * 0.5, false).expect("fading");
484        assert!(fading.alpha > 0.0 && fading.alpha < 0.3, "{}", fading.alpha);
485        assert!(!m.tick(0.45 + EXIT_SECS + 0.001));
486        assert_eq!(m.active_id(), None);
487    }
488
489    #[test]
490    fn reduced_motion_shows_without_a_rise() {
491        let mut m = TooltipMachine::default();
492        m.request("a", "保存", TooltipSide::Top, trigger(), 0.0);
493        m.tick(0.26);
494        let visual = m.visual(0.26, true).expect("visible");
495        assert_eq!(visual.alpha, 1.0);
496        assert_eq!(visual.rise, 1.0);
497    }
498
499    struct OverlayHost {
500        overlay: gpui_kit::Entity<ArcOverlay>,
501    }
502
503    impl Render for OverlayHost {
504        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
505            div().size_full().child(self.overlay.clone())
506        }
507    }
508
509    #[gpui_kit::test]
510    fn wrapper_hover_fires_when_the_pointer_is_over_a_child_button(cx: &mut TestAppContext) {
511        use std::cell::Cell;
512
513        struct Probe {
514            hits: std::rc::Rc<Cell<usize>>,
515        }
516
517        impl Render for Probe {
518            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
519                let hits = self.hits.clone();
520                div()
521                    .id("wrap")
522                    .w(px(240.0))
523                    .h(px(80.0))
524                    .p(px(8.0))
525                    .on_hover(move |hovered, _, _| {
526                        if *hovered {
527                            hits.set(hits.get() + 1);
528                        }
529                    })
530                    .child(
531                        gpui_kit::base::Button::new("inner")
532                            .w(px(120.0))
533                            .h(px(40.0))
534                            .child("inner"),
535                    )
536            }
537        }
538
539        cx.update(|cx| {
540            gpui_kit::init(cx);
541            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
542        });
543        let hits = std::rc::Rc::new(Cell::new(0));
544        let (_view, cx) = cx.add_window_view(|_, _| Probe { hits: hits.clone() });
545        cx.update(|window, cx| {
546            window.render_frame(cx);
547            window.hover("inner", cx);
548            window.render_frame(cx);
549        });
550        assert!(
551            hits.get() > 0,
552            "a wrapper's on_hover must still fire over a child button"
553        );
554    }
555
556    #[gpui_kit::test]
557    fn overlay_layer_paints_the_bubble_with_the_tooltip_role(cx: &mut TestAppContext) {
558        cx.update(|cx| {
559            gpui_kit::init(cx);
560            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
561        });
562        let overlay = cx.update(|cx| {
563            cx.new(|_| ArcOverlay {
564                machine: TooltipMachine::default(),
565            })
566        });
567        let (_view, cx) = cx.add_window_view(|_, _| OverlayHost {
568            overlay: overlay.clone(),
569        });
570        cx.update(|window, cx| {
571            overlay.update(cx, |overlay, cx| {
572                overlay.request_tooltip("hit", "保存更改", TooltipSide::Top, trigger(), cx);
573            });
574            window.render_frame(cx);
575        });
576        cx.executor()
577            .advance_clock(std::time::Duration::from_millis(400));
578        cx.update(|window, cx| {
579            window.render_frame(cx);
580            window.render_frame(cx);
581            assert_eq!(window.find_by_label("保存更改").role(), Some(Role::Tooltip));
582        });
583    }
584}