Skip to main content

arc_ui/overlay/
popover.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/popover/popover.tsx` & `.module.css`
3//!
4//! P3 Component #2: `popover`
5//!
6//! - Behaviour comes from `gpui_kit::base::Popover` (the Arc/Radix equivalent): the trigger toggles
7//!   the panel, an outside press or Escape dismisses it, and the panel takes focus as a non-modal
8//!   dialog. Only the surface and motion are Arc's.
9//! - Panel: `surface_raised` fill, `1px border`, `panel` radius, `floating` shadow, 16px padding,
10//!   12rem minimum and 22rem maximum width.
11//! - Enter: fades in over `duration.fast` / `ease.enter` while sliding `5px` from the trigger on a
12//!   `spring.morph` (`duration-spring` in Arc). Placement prefers the requested side with a 6px gap.
13//! - Local design: the exit half of the transition is omitted (the base popover unmounts content as
14//!   soon as it closes) and there is no automatic side flip (the base anchors on one side).
15
16use std::{cell::Cell, rc::Rc};
17
18use arc_motion::{CubicBezier, is_reduced_motion, motion_now};
19use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, Typography};
20use gpui_kit::{
21    Anchor, AnyElement, App, ElementId, IntoElement, ParentElement, RenderOnce, Styled,
22    TestSupportExt as _, Window,
23    base::{Button as BaseButton, Popover as BasePopover, Selectable},
24    div,
25    prelude::*,
26    px,
27};
28
29/// Side of the trigger the panel prefers (Arc's `side`, default `Bottom`).
30#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
31pub enum PopoverSide {
32    Top,
33    #[default]
34    Bottom,
35    Left,
36    Right,
37}
38
39/// Gap between the trigger and the panel (`sideOffset`).
40pub const OFFSET: f32 = 6.0;
41/// `12rem` / `22rem` panel width bounds.
42pub const MIN_WIDTH: f32 = 192.0;
43pub const MAX_WIDTH: f32 = 352.0;
44/// Enter fade (`duration.fast`) and slide (`duration-spring`, approximated by `spring.morph`).
45pub const FADE_SECS: f64 = 0.16;
46pub const SLIDE_SECS: f64 = 0.42;
47/// Distance the panel travels toward its trigger.
48pub const SLIDE_PX: f32 = 5.0;
49
50type ContentBuilder = Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>;
51
52/// `Popover::trigger` wants a `Selectable`; Arc triggers are plain elements, so wrap one and let
53/// the base popover's `selected(open)` call be a no-op (Arc's trigger has no selected state).
54struct TriggerShell(AnyElement);
55
56impl Selectable for TriggerShell {
57    fn selected(self, _selected: bool) -> Self {
58        self
59    }
60
61    fn is_selected(&self) -> bool {
62        false
63    }
64}
65
66impl IntoElement for TriggerShell {
67    type Element = AnyElement;
68
69    fn into_element(self) -> Self::Element {
70        self.0
71    }
72}
73
74fn anchor_for(side: PopoverSide) -> Anchor {
75    match side {
76        // `Popup` anchors the panel's top-left at the trigger's bottom-left, and so on.
77        PopoverSide::Bottom => Anchor::TopLeft,
78        PopoverSide::Top => Anchor::BottomLeft,
79        PopoverSide::Right => Anchor::LeftCenter,
80        PopoverSide::Left => Anchor::RightCenter,
81    }
82}
83
84fn slide_sign(side: PopoverSide) -> f32 {
85    match side {
86        // A panel below its trigger starts slightly above its resting place, and vice versa.
87        PopoverSide::Bottom => -1.0,
88        PopoverSide::Top => 1.0,
89        _ => 0.0,
90    }
91}
92
93/// 0..=1 fade and 5px slide progress for a panel opened at `opened_at`.
94pub fn enter_progress(elapsed: f64, reduced: bool) -> (f32, f32) {
95    if reduced {
96        return (1.0, 1.0);
97    }
98    let fade_t = (elapsed / FADE_SECS).clamp(0.0, 1.0) as f32;
99    let slide_t = (elapsed / SLIDE_SECS).clamp(0.0, 1.0) as f32;
100    (
101        CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(fade_t),
102        CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(slide_t),
103    )
104}
105
106/// Arc `Popover` — a click-anchored panel with Arc's surface and entrance.
107#[derive(IntoElement)]
108pub struct ArcPopover {
109    id: ElementId,
110    side: PopoverSide,
111    trigger: AnyElement,
112    content: Option<ContentBuilder>,
113    opened_at: Rc<Cell<f64>>,
114}
115
116impl ArcPopover {
117    pub fn new(
118        id: impl Into<ElementId>,
119        content: impl Fn(&mut Window, &mut App) -> AnyElement + 'static,
120    ) -> Self {
121        Self {
122            id: id.into(),
123            side: PopoverSide::Bottom,
124            trigger: BaseButton::new("arc-popover-trigger-placeholder").into_any_element(),
125            content: Some(Rc::new(content)),
126            opened_at: Rc::new(Cell::new(f64::NEG_INFINITY)),
127        }
128    }
129
130    pub fn side(mut self, side: PopoverSide) -> Self {
131        self.side = side;
132        self
133    }
134
135    pub fn trigger(mut self, trigger: impl Selectable + IntoElement + 'static) -> Self {
136        self.trigger = trigger.into_any_element();
137        self
138    }
139}
140
141impl RenderOnce for ArcPopover {
142    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
143        let theme = cx.arc_theme().clone();
144        let colors = theme.colors;
145        let reduced = is_reduced_motion(cx);
146
147        let opened_at = self.opened_at.clone();
148        let opened_for_change = self.opened_at.clone();
149        let content = self.content.clone();
150        let side = self.side;
151        let id = self.id.clone();
152
153        let callbacks = Rc::new(move |open: &bool, _window: &mut Window, cx: &mut App| {
154            if *open {
155                opened_for_change.set(motion_now(cx));
156            }
157        });
158
159        let popover_id = id.clone();
160        let body =
161            move |_state: &mut gpui_kit::base::PopoverState,
162                  window: &mut Window,
163                  cx: &mut gpui_kit::Context<'_, gpui_kit::base::PopoverState>| {
164                let cx: &mut App = cx;
165                let now = motion_now(cx);
166                let (fade, slide) = enter_progress(now - opened_at.get(), reduced);
167                if slide < 0.999 || fade < 0.999 {
168                    window.request_animation_frame();
169                }
170                let dy = (1.0 - slide) * SLIDE_PX * slide_sign(side);
171                let inner = content
172                    .as_ref()
173                    .map(|build| build(window, cx))
174                    .unwrap_or_else(|| div().into_any_element());
175
176                div()
177                    .id(ElementId::NamedChild(
178                        popover_id.clone().into(),
179                        "panel".into(),
180                    ))
181                    .test_support()
182                    .min_w(px(MIN_WIDTH))
183                    .max_w(px(MAX_WIDTH))
184                    .p(Spacing::S4)
185                    .rounded(Radii::PANEL)
186                    .border_1()
187                    .border_color(colors.border)
188                    .bg(colors.surface_raised)
189                    .text_color(colors.foreground)
190                    .text_size(Typography::TEXT_SM)
191                    .shadow(Shadows::floating(theme.mode))
192                    .opacity(fade.clamp(0.0, 1.0))
193                    .mt(px(dy))
194                    .child(inner)
195                    .into_any_element()
196            };
197
198        BasePopover::new(id)
199            .anchor(anchor_for(self.side))
200            .offset(px(OFFSET))
201            .trigger(TriggerShell(self.trigger))
202            .on_open_change(move |open, window, cx| callbacks(open, window, cx))
203            .content(body)
204    }
205}
206
207/// Makes `arc_ui::Button` usable as a popover trigger (the base popover asks its trigger for a
208/// selected state; Arc's trigger only changes colour while pressed, so this is a visual no-op).
209impl Selectable for crate::actions::button::Button {
210    fn selected(self, _selected: bool) -> Self {
211        self
212    }
213
214    fn is_selected(&self) -> bool {
215        false
216    }
217}
218
219#[cfg(test)]
220mod tests {
221    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
222    use gpui_kit::{Render, TestAppContext, div, test::TestWindowExt as _};
223
224    use super::*;
225
226    #[test]
227    fn enter_fades_fast_and_slides_with_the_spring() {
228        let (fade0, slide0) = enter_progress(0.0, false);
229        assert!(fade0 < 1e-4 && slide0 < 1e-4);
230        let (fade_mid, slide_mid) = enter_progress(FADE_SECS, false);
231        assert!(fade_mid > 0.99, "fade finishes first: {fade_mid}");
232        assert!(slide_mid < 0.99, "slide still running: {slide_mid}");
233        let (_, slide_done) = enter_progress(SLIDE_SECS + 0.01, false);
234        assert!(slide_done > 0.999);
235        assert_eq!(enter_progress(0.0, true), (1.0, 1.0));
236    }
237
238    struct Host;
239
240    impl Render for Host {
241        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
242            div().size_full().p(px(120.0)).child(
243                ArcPopover::new("demo-popover", |_, _| {
244                    div().child("面板内容").into_any_element()
245                })
246                .trigger(BaseButton::new("demo-trigger").child("打开")),
247            )
248        }
249    }
250
251    #[gpui_kit::test]
252    fn popover_opens_below_the_trigger_and_dismisses_outside(cx: &mut TestAppContext) {
253        cx.update(|cx| {
254            gpui_kit::init(cx);
255            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
256        });
257        let (_view, cx) = cx.add_window_view(|_, _| Host);
258        cx.update(|window, cx| {
259            window.render_frame(cx);
260            window.render_frame(cx);
261            window.click("demo-trigger", cx);
262            window.render_frame(cx);
263            let root: std::sync::Arc<ElementId> = ElementId::from("demo-popover").into();
264            let panel = window.find(ElementId::NamedChild(root, "panel".into()));
265            let trigger = window.find(ElementId::from("demo-trigger"));
266            assert!(
267                f32::from(panel.bounds().origin.y) >= f32::from(trigger.bounds().bottom()),
268                "panel should sit below the trigger: panel={:?} trigger={:?}",
269                panel.bounds(),
270                trigger.bounds()
271            );
272        });
273    }
274}