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/// On an action form: after a successful submit, stay on the page instead of
241/// refreshing it or following `_redirect` (which then only applies to
242/// browsers without JavaScript). Elements marked with [`action_result`] show
243/// what the action returned, and the form gets `data-nr-state="success"` for
244/// styling.
245///
246/// ```
247/// use next_rust_view::*;
248/// let html = render_static(form![stay_on_success(true), reset_on_success(true), p![action_result("")]]);
249/// assert_eq!(html, r#"<form data-nr-stay="" data-nr-reset=""><p data-nr-result=""></p></form>"#);
250/// ```
251pub fn stay_on_success(enabled: bool) -> Attr {
252    if enabled { Attr::new("data-nr-stay", "") } else { Attr::none() }
253}
254
255/// On a form with [`stay_on_success`]: clear its fields after a successful
256/// submit.
257pub fn reset_on_success(enabled: bool) -> Attr {
258    if enabled { Attr::new("data-nr-reset", "") } else { Attr::none() }
259}
260
261/// Inside a form with [`stay_on_success`]: show the action's return value
262/// here after a successful submit. `""` shows the whole value (a string or
263/// number); a key shows that field of a returned object. Filled as text,
264/// never as HTML.
265pub fn action_result(key: impl AttrText) -> Attr {
266    Attr::new("data-nr-result", key.into_attr_text())
267}
268
269/// Keep the scroll position after a client navigation (`Link!`).
270pub fn scroll(enabled: bool) -> Attr {
271    if enabled { Attr::none() } else { Attr::new("data-nr-scroll", "false") }
272}
273
274/// `type` attribute (also available as `r#type`).
275pub fn type_(value: impl AttrText) -> Attr {
276    Attr::new("type", value.into_attr_text())
277}
278
279/// `for` attribute of `<label>`.
280pub fn for_(value: impl AttrText) -> Attr {
281    Attr::new("for", value.into_attr_text())
282}
283
284/// `r#type("submit")`
285pub fn r#type(value: impl AttrText) -> Attr {
286    type_(value)
287}
288
289/// `r#for("email")`
290pub fn r#for(value: impl AttrText) -> Attr {
291    for_(value)
292}
293
294/// `r#async(true)` for scripts.
295pub fn r#async(on: bool) -> Attr {
296    Attr::boolean("async", on)
297}
298
299macro_rules! text_attrs {
300    ($($(#[$m:meta])* $fn_name:ident => $name:literal),* $(,)?) => {$(
301        $(#[$m])*
302        #[doc = concat!("`", $name, "` attribute.")]
303        pub fn $fn_name(value: impl AttrText) -> Attr {
304            Attr::new($name, value.into_attr_text())
305        }
306    )*};
307}
308
309text_attrs! {
310    id => "id",
311    href => "href",
312    src => "src",
313    srcset => "srcset",
314    sizes => "sizes",
315    alt => "alt",
316    title => "title",
317    style => "style",
318    name => "name",
319    value => "value",
320    placeholder => "placeholder",
321    method => "method",
322    action => "action",
323    enctype => "enctype",
324    rel => "rel",
325    target => "target",
326    width => "width",
327    height => "height",
328    lang => "lang",
329    dir => "dir",
330    role => "role",
331    tabindex => "tabindex",
332    content => "content",
333    charset => "charset",
334    http_equiv => "http-equiv",
335    min => "min",
336    max => "max",
337    step => "step",
338    pattern => "pattern",
339    minlength => "minlength",
340    maxlength => "maxlength",
341    autocomplete => "autocomplete",
342    inputmode => "inputmode",
343    colspan => "colspan",
344    rowspan => "rowspan",
345    loading => "loading",
346    decoding => "decoding",
347    fetchpriority => "fetchpriority",
348    download => "download",
349    crossorigin => "crossorigin",
350    integrity => "integrity",
351    referrerpolicy => "referrerpolicy",
352    datetime => "datetime",
353    form_attr => "form",
354    list => "list",
355    accept => "accept",
356    rows => "rows",
357    cols => "cols",
358    wrap => "wrap",
359    label_attr => "label",
360    media => "media",
361    as_ => "as",
362    nonce => "nonce",
363    slot_attr => "slot",
364    translate => "translate",
365    spellcheck => "spellcheck",
366    enterkeyhint => "enterkeyhint",
367    view_box => "viewBox",
368    fill => "fill",
369    stroke => "stroke",
370    d => "d",
371    xmlns => "xmlns",
372}
373
374macro_rules! bool_attrs {
375    ($($fn_name:ident => $name:literal),* $(,)?) => {$(
376        #[doc = concat!("`", $name, "` boolean attribute.")]
377        pub fn $fn_name(on: bool) -> Attr {
378            Attr::boolean($name, on)
379        }
380    )*};
381}
382
383bool_attrs! {
384    disabled => "disabled",
385    checked => "checked",
386    selected => "selected",
387    required => "required",
388    readonly => "readonly",
389    multiple => "multiple",
390    hidden => "hidden",
391    autofocus => "autofocus",
392    open => "open",
393    defer => "defer",
394    novalidate => "novalidate",
395    controls => "controls",
396    autoplay => "autoplay",
397    muted => "muted",
398    playsinline => "playsinline",
399    inert => "inert",
400    ismap => "ismap",
401    reversed => "reversed",
402    nomodule => "nomodule",
403}
404
405impl AttrValue {
406    pub fn as_text(&self) -> Option<&str> {
407        match self {
408            AttrValue::Text(t) => Some(t),
409            AttrValue::Bool(_) => None,
410        }
411    }
412}