Skip to main content

hypersig_ui/
collapsible.rs

1//! Collapsibles: a button that shows and hides one region.
2
3use hypersig::html::{El, Id, attr, div};
4use hypersig::{Sig, if_else};
5
6use crate::button::{ButtonSize, ButtonVariant, button};
7
8/// A region shown while `open` is true, and the button that flips it.
9///
10/// It follows the WAI-ARIA disclosure pattern. The button has
11/// `aria-expanded` bound to `open` and `aria-controls` pointing at the
12/// region, so a screen reader announces it as expanded or collapsed, and
13/// Enter and Space flip it. The region's id is derived from the signal's
14/// path. The button and the region are separate elements, so the button can
15/// sit in a heading or a toolbar away from the region.
16///
17/// Use [`Accordion`](crate::Accordion) for a stack of sections the visitor
18/// opens without the server or other signals reading which one is open.
19///
20/// ```
21/// use hypersig::html::p;
22/// use hypersig::{Page, Signals};
23/// use hypersig_ui::{ButtonSize, ButtonVariant, Collapsible};
24/// use serde::{Deserialize, Serialize};
25///
26/// #[derive(Signals, Serialize, Deserialize)]
27/// struct Order {
28///     details: bool,
29/// }
30///
31/// let details = Collapsible::new(Order::details());
32/// let html = Page::new("Order", Order { details: false })
33///     .child(details.trigger(ButtonVariant::Ghost, ButtonSize::Sm).text("Details"))
34///     .child(details.content().child(p().text("Shipped on Monday.")))
35///     .render();
36/// assert!(html.contains(r#"aria-expanded="false""#));
37/// assert!(html.contains(r#"aria-controls="ui-details-content""#));
38/// ```
39pub struct Collapsible<S> {
40    open: Sig<S, bool>,
41}
42
43impl<S> Collapsible<S> {
44    /// A collapsible whose region is shown while `open` is true.
45    #[must_use]
46    pub fn new(open: Sig<S, bool>) -> Self {
47        Self { open }
48    }
49
50    fn content_id(self) -> Id {
51        crate::id::of(self.open, "content")
52    }
53
54    /// The button that shows and hides the region.
55    #[must_use]
56    pub fn trigger(self, variant: ButtonVariant, size: ButtonSize) -> El<S> {
57        let open = self.open;
58        button(variant, size)
59            .aria_controls(&[&self.content_id()])
60            .bind_attr(attr::ARIA_EXPANDED, if_else(open, "true", "false"))
61            .on_click(open.toggle())
62    }
63
64    /// The region, empty, for the content added with [`El::child`].
65    #[must_use]
66    pub fn content(self) -> El<S> {
67        div().id(self.content_id()).show(self.open)
68    }
69}
70
71impl<S> Clone for Collapsible<S> {
72    fn clone(&self) -> Self {
73        *self
74    }
75}
76
77impl<S> Copy for Collapsible<S> {}
78
79impl<S> std::fmt::Debug for Collapsible<S> {
80    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81        f.debug_tuple("Collapsible").field(&self.open).finish()
82    }
83}
84
85#[cfg(test)]
86mod tests {
87    use hypersig::{Page, Signals};
88    use serde::{Deserialize, Serialize};
89
90    use super::Collapsible;
91    use crate::{ButtonSize, ButtonVariant};
92
93    #[derive(Signals, Serialize, Deserialize)]
94    struct Order {
95        details: bool,
96    }
97
98    #[test]
99    fn the_region_is_hidden_while_closed_and_the_button_flips_it() {
100        let details = Collapsible::new(Order::details());
101        let html = Page::new("Order", Order { details: false })
102            .child(details.trigger(ButtonVariant::Ghost, ButtonSize::Sm))
103            .child(details.content())
104            .render();
105        assert!(html.contains(r#"id="ui-details-content""#));
106        assert!(html.contains("data-hs-on-click"));
107        assert!(html.contains(r#"aria-expanded="false""#));
108    }
109}