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. By default a page is prefetched when the
167/// mouse rests on its link for 400 ms.
168pub fn prefetch(enabled: bool) -> Attr {
169    if enabled { Attr::none() } else { Attr::new("data-nr-prefetch", "false") }
170}
171
172/// Replace the history entry instead of pushing a new one (`Link!`).
173pub fn replace(enabled: bool) -> Attr {
174    if enabled { Attr::new("data-nr-replace", "") } else { Attr::none() }
175}
176
177/// Make a link do a full page load instead of client-side navigation:
178/// `a![href("/logout"), reload(true), "Log out"]`.
179pub fn reload(enabled: bool) -> Attr {
180    if enabled { Attr::new("data-nr-reload", "") } else { Attr::none() }
181}
182
183/// Mark a link as the current page: when the URL path equals the link's path,
184/// the link gets this class and `aria-current="page"`. Applied by the server
185/// when rendering and kept up to date by the client runtime after every
186/// navigation, so it also works in layouts that stay on screen.
187///
188/// `a![href("/docs"), active_class("active"), "Docs"]`
189pub fn active_class(class: impl AttrText) -> Attr {
190    Attr::new("data-nr-active", class.into_attr_text())
191}
192
193/// Like [`active_class`], but also active on every page below the link's path:
194/// a link to `/docs` is active on `/docs/routing`.
195pub fn active_class_prefix(class: impl AttrText) -> Attr {
196    Attr::new("data-nr-active-prefix", class.into_attr_text())
197}
198
199/// Whether a link to `href` is active on `path`, exactly or as a prefix.
200pub fn link_is_active(href: &str, path: &str, prefix: bool) -> bool {
201    let target = href.split(['?', '#']).next().unwrap_or("");
202    let target = if target.len() > 1 { target.trim_end_matches('/') } else { target };
203    let path = if path.len() > 1 { path.trim_end_matches('/') } else { path };
204    if !target.starts_with('/') || target.starts_with("//") {
205        return false;
206    }
207    path == target || (prefix && (target == "/" || path.strip_prefix(target).is_some_and(|rest| rest.starts_with('/'))))
208}
209
210/// Apply [`active_class`] / [`active_class_prefix`] for `path` to a view tree
211/// (async boundaries are left to the client runtime).
212pub fn mark_active_links(node: &mut crate::Node, path: &str) {
213    match node {
214        crate::Node::Element(el) => {
215            let exact = el.attr("data-nr-active").map(str::to_owned);
216            let prefix = el.attr("data-nr-active-prefix").map(str::to_owned);
217            if let Some(href) = el.attr("href").map(str::to_owned) {
218                for (class, is_prefix) in [(exact, false), (prefix, true)] {
219                    if let Some(class) = class
220                        && link_is_active(&href, path, is_prefix)
221                    {
222                        el.set_attr(Attr::new("class", class));
223                        el.set_attr(Attr::new("aria-current", "page"));
224                    }
225                }
226            }
227            for child in &mut el.children {
228                mark_active_links(child, path);
229            }
230        }
231        crate::Node::Fragment(children) => {
232            for child in children {
233                mark_active_links(child, path);
234            }
235        }
236        _ => {}
237    }
238}
239
240/// Keep the scroll position after a client navigation (`Link!`).
241pub fn scroll(enabled: bool) -> Attr {
242    if enabled { Attr::none() } else { Attr::new("data-nr-scroll", "false") }
243}
244
245/// `type` attribute (also available as `r#type`).
246pub fn type_(value: impl AttrText) -> Attr {
247    Attr::new("type", value.into_attr_text())
248}
249
250/// `for` attribute of `<label>`.
251pub fn for_(value: impl AttrText) -> Attr {
252    Attr::new("for", value.into_attr_text())
253}
254
255/// `r#type("submit")`
256pub fn r#type(value: impl AttrText) -> Attr {
257    type_(value)
258}
259
260/// `r#for("email")`
261pub fn r#for(value: impl AttrText) -> Attr {
262    for_(value)
263}
264
265/// `r#async(true)` for scripts.
266pub fn r#async(on: bool) -> Attr {
267    Attr::boolean("async", on)
268}
269
270macro_rules! text_attrs {
271    ($($(#[$m:meta])* $fn_name:ident => $name:literal),* $(,)?) => {$(
272        $(#[$m])*
273        #[doc = concat!("`", $name, "` attribute.")]
274        pub fn $fn_name(value: impl AttrText) -> Attr {
275            Attr::new($name, value.into_attr_text())
276        }
277    )*};
278}
279
280text_attrs! {
281    id => "id",
282    href => "href",
283    src => "src",
284    srcset => "srcset",
285    sizes => "sizes",
286    alt => "alt",
287    title => "title",
288    style => "style",
289    name => "name",
290    value => "value",
291    placeholder => "placeholder",
292    method => "method",
293    action => "action",
294    enctype => "enctype",
295    rel => "rel",
296    target => "target",
297    width => "width",
298    height => "height",
299    lang => "lang",
300    dir => "dir",
301    role => "role",
302    tabindex => "tabindex",
303    content => "content",
304    charset => "charset",
305    http_equiv => "http-equiv",
306    min => "min",
307    max => "max",
308    step => "step",
309    pattern => "pattern",
310    minlength => "minlength",
311    maxlength => "maxlength",
312    autocomplete => "autocomplete",
313    inputmode => "inputmode",
314    colspan => "colspan",
315    rowspan => "rowspan",
316    loading => "loading",
317    decoding => "decoding",
318    fetchpriority => "fetchpriority",
319    download => "download",
320    crossorigin => "crossorigin",
321    integrity => "integrity",
322    referrerpolicy => "referrerpolicy",
323    datetime => "datetime",
324    form_attr => "form",
325    list => "list",
326    accept => "accept",
327    rows => "rows",
328    cols => "cols",
329    wrap => "wrap",
330    label_attr => "label",
331    media => "media",
332    as_ => "as",
333    nonce => "nonce",
334    slot_attr => "slot",
335    translate => "translate",
336    spellcheck => "spellcheck",
337    enterkeyhint => "enterkeyhint",
338    view_box => "viewBox",
339    fill => "fill",
340    stroke => "stroke",
341    d => "d",
342    xmlns => "xmlns",
343}
344
345macro_rules! bool_attrs {
346    ($($fn_name:ident => $name:literal),* $(,)?) => {$(
347        #[doc = concat!("`", $name, "` boolean attribute.")]
348        pub fn $fn_name(on: bool) -> Attr {
349            Attr::boolean($name, on)
350        }
351    )*};
352}
353
354bool_attrs! {
355    disabled => "disabled",
356    checked => "checked",
357    selected => "selected",
358    required => "required",
359    readonly => "readonly",
360    multiple => "multiple",
361    hidden => "hidden",
362    autofocus => "autofocus",
363    open => "open",
364    defer => "defer",
365    novalidate => "novalidate",
366    controls => "controls",
367    autoplay => "autoplay",
368    muted => "muted",
369    playsinline => "playsinline",
370    inert => "inert",
371    ismap => "ismap",
372    reversed => "reversed",
373    nomodule => "nomodule",
374}
375
376impl AttrValue {
377    pub fn as_text(&self) -> Option<&str> {
378        match self {
379            AttrValue::Text(t) => Some(t),
380            AttrValue::Bool(_) => None,
381        }
382    }
383}