Skip to main content

hypersig_ui/
popover.rs

1//! Popovers: a panel of content that a button opens beside itself.
2
3use std::fmt;
4
5use hypersig::NodeRef;
6use hypersig::html::{El, Id, Role, attr, div};
7use hypersig::style::Style;
8use hypersig::style::value::{BorderStyle, PositionTryFallbacks, px, raw, rem};
9
10use crate::button::{ButtonSize, ButtonVariant, button};
11use crate::id::anchor;
12use crate::token;
13
14/// A panel opened by a button beside it.
15///
16/// It sits on a page whose signals are `S`.
17///
18/// Declare one as a `const` from a [`NodeRef`] that
19/// [`node_ref!`](hypersig::node_ref) declares, and use the same value for
20/// the button and the panel, so they agree on the panel's id, which is the
21/// node ref's name. The panel is a `popover="auto"` with `role="dialog"`,
22/// named by its button, and the button opens and closes it through invoker
23/// commands with `aria-haspopup="dialog"`. The browser puts the panel above
24/// the page, closes it on Escape or on a click outside, and returns focus to
25/// the button when focus was inside it. Focus stays on the button as the
26/// panel opens, so place the panel right after its button, where Tab moves
27/// from the button into it.
28///
29/// The panel is placed under the button with CSS anchor positioning and
30/// flips above it where there is no room below. The panel carries the node
31/// ref, so placing one popover twice on a page makes
32/// [`Page::render`](hypersig::Page::render) panic. Close it from a statement
33/// with [`NodeRef::hide_popover`] on the same node ref.
34///
35/// ```
36/// use hypersig::html::p;
37/// use hypersig::{NodeRef, Signals};
38/// use hypersig_ui::{ButtonSize, ButtonVariant, Popover};
39/// use serde::{Deserialize, Serialize};
40///
41/// #[derive(Signals, Serialize, Deserialize)]
42/// struct Profile {}
43///
44/// hypersig::node_ref!(const DETAILS: NodeRef<Profile>);
45/// const INFO: Popover<Profile> = Popover::new(DETAILS);
46///
47/// # fn main() {
48/// let open = INFO.trigger(ButtonVariant::Outline, ButtonSize::Default).text("Details");
49/// let panel = INFO.popover().child(p().text("Joined in 2024."));
50/// assert!(open.render().contains(r#"command="toggle-popover""#));
51/// assert!(panel.render().contains(r#"popover="auto""#));
52/// # }
53/// ```
54pub struct Popover<S> {
55    panel: NodeRef<S>,
56}
57
58impl<S> Popover<S> {
59    /// A popover that `panel` names, whose id is the name of `panel`.
60    #[must_use]
61    pub const fn new(panel: NodeRef<S>) -> Self {
62        Self { panel }
63    }
64
65    fn id(self) -> Id {
66        self.panel.id()
67    }
68
69    fn trigger_id(self) -> Id {
70        self.id().with_key("trigger")
71    }
72
73    fn anchor(self) -> String {
74        anchor(&self.id())
75    }
76
77    /// The button that opens and closes the panel.
78    #[must_use]
79    pub fn trigger(self, variant: ButtonVariant, size: ButtonSize) -> El<S> {
80        button(variant, size)
81            .id(self.trigger_id())
82            .attr(attr::ARIA_HASPOPUP, "dialog")
83            .command_for(&self.id())
84            .attr(attr::COMMAND, "toggle-popover")
85            .css(Style::new().anchor_name(raw(self.anchor())))
86    }
87
88    /// The panel, empty, for the content added with [`El::child`].
89    #[must_use]
90    pub fn popover(self) -> El<S> {
91        div()
92            .id(self.id())
93            .attr(attr::POPOVER, "auto")
94            .role(Role::Dialog)
95            .aria_labelledby(&[&self.trigger_id()])
96            .node_ref(self.panel)
97            .css(panel_style(self.anchor()))
98    }
99}
100
101impl<S> Clone for Popover<S> {
102    fn clone(&self) -> Self {
103        *self
104    }
105}
106
107impl<S> Copy for Popover<S> {}
108
109impl<S> fmt::Debug for Popover<S> {
110    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111        f.debug_tuple("Popover").field(&self.panel).finish()
112    }
113}
114
115fn panel_style(anchor: String) -> Style {
116    // A popover is centered in the viewport by the browser's `inset: 0` and
117    // `margin: auto`, which the anchor position replaces.
118    Style::new()
119        .position_anchor(raw(anchor))
120        .position_area(raw("block-end span-inline-end"))
121        .position_try_fallbacks(PositionTryFallbacks::FlipBlock)
122        .inset(raw("auto"))
123        .margin(px(0))
124        .margin_top(rem(0.25))
125        .width(rem(18))
126        .max_width(raw("calc(100vw - 2rem)"))
127        .padding(rem(1))
128        .border_width(px(1))
129        .border_style(BorderStyle::Solid)
130        .border_color(token::border().var())
131        .border_radius(px(6))
132        .background_color(token::popover().var())
133        .color(token::popover_foreground().var())
134        .box_shadow(raw(
135            "0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",
136        ))
137}
138
139#[cfg(test)]
140mod tests {
141    use hypersig::html::div;
142
143    use super::Popover;
144
145    struct Page;
146
147    hypersig::node_ref!(const PANEL: NodeRef<Page>);
148    const INFO: Popover<Page> = Popover::new(PANEL);
149
150    #[test]
151    fn the_panel_is_named_by_its_button() {
152        let trigger = INFO
153            .trigger(crate::ButtonVariant::Outline, crate::ButtonSize::Default)
154            .render();
155        let panel = INFO.popover().render();
156        let id = "hypersig_ui::popover::tests::PANEL";
157        assert!(trigger.contains(&format!(r#"id="{id}-trigger""#)));
158        assert!(trigger.contains(&format!(r#"commandfor="{id}""#)));
159        assert!(panel.contains(&format!(r#"aria-labelledby="{id}-trigger""#)));
160        assert!(panel.contains(r#"role="dialog""#));
161    }
162
163    #[test]
164    #[should_panic(
165        expected = "`hypersig_ui::popover::tests::PANEL` where the runtime can reach both"
166    )]
167    fn one_popover_placed_twice_panics_when_rendered() {
168        let _ = div::<Page>()
169            .child(INFO.popover())
170            .child(INFO.popover())
171            .render();
172    }
173}