Skip to main content

next_rust_ui/
toggle.rs

1//! Checkbox, switch and radio buttons. Real form inputs, styled; no script.
2
3use next_rust_view::{Attr, Element, Node, View};
4
5use crate::button::common_methods;
6use crate::icons::{self, icon};
7use crate::{Color, Extra, MaybeText, Radius, Size, apply, attr, flag, next_id, root, styled};
8
9/// Properties shared by checkbox, switch and radio.
10#[derive(Default)]
11struct Toggle {
12    name: Option<String>,
13    value: Option<String>,
14    checked: bool,
15    disabled: bool,
16    required: bool,
17    color: Color,
18    size: Size,
19    radius: Option<Radius>,
20    description: Option<String>,
21    unstyled: bool,
22    extra: Extra,
23}
24
25macro_rules! toggle_methods {
26    () => {
27        pub fn name(mut self, v: impl Into<String>) -> Self {
28            self.t.name = Some(v.into());
29            self
30        }
31        /// Submitted value (`on` when not given).
32        pub fn value(mut self, v: impl Into<String>) -> Self {
33            self.t.value = Some(v.into());
34            self
35        }
36        pub fn checked(mut self, v: bool) -> Self {
37            self.t.checked = v;
38            self
39        }
40        pub fn disabled(mut self, v: bool) -> Self {
41            self.t.disabled = v;
42            self
43        }
44        pub fn required(mut self, v: bool) -> Self {
45            self.t.required = v;
46            self
47        }
48        pub fn color(mut self, v: Color) -> Self {
49            self.t.color = v;
50            self
51        }
52        pub fn size(mut self, v: Size) -> Self {
53            self.t.size = v;
54            self
55        }
56        pub fn radius(mut self, v: Radius) -> Self {
57            self.t.radius = Some(v);
58            self
59        }
60        /// Secondary text under the label.
61        pub fn description(mut self, v: impl MaybeText) -> Self {
62            self.t.description = v.into_text();
63            self
64        }
65        /// Extra classes for the outer element. They win over the defaults.
66        pub fn class(mut self, v: impl Into<String>) -> Self {
67            self.t.extra.push(next_rust_view::attrs::class(v.into()));
68            self
69        }
70        pub fn unstyled(mut self, v: bool) -> Self {
71            self.t.unstyled = v;
72            self
73        }
74        /// Add an attribute to the `<input>` or a child to the label;
75        /// `class(..)` goes to the outer element.
76        pub fn with(mut self, part: impl next_rust_view::Part) -> Self {
77            self.t.extra.push(part);
78            self
79        }
80    };
81}
82
83impl Toggle {
84    /// `<label class=…><input …>{control}<span label>…</span></label>`.
85    fn render(self, kind: &'static str, input_type: &str, role: Option<&str>, control: Node) -> Node {
86        let (class, attrs, children) = self.extra.split();
87        let size = format!("{kind}-{}", self.size.suffix());
88        let classes = [kind, self.color.class(), &size, self.radius.map(Radius::class).unwrap_or("")];
89        let mut el = root("label", &classes, self.unstyled, class);
90        el.set_attr(flag("data-disabled", self.disabled));
91        let id = next_id(kind);
92        let mut input = Element::new_void("input")
93            .with(attr("class", format!("{kind}-input")))
94            .with(attr("type", input_type.to_owned()))
95            .with(flag("checked", self.checked))
96            .with(flag("disabled", self.disabled))
97            .with(flag("required", self.required));
98        if let Some(role) = role {
99            input.set_attr(attr("role", role.to_owned()));
100        }
101        if let Some(n) = self.name {
102            input.set_attr(attr("name", n));
103        }
104        if let Some(v) = self.value {
105            input.set_attr(attr("value", v));
106        }
107        if self.description.is_some() {
108            input.set_attr(attr("aria-describedby", format!("{id}-description")));
109        }
110        apply(&mut input, attrs);
111        el.children.push(input.into_node());
112        el.children.push(control);
113        if !children.is_empty() || self.description.is_some() {
114            let mut text = Element::new("span").with(attr("class", format!("{kind}-text")));
115            if !children.is_empty() {
116                text = text.with(Element::new("span").with(attr("class", format!("{kind}-label"))).with(children));
117            }
118            if let Some(d) = self.description {
119                text = text.with(
120                    Element::new("span")
121                        .with(attr("class", "nr-toggle-description"))
122                        .with(attr("id", format!("{id}-description")))
123                        .with(d),
124                );
125            }
126            el.children.push(text.into_node());
127        }
128        styled(el)
129    }
130}
131
132/// A checkbox with a label.
133///
134/// ```
135/// # use next_rust_ui::*; use next_rust_view::*;
136/// let html = render_static(Checkbox![name = "terms", required = true, "I agree"]);
137/// assert!(html.contains(r#"<input class="nr-checkbox-input" type="checkbox" required name="terms">"#));
138/// ```
139#[derive(Default)]
140pub struct Checkbox {
141    t: Toggle,
142}
143
144impl Checkbox {
145    pub fn new() -> Self {
146        Self::default()
147    }
148    toggle_methods!();
149}
150
151impl View for Checkbox {
152    fn into_node(self) -> Node {
153        let box_ = Element::new("span")
154            .with(attr("class", "nr-checkbox-box"))
155            .with(attr("aria-hidden", "true"))
156            .with(icon(icons::check().stroke_width(3.0)))
157            .into_node();
158        self.t.render("nr-checkbox", "checkbox", None, box_)
159    }
160}
161
162/// An on/off switch.
163#[derive(Default)]
164pub struct Switch {
165    t: Toggle,
166}
167
168impl Switch {
169    pub fn new() -> Self {
170        Self::default()
171    }
172    toggle_methods!();
173}
174
175impl View for Switch {
176    fn into_node(self) -> Node {
177        let track = Element::new("span")
178            .with(attr("class", "nr-switch-track"))
179            .with(attr("aria-hidden", "true"))
180            .with(Element::new("span").with(attr("class", "nr-switch-thumb")))
181            .into_node();
182        self.t.render("nr-switch", "checkbox", Some("switch"), track)
183    }
184}
185
186/// One choice of a [`RadioGroup`].
187#[derive(Default)]
188pub struct Radio {
189    t: Toggle,
190}
191
192impl Radio {
193    pub fn new() -> Self {
194        Self::default()
195    }
196    toggle_methods!();
197}
198
199impl View for Radio {
200    fn into_node(self) -> Node {
201        let dot =
202            Element::new("span").with(attr("class", "nr-radio-circle")).with(attr("aria-hidden", "true")).into_node();
203        self.t.render("nr-radio", "radio", None, dot)
204    }
205}
206
207/// Values accepted inside `RadioGroup![..]`.
208pub trait RadioGroupPart {
209    fn add_to(self, group: &mut RadioGroup);
210}
211impl RadioGroupPart for Radio {
212    fn add_to(self, group: &mut RadioGroup) {
213        group.radios.push(self);
214    }
215}
216impl RadioGroupPart for Vec<Radio> {
217    fn add_to(self, group: &mut RadioGroup) {
218        group.radios.extend(self);
219    }
220}
221impl RadioGroupPart for Attr {
222    fn add_to(self, group: &mut RadioGroup) {
223        group.extra.push(self);
224    }
225}
226
227/// Radio buttons sharing a name, with a label, description and error.
228///
229/// ```
230/// # use next_rust_ui::*; use next_rust_view::*;
231/// let html = render_static(RadioGroup![label = "Plan", name = "plan", value = "pro",
232///     Radio![value = "free", "Free"], Radio![value = "pro", "Pro"]]);
233/// assert!(html.contains(r#"type="radio" checked name="plan" value="pro""#));
234/// ```
235#[derive(Default)]
236pub struct RadioGroup {
237    label: Option<String>,
238    name: Option<String>,
239    value: Option<String>,
240    description: Option<String>,
241    error_message: Option<String>,
242    horizontal: bool,
243    disabled: bool,
244    required: bool,
245    color: Color,
246    size: Size,
247    radios: Vec<Radio>,
248    unstyled: bool,
249    extra: Extra,
250}
251
252impl RadioGroup {
253    pub fn new() -> Self {
254        Self::default()
255    }
256    common_methods!();
257
258    /// Add radios or attributes for the group; `class(..)` goes to the outer element.
259    pub fn with(mut self, part: impl RadioGroupPart) -> Self {
260        part.add_to(&mut self);
261        self
262    }
263    pub fn label(mut self, v: impl Into<String>) -> Self {
264        self.label = Some(v.into());
265        self
266    }
267    /// Name shared by the radios.
268    pub fn name(mut self, v: impl Into<String>) -> Self {
269        self.name = Some(v.into());
270        self
271    }
272    /// The selected value.
273    pub fn value(mut self, v: impl MaybeText) -> Self {
274        self.value = v.into_text();
275        self
276    }
277    pub fn description(mut self, v: impl MaybeText) -> Self {
278        self.description = v.into_text();
279        self
280    }
281    pub fn error_message(mut self, v: impl MaybeText) -> Self {
282        self.error_message = v.into_text();
283        self
284    }
285    /// Lay the radios out in a row.
286    pub fn horizontal(mut self, v: bool) -> Self {
287        self.horizontal = v;
288        self
289    }
290    pub fn disabled(mut self, v: bool) -> Self {
291        self.disabled = v;
292        self
293    }
294    pub fn required(mut self, v: bool) -> Self {
295        self.required = v;
296        self
297    }
298    pub fn color(mut self, v: Color) -> Self {
299        self.color = v;
300        self
301    }
302    pub fn size(mut self, v: Size) -> Self {
303        self.size = v;
304        self
305    }
306}
307
308impl View for RadioGroup {
309    fn into_node(self) -> Node {
310        let (class, attrs, _) = self.extra.split();
311        let mut el = root(
312            "fieldset",
313            &["nr-radio-group", if self.horizontal { "nr-radio-group-row" } else { "" }],
314            self.unstyled,
315            class,
316        );
317        el.set_attr(flag("disabled", self.disabled));
318        el.set_attr(flag("data-invalid", self.error_message.is_some()));
319        el.set_attr(attr("role", "radiogroup"));
320        apply(&mut el, attrs);
321        if let Some(label) = self.label {
322            el.children.push(Element::new("legend").with(attr("class", "nr-field-label")).with(label).into_node());
323        }
324        let mut items = Element::new("div").with(attr("class", "nr-radio-group-items"));
325        for mut radio in self.radios {
326            if radio.t.name.is_none() {
327                radio.t.name = self.name.clone();
328            }
329            if self.value.is_some() && radio.t.value == self.value {
330                radio.t.checked = true;
331            }
332            radio.t.color = self.color;
333            radio.t.size = self.size;
334            radio.t.required |= self.required;
335            items.children.push(radio.into_node());
336        }
337        el.children.push(items.into_node());
338        if let Some(d) = self.description {
339            el.children.push(Element::new("p").with(attr("class", "nr-field-description")).with(d).into_node());
340        }
341        if self.error_message.is_some() || self.name.is_some() {
342            let mut err = Element::new("p").with(attr("class", "nr-field-error")).with(attr("aria-live", "polite"));
343            if let Some(name) = &self.name {
344                err = err.with(attr("data-nr-error", name.clone()));
345            }
346            el.children.push(err.with(self.error_message).into_node());
347        }
348        styled(el)
349    }
350}