Skip to main content

ui/
popover.rs

1//! Popover / menu primitives: an anchored floating layer with the `menu-in`
2//! animation, outside-click dismissal, and pure keyboard-navigation + search
3//! reducers shared by every picker and menu (feature-inventory §1.12 popovers).
4//!
5//! gpui pattern (examples/popover.rs at the pinned rev): the trigger element
6//! conditionally children a `deferred(anchored().child(content))` — deferred
7//! paints on a floating layer above everything, anchored positions it relative
8//! to the trigger (or an explicit point for context menus).
9//!
10//! Pure logic (wrap-around list navigation, ranked substring filtering, key
11//! classification) lives in free functions with unit tests; the elements only
12//! feed them measurements/events.
13
14mod anchor;
15mod modal;
16mod nav;
17mod parts;
18pub mod submenu;
19
20pub use anchor::*;
21pub use modal::*;
22pub use nav::*;
23pub use parts::*;
24pub use submenu::Chain;
25
26use crate::{icons, stack};
27use gpui::{
28    Anchor, AnyElement, ElementId, IntoElement, Pixels, Point, SharedString, div, prelude::*, px,
29};
30use icons::Icon;
31use motion::{self as motion, AnimationExt as _, Fade, PULSE, Painter};
32use theme::{TextStyle, Theme, Typeset, ink};
33
34/// The deferred priority a modal and a sheet paint at.
35const MODAL_LAYER: usize = 2;
36
37/// The deferred priority a menu and its submenus paint at: over a modal, so a
38/// menu opened inside one shows.
39const MENU_LAYER: usize = 3;
40
41// ---------------------------------------------------------------------------
42// Loadable — async slot state shared by pickers/settings pages
43// ---------------------------------------------------------------------------
44
45/// One async-loaded slot: `Idle` (never requested) → `Loading` (skeletons) →
46/// `Ready` / `Error` (inline message + Retry).
47#[derive(Debug, Clone, PartialEq, Default)]
48pub enum Loadable<T> {
49    #[default]
50    Idle,
51    Loading,
52    Ready(T),
53    Error(String),
54}
55
56impl<T> Loadable<T> {
57    pub fn ready(&self) -> Option<&T> {
58        match self {
59            Loadable::Ready(value) => Some(value),
60            _ => None,
61        }
62    }
63
64    pub fn is_loading(&self) -> bool {
65        matches!(self, Loadable::Loading)
66    }
67
68    pub fn error(&self) -> Option<&str> {
69        match self {
70            Loadable::Error(message) => Some(message),
71            _ => None,
72        }
73    }
74}
75
76// ---------------------------------------------------------------------------
77// Popup — open/closing/closed lifecycle (exit animations)
78// ---------------------------------------------------------------------------
79
80/// Popup state with an exit phase. gpui unmounts an element the frame its
81/// state drops, so a closing animation needs the state held alive while
82/// [`motion::menu_out`] plays: `open` → `begin_close` (render keeps mounting,
83/// with the out animation and dead hit-testing) → [`reap_popup`]'s timer
84/// `finish_close`es ~[`motion::MENU_OUT`] later. Use [`Self::is_open`] for
85/// logic (a closing popup already reads as closed) and [`Self::get`] /
86/// [`Self::is_closing`] for rendering.
87pub struct Popup<T> {
88    /// `Some((state, closing_since))` while mounted; `closing_since` is the
89    /// exit-phase start.
90    inner: Option<(T, Option<web_time::Instant>)>,
91    /// Whether the popup was still mounted when the current trigger press
92    /// began — see [`Self::note_trigger_press`].
93    pressed_while_open: bool,
94    generation: u64,
95}
96
97impl<T> Default for Popup<T> {
98    fn default() -> Self {
99        Self {
100            inner: None,
101            pressed_while_open: false,
102            generation: 0,
103        }
104    }
105}
106
107impl<T> Popup<T> {
108    pub fn open(&mut self, value: T) {
109        self.generation = self.generation.wrapping_add(1);
110        self.inner = Some((value, None));
111    }
112
113    /// Open and interactive (not closing).
114    pub fn is_open(&self) -> bool {
115        matches!(self.inner, Some((_, None)))
116    }
117
118    pub fn is_closing(&self) -> bool {
119        matches!(self.inner, Some((_, Some(_))))
120    }
121
122    /// When the exit phase began — what the render path hands to the popover
123    /// wrappers, which derive the eased exit progress from it each frame.
124    pub fn closing_since(&self) -> Option<web_time::Instant> {
125        match &self.inner {
126            Some((_, Some(since))) => Some(*since),
127            _ => None,
128        }
129    }
130
131    /// The state while mounted — open OR playing the exit animation. Render
132    /// paths use this; logic paths use [`Self::as_open`]/[`Self::open_mut`].
133    pub fn get(&self) -> Option<&T> {
134        self.inner.as_ref().map(|(value, _)| value)
135    }
136
137    /// The state only while genuinely open — `None` during the exit phase, so
138    /// event handlers on a dying popup fall through.
139    pub fn as_open(&self) -> Option<&T> {
140        match &self.inner {
141            Some((value, None)) => Some(value),
142            _ => None,
143        }
144    }
145
146    pub fn open_mut(&mut self) -> Option<&mut T> {
147        match &mut self.inner {
148            Some((value, None)) => Some(value),
149            _ => None,
150        }
151    }
152
153    /// Unmount immediately, without an exit animation.
154    pub fn close(&mut self) {
155        self.inner = None;
156    }
157
158    /// Enter the exit phase. Returns `true` when this call started it (the
159    /// caller then schedules [`reap_popup`]); `false` if already closing or
160    /// closed.
161    pub fn begin_close(&mut self) -> bool {
162        match &mut self.inner {
163            Some((_, closing @ None)) => {
164                self.generation = self.generation.wrapping_add(1);
165                *closing = Some(web_time::Instant::now());
166                true
167            }
168            _ => false,
169        }
170    }
171
172    /// Record whether the trigger press found an interactive popup.
173    /// Call during capture, before the card's outside-press dismissal.
174    pub fn note_trigger_press(&mut self) {
175        self.note_trigger_press_matching(|_| true);
176    }
177
178    /// [`Self::note_trigger_press`] for popups whose state distinguishes
179    /// which trigger owns them (e.g. one `Popup<PickerKind>` shared by
180    /// several triggers): only a press on the OWNING trigger counts, so
181    /// clicking a different trigger switches menus instead of swallowing.
182    pub fn note_trigger_press_matching(&mut self, owns: impl FnOnce(&T) -> bool) {
183        self.pressed_while_open = self.as_open().is_some_and(owns);
184    }
185
186    /// Consume the press note: `true` when the press that produced the
187    /// current click found the popup interactive — the click should leave it
188    /// closed rather than reopen it.
189    pub fn take_press_was_open(&mut self) -> bool {
190        std::mem::take(&mut self.pressed_while_open)
191    }
192
193    /// Drop the state now the exit phase has run its course. A popup reopened
194    /// since the matching [`Self::begin_close`] is left alone — it is `None`
195    /// again in the second slot, and the newer phase's own reap handles it.
196    ///
197    /// It does not re-check the clock. [`reap_popup`] already waited out the
198    /// span on the executor's timer, and asking `Instant::elapsed` to agree
199    /// makes one deadline depend on two clocks — where they disagree, and a
200    /// throttled executor is where, the popup is stranded open with nothing
201    /// left to retry.
202    pub fn finish_close(&mut self) {
203        if matches!(&self.inner, Some((_, Some(_)))) {
204            self.inner = None;
205        }
206    }
207}
208
209/// Schedule the reap for a [`Popup::begin_close`]: after the exit animation's
210/// span, drop the popup state and repaint. `popup` re-borrows the field from
211/// the view (the state can't be captured — the view owns it).
212pub fn reap_popup<V: 'static, T: 'static>(
213    view: &mut V,
214    cx: &mut gpui::Context<V>,
215    popup: impl Fn(&mut V) -> &mut Popup<T> + 'static,
216) {
217    let generation = popup(view).generation;
218    cx.spawn(async move |view, cx| {
219        cx.background_executor()
220            .timer(
221                motion::MENU_OUT
222                    .total()
223                    .mul_f32(motion::speed_scale())
224                    .saturating_add(std::time::Duration::from_millis(20)),
225            )
226            .await;
227        view.update(cx, |view, cx| {
228            let popup = popup(view);
229            if popup.generation == generation && popup.is_closing() {
230                popup.finish_close();
231                cx.notify();
232            }
233        })
234        .ok();
235    })
236    .detach();
237}
238
239/// Begin a popup's exit phase and schedule its reap — [`Popup::begin_close`]
240/// and [`reap_popup`], which are only ever correct together. A popup already
241/// closing or closed is left alone.
242pub fn close_popup<V: 'static, T: 'static>(
243    view: &mut V,
244    cx: &mut gpui::Context<V>,
245    popup: impl Fn(&mut V) -> &mut Popup<T> + Copy + 'static,
246) {
247    if popup(view).begin_close() {
248        reap_popup(view, cx, popup);
249        cx.notify();
250    }
251}
252
253/// Dismiss an open `popup` on an outside press and consume that press.
254/// A closing popup leaves outside presses untouched.
255pub fn dismiss_on_out<V: 'static, T: 'static, E: gpui::InteractiveElement>(
256    el: E,
257    popup: impl Fn(&mut V) -> &mut Popup<T> + Copy + 'static,
258    cx: &gpui::Context<V>,
259) -> E {
260    el.on_mouse_down_out(cx.listener(move |view, _: &gpui::MouseDownEvent, _, cx| {
261        if popup(view).is_open() {
262            close_popup(view, cx, popup);
263            cx.stop_propagation();
264        }
265    }))
266}
267
268/// Wire a trigger to the popup it toggles: press note on the way down, open or
269/// close on the way up.
270///
271/// The press/release split is why this exists rather than a plain
272/// `on_click`. `on_mouse_down_out` fires on the **press** and `on_click` on the
273/// **release**, so one physical click on the trigger of an open menu runs the
274/// card's dismissal first and the trigger's toggle second — by which time the
275/// state a toggle would branch on is already gone, and the menu reopens on the
276/// click that shut it (user report). No click handler can tell the two apart;
277/// the note has to be taken in the phase the dismissal cannot precede.
278///
279/// `value` is what to open with, from the click that opened it — a point for a
280/// menu anchored where it was pressed, or `move |_| ..` for one that already
281/// knows.
282///
283/// This is a true toggle either way: a card that dismisses itself on the
284/// out-press is already closing by the release and the close here is a no-op,
285/// while a card that does not (one dismissed by Escape alone, or one the
286/// trigger sits inside) is closed by the release itself.
287pub fn menu_trigger<V: 'static, T: 'static, E: gpui::StatefulInteractiveElement>(
288    el: E,
289    popup: impl Fn(&mut V) -> &mut Popup<T> + Copy + 'static,
290    value: impl Fn(&gpui::ClickEvent) -> T + 'static,
291    cx: &gpui::Context<V>,
292) -> E {
293    menu_trigger_matching(el, popup, |_| true, value, cx)
294}
295
296/// [`menu_trigger`] for one popup shared by several triggers (a `Popup<Menu>`
297/// with a row's index inside it): `owns` says whether the open popup is *this*
298/// trigger's, so pressing another trigger switches menus instead of swallowing
299/// the press. See [`Popup::note_trigger_press_matching`].
300pub fn menu_trigger_matching<V: 'static, T: 'static, E: gpui::StatefulInteractiveElement>(
301    el: E,
302    popup: impl Fn(&mut V) -> &mut Popup<T> + Copy + 'static,
303    owns: impl Fn(&T) -> bool + 'static,
304    value: impl Fn(&gpui::ClickEvent) -> T + 'static,
305    cx: &gpui::Context<V>,
306) -> E {
307    trigger_press_matching(el, popup, owns, cx).on_click(cx.listener(
308        move |view, event: &gpui::ClickEvent, _, cx| {
309            if popup(view).take_press_was_open() {
310                close_popup(view, cx, popup);
311            } else {
312                popup(view).open(value(event));
313            }
314            cx.notify();
315        },
316    ))
317}
318
319/// The press half of [`menu_trigger`] on its own, for a trigger whose open is
320/// more than `Popup::open` — a combobox that clears its query and focuses it, a
321/// gutter handle whose menu belongs to the release of a possible drag. The
322/// click side is then the caller's, and reads the note with
323/// [`Popup::take_press_was_open`].
324pub fn trigger_press<V: 'static, T: 'static, E: gpui::InteractiveElement>(
325    el: E,
326    popup: impl Fn(&mut V) -> &mut Popup<T> + Copy + 'static,
327    cx: &gpui::Context<V>,
328) -> E {
329    trigger_press_matching(el, popup, |_| true, cx)
330}
331
332/// [`trigger_press`] for one popup shared by several triggers — see
333/// [`menu_trigger_matching`].
334pub fn trigger_press_matching<V: 'static, T: 'static, E: gpui::InteractiveElement>(
335    el: E,
336    popup: impl Fn(&mut V) -> &mut Popup<T> + Copy + 'static,
337    owns: impl Fn(&T) -> bool + 'static,
338    cx: &gpui::Context<V>,
339) -> E {
340    el.capture_any_mouse_down(cx.listener(move |view, _: &gpui::MouseDownEvent, _, _| {
341        popup(view).note_trigger_press_matching(&owns);
342    }))
343}
344
345// ---------------------------------------------------------------------------
346// Elements
347// ---------------------------------------------------------------------------
348
349/// The inner inset of a [`popover_card`], and so the amount [`menu_row`]'s
350/// corners come in by. Named because two things read it: the card's padding and
351/// its rows' radius. Change it and the rows follow.
352pub const MENU_PAD: f32 = 4.0;
353
354/// The gap a floating layer keeps from the window edge once it has run out of
355/// room and is snapped back inside it.
356pub(crate) const SNAP: f32 = 8.0;
357
358/// How far a [`menu_row`]'s text sits in from its own edge. Content that is
359/// not a row lines up with the rows' text by insetting this much.
360pub const MENU_ROW_INSET: f32 = 8.0;
361
362/// A [`menu_row`]'s padding above and below its line box. Named because a
363/// list that caps itself at a row count has to know how tall a row is.
364pub(crate) const MENU_ROW_PAD_Y: f32 = 6.0;
365
366/// How tall a one-line [`menu_row`] paints. Derived rather than stored: the
367/// two would drift, and it moves with the reader's text size.
368pub(crate) fn menu_row_height() -> f32 {
369    TextStyle::Body.painted_line_height() + 2.0 * MENU_ROW_PAD_Y
370}
371
372/// The floating-menu card. With `theme.glass` on it paints contents only, and
373/// the fill, hairline and shadow are the surface's it is mounted on.
374pub fn popover_card(theme: &Theme) -> gpui::Div {
375    let card = div()
376        .rounded(px(Theme::surface_radius()))
377        .p(px(MENU_PAD))
378        .overflow_hidden()
379        .text_style(TextStyle::Body)
380        .text_color(theme.text);
381    // Contents only. Fill, boundary and shadow are the surface's — every look
382    // paints its own, so nothing here has to know which one is under it. An
383    // card with the recipes off has no surface at all, and keeps the fill.
384    if theme.glass {
385        card
386    } else {
387        card.bg(theme.surface_overlay)
388            .border_1()
389            .border_color(theme.border)
390            .shadow_lg()
391    }
392}
393
394/// [`popover_card`] without the `p-1` inset — for popovers that manage their
395/// own internal panes (the harness/model picker's rail + list split).
396pub fn popover_card_flush(theme: &Theme) -> gpui::Div {
397    popover_card(theme).p(px(0.0))
398}