Skip to main content

next_rust_ui/
input.rs

1//! Text fields: [`Input`], [`PasswordInput`], [`Textarea`], and the field
2//! frame shared with [`crate::Select`] and [`crate::DatePicker`].
3
4use next_rust_view::{Attr, Element, Node, View};
5
6use crate::icons::{self, icon};
7use crate::{
8    Color, Extra, FieldVariant, MaybeText, Radius, Size, apply, attr, flag, next_id, part_class, root, styled,
9};
10
11/// Where a field's label goes.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
13pub enum LabelPlacement {
14    /// Inside the box: it floats above the value once there is one.
15    #[default]
16    Inside,
17    /// Above the box.
18    Outside,
19    /// To the left of the box.
20    OutsideLeft,
21}
22
23/// Properties every field has.
24#[derive(Default)]
25pub(crate) struct Field {
26    pub label: Option<String>,
27    pub placeholder: Option<String>,
28    pub description: Option<String>,
29    pub error_message: Option<String>,
30    pub invalid: bool,
31    pub name: Option<String>,
32    pub id: Option<String>,
33    pub value: Option<String>,
34    pub required: bool,
35    pub disabled: bool,
36    pub readonly: bool,
37    pub color: Color,
38    pub size: Size,
39    pub variant: FieldVariant,
40    pub radius: Option<Radius>,
41    pub label_placement: LabelPlacement,
42    pub start_content: Option<Node>,
43    pub end_content: Option<Node>,
44    pub full_width: Option<bool>,
45    pub label_class: Option<String>,
46    pub wrapper_class: Option<String>,
47    pub input_class: Option<String>,
48    pub description_class: Option<String>,
49    pub error_class: Option<String>,
50    pub unstyled: bool,
51    pub extra: Extra,
52}
53
54/// The builder methods for [`Field`] properties.
55macro_rules! field_methods {
56    () => {
57        /// Text of the label.
58        pub fn label(mut self, v: impl Into<String>) -> Self {
59            self.field.label = Some(v.into());
60            self
61        }
62        pub fn placeholder(mut self, v: impl Into<String>) -> Self {
63            self.field.placeholder = Some(v.into());
64            self
65        }
66        /// Help text under the field.
67        pub fn description(mut self, v: impl crate::MaybeText) -> Self {
68            self.field.description = v.into_text();
69            self
70        }
71        /// Error text under the field; also marks it invalid.
72        /// `error_message = form.error("email")` shows server validation errors.
73        pub fn error_message(mut self, v: impl crate::MaybeText) -> Self {
74            self.field.error_message = v.into_text();
75            self
76        }
77        /// Show the field as invalid without a message.
78        pub fn invalid(mut self, v: bool) -> Self {
79            self.field.invalid = v;
80            self
81        }
82        /// Form field name. Server-action validation errors for this name
83        /// appear under the field automatically.
84        pub fn name(mut self, v: impl Into<String>) -> Self {
85            self.field.name = Some(v.into());
86            self
87        }
88        /// `id` of the control (generated when not given).
89        pub fn id(mut self, v: impl Into<String>) -> Self {
90            self.field.id = Some(v.into());
91            self
92        }
93        /// Initial value: `value = form.value("email")`.
94        pub fn value(mut self, v: impl crate::MaybeText) -> Self {
95            self.field.value = v.into_text();
96            self
97        }
98        pub fn required(mut self, v: bool) -> Self {
99            self.field.required = v;
100            self
101        }
102        pub fn disabled(mut self, v: bool) -> Self {
103            self.field.disabled = v;
104            self
105        }
106        pub fn readonly(mut self, v: bool) -> Self {
107            self.field.readonly = v;
108            self
109        }
110        /// Color of the focused field.
111        pub fn color(mut self, v: crate::Color) -> Self {
112            self.field.color = v;
113            self
114        }
115        pub fn size(mut self, v: crate::Size) -> Self {
116            self.field.size = v;
117            self
118        }
119        pub fn variant(mut self, v: crate::FieldVariant) -> Self {
120            self.field.variant = v;
121            self
122        }
123        pub fn radius(mut self, v: crate::Radius) -> Self {
124            self.field.radius = Some(v);
125            self
126        }
127        pub fn label_placement(mut self, v: crate::LabelPlacement) -> Self {
128            self.field.label_placement = v;
129            self
130        }
131        /// Content at the start of the box, typically an icon.
132        pub fn start_content(mut self, v: impl next_rust_view::View) -> Self {
133            self.field.start_content = Some(v.into_node());
134            self
135        }
136        /// Content at the end of the box.
137        pub fn end_content(mut self, v: impl next_rust_view::View) -> Self {
138            self.field.end_content = Some(v.into_node());
139            self
140        }
141        /// Take the full width of the container (the default).
142        pub fn full_width(mut self, v: bool) -> Self {
143            self.field.full_width = Some(v);
144            self
145        }
146        /// Extra classes for the label.
147        pub fn label_class(mut self, v: impl Into<String>) -> Self {
148            self.field.label_class = Some(v.into());
149            self
150        }
151        /// Extra classes for the box around the control.
152        pub fn wrapper_class(mut self, v: impl Into<String>) -> Self {
153            self.field.wrapper_class = Some(v.into());
154            self
155        }
156        /// Extra classes for the control itself.
157        pub fn input_class(mut self, v: impl Into<String>) -> Self {
158            self.field.input_class = Some(v.into());
159            self
160        }
161        pub fn description_class(mut self, v: impl Into<String>) -> Self {
162            self.field.description_class = Some(v.into());
163            self
164        }
165        pub fn error_class(mut self, v: impl Into<String>) -> Self {
166            self.field.error_class = Some(v.into());
167            self
168        }
169        /// Extra classes for the outer element. They win over the defaults.
170        pub fn class(mut self, v: impl Into<String>) -> Self {
171            self.field.extra.push(next_rust_view::attrs::class(v.into()));
172            self
173        }
174        /// Leave out the default classes of the outer element.
175        pub fn unstyled(mut self, v: bool) -> Self {
176            self.field.unstyled = v;
177            self
178        }
179    };
180}
181pub(crate) use field_methods;
182
183/// What a field renders around its control.
184pub(crate) struct Frame {
185    /// Component class: `nr-input`, `nr-select`, ...
186    pub kind: &'static str,
187    /// The label floats inside the box (the control shows no placeholder).
188    pub floats: bool,
189    /// Popovers, placed at the end of the box.
190    pub after_box: Vec<Node>,
191    /// Extra root attributes (`data-nr-ui`, ...).
192    pub root_attrs: Vec<Attr>,
193    /// Extra end content (toggle buttons).
194    pub end: Vec<Node>,
195}
196
197impl Field {
198    /// The id of the control, generated once.
199    pub fn control_id(&mut self) -> String {
200        self.id.get_or_insert_with(|| next_id("nr-field")).clone()
201    }
202
203    pub fn is_invalid(&self) -> bool {
204        self.invalid || self.error_message.is_some()
205    }
206
207    /// Attributes every control gets: id, name, required, disabled, aria.
208    pub fn control_attrs(&mut self) -> Vec<Attr> {
209        let id = self.control_id();
210        let mut attrs = vec![attr("id", id.clone())];
211        if let Some(name) = &self.name {
212            attrs.push(attr("name", name.clone()));
213        }
214        attrs.push(flag("required", self.required));
215        attrs.push(flag("disabled", self.disabled));
216        let mut described = Vec::new();
217        if self.description.is_some() {
218            described.push(format!("{id}-description"));
219        }
220        if self.error_message.is_some() || self.name.is_some() {
221            described.push(format!("{id}-error"));
222        }
223        if !described.is_empty() {
224            attrs.push(attr("aria-describedby", described.join(" ")));
225        }
226        if self.is_invalid() {
227            attrs.push(attr("aria-invalid", "true"));
228        }
229        attrs
230    }
231
232    fn label_node(&self, id: &str) -> Option<Node> {
233        let label = self.label.as_ref()?;
234        let mut el = Element::new("label")
235            .with(part_class("nr-field-label", &self.label_class))
236            .with(attr("for", id.to_owned()))
237            .with(attr("id", format!("{id}-label")))
238            .with(label.clone());
239        if self.required {
240            el = el.with(
241                Element::new("span")
242                    .with(attr("class", "nr-field-required"))
243                    .with(attr("aria-hidden", "true"))
244                    .with("*"),
245            );
246        }
247        Some(el.into_node())
248    }
249
250    /// The whole field around `control`.
251    pub fn render(mut self, control: Node, frame: Frame) -> Node {
252        let id = self.control_id();
253        let (class, attrs, _) = std::mem::take(&mut self.extra).split();
254        let size = format!("nr-field-{}", self.size.suffix());
255        let placement = match self.label_placement {
256            LabelPlacement::Inside => "nr-label-inside",
257            LabelPlacement::Outside => "nr-label-outside",
258            LabelPlacement::OutsideLeft => "nr-label-left",
259        };
260        let has_label = self.label.is_some();
261        let classes = [
262            "nr-field",
263            frame.kind,
264            self.variant.class(),
265            self.color.class(),
266            &size,
267            if has_label { placement } else { "nr-label-none" },
268            self.radius.map(Radius::class).unwrap_or(""),
269            if self.full_width.unwrap_or(true) { "nr-field-full" } else { "" },
270        ];
271        let mut el = root("div", &classes, self.unstyled, class);
272        el.set_attr(flag("data-invalid", self.is_invalid()));
273        el.set_attr(flag("data-disabled", self.disabled));
274        el.set_attr(flag("data-float", frame.floats && has_label && self.label_placement == LabelPlacement::Inside));
275        apply(&mut el, frame.root_attrs);
276        apply(&mut el, attrs);
277
278        let inside = self.label_placement == LabelPlacement::Inside;
279        if !inside {
280            el.children.extend(self.label_node(&id));
281        }
282        let mut wrap = Element::new("div").with(part_class("nr-field-wrap", &self.wrapper_class));
283        if let Some(start) = self.start_content.take() {
284            wrap.children.push(Element::new("span").with(attr("class", "nr-field-start")).with(start).into_node());
285        }
286        let mut inner = Element::new("div").with(attr("class", "nr-field-inner"));
287        if inside {
288            inner.children.extend(self.label_node(&id));
289        }
290        inner.children.push(control);
291        wrap.children.push(inner.into_node());
292        let mut end: Vec<Node> = self.end_content.take().into_iter().collect();
293        end.extend(frame.end);
294        if !end.is_empty() {
295            wrap.children.push(Element::new("span").with(attr("class", "nr-field-end")).with(end).into_node());
296        }
297        // Popovers are positioned against the box.
298        wrap.children.extend(frame.after_box);
299        let mut main = Element::new("div").with(attr("class", "nr-field-main"));
300        main.children.push(wrap.into_node());
301        if let Some(description) = &self.description {
302            main.children.push(
303                Element::new("p")
304                    .with(part_class("nr-field-description", &self.description_class))
305                    .with(attr("id", format!("{id}-description")))
306                    .with(description.clone())
307                    .into_node(),
308            );
309        }
310        if self.error_message.is_some() || self.name.is_some() {
311            // Kept even when empty: the client runtime writes server-action
312            // validation errors for `name` into it.
313            let mut err = Element::new("p")
314                .with(part_class("nr-field-error", &self.error_class))
315                .with(attr("id", format!("{id}-error")))
316                .with(attr("aria-live", "polite"));
317            if let Some(name) = &self.name {
318                err = err.with(attr("data-nr-error", name.clone()));
319            }
320            main.children.push(err.with(self.error_message.clone()).into_node());
321        }
322        el.children.push(main.into_node());
323        styled(el)
324    }
325}
326
327/// A text input.
328///
329/// ```
330/// # use next_rust_ui::*; use next_rust_view::*;
331/// let html = render_static(Input![label = "Email", name = "email", kind = "email", required = true]);
332/// assert!(html.contains(r#"<input class="nr-field-input" type="email" placeholder=" " id="#));
333/// assert!(html.contains(r#"data-nr-error="email""#));
334/// ```
335#[derive(Default)]
336pub struct Input {
337    field: Field,
338    kind: Option<String>,
339    clearable: bool,
340}
341
342impl Input {
343    pub fn new() -> Self {
344        Self::default()
345    }
346    field_methods!();
347
348    /// Add an attribute to the `<input>` (`attr("autocomplete", "email")`,
349    /// `aria(..)`, ...); `class(..)` goes to the outer element.
350    pub fn with(mut self, part: impl next_rust_view::Part) -> Self {
351        self.field.extra.push(part);
352        self
353    }
354    /// The input `type`: `"email"`, `"number"`, `"search"`, ... (default `"text"`).
355    pub fn kind(mut self, v: impl Into<String>) -> Self {
356        self.kind = Some(v.into());
357        self
358    }
359    /// A button that clears the value.
360    pub fn clearable(mut self, v: bool) -> Self {
361        self.clearable = v;
362        self
363    }
364
365    fn render(mut self, password: bool) -> Node {
366        let kind = if password { "password".to_owned() } else { self.kind.take().unwrap_or_else(|| "text".into()) };
367        let (class, attrs, _) = std::mem::take(&mut self.field.extra).split();
368        if let Some(class) = class {
369            self.field.extra.push(class);
370        }
371        let floats = self.field.placeholder.is_none();
372        let mut input = Element::new_void("input")
373            .with(part_class("nr-field-input", &self.field.input_class))
374            .with(attr("type", kind))
375            .with(attr("placeholder", self.field.placeholder.clone().unwrap_or_else(|| " ".into())));
376        apply(&mut input, self.field.control_attrs());
377        if let Some(value) = &self.field.value {
378            input.set_attr(attr("value", value.clone()));
379        }
380        input.set_attr(flag("readonly", self.field.readonly));
381        if password && !attrs.iter().any(|a| a.name == "autocomplete") {
382            input.set_attr(attr("autocomplete", "current-password"));
383        }
384        apply(&mut input, attrs);
385
386        let mut end = Vec::new();
387        let mut root_attrs = Vec::new();
388        if self.clearable {
389            root_attrs.push(attr("data-nr-ui", "field"));
390            end.push(icon_button("nr-field-clear", "Clear", "clear", icon(icons::close())));
391        }
392        if password {
393            root_attrs.push(attr("data-nr-ui", "field"));
394            end.push(
395                Element::new("button")
396                    .with(attr("type", "button"))
397                    .with(attr("class", "nr-field-action nr-password-toggle"))
398                    .with(attr("data-nr-field-action", "toggle-password"))
399                    .with(attr("aria-label", "Show password"))
400                    .with(attr("aria-pressed", "false"))
401                    .with(Element::new("span").with(attr("class", "nr-password-show")).with(icon(icons::eye())))
402                    .with(Element::new("span").with(attr("class", "nr-password-hide")).with(icon(icons::eye_off())))
403                    .into_node(),
404            );
405        }
406        let kind = if password { "nr-input nr-password" } else { "nr-input" };
407        self.field.render(input.into_node(), Frame { kind, floats, after_box: Vec::new(), root_attrs, end })
408    }
409}
410
411/// A small button inside a field (clear, toggle, open).
412pub(crate) fn icon_button(class: &str, label: &str, action: &str, content: Node) -> Node {
413    Element::new("button")
414        .with(attr("type", "button"))
415        .with(attr("class", format!("nr-field-action {class}")))
416        .with(attr("data-nr-field-action", action.to_owned()))
417        .with(attr("aria-label", label.to_owned()))
418        .with(attr("tabindex", "-1"))
419        .with(content)
420        .into_node()
421}
422
423impl View for Input {
424    fn into_node(self) -> Node {
425        self.render(false)
426    }
427}
428
429/// A password input with a button that shows and hides the password.
430#[derive(Default)]
431pub struct PasswordInput {
432    input: Input,
433}
434
435impl PasswordInput {
436    pub fn new() -> Self {
437        Self::default()
438    }
439
440    /// Add an attribute to the `<input>`; `class(..)` goes to the outer element.
441    pub fn with(mut self, part: impl next_rust_view::Part) -> Self {
442        self.input = self.input.with(part);
443        self
444    }
445}
446
447/// `PasswordInput` has the same properties as `Input`.
448macro_rules! delegate_field {
449    ($($name:ident($ty:ty)),* $(,)?) => {
450        impl PasswordInput {$(
451            #[doc = concat!("See [`Input::", stringify!($name), "`].")]
452            pub fn $name(mut self, v: $ty) -> Self {
453                self.input = self.input.$name(v);
454                self
455            }
456        )*}
457    };
458}
459delegate_field!(
460    label(&str),
461    placeholder(&str),
462    name(&str),
463    id(&str),
464    required(bool),
465    disabled(bool),
466    readonly(bool),
467    color(Color),
468    size(Size),
469    variant(FieldVariant),
470    radius(Radius),
471    label_placement(LabelPlacement),
472    full_width(bool),
473    label_class(&str),
474    wrapper_class(&str),
475    input_class(&str),
476    description_class(&str),
477    error_class(&str),
478    class(&str),
479    unstyled(bool),
480);
481
482impl PasswordInput {
483    pub fn description(mut self, v: impl MaybeText) -> Self {
484        self.input = self.input.description(v);
485        self
486    }
487    pub fn error_message(mut self, v: impl MaybeText) -> Self {
488        self.input = self.input.error_message(v);
489        self
490    }
491    pub fn invalid(mut self, v: bool) -> Self {
492        self.input = self.input.invalid(v);
493        self
494    }
495    pub fn value(mut self, v: impl MaybeText) -> Self {
496        self.input = self.input.value(v);
497        self
498    }
499    pub fn start_content(mut self, v: impl View) -> Self {
500        self.input = self.input.start_content(v);
501        self
502    }
503    pub fn end_content(mut self, v: impl View) -> Self {
504        self.input = self.input.end_content(v);
505        self
506    }
507    /// `autocomplete="new-password"` for sign-up forms.
508    pub fn new_password(self, v: bool) -> Self {
509        if v { self.with(attr("autocomplete", "new-password")) } else { self }
510    }
511}
512
513impl View for PasswordInput {
514    fn into_node(self) -> Node {
515        self.input.render(true)
516    }
517}
518
519/// A multi-line text input that grows with its content.
520#[derive(Default)]
521pub struct Textarea {
522    field: Field,
523    rows: Option<u32>,
524}
525
526impl Textarea {
527    pub fn new() -> Self {
528        Self::default()
529    }
530    field_methods!();
531
532    /// Add an attribute to the `<textarea>`; `class(..)` goes to the outer element.
533    pub fn with(mut self, part: impl next_rust_view::Part) -> Self {
534        self.field.extra.push(part);
535        self
536    }
537    /// Minimum number of rows (default 3).
538    pub fn rows(mut self, v: u32) -> Self {
539        self.rows = Some(v);
540        self
541    }
542}
543
544impl View for Textarea {
545    fn into_node(mut self) -> Node {
546        let (class, attrs, _) = std::mem::take(&mut self.field.extra).split();
547        if let Some(class) = class {
548            self.field.extra.push(class);
549        }
550        let floats = self.field.placeholder.is_none();
551        let mut area = Element::new("textarea")
552            .with(part_class("nr-field-input nr-textarea-input", &self.field.input_class))
553            .with(attr("rows", self.rows.unwrap_or(3).to_string()))
554            .with(attr("placeholder", self.field.placeholder.clone().unwrap_or_else(|| " ".into())));
555        apply(&mut area, self.field.control_attrs());
556        area.set_attr(flag("readonly", self.field.readonly));
557        apply(&mut area, attrs);
558        area.children.extend(self.field.value.clone().map(View::into_node));
559        self.field.render(
560            area.into_node(),
561            Frame { kind: "nr-textarea", floats, after_box: Vec::new(), root_attrs: Vec::new(), end: Vec::new() },
562        )
563    }
564}