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/// Make a link do a full page load instead of client-side navigation:
177/// `a![href("/logout"), reload(true), "Log out"]`.
178pub fn reload(enabled: bool) -> Attr {
179    if enabled { Attr::new("data-nr-reload", "") } else { Attr::none() }
180}
181
182/// Keep the scroll position after a client navigation (`Link!`).
183pub fn scroll(enabled: bool) -> Attr {
184    if enabled { Attr::none() } else { Attr::new("data-nr-scroll", "false") }
185}
186
187/// `type` attribute (also available as `r#type`).
188pub fn type_(value: impl AttrText) -> Attr {
189    Attr::new("type", value.into_attr_text())
190}
191
192/// `for` attribute of `<label>`.
193pub fn for_(value: impl AttrText) -> Attr {
194    Attr::new("for", value.into_attr_text())
195}
196
197/// `r#type("submit")`
198pub fn r#type(value: impl AttrText) -> Attr {
199    type_(value)
200}
201
202/// `r#for("email")`
203pub fn r#for(value: impl AttrText) -> Attr {
204    for_(value)
205}
206
207/// `r#async(true)` for scripts.
208pub fn r#async(on: bool) -> Attr {
209    Attr::boolean("async", on)
210}
211
212macro_rules! text_attrs {
213    ($($(#[$m:meta])* $fn_name:ident => $name:literal),* $(,)?) => {$(
214        $(#[$m])*
215        #[doc = concat!("`", $name, "` attribute.")]
216        pub fn $fn_name(value: impl AttrText) -> Attr {
217            Attr::new($name, value.into_attr_text())
218        }
219    )*};
220}
221
222text_attrs! {
223    id => "id",
224    href => "href",
225    src => "src",
226    srcset => "srcset",
227    sizes => "sizes",
228    alt => "alt",
229    title => "title",
230    style => "style",
231    name => "name",
232    value => "value",
233    placeholder => "placeholder",
234    method => "method",
235    action => "action",
236    enctype => "enctype",
237    rel => "rel",
238    target => "target",
239    width => "width",
240    height => "height",
241    lang => "lang",
242    dir => "dir",
243    role => "role",
244    tabindex => "tabindex",
245    content => "content",
246    charset => "charset",
247    http_equiv => "http-equiv",
248    min => "min",
249    max => "max",
250    step => "step",
251    pattern => "pattern",
252    minlength => "minlength",
253    maxlength => "maxlength",
254    autocomplete => "autocomplete",
255    inputmode => "inputmode",
256    colspan => "colspan",
257    rowspan => "rowspan",
258    loading => "loading",
259    decoding => "decoding",
260    fetchpriority => "fetchpriority",
261    download => "download",
262    crossorigin => "crossorigin",
263    integrity => "integrity",
264    referrerpolicy => "referrerpolicy",
265    datetime => "datetime",
266    form_attr => "form",
267    list => "list",
268    accept => "accept",
269    rows => "rows",
270    cols => "cols",
271    wrap => "wrap",
272    label_attr => "label",
273    media => "media",
274    as_ => "as",
275    nonce => "nonce",
276    slot_attr => "slot",
277    translate => "translate",
278    spellcheck => "spellcheck",
279    enterkeyhint => "enterkeyhint",
280    view_box => "viewBox",
281    fill => "fill",
282    stroke => "stroke",
283    d => "d",
284    xmlns => "xmlns",
285}
286
287macro_rules! bool_attrs {
288    ($($fn_name:ident => $name:literal),* $(,)?) => {$(
289        #[doc = concat!("`", $name, "` boolean attribute.")]
290        pub fn $fn_name(on: bool) -> Attr {
291            Attr::boolean($name, on)
292        }
293    )*};
294}
295
296bool_attrs! {
297    disabled => "disabled",
298    checked => "checked",
299    selected => "selected",
300    required => "required",
301    readonly => "readonly",
302    multiple => "multiple",
303    hidden => "hidden",
304    autofocus => "autofocus",
305    open => "open",
306    defer => "defer",
307    novalidate => "novalidate",
308    controls => "controls",
309    autoplay => "autoplay",
310    muted => "muted",
311    playsinline => "playsinline",
312    inert => "inert",
313    ismap => "ismap",
314    reversed => "reversed",
315    nomodule => "nomodule",
316}
317
318impl AttrValue {
319    pub fn as_text(&self) -> Option<&str> {
320        match self {
321            AttrValue::Text(t) => Some(t),
322            AttrValue::Bool(_) => None,
323        }
324    }
325}