arc-ui 0.4.0

Physics-first native Rust desktop UI component library & charts for GPUI (120+ interactive components ported from Arc).
Documentation
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/popover/popover.tsx` & `.module.css`
//!
//! P3 Component #2: `popover`
//!
//! - Behaviour comes from `gpui_kit::base::Popover` (the Arc/Radix equivalent): the trigger toggles
//!   the panel, an outside press or Escape dismisses it, and the panel takes focus as a non-modal
//!   dialog. Only the surface and motion are Arc's.
//! - Panel: `surface_raised` fill, `1px border`, `panel` radius, `floating` shadow, 16px padding,
//!   12rem minimum and 22rem maximum width.
//! - Enter: fades in over `duration.fast` / `ease.enter` while sliding `5px` from the trigger on a
//!   `spring.morph` (`duration-spring` in Arc). Placement prefers the requested side with a 6px gap.
//! - Local design: the exit half of the transition is omitted (the base popover unmounts content as
//!   soon as it closes) and there is no automatic side flip (the base anchors on one side).

use std::{cell::Cell, rc::Rc};

use arc_motion::{CubicBezier, is_reduced_motion, motion_now};
use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, Typography};
use gpui_kit::{
    Anchor, AnyElement, App, ElementId, IntoElement, ParentElement, RenderOnce, Styled,
    TestSupportExt as _, Window,
    base::{Button as BaseButton, Popover as BasePopover, Selectable},
    div,
    prelude::*,
    px,
};

/// Side of the trigger the panel prefers (Arc's `side`, default `Bottom`).
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum PopoverSide {
    Top,
    #[default]
    Bottom,
    Left,
    Right,
}

/// Gap between the trigger and the panel (`sideOffset`).
pub const OFFSET: f32 = 6.0;
/// `12rem` / `22rem` panel width bounds.
pub const MIN_WIDTH: f32 = 192.0;
pub const MAX_WIDTH: f32 = 352.0;
/// Enter fade (`duration.fast`) and slide (`duration-spring`, approximated by `spring.morph`).
pub const FADE_SECS: f64 = 0.16;
pub const SLIDE_SECS: f64 = 0.42;
/// Distance the panel travels toward its trigger.
pub const SLIDE_PX: f32 = 5.0;

type ContentBuilder = Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>;

/// `Popover::trigger` wants a `Selectable`; Arc triggers are plain elements, so wrap one and let
/// the base popover's `selected(open)` call be a no-op (Arc's trigger has no selected state).
struct TriggerShell(AnyElement);

impl Selectable for TriggerShell {
    fn selected(self, _selected: bool) -> Self {
        self
    }

    fn is_selected(&self) -> bool {
        false
    }
}

impl IntoElement for TriggerShell {
    type Element = AnyElement;

    fn into_element(self) -> Self::Element {
        self.0
    }
}

fn anchor_for(side: PopoverSide) -> Anchor {
    match side {
        // `Popup` anchors the panel's top-left at the trigger's bottom-left, and so on.
        PopoverSide::Bottom => Anchor::TopLeft,
        PopoverSide::Top => Anchor::BottomLeft,
        PopoverSide::Right => Anchor::LeftCenter,
        PopoverSide::Left => Anchor::RightCenter,
    }
}

fn slide_sign(side: PopoverSide) -> f32 {
    match side {
        // A panel below its trigger starts slightly above its resting place, and vice versa.
        PopoverSide::Bottom => -1.0,
        PopoverSide::Top => 1.0,
        _ => 0.0,
    }
}

/// 0..=1 fade and 5px slide progress for a panel opened at `opened_at`.
pub fn enter_progress(elapsed: f64, reduced: bool) -> (f32, f32) {
    if reduced {
        return (1.0, 1.0);
    }
    let fade_t = (elapsed / FADE_SECS).clamp(0.0, 1.0) as f32;
    let slide_t = (elapsed / SLIDE_SECS).clamp(0.0, 1.0) as f32;
    (
        CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(fade_t),
        CubicBezier::new(0.16, 1.0, 0.3, 1.0).sample(slide_t),
    )
}

/// Arc `Popover` — a click-anchored panel with Arc's surface and entrance.
#[derive(IntoElement)]
pub struct ArcPopover {
    id: ElementId,
    side: PopoverSide,
    trigger: AnyElement,
    content: Option<ContentBuilder>,
    opened_at: Rc<Cell<f64>>,
}

impl ArcPopover {
    pub fn new(
        id: impl Into<ElementId>,
        content: impl Fn(&mut Window, &mut App) -> AnyElement + 'static,
    ) -> Self {
        Self {
            id: id.into(),
            side: PopoverSide::Bottom,
            trigger: BaseButton::new("arc-popover-trigger-placeholder").into_any_element(),
            content: Some(Rc::new(content)),
            opened_at: Rc::new(Cell::new(f64::NEG_INFINITY)),
        }
    }

    pub fn side(mut self, side: PopoverSide) -> Self {
        self.side = side;
        self
    }

    pub fn trigger(mut self, trigger: impl Selectable + IntoElement + 'static) -> Self {
        self.trigger = trigger.into_any_element();
        self
    }
}

impl RenderOnce for ArcPopover {
    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = cx.arc_theme().clone();
        let colors = theme.colors;
        let reduced = is_reduced_motion(cx);

        let opened_at = self.opened_at.clone();
        let opened_for_change = self.opened_at.clone();
        let content = self.content.clone();
        let side = self.side;
        let id = self.id.clone();

        let callbacks = Rc::new(move |open: &bool, _window: &mut Window, cx: &mut App| {
            if *open {
                opened_for_change.set(motion_now(cx));
            }
        });

        let popover_id = id.clone();
        let body =
            move |_state: &mut gpui_kit::base::PopoverState,
                  window: &mut Window,
                  cx: &mut gpui_kit::Context<'_, gpui_kit::base::PopoverState>| {
                let cx: &mut App = cx;
                let now = motion_now(cx);
                let (fade, slide) = enter_progress(now - opened_at.get(), reduced);
                if slide < 0.999 || fade < 0.999 {
                    window.request_animation_frame();
                }
                let dy = (1.0 - slide) * SLIDE_PX * slide_sign(side);
                let inner = content
                    .as_ref()
                    .map(|build| build(window, cx))
                    .unwrap_or_else(|| div().into_any_element());

                div()
                    .id(ElementId::NamedChild(
                        popover_id.clone().into(),
                        "panel".into(),
                    ))
                    .test_support()
                    .min_w(px(MIN_WIDTH))
                    .max_w(px(MAX_WIDTH))
                    .p(Spacing::S4)
                    .rounded(Radii::PANEL)
                    .border_1()
                    .border_color(colors.border)
                    .bg(colors.surface_raised)
                    .text_color(colors.foreground)
                    .text_size(Typography::TEXT_SM)
                    .shadow(Shadows::floating(theme.mode))
                    .opacity(fade.clamp(0.0, 1.0))
                    .mt(px(dy))
                    .child(inner)
                    .into_any_element()
            };

        BasePopover::new(id)
            .anchor(anchor_for(self.side))
            .offset(px(OFFSET))
            .trigger(TriggerShell(self.trigger))
            .on_open_change(move |open, window, cx| callbacks(open, window, cx))
            .content(body)
    }
}

/// Makes `arc_ui::Button` usable as a popover trigger (the base popover asks its trigger for a
/// selected state; Arc's trigger only changes colour while pressed, so this is a visual no-op).
impl Selectable for crate::actions::button::Button {
    fn selected(self, _selected: bool) -> Self {
        self
    }

    fn is_selected(&self) -> bool {
        false
    }
}

#[cfg(test)]
mod tests {
    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
    use gpui_kit::{Render, TestAppContext, div, test::TestWindowExt as _};

    use super::*;

    #[test]
    fn enter_fades_fast_and_slides_with_the_spring() {
        let (fade0, slide0) = enter_progress(0.0, false);
        assert!(fade0 < 1e-4 && slide0 < 1e-4);
        let (fade_mid, slide_mid) = enter_progress(FADE_SECS, false);
        assert!(fade_mid > 0.99, "fade finishes first: {fade_mid}");
        assert!(slide_mid < 0.99, "slide still running: {slide_mid}");
        let (_, slide_done) = enter_progress(SLIDE_SECS + 0.01, false);
        assert!(slide_done > 0.999);
        assert_eq!(enter_progress(0.0, true), (1.0, 1.0));
    }

    struct Host;

    impl Render for Host {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            div().size_full().p(px(120.0)).child(
                ArcPopover::new("demo-popover", |_, _| {
                    div().child("面板内容").into_any_element()
                })
                .trigger(BaseButton::new("demo-trigger").child("打开")),
            )
        }
    }

    #[gpui_kit::test]
    fn popover_opens_below_the_trigger_and_dismisses_outside(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
        });
        let (_view, cx) = cx.add_window_view(|_, _| Host);
        cx.update(|window, cx| {
            window.render_frame(cx);
            window.render_frame(cx);
            window.click("demo-trigger", cx);
            window.render_frame(cx);
            let root: std::sync::Arc<ElementId> = ElementId::from("demo-popover").into();
            let panel = window.find(ElementId::NamedChild(root, "panel".into()));
            let trigger = window.find(ElementId::from("demo-trigger"));
            assert!(
                f32::from(panel.bounds().origin.y) >= f32::from(trigger.bounds().bottom()),
                "panel should sit below the trigger: panel={:?} trigger={:?}",
                panel.bounds(),
                trigger.bounds()
            );
        });
    }
}