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