Skip to main content

next_rust_ui/
overlay.rs

1//! Modals.
2
3use next_rust_view::{Element, Node, View};
4
5use crate::button::{common_methods, with_parts};
6use crate::icons::{self, icon};
7use crate::layout::Width;
8use crate::{Extra, Radius, apply, attr, flag, next_id, root, styled};
9
10/// Where a [`Modal`] sits on the screen.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
12pub enum ModalPlacement {
13    #[default]
14    Center,
15    Top,
16    /// A sheet from the bottom: the usual choice on phones.
17    Bottom,
18}
19
20/// A dialog over the page: a `<dialog>` element.
21///
22/// Open it with [`Press::open_modal`](crate::Press::open_modal) on any
23/// pressable component, or with the `open` property to show it right away.
24/// Its close button and `Escape` work without any script; the component
25/// script adds opening as a true modal (focus kept inside, the page inert)
26/// and closing on a click outside.
27///
28/// ```
29/// # use next_rust_ui::*; use next_rust_view::*;
30/// let m = Modal![id = "confirm", title = "Delete the class?",
31///     ModalBody![p!["This cannot be undone."]],
32///     ModalFooter![Button![on_press = Press::close_modal(), "Cancel"]],
33/// ];
34/// let html = render_static(m);
35/// assert!(html.contains(r#"<dialog class="nr-modal nr-modal-md nr-modal-center" id="confirm""#), "{html}");
36/// assert!(html.contains(r#"<form method="dialog""#), "closes without a script");
37/// ```
38#[derive(Default)]
39pub struct Modal {
40    id: Option<String>,
41    title: Option<String>,
42    size: Width,
43    placement: ModalPlacement,
44    radius: Option<Radius>,
45    open: bool,
46    closable: bool,
47    dismissable: bool,
48    scroll_inside: bool,
49    unstyled: bool,
50    extra: Extra,
51}
52
53impl Modal {
54    pub fn new() -> Self {
55        Self { size: Width::Md, closable: true, dismissable: true, ..Self::default() }
56    }
57    common_methods!();
58    with_parts!();
59
60    /// The id [`Press::open_modal`](crate::Press::open_modal) refers to.
61    pub fn id(mut self, v: impl Into<String>) -> Self {
62        self.id = Some(v.into());
63        self
64    }
65    /// A heading at the top (also the dialog's accessible name).
66    pub fn title(mut self, v: impl Into<String>) -> Self {
67        self.title = Some(v.into());
68        self
69    }
70    /// `Sm` 24rem, `Md` 32rem, `Lg` 40rem, `Xl` 48rem, `Xxl` 64rem, `Full`.
71    pub fn size(mut self, v: Width) -> Self {
72        self.size = v;
73        self
74    }
75    pub fn placement(mut self, v: ModalPlacement) -> Self {
76        self.placement = v;
77        self
78    }
79    pub fn radius(mut self, v: Radius) -> Self {
80        self.radius = Some(v);
81        self
82    }
83    /// Shown when the page loads (as a modal once the script runs).
84    pub fn open(mut self, v: bool) -> Self {
85        self.open = v;
86        self
87    }
88    /// A close button in the corner (on by default).
89    pub fn closable(mut self, v: bool) -> Self {
90        self.closable = v;
91        self
92    }
93    /// A click on the backdrop closes it (on by default). `Escape` always does.
94    pub fn dismissable(mut self, v: bool) -> Self {
95        self.dismissable = v;
96        self
97    }
98    /// Long content scrolls inside the body, the header and footer stay put.
99    pub fn scroll_inside(mut self, v: bool) -> Self {
100        self.scroll_inside = v;
101        self
102    }
103}
104
105impl View for Modal {
106    fn into_node(self) -> Node {
107        let (class, attrs, children) = self.extra.split();
108        let size = match self.size {
109            Width::Sm => "nr-modal-sm",
110            Width::Md => "nr-modal-md",
111            Width::Lg => "nr-modal-lg",
112            Width::Xl => "nr-modal-xl",
113            Width::Xxl => "nr-modal-2xl",
114            Width::Full => "nr-modal-full",
115        };
116        let placement = match self.placement {
117            ModalPlacement::Center => "nr-modal-center",
118            ModalPlacement::Top => "nr-modal-top",
119            ModalPlacement::Bottom => "nr-modal-bottom",
120        };
121        let classes = [
122            "nr-modal",
123            size,
124            placement,
125            self.radius.map(Radius::class).unwrap_or(""),
126            if self.scroll_inside { "nr-modal-scroll" } else { "" },
127        ];
128        let mut el = root("dialog", &classes, self.unstyled, class);
129        let id = self.id.unwrap_or_else(|| next_id("nr-modal"));
130        el.set_attr(attr("id", id.clone()));
131        el.set_attr(attr("data-nr-ui", "modal"));
132        el.set_attr(flag("open", self.open));
133        el.set_attr(flag("data-dismissable", self.dismissable));
134        if self.title.is_some() {
135            el.set_attr(attr("aria-labelledby", format!("{id}-title")));
136        }
137        apply(&mut el, attrs);
138
139        let mut boxed = Element::new("div").with(attr("class", "nr-modal-box"));
140        if self.title.is_some() || self.closable {
141            let mut header = Element::new("div").with(attr("class", "nr-modal-header"));
142            if let Some(title) = self.title {
143                header.children.push(
144                    Element::new("h2")
145                        .with(attr("class", "nr-modal-title"))
146                        .with(attr("id", format!("{id}-title")))
147                        .with(title)
148                        .into_node(),
149                );
150            }
151            if self.closable {
152                // Its own `method="dialog"` form: closes natively, and never
153                // nests inside a form the body may hold.
154                header.children.push(
155                    Element::new("form")
156                        .with(attr("method", "dialog"))
157                        .with(attr("class", "nr-modal-closer"))
158                        .with(
159                            Element::new("button")
160                                .with(attr("type", "submit"))
161                                .with(attr("class", "nr-modal-close"))
162                                .with(attr("aria-label", "Close"))
163                                .with(icon(icons::close())),
164                        )
165                        .into_node(),
166                );
167            }
168            boxed.children.push(header.into_node());
169        }
170        boxed.children.extend(children);
171        el.children.push(boxed.into_node());
172        styled(el)
173    }
174}
175
176macro_rules! modal_part {
177    ($name:ident, $class:literal, $doc:literal) => {
178        #[doc = $doc]
179        #[derive(Default)]
180        pub struct $name {
181            unstyled: bool,
182            extra: Extra,
183        }
184
185        impl $name {
186            pub fn new() -> Self {
187                Self::default()
188            }
189            common_methods!();
190            with_parts!();
191        }
192
193        impl View for $name {
194            fn into_node(self) -> Node {
195                let (class, attrs, children) = self.extra.split();
196                let mut el = root("div", &[$class], self.unstyled, class);
197                apply(&mut el, attrs);
198                el.children = children;
199                styled(el)
200            }
201        }
202    };
203}
204
205modal_part!(ModalBody, "nr-modal-body", "The content of a [`Modal`].");
206modal_part!(ModalFooter, "nr-modal-footer", "The bottom of a [`Modal`], typically its actions.");