Skip to main content

fc_ui/capabilities/overlays/
hover_card.rs

1//! Hover card component with popover on hover.
2
3use gpui::{prelude::FluentBuilder as _, *};
4use std::time::Duration;
5
6use crate::capabilities::foundation::theme::use_theme;
7
8#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
9pub enum HoverCardPosition {
10    Top,
11    #[default]
12    Bottom,
13    Left,
14    Right,
15}
16
17#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
18pub enum HoverCardAlignment {
19    Start,
20    #[default]
21    Center,
22    End,
23}
24
25pub struct HoverCardState {
26    visible: bool,
27    pending_open: bool,
28    generation: u64,
29}
30
31impl HoverCardState {
32    fn open_delayed(&mut self, delay: Duration, window: &mut Window, cx: &mut Context<Self>) {
33        self.pending_open = true;
34        self.generation = self.generation.wrapping_add(1);
35        let generation = self.generation;
36        cx.spawn_in(window, async move |this, cx| {
37            smol::Timer::after(delay).await;
38            let _ = this.update(cx, |this, cx| {
39                if this.pending_open && this.generation == generation && !this.visible {
40                    this.visible = true;
41                    this.pending_open = false;
42                    cx.notify();
43                }
44            });
45        })
46        .detach();
47    }
48
49    fn schedule_close(
50        &mut self,
51        delay: Option<Duration>,
52        window: &mut Window,
53        cx: &mut Context<Self>,
54    ) {
55        self.pending_open = false;
56        self.generation = self.generation.wrapping_add(1);
57        match delay {
58            Some(delay) => {
59                let generation = self.generation;
60                cx.spawn_in(window, async move |this, cx| {
61                    smol::Timer::after(delay).await;
62                    let _ = this.update(cx, |this, cx| {
63                        if !this.pending_open && this.generation == generation && this.visible {
64                            this.visible = false;
65                            cx.notify();
66                        }
67                    });
68                })
69                .detach();
70            }
71            None => {
72                if self.visible {
73                    self.visible = false;
74                    cx.notify();
75                }
76            }
77        }
78    }
79}
80
81#[derive(IntoElement)]
82pub struct HoverCard {
83    id: Option<ElementId>,
84    trigger: AnyElement,
85    content: AnyElement,
86    position: HoverCardPosition,
87    alignment: HoverCardAlignment,
88    open_delay: Duration,
89    close_delay: Duration,
90    is_open: bool,
91    style: StyleRefinement,
92}
93
94impl HoverCard {
95    pub fn new() -> Self {
96        Self {
97            id: None,
98            trigger: div().into_any_element(),
99            content: div().into_any_element(),
100            position: HoverCardPosition::default(),
101            alignment: HoverCardAlignment::default(),
102            open_delay: Duration::from_millis(200),
103            close_delay: Duration::from_millis(300),
104            is_open: false,
105            style: StyleRefinement::default(),
106        }
107    }
108
109    /// Sets a unique element id. Required for the internal hover tracking
110    /// that honors [`HoverCard::open_delay`] and [`HoverCard::close_delay`];
111    /// without an id the card only renders while `is_open` is set.
112    pub fn id(mut self, id: impl Into<ElementId>) -> Self {
113        self.id = Some(id.into());
114        self
115    }
116
117    pub fn trigger(mut self, trigger: impl IntoElement) -> Self {
118        self.trigger = trigger.into_any_element();
119        self
120    }
121
122    pub fn content(mut self, content: impl IntoElement) -> Self {
123        self.content = content.into_any_element();
124        self
125    }
126
127    pub fn position(mut self, position: HoverCardPosition) -> Self {
128        self.position = position;
129        self
130    }
131
132    pub fn alignment(mut self, alignment: HoverCardAlignment) -> Self {
133        self.alignment = alignment;
134        self
135    }
136
137    pub fn open_delay(mut self, delay: Duration) -> Self {
138        self.open_delay = delay;
139        self
140    }
141
142    pub fn close_delay(mut self, delay: Duration) -> Self {
143        self.close_delay = delay;
144        self
145    }
146
147    /// Not implemented: no arrow element is rendered and this setting has no
148    /// effect.
149    #[deprecated(note = "arrow rendering is not implemented; this method has no effect")]
150    pub fn arrow(self, _show_arrow: bool) -> Self {
151        self
152    }
153
154    pub fn is_open(mut self, is_open: bool) -> Self {
155        self.is_open = is_open;
156        self
157    }
158}
159
160impl Default for HoverCard {
161    fn default() -> Self {
162        Self::new()
163    }
164}
165
166impl Styled for HoverCard {
167    fn style(&mut self) -> &mut StyleRefinement {
168        &mut self.style
169    }
170}
171
172impl RenderOnce for HoverCard {
173    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
174        let theme = use_theme(cx);
175        let user_style = self.style;
176        let position = self.position;
177        let alignment = self.alignment;
178        let open_delay = self.open_delay;
179        let close_delay = self.close_delay;
180        let is_open = self.is_open;
181
182        let hover_managed = !is_open && self.id.is_some();
183        let wrapper_id = self.id.clone();
184        let card_id = self
185            .id
186            .as_ref()
187            .map(|id| ElementId::Name(format!("{id:?}::content").into()));
188        let state = self.id.clone().map(|id| {
189            window.use_keyed_state(id, cx, |_, _| HoverCardState {
190                visible: false,
191                pending_open: false,
192                generation: 0,
193            })
194        });
195        let visible = is_open
196            || state
197                .as_ref()
198                .map(|state| state.read(cx).visible)
199                .unwrap_or(false);
200
201        div()
202            .relative()
203            .child(self.trigger)
204            .when(visible, |this: Div| {
205                let state_for_card = state.clone();
206                this.child(
207                    div()
208                        .absolute()
209                        .when(position == HoverCardPosition::Bottom, |this: Div| {
210                            this.top_full().mt(px(8.0))
211                        })
212                        .when(position == HoverCardPosition::Top, |this: Div| {
213                            this.bottom_full().mb(px(8.0))
214                        })
215                        .when(position == HoverCardPosition::Left, |this: Div| {
216                            this.right_full().mr(px(8.0))
217                        })
218                        .when(position == HoverCardPosition::Right, |this: Div| {
219                            this.left_full().ml(px(8.0))
220                        })
221                        .when(
222                            (position == HoverCardPosition::Top
223                                || position == HoverCardPosition::Bottom)
224                                && alignment == HoverCardAlignment::Start,
225                            |this: Div| this.left_0(),
226                        )
227                        .when(
228                            (position == HoverCardPosition::Top
229                                || position == HoverCardPosition::Bottom)
230                                && alignment == HoverCardAlignment::End,
231                            |this: Div| this.right_0(),
232                        )
233                        .child(
234                            div()
235                                .min_w(px(200.0))
236                                .max_w(px(400.0))
237                                .bg(theme.tokens.popover)
238                                .border_1()
239                                .border_color(theme.tokens.border)
240                                .rounded(theme.tokens.radius_md)
241                                .shadow(smallvec::smallvec![BoxShadow {
242                                    color: hsla(0.0, 0.0, 0.0, 0.1),
243                                    offset: point(px(0.0), px(4.0)),
244                                    blur_radius: px(12.0),
245                                    spread_radius: px(0.0),
246                                    inset: false,
247                                }])
248                                .map(|this| {
249                                    let mut div = this;
250                                    div.style().refine(&user_style);
251                                    div
252                                })
253                                .child(self.content),
254                        )
255                        .map(|this| {
256                            if hover_managed {
257                                let state = state_for_card.unwrap();
258                                this.id(card_id.clone().unwrap())
259                                    .on_hover(move |&hovered, window, cx| {
260                                        state.update(cx, |state, cx| {
261                                            if hovered {
262                                                state.pending_open = false;
263                                                state.generation = state.generation.wrapping_add(1);
264                                            } else {
265                                                let delay = (close_delay > Duration::ZERO)
266                                                    .then_some(close_delay);
267                                                state.schedule_close(delay, window, cx);
268                                            }
269                                        });
270                                    })
271                                    .into_any_element()
272                            } else {
273                                this.into_any_element()
274                            }
275                        }),
276                )
277            })
278            .map(|this| {
279                if hover_managed {
280                    let state = state.unwrap();
281                    this.id(wrapper_id.unwrap())
282                        .on_hover(move |&hovered, window, cx| {
283                            state.update(cx, |state, cx| {
284                                if hovered {
285                                    if !state.visible && !state.pending_open {
286                                        state.open_delayed(open_delay, window, cx);
287                                    }
288                                } else {
289                                    let delay =
290                                        (close_delay > Duration::ZERO).then_some(close_delay);
291                                    state.schedule_close(delay, window, cx);
292                                }
293                            });
294                        })
295                        .into_any_element()
296                } else {
297                    this.into_any_element()
298                }
299            })
300    }
301}