Floating content anchored to a trigger that closes on outside click or Escape.
use gpui::{div, prelude::*, px, Context, FontWeight, Window};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonSize, ButtonVariant};
use crate::ui::popover::Popover;
#[derive(Default)]
pub struct ShareView {
open: bool,
}
impl Render for ShareView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
Popover::new("share", self.open)
.trigger(Button::new("share-trigger", "Share").variant(ButtonVariant::Outline))
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
.child(
div()
.flex()
.flex_col()
.gap_1()
.child(div().font_weight(FontWeight::MEDIUM).child("Share document"))
.child(
div()
.text_color(theme.muted_foreground)
.child("Anyone with the link can view it."),
),
)
.child(
div()
.mt_4()
.flex()
.items_center()
.gap_2()
.child(
div()
.flex_1()
.h(px(32.0))
.px_3()
.flex()
.items_center()
.rounded(theme.radius)
.border_1()
.border_color(theme.input)
.text_color(theme.muted_foreground)
.child("hyuskui.com/d/x7k2"),
)
.child(
Button::new("copy-link", "Copy")
.size(ButtonSize::Sm)
.on_click(cx.listener(|this, _, _, cx| {
this.open = false;
cx.notify();
})),
),
)
}
}Installation
Copies src/ui/popover.rs into your project, along with any components it depends on, and registers the module in src/ui/mod.rs.
Install the theme
Every component reads colors from
crate::theme. Follow the installation guide if you have not added it yet.Copy the source
Paste the code below into
src/ui/popover.rs.src/ui/popover.rs use std::{cell::OnceCell, rc::Rc, time::Duration}; use gpui::{ anchored, deferred, div, point, prelude::*, px, Anchor, AnyElement, App, Bounds, ElementId, FocusHandle, Pixels, Point, Styled, Window, }; use crate::theme::ActiveTheme; /// Which side of the trigger the content opens on. #[derive(Clone, Copy, Default, PartialEq)] pub enum Side { Top, #[default] Bottom, Left, Right, } /// How the content lines up with the trigger along that side. #[derive(Clone, Copy, Default, PartialEq)] pub enum Align { Start, #[default] Center, End, } /// Gap between trigger and content, like Radix's `sideOffset`. const SIDE_OFFSET: Pixels = px(4.0); /// Content never touches the window edge. const WINDOW_MARGIN: Pixels = px(8.0); /// The content's corner, the trigger corner it sits on, and the gap between them. /// `anchored().attach(..)` flips both to the opposite side when the preferred one has no room. pub fn placement(side: Side, align: Align) -> (Anchor, Anchor, Point<Pixels>) { use Anchor::*; match (side, align) { (Side::Bottom, Align::Start) => (TopLeft, BottomLeft, point(px(0.0), SIDE_OFFSET)), (Side::Bottom, Align::Center) => (TopCenter, BottomCenter, point(px(0.0), SIDE_OFFSET)), (Side::Bottom, Align::End) => (TopRight, BottomRight, point(px(0.0), SIDE_OFFSET)), (Side::Top, Align::Start) => (BottomLeft, TopLeft, point(px(0.0), -SIDE_OFFSET)), (Side::Top, Align::Center) => (BottomCenter, TopCenter, point(px(0.0), -SIDE_OFFSET)), (Side::Top, Align::End) => (BottomRight, TopRight, point(px(0.0), -SIDE_OFFSET)), (Side::Right, Align::Start) => (TopLeft, TopRight, point(SIDE_OFFSET, px(0.0))), (Side::Right, Align::Center) => (LeftCenter, RightCenter, point(SIDE_OFFSET, px(0.0))), (Side::Right, Align::End) => (BottomLeft, BottomRight, point(SIDE_OFFSET, px(0.0))), (Side::Left, Align::Start) => (TopRight, TopLeft, point(-SIDE_OFFSET, px(0.0))), (Side::Left, Align::Center) => (RightCenter, LeftCenter, point(-SIDE_OFFSET, px(0.0))), (Side::Left, Align::End) => (BottomRight, BottomLeft, point(-SIDE_OFFSET, px(0.0))), } } /// Focuses `focus` once the deferred content is part of the dispatch tree, so it receives Escape. /// Deferred elements are linked into the tree a frame late; Zed's popover menus wait two frames too. pub fn focus_when_mounted(focus: FocusHandle, window: &Window) { window.on_next_frame(move |window, _| { window.on_next_frame(move |window, cx| window.focus(&focus, cx)); }); } /// Call from `on_open_change` when the trigger's focus handle is tracked around the whole /// popover: if it closes with focus inside the content (Escape, or a press outside that focused /// nothing), focus goes back to the trigger, as Radix does. pub fn return_focus(open: bool, trigger: &FocusHandle, window: &mut Window, cx: &mut App) { if !open && trigger.contains_focused(window, cx) && !trigger.is_focused(window) { window.focus(trigger, cx); } } /// How far content travels in from its trigger as it opens, like shadcn's `slide-in-from-*-2`. pub const SLIDE_IN: Pixels = px(8.0); /// GPUI can't scale an element, so `zoom-in-95` / `zoom-out-95` are drawn as the content's /// center moving this far toward the trigger it grows out of. const ZOOM_SHIFT: Pixels = px(4.0); /// CSS `cubic-bezier(x1, y1, x2, y2)` at time `t`. pub fn cubic_bezier(x1: f32, y1: f32, x2: f32, y2: f32, t: f32) -> f32 { let sample = |a: f32, b: f32, s: f32| { let r = 1.0 - s; 3.0 * r * r * s * a + 3.0 * r * s * s * b + s * s * s }; let t = t.clamp(0.0, 1.0); let (mut lo, mut hi, mut s) = (0.0_f32, 1.0_f32, t); for _ in 0..24 { let x = sample(x1, x2, s); if (x - t).abs() < 1e-4 { break; } if x < t { lo = s; } else { hi = s; } s = (lo + hi) / 2.0; } sample(y1, y2, s) } /// CSS `ease`, the default timing of shadcn's `animate-in` / `animate-out`. pub fn ease(t: f32) -> f32 { cubic_bezier(0.25, 0.1, 0.25, 1.0, t) } /// How long an overlay takes to animate in and out, and the curve it follows. #[derive(Clone, Copy)] pub struct Transition { /// How long the content takes to animate in. pub enter: Duration, /// How long the content takes to animate out; it stays mounted until it has. pub exit: Duration, /// The curve both follow. pub easing: fn(f32) -> f32, } impl Transition { /// shadcn's popover-style content: 150ms in and out with CSS `ease`. pub const POPOVER: Self = Self { enter: Duration::from_millis(150), exit: Duration::from_millis(150), easing: ease, }; } /// Time on GPUI's clock since the first call, for timing animations by hand. GPUI doesn't /// export its `Instant`, so moments are kept as offsets from one reading. pub fn animation_clock(cx: &App) -> Duration { type SinceEpoch = Box<dyn Fn(&App) -> Duration>; thread_local! { static SINCE_EPOCH: OnceCell<SinceEpoch> = const { OnceCell::new() }; } SINCE_EPOCH.with(|cell| { let since = cell.get_or_init(|| { let epoch = cx.background_executor().now(); Box::new(move |cx: &App| cx.background_executor().now().saturating_duration_since(epoch)) }); since(cx) }) } /// An overlay's enter / exit transition, kept across frames (e.g. in keyed state) so content /// stays mounted while it animates out, and picks up from where it is when interrupted. #[derive(Clone, Copy, Default)] pub struct Presence { open: bool, from: f32, since: Duration, } /// One frame of a [`Presence`]. #[derive(Clone, Copy)] pub struct PresenceFrame { /// 0 fully hidden, 1 fully shown, eased. pub value: f32, /// Whether it is heading open (entering) rather than closed (exiting). pub opening: bool, /// Whether it is still moving; frames are requested until it settles. pub animating: bool, } impl PresenceFrame { /// Whether the content should be mounted this frame. pub fn visible(&self) -> bool { self.opening || self.animating } } impl Presence { fn value(&self, now: Duration, transition: Transition) -> f32 { let target = if self.open { 1.0 } else { 0.0 }; let span = (target - self.from).abs(); let duration = if self.open { transition.enter } else { transition.exit }; // A transition interrupted part way only has the rest of the way to go. let duration = duration.as_secs_f32() * span; if span == 0.0 || duration <= 0.0 { return target; } let t = ((now.saturating_sub(self.since)).as_secs_f32() / duration).min(1.0); self.from + (target - self.from) * (transition.easing)(t) } /// Steers toward `open` and returns this frame's state, asking `window` for another frame /// while it moves. Honors [`App::reduce_motion`]. pub fn update(&mut self, open: bool, transition: Transition, window: &Window, cx: &App) -> PresenceFrame { let now = animation_clock(cx); if open != self.open { self.from = self.value(now, transition); self.open = open; self.since = now; } if cx.reduce_motion() { self.from = if open { 1.0 } else { 0.0 }; } let value = self.value(now, transition); let animating = value != if open { 1.0 } else { 0.0 }; if animating { window.request_animation_frame(); } PresenceFrame { value, opening: open, animating, } } } /// shadcn's popover-style motion: `fade-in-0 zoom-in-95 slide-in-from-<trigger side>-2` while /// opening, `fade-out-0 zoom-out-95` while closing. `side` is where the content sits relative /// to its trigger; `slide` is how far it travels in (use [`SLIDE_IN`], or `px(0.0)` for none). pub fn animate_overlay<E: Styled>(element: E, side: Side, frame: PresenceFrame, slide: Pixels) -> E { let distance = if frame.opening { slide.max(ZOOM_SHIFT) } else { ZOOM_SHIFT } * (1.0 - frame.value); let element = element.opacity(frame.value.clamp(0.0, 1.0)); match side { Side::Bottom => element.top(-distance), Side::Top => element.top(distance), Side::Right => element.left(-distance), Side::Left => element.left(distance), } } type OpenChangeHandler = Rc<dyn Fn(&bool, &mut Window, &mut App) + 'static>; /// Floating content anchored to a trigger. The parent view owns `open`; clicking the trigger, /// clicking outside, or pressing Escape asks it to change through `on_open_change`. #[derive(IntoElement)] pub struct Popover { id: ElementId, open: bool, trigger: Option<AnyElement>, children: Vec<AnyElement>, side: Side, align: Align, width: Pixels, padded: bool, full_width: bool, on_open_change: Option<OpenChangeHandler>, } /// GPUI only knows where the trigger is after layout, so its bounds from the last frame are kept /// to attach the content. The focus handle has to outlive a frame for Escape to reach the content. struct PopoverState { trigger_bounds: Option<Bounds<Pixels>>, focus: FocusHandle, was_open: bool, presence: Presence, } impl Popover { pub fn new(id: impl Into<ElementId>, open: bool) -> Self { Self { id: id.into(), open, trigger: None, children: Vec::new(), side: Side::default(), align: Align::default(), width: px(288.0), padded: true, full_width: false, on_open_change: None, } } /// The element that toggles the popover when clicked. pub fn trigger(mut self, trigger: impl IntoElement) -> Self { self.trigger = Some(trigger.into_any_element()); self } pub fn side(mut self, side: Side) -> Self { self.side = side; self } pub fn align(mut self, align: Align) -> Self { self.align = align; self } pub fn width(mut self, width: impl Into<Pixels>) -> Self { self.width = width.into(); self } /// Stretches the trigger to the popover's full width, for a trigger that should fill its /// row, such as a switcher in a sidebar. pub fn full_width(mut self, full_width: bool) -> Self { self.full_width = full_width; self } /// Menus draw their own row padding, so they turn the content padding off. pub fn padded(mut self, padded: bool) -> Self { self.padded = padded; self } /// Receives the *next* open value. pub fn on_open_change( mut self, handler: impl Fn(&bool, &mut Window, &mut App) + 'static, ) -> Self { self.on_open_change = Some(Rc::new(handler)); self } } impl ParentElement for Popover { fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) { self.children.extend(elements); } } impl RenderOnce for Popover { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let open = self.open; let state = window.use_keyed_state(self.id.clone(), cx, |_, cx| PopoverState { trigger_bounds: None, focus: cx.focus_handle(), was_open: false, presence: Presence::default(), }); let (trigger_bounds, focus, just_opened, frame) = state.update(cx, |state, cx| { let just_opened = open && !state.was_open; state.was_open = open; let frame = state.presence.update(open, Transition::POPOVER, window, cx); (state.trigger_bounds, state.focus.clone(), just_opened, frame) }); if just_opened { focus_when_mounted(focus.clone(), window); } let theme = cx.theme(); let on_open_change = self.on_open_change; let trigger = self.trigger.map(|trigger| { let handler = on_open_change.clone(); div() .id("popover-trigger") .when(self.full_width, |this| this.flex_1().min_w_0()) .when_some(handler, |this, handler| { this.on_click(move |_, window, cx| handler(&!open, window, cx)) }) .child(trigger) }); let side = self.side; let content = trigger_bounds.filter(|_| frame.visible()).map(|bounds| { let (anchor, corner, offset) = placement(self.side, self.align); let close = on_open_change.clone(); let escape = on_open_change.clone(); // Content animating out no longer blocks the page or answers to the pointer. let panel = div() .when(open, |this| this.occlude()) .track_focus(&focus) .w(self.width) .rounded(theme.radius) .border_1() .border_color(theme.border) .bg(theme.background) .text_color(theme.foreground) .text_sm() .shadow_md() .when(self.padded, |this| this.p(px(16.0))) // Mousedown on the trigger is left to its click handler, or it would close // here and reopen on mouseup. .when(open, |this| { this.on_mouse_down_out(move |event, window, cx| { if !bounds.contains(&event.position) { if let Some(close) = &close { close(&false, window, cx); } } }) .on_key_down(move |event, window, cx| { if event.keystroke.key == "escape" { if let Some(escape) = &escape { escape(&false, window, cx); } cx.stop_propagation(); } }) }) .children(self.children); let panel = animate_overlay(panel, side, frame, SLIDE_IN); deferred( anchored() .attach(bounds, corner) .anchor(anchor) .offset(offset) .snap_to_window_with_margin(WINDOW_MARGIN) .child(panel), ) .with_priority(1) }); div() .flex() .on_children_prepainted(move |bounds, _, cx| { state.update(cx, |state, cx| { let first = bounds.first().copied(); if state.trigger_bounds != first { state.trigger_bounds = first; cx.notify(); } }); }) .id(self.id) .children(trigger) .children(content) } }Register the module
// src/ui/mod.rs pub mod popover;
Usage
use crate::ui::popover::*;Examples
Basic
A popover with a title and a description. Click the trigger again, click outside or press Escape to close it.
use gpui::{div, prelude::*, Context, FontWeight, Window};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::popover::Popover;
#[derive(Default)]
pub struct PopoverBasic {
open: bool,
}
impl Render for PopoverBasic {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
Popover::new("popover-basic", self.open)
.trigger(Button::new("popover-basic-trigger", "Open Popover").variant(ButtonVariant::Outline))
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
.child(
div()
.flex()
.flex_col()
.gap_1()
.child(div().font_weight(FontWeight::MEDIUM).child("Dimensions"))
.child(div().text_color(theme.muted_foreground).child("Set the dimensions for the layer.")),
)
}
}Align
align lines the content up with the trigger's start, center (the default) or end.
use gpui::{div, prelude::*, px, Context, Window};
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::popover::{Align, Popover};
#[derive(Default)]
pub struct PopoverAlign {
/// Index of the open popover, if any.
open: Option<usize>,
}
impl Render for PopoverAlign {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let aligns = [("Start", Align::Start), ("Center", Align::Center), ("End", Align::End)];
div()
.flex()
.gap_6()
.children(aligns.into_iter().enumerate().map(|(ix, (label, align))| {
Popover::new(("popover-align", ix), self.open == Some(ix))
.align(align)
.width(px(160.0))
.trigger(Button::new(("popover-align-trigger", ix), label).variant(ButtonVariant::Outline))
.on_open_change(cx.listener(move |this, open: &bool, _, cx| {
this.open = open.then_some(ix);
cx.notify();
}))
.child(format!("Aligned to the {}", label.to_lowercase()))
}))
}
}With Form
A popover can hold inputs. Each TextInput is an entity, kept across frames with use_keyed_state, so its text survives the popover closing.
use gpui::{div, prelude::*, px, Context, FontWeight, Window};
use crate::theme::ActiveTheme;
use crate::ui::button::{Button, ButtonVariant};
use crate::ui::input::TextInput;
use crate::ui::label::Label;
use crate::ui::popover::Popover;
const FIELDS: [(&str, &str); 4] = [
("Width", "100%"),
("Max. width", "300px"),
("Height", "25px"),
("Max. height", "none"),
];
#[derive(Default)]
pub struct PopoverWithForm {
open: bool,
}
impl Render for PopoverWithForm {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let inputs: Vec<_> = FIELDS
.iter()
.enumerate()
.map(|(ix, (label, value))| {
let input = window.use_keyed_state(("popover-form-input", ix), cx, |_, cx| {
TextInput::new(cx).default_value(*value)
});
div()
.flex()
.items_center()
.gap_4()
.child(div().w(px(88.0)).flex_none().child(Label::new(*label)))
.child(div().flex_1().child(input))
})
.collect();
let theme = cx.theme();
Popover::new("popover-form", self.open)
.width(px(320.0))
.trigger(Button::new("popover-form-trigger", "Open Popover").variant(ButtonVariant::Outline))
.on_open_change(cx.listener(|this, open: &bool, _, cx| {
this.open = *open;
cx.notify();
}))
.child(
div()
.flex()
.flex_col()
.gap_1()
.child(div().font_weight(FontWeight::MEDIUM).child("Dimensions"))
.child(div().text_color(theme.muted_foreground).child("Set the dimensions for the layer.")),
)
.child(div().mt_4().flex().flex_col().gap_2().children(inputs))
}
}API Reference
Side
Which side of the trigger the content opens on.
Side::TopSide::BottomSide::LeftSide::RightAlign
How the content lines up with the trigger along that side.
Align::StartAlign::CenterAlign::EndPresence
An overlay's enter / exit transition, kept across frames (e.g. in keyed state) so content stays mounted while it animates out, and picks up from where it is when interrupted.
.update(open: bool, transition: Transition, window: &Window, cx: &App) -> PresenceFrameSteers toward open and returns this frame's state, asking window for another frame while it moves. Honors [App::reduce_motion].
PresenceFrame
One frame of a [Presence].
.visible() -> boolWhether the content should be mounted this frame.
Popover
Floating content anchored to a trigger. The parent view owns open; clicking the trigger, clicking outside, or pressing Escape asks it to change through on_open_change.
Popover::new(id: impl Into<ElementId>, open: bool) -> Self.trigger(trigger: impl IntoElement)The element that toggles the popover when clicked.
.side(side: Side).align(align: Align).width(width: impl Into<Pixels>).full_width(full_width: bool)Stretches the trigger to the popover's full width, for a trigger that should fill its row, such as a switcher in a sidebar.
.padded(padded: bool)Menus draw their own row padding, so they turn the content padding off.
.on_open_change(handler: impl Fn(&bool, &mut Window, &mut App) + 'static)Receives the *next* open value.