Skip to main content

next_rust_view/
attrs.rs

1//! Attribute helpers.
2//!
3//! ```
4//! use next_rust_view::*;
5//! let el = input![r#type("email"), name("email"), required(true), aria("label", "Email")];
6//! assert_eq!(render_static(el), r#"<input type="email" name="email" required aria-label="Email">"#);
7//! ```
8
9use std::borrow::Cow;
10
11use crate::node::{Attr, AttrValue};
12use crate::style::CssClass;
13
14/// Any attribute: `attr("hx-get", "/x")`. Event handler attributes (`on*`)
15/// are refused here; see [`raw_attr`].
16pub fn attr(name: impl Into<Cow<'static, str>>, value: impl AttrText) -> Attr {
17    Attr::new(name, value.into_attr_text())
18}
19
20/// An attribute that is allowed to carry script, e.g. `onclick`. The value is
21/// still HTML-escaped, but its *content* will execute: never pass user input.
22pub fn raw_attr(name: impl Into<Cow<'static, str>>, value: impl AttrText) -> Attr {
23    let mut a = Attr::new(name, value.into_attr_text());
24    a.trusted = true;
25    a
26}
27
28/// Values accepted as attribute text.
29pub trait AttrText {
30    fn into_attr_text(self) -> Cow<'static, str>;
31}
32
33impl AttrText for &str {
34    fn into_attr_text(self) -> Cow<'static, str> {
35        Cow::Owned(self.to_owned())
36    }
37}
38impl AttrText for String {
39    fn into_attr_text(self) -> Cow<'static, str> {
40        Cow::Owned(self)
41    }
42}
43impl AttrText for &String {
44    fn into_attr_text(self) -> Cow<'static, str> {
45        Cow::Owned(self.clone())
46    }
47}
48impl AttrText for Cow<'static, str> {
49    fn into_attr_text(self) -> Cow<'static, str> {
50        self
51    }
52}
53macro_rules! num_attr_text {
54    ($($t:ty),*) => {$(
55        impl AttrText for $t {
56            fn into_attr_text(self) -> Cow<'static, str> { Cow::Owned(self.to_string()) }
57        }
58    )*};
59}
60num_attr_text!(i32, i64, u8, u16, u32, u64, usize, f32, f64);
61
62/// Values accepted by [`class`].
63pub trait ClassValue {
64    fn push_class(self, out: &mut String, sheets: &mut Vec<&'static crate::Stylesheet>);
65}
66
67fn push_word(out: &mut String, word: &str) {
68    let word = word.trim();
69    if word.is_empty() {
70        return;
71    }
72    if !out.is_empty() {
73        out.push(' ');
74    }
75    out.push_str(word);
76}
77
78impl ClassValue for &str {
79    fn push_class(self, out: &mut String, _: &mut Vec<&'static crate::Stylesheet>) {
80        push_word(out, self);
81    }
82}
83impl ClassValue for String {
84    fn push_class(self, out: &mut String, _: &mut Vec<&'static crate::Stylesheet>) {
85        push_word(out, &self);
86    }
87}
88impl ClassValue for &String {
89    fn push_class(self, out: &mut String, _: &mut Vec<&'static crate::Stylesheet>) {
90        push_word(out, self);
91    }
92}
93impl ClassValue for CssClass {
94    fn push_class(self, out: &mut String, sheets: &mut Vec<&'static crate::Stylesheet>) {
95        push_word(out, self.name);
96        sheets.push(self.sheet);
97    }
98}
99impl<T: ClassValue> ClassValue for Option<T> {
100    fn push_class(self, out: &mut String, sheets: &mut Vec<&'static crate::Stylesheet>) {
101        if let Some(v) = self {
102            v.push_class(out, sheets);
103        }
104    }
105}
106impl<T: ClassValue, const N: usize> ClassValue for [T; N] {
107    fn push_class(self, out: &mut String, sheets: &mut Vec<&'static crate::Stylesheet>) {
108        for v in self {
109            v.push_class(out, sheets);
110        }
111    }
112}
113impl<T: ClassValue> ClassValue for Vec<T> {
114    fn push_class(self, out: &mut String, sheets: &mut Vec<&'static crate::Stylesheet>) {
115        for v in self {
116            v.push_class(out, sheets);
117        }
118    }
119}
120/// `(value, condition)` – include `value` only when `condition` is true.
121impl<T: ClassValue> ClassValue for (T, bool) {
122    fn push_class(self, out: &mut String, sheets: &mut Vec<&'static crate::Stylesheet>) {
123        if self.1 {
124            self.0.push_class(out, sheets);
125        }
126    }
127}
128
129/// `class("a b")`, `class(styles.card)`, `class(["a", "b"])`,
130/// `class([("active", is_active)])`. Multiple `class` parts are merged.
131pub fn class(value: impl ClassValue) -> Attr {
132    let mut s = String::new();
133    let mut sheets = Vec::new();
134    value.push_class(&mut s, &mut sheets);
135    let mut a = Attr::new("class", s);
136    a.sheets = sheets;
137    a
138}
139
140/// Include `attr` only when `condition` holds.
141pub fn attr_if(condition: bool, attr: Attr) -> Attr {
142    if condition { attr } else { Attr::none() }
143}
144
145/// `data-*` attribute: `data("id", "42")` → `data-id="42"`.
146pub fn data(name: &str, value: impl AttrText) -> Attr {
147    Attr::new(format!("data-{name}"), value.into_attr_text())
148}
149
150/// `aria-*` attribute: `aria("label", "Close")` → `aria-label="Close"`.
151pub fn aria(name: &str, value: impl AttrText) -> Attr {
152    Attr::new(format!("aria-{name}"), value.into_attr_text())
153}
154
155/// Stable identity for list items, used by client-side hydration.
156pub fn key(value: impl AttrText) -> Attr {
157    Attr::new("data-nr-key", value.into_attr_text())
158}
159
160/// Declarative client event binding for interactive islands:
161/// `on("click", "increment")` → `data-nr-on-click="increment"`.
162pub fn on(event: &str, handler: impl AttrText) -> Attr {
163    Attr::new(format!("data-nr-on-{event}"), handler.into_attr_text())
164}
165
166/// Disable prefetching for a `Link!`.
167pub fn prefetch(enabled: bool) -> Attr {
168    if enabled { Attr::none() } else { Attr::new("data-nr-prefetch", "false") }
169}
170
171/// Replace the history entry instead of pushing a new one (`Link!`).
172pub fn replace(enabled: bool) -> Attr {
173    if enabled { Attr::new("data-nr-replace", "") } else { Attr::none() }
174}
175
176/// Keep the scroll position after a client navigation (`Link!`).
177pub fn scroll(enabled: bool) -> Attr {
178    if enabled { Attr::none() } else { Attr::new("data-nr-scroll", "false") }
179}
180
181/// `type` attribute (also available as `r#type`).
182pub fn type_(value: impl AttrText) -> Attr {
183    Attr::new("type", value.into_attr_text())
184}
185
186/// `for` attribute of `<label>`.
187pub fn for_(value: impl AttrText) -> Attr {
188    Attr::new("for", value.into_attr_text())
189}
190
191/// `r#type("submit")`
192pub fn r#type(value: impl AttrText) -> Attr {
193    type_(value)
194}
195
196/// `r#for("email")`
197pub fn r#for(value: impl AttrText) -> Attr {
198    for_(value)
199}
200
201/// `r#async(true)` for scripts.
202pub fn r#async(on: bool) -> Attr {
203    Attr::boolean("async", on)
204}
205
206macro_rules! text_attrs {
207    ($($(#[$m:meta])* $fn_name:ident => $name:literal),* $(,)?) => {$(
208        $(#[$m])*
209        #[doc = concat!("`", $name, "` attribute.")]
210        pub fn $fn_name(value: impl AttrText) -> Attr {
211            Attr::new($name, value.into_attr_text())
212        }
213    )*};
214}
215
216text_attrs! {
217    id => "id",
218    href => "href",
219    src => "src",
220    srcset => "srcset",
221    sizes => "sizes",
222    alt => "alt",
223    title => "title",
224    style => "style",
225    name => "name",
226    value => "value",
227    placeholder => "placeholder",
228    method => "method",
229    action => "action",
230    enctype => "enctype",
231    rel => "rel",
232    target => "target",
233    width => "width",
234    height => "height",
235    lang => "lang",
236    dir => "dir",
237    role => "role",
238    tabindex => "tabindex",
239    content => "content",
240    charset => "charset",
241    http_equiv => "http-equiv",
242    min => "min",
243    max => "max",
244    step => "step",
245    pattern => "pattern",
246    minlength => "minlength",
247    maxlength => "maxlength",
248    autocomplete => "autocomplete",
249    inputmode => "inputmode",
250    colspan => "colspan",
251    rowspan => "rowspan",
252    loading => "loading",
253    decoding => "decoding",
254    fetchpriority => "fetchpriority",
255    download => "download",
256    crossorigin => "crossorigin",
257    integrity => "integrity",
258    referrerpolicy => "referrerpolicy",
259    datetime => "datetime",
260    form_attr => "form",
261    list => "list",
262    accept => "accept",
263    rows => "rows",
264    cols => "cols",
265    wrap => "wrap",
266    label_attr => "label",
267    media => "media",
268    as_ => "as",
269    nonce => "nonce",
270    slot_attr => "slot",
271    translate => "translate",
272    spellcheck => "spellcheck",
273    enterkeyhint => "enterkeyhint",
274    view_box => "viewBox",
275    fill => "fill",
276    stroke => "stroke",
277    d => "d",
278    xmlns => "xmlns",
279}
280
281macro_rules! bool_attrs {
282    ($($fn_name:ident => $name:literal),* $(,)?) => {$(
283        #[doc = concat!("`", $name, "` boolean attribute.")]
284        pub fn $fn_name(on: bool) -> Attr {
285            Attr::boolean($name, on)
286        }
287    )*};
288}
289
290bool_attrs! {
291    disabled => "disabled",
292    checked => "checked",
293    selected => "selected",
294    required => "required",
295    readonly => "readonly",
296    multiple => "multiple",
297    hidden => "hidden",
298    autofocus => "autofocus",
299    open => "open",
300    defer => "defer",
301    novalidate => "novalidate",
302    controls => "controls",
303    autoplay => "autoplay",
304    muted => "muted",
305    playsinline => "playsinline",
306    inert => "inert",
307    ismap => "ismap",
308    reversed => "reversed",
309    nomodule => "nomodule",
310}
311
312impl AttrValue {
313    pub fn as_text(&self) -> Option<&str> {
314        match self {
315            AttrValue::Text(t) => Some(t),
316            AttrValue::Bool(_) => None,
317        }
318    }
319}