Skip to main content

next_rust_ui/
button.rs

1//! Buttons.
2
3use next_rust_view::{Node, View};
4
5use crate::feedback::spinner_node;
6use crate::{Color, Extra, Press, Radius, Size, Variant, apply, attr, flag, root, styled};
7
8/// Add the `class`, `unstyled` and `with` methods every component has.
9macro_rules! common_methods {
10    () => {
11        /// Extra classes for the outer element. They win over the defaults.
12        pub fn class(mut self, v: impl Into<String>) -> Self {
13            self.extra.push(next_rust_view::attrs::class(v.into()));
14            self
15        }
16        /// Leave out the default classes of the outer element.
17        pub fn unstyled(mut self, v: bool) -> Self {
18            self.unstyled = v;
19            self
20        }
21    };
22}
23pub(crate) use common_methods;
24
25/// Add the `with` method: attributes and children, like in an element macro.
26macro_rules! with_parts {
27    () => {
28        /// Add an attribute (`class(..)`, `id(..)`, `aria(..)`, ...) or a child.
29        pub fn with(mut self, part: impl next_rust_view::Part) -> Self {
30            self.extra.push(part);
31            self
32        }
33    };
34}
35pub(crate) use with_parts;
36
37/// A button, or a link styled as one (`href`).
38///
39/// ```
40/// # use next_rust_ui::*; use next_rust_view::*;
41/// let b = Button![variant = Variant::Bordered, color = Color::Danger, size = Size::Sm, "Delete"];
42/// assert!(render_static(b).contains(r#"<button class="nr-btn nr-btn-bordered nr-c-danger nr-btn-sm" type="button">Delete</button>"#));
43/// ```
44#[derive(Default)]
45pub struct Button {
46    color: Color,
47    variant: Variant,
48    size: Size,
49    radius: Option<Radius>,
50    full_width: bool,
51    icon_only: bool,
52    loading: bool,
53    disabled: bool,
54    submit: bool,
55    href: Option<String>,
56    start_content: Option<Node>,
57    end_content: Option<Node>,
58    press: Option<Press>,
59    unstyled: bool,
60    extra: Extra,
61}
62
63impl Button {
64    pub fn new() -> Self {
65        Self::default()
66    }
67    common_methods!();
68    with_parts!();
69
70    pub fn color(mut self, v: Color) -> Self {
71        self.color = v;
72        self
73    }
74    pub fn variant(mut self, v: Variant) -> Self {
75        self.variant = v;
76        self
77    }
78    pub fn size(mut self, v: Size) -> Self {
79        self.size = v;
80        self
81    }
82    pub fn radius(mut self, v: Radius) -> Self {
83        self.radius = Some(v);
84        self
85    }
86    /// Take the full width of the container.
87    pub fn full_width(mut self, v: bool) -> Self {
88        self.full_width = v;
89        self
90    }
91    /// A square button holding only an icon (give it an `aria("label", ..)`).
92    pub fn icon_only(mut self, v: bool) -> Self {
93        self.icon_only = v;
94        self
95    }
96    /// Show a spinner and ignore presses.
97    pub fn loading(mut self, v: bool) -> Self {
98        self.loading = v;
99        self
100    }
101    pub fn disabled(mut self, v: bool) -> Self {
102        self.disabled = v;
103        self
104    }
105    /// A submit button (`type="submit"`). Buttons are `type="button"` otherwise.
106    /// Inside a form posting to a server action, it shows a spinner while the form submits.
107    pub fn submit(mut self, v: bool) -> Self {
108        self.submit = v;
109        self
110    }
111    /// Render a link that looks like a button (client-side navigation).
112    pub fn href(mut self, v: impl Into<String>) -> Self {
113        self.href = Some(v.into());
114        self
115    }
116    /// Content before the label, typically an icon.
117    pub fn start_content(mut self, v: impl View) -> Self {
118        self.start_content = Some(v.into_node());
119        self
120    }
121    /// Content after the label.
122    pub fn end_content(mut self, v: impl View) -> Self {
123        self.end_content = Some(v.into_node());
124        self
125    }
126    /// What pressing the button does: `on_press = action!(save)`, or a [`Press`].
127    pub fn on_press(mut self, v: impl Into<Press>) -> Self {
128        self.press = Some(v.into());
129        self
130    }
131    /// Same as [`Button::on_press`].
132    pub fn on_click(self, v: impl Into<Press>) -> Self {
133        self.on_press(v)
134    }
135}
136
137impl View for Button {
138    fn into_node(self) -> Node {
139        let (class, attrs, children) = self.extra.split();
140        let variant = format!("nr-btn-{}", self.variant.suffix());
141        let size = format!("nr-btn-{}", self.size.suffix());
142        let classes = [
143            "nr-btn",
144            &variant,
145            self.color.class(),
146            &size,
147            self.radius.map(Radius::class).unwrap_or(""),
148            if self.full_width { "nr-btn-full" } else { "" },
149            if self.icon_only { "nr-btn-icon" } else { "" },
150        ];
151        let tag = if self.href.is_some() { "a" } else { "button" };
152        let mut el = root(tag, &classes, self.unstyled, class);
153        let inactive = self.disabled || self.loading;
154        match &self.href {
155            Some(href) => {
156                el.set_attr(attr("href", href.clone()));
157                el.set_attr(attr("data-nr-link", ""));
158                if inactive {
159                    el.set_attr(attr("aria-disabled", "true"));
160                    el.set_attr(attr("tabindex", "-1"));
161                }
162            }
163            None => {
164                el.set_attr(attr("type", if self.submit { "submit" } else { "button" }));
165                el.set_attr(flag("disabled", inactive));
166            }
167        }
168        if self.loading {
169            el.set_attr(attr("data-loading", "true"));
170            el.set_attr(attr("aria-busy", "true"));
171        }
172        if let Some(press) = &self.press {
173            apply(&mut el, press.attrs());
174        }
175        apply(&mut el, attrs);
176        let start = if self.loading { Some(spinner_node("nr-btn-spinner")) } else { self.start_content };
177        if let Some(start) = start {
178            el.children.push(start);
179        } else if self.submit || self.press.as_ref().is_some_and(Press::is_action) {
180            // Shown while the form submits or the action runs (see the stylesheet).
181            el.children.push(spinner_node("nr-btn-spinner nr-btn-pending"));
182        }
183        el.children.extend(children);
184        if let Some(end) = self.end_content {
185            el.children.push(end);
186        }
187        styled(el)
188    }
189}
190
191/// Buttons joined into one control.
192#[derive(Default)]
193pub struct ButtonGroup {
194    full_width: bool,
195    unstyled: bool,
196    extra: Extra,
197}
198
199impl ButtonGroup {
200    pub fn new() -> Self {
201        Self::default()
202    }
203    common_methods!();
204    with_parts!();
205
206    pub fn full_width(mut self, v: bool) -> Self {
207        self.full_width = v;
208        self
209    }
210}
211
212impl View for ButtonGroup {
213    fn into_node(self) -> Node {
214        let (class, attrs, children) = self.extra.split();
215        let mut el =
216            root("div", &["nr-btn-group", if self.full_width { "nr-btn-full" } else { "" }], self.unstyled, class);
217        el.set_attr(attr("role", "group"));
218        apply(&mut el, attrs);
219        el.children = children;
220        styled(el)
221    }
222}