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