Skip to main content

gpui_material_components/overlay/tooltip/
interaction.rs

1use std::time::Duration;
2
3use gpui::{App, Context, Entity, EntityId, FocusHandle, Subscription, Task, Window};
4
5use super::TooltipCallback;
6
7/// Visibility retained by the owner of a persistent rich tooltip.
8#[derive(Default)]
9pub struct TooltipState {
10    visible: bool,
11}
12
13impl TooltipState {
14    /// Creates a hidden tooltip visibility state.
15    pub fn new() -> Self {
16        Self::default()
17    }
18
19    /// Returns the requested visibility.
20    pub fn is_visible(&self) -> bool {
21        self.visible
22    }
23
24    /// Requests that the tooltip be shown and notifies observers if visibility changed.
25    pub fn show(&mut self, cx: &mut Context<Self>) {
26        self.set_visible(true, cx);
27    }
28
29    /// Requests that the tooltip be hidden and notifies observers if visibility changed.
30    pub fn dismiss(&mut self, cx: &mut Context<Self>) {
31        self.set_visible(false, cx);
32    }
33
34    fn set_visible(&mut self, visible: bool, cx: &mut Context<Self>) {
35        if self.visible != visible {
36            self.visible = visible;
37            cx.notify();
38        }
39    }
40}
41
42pub(super) struct Interaction {
43    open: bool,
44    trigger_hover: bool,
45    surface_hover: bool,
46    keyboard: bool,
47    suppress_focus: bool,
48    surface_focus: bool,
49    transient: bool,
50    task: Option<Task<()>>,
51    trigger: Option<(FocusHandle, [Subscription; 2])>,
52    visibility: Option<(EntityId, Subscription)>,
53    pub(super) surface: FocusHandle,
54    _surface_tracking: [Subscription; 2],
55    presented: bool,
56    previous_focus: Option<FocusHandle>,
57    pub(super) pressed: bool,
58    show_delay: Duration,
59    hide_delay: Duration,
60}
61
62impl Interaction {
63    pub(super) fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
64        let surface = cx.focus_handle().tab_stop(false);
65        let enter = cx.weak_entity();
66        let leave = enter.clone();
67        let on_enter = window.on_focus_in(&surface, cx, move |window, cx| {
68            let _ = enter.update(cx, |state, cx| {
69                state.surface_focus = true;
70                state.schedule(window, cx);
71            });
72        });
73        let on_leave = window.on_focus_out(&surface, cx, move |_, window, cx| {
74            let _ = leave.update(cx, |state, cx| {
75                state.surface_focus = false;
76                state.schedule(window, cx);
77            });
78        });
79        Self {
80            open: false,
81            trigger_hover: false,
82            surface_hover: false,
83            keyboard: false,
84            suppress_focus: false,
85            surface_focus: false,
86            transient: false,
87            task: None,
88            trigger: None,
89            visibility: None,
90            surface,
91            _surface_tracking: [on_enter, on_leave],
92            presented: false,
93            previous_focus: None,
94            pressed: false,
95            show_delay: Duration::from_millis(500),
96            hide_delay: Duration::from_millis(200),
97        }
98    }
99
100    pub(super) fn configure(
101        &mut self,
102        transient: bool,
103        delays: (Duration, Duration),
104        trigger: Option<&FocusHandle>,
105        visibility: Option<&Entity<TooltipState>>,
106        window: &mut Window,
107        cx: &mut Context<Self>,
108    ) {
109        (self.show_delay, self.hide_delay) = delays;
110        if self.transient != transient {
111            self.transient = transient;
112            self.open = false;
113            self.task = None;
114            self.trigger_hover = false;
115            self.surface_hover = false;
116            self.keyboard = false;
117        }
118        let tracked = trigger.filter(|_| transient);
119        if self.trigger.as_ref().map(|(focus, _)| focus) != tracked {
120            self.trigger = tracked.map(|focus| {
121                let enter = cx.weak_entity();
122                let leave = enter.clone();
123                let on_enter = window.on_focus_in(focus, cx, move |window, cx| {
124                    let _ = enter.update(cx, |state, cx| {
125                        state.keyboard = !state.suppress_focus;
126                        state.schedule(window, cx);
127                    });
128                });
129                let on_leave = window.on_focus_out(focus, cx, move |_, window, cx| {
130                    let _ = leave.update(cx, |state, cx| {
131                        state.keyboard = false;
132                        state.suppress_focus = false;
133                        state.schedule(window, cx);
134                    });
135                });
136                self.keyboard = focus.contains_focused(window, cx);
137                (focus.clone(), [on_enter, on_leave])
138            });
139            if tracked.is_none() {
140                self.keyboard = false;
141            }
142        }
143        if self.visibility.as_ref().map(|(id, _)| *id) != visibility.map(Entity::entity_id) {
144            self.visibility = visibility.map(|state| {
145                (
146                    state.entity_id(),
147                    window.observe(state, cx, |_, window, _| window.refresh()),
148                )
149            });
150        }
151    }
152
153    pub(super) fn hover(
154        &mut self,
155        surface: bool,
156        hovering: bool,
157        window: &mut Window,
158        cx: &mut Context<Self>,
159    ) {
160        if surface {
161            self.surface_hover = hovering;
162        } else {
163            self.trigger_hover = hovering;
164        }
165        self.schedule(window, cx);
166    }
167
168    fn schedule(&mut self, window: &mut Window, cx: &mut Context<Self>) {
169        if !self.transient {
170            return;
171        }
172        let open = self.trigger_hover || self.surface_hover || self.keyboard || self.surface_focus;
173        self.task = None;
174        if open == self.open {
175            return;
176        }
177        if self.keyboard && open {
178            self.open = true;
179            window.refresh();
180            return;
181        }
182        let delay = if open {
183            self.show_delay
184        } else {
185            self.hide_delay
186        };
187        self.task = Some(cx.spawn_in(window, async move |state, cx| {
188            cx.background_executor().timer(delay).await;
189            let _ = state.update_in(cx, |state, window, _| {
190                state.task = None;
191                state.open = open;
192                window.refresh();
193            });
194        }));
195    }
196
197    pub(super) fn is_open(&self, window: &Window, cx: &App) -> bool {
198        self.transient
199            && (self.open
200                || self.keyboard
201                || !self.suppress_focus
202                    && (self.surface.contains_focused(window, cx)
203                        || self
204                            .trigger
205                            .as_ref()
206                            .is_some_and(|(trigger, _)| trigger.is_focused(window))))
207    }
208
209    fn dismiss(&mut self, window: &mut Window) {
210        let changed = self.open
211            || self.task.is_some()
212            || self.trigger_hover
213            || self.surface_hover
214            || self.keyboard
215            || self.surface_focus
216            || !self.suppress_focus;
217        self.open = false;
218        self.task = None;
219        self.trigger_hover = false;
220        self.surface_hover = false;
221        self.keyboard = false;
222        self.surface_focus = false;
223        self.suppress_focus = true;
224        if changed {
225            window.refresh();
226        }
227    }
228
229    pub(super) fn present(
230        &mut self,
231        open: bool,
232        trigger: Option<&FocusHandle>,
233        enter: Option<FocusHandle>,
234        window: &mut Window,
235        cx: &mut Context<Self>,
236    ) {
237        if self.presented == open {
238            return;
239        }
240        self.presented = open;
241        if open {
242            self.previous_focus = window.focused(cx);
243            if let Some(enter) = enter {
244                let state = cx.weak_entity();
245                window.on_next_frame(move |window, cx| {
246                    if state
247                        .upgrade()
248                        .is_some_and(|state| state.read(cx).presented)
249                    {
250                        enter.focus(window, cx);
251                    }
252                });
253            }
254        } else {
255            let previous = self.previous_focus.take();
256            if self.surface.contains_focused(window, cx)
257                && let Some(focus) = trigger.cloned().or(previous)
258            {
259                self.suppress_focus = true;
260                let state = cx.weak_entity();
261                window.defer(cx, move |window, cx| {
262                    if state
263                        .upgrade()
264                        .is_some_and(|state| !state.read(cx).presented)
265                    {
266                        focus.focus(window, cx);
267                    }
268                });
269            }
270        }
271    }
272}
273
274#[derive(Clone)]
275pub(super) struct Dismiss {
276    pub(super) transient: Entity<Interaction>,
277    pub(super) persistent: Option<Entity<TooltipState>>,
278    pub(super) request: Option<TooltipCallback>,
279}
280
281impl Dismiss {
282    pub(super) fn request(&self, window: &mut Window, cx: &mut App) {
283        if let Some(state) = &self.persistent {
284            if !state.read(cx).is_visible() {
285                return;
286            }
287            if let Some(callback) = &self.request {
288                callback(window, cx);
289            } else {
290                state.update(cx, |state, cx| state.dismiss(cx));
291            }
292        } else if self.transient.read(cx).is_open(window, cx) {
293            self.transient.update(cx, |state, _| state.dismiss(window));
294            if let Some(callback) = &self.request {
295                callback(window, cx);
296            }
297        }
298    }
299}