1use std::borrow::Cow;
10
11use crate::node::{Attr, AttrValue};
12use crate::style::CssClass;
13
14pub fn attr(name: impl Into<Cow<'static, str>>, value: impl AttrText) -> Attr {
17 Attr::new(name, value.into_attr_text())
18}
19
20pub 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
28pub 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
62pub 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}
120impl<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
129pub 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
140pub fn attr_if(condition: bool, attr: Attr) -> Attr {
142 if condition { attr } else { Attr::none() }
143}
144
145pub fn data(name: &str, value: impl AttrText) -> Attr {
147 Attr::new(format!("data-{name}"), value.into_attr_text())
148}
149
150pub fn aria(name: &str, value: impl AttrText) -> Attr {
152 Attr::new(format!("aria-{name}"), value.into_attr_text())
153}
154
155pub fn key(value: impl AttrText) -> Attr {
157 Attr::new("data-nr-key", value.into_attr_text())
158}
159
160pub fn on(event: &str, handler: impl AttrText) -> Attr {
163 Attr::new(format!("data-nr-on-{event}"), handler.into_attr_text())
164}
165
166pub fn prefetch(enabled: bool) -> Attr {
169 if enabled { Attr::none() } else { Attr::new("data-nr-prefetch", "false") }
170}
171
172pub fn replace(enabled: bool) -> Attr {
174 if enabled { Attr::new("data-nr-replace", "") } else { Attr::none() }
175}
176
177pub fn reload(enabled: bool) -> Attr {
180 if enabled { Attr::new("data-nr-reload", "") } else { Attr::none() }
181}
182
183pub fn active_class(class: impl AttrText) -> Attr {
190 Attr::new("data-nr-active", class.into_attr_text())
191}
192
193pub fn active_class_prefix(class: impl AttrText) -> Attr {
196 Attr::new("data-nr-active-prefix", class.into_attr_text())
197}
198
199pub 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
210pub 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
240pub fn stay_on_success(enabled: bool) -> Attr {
252 if enabled { Attr::new("data-nr-stay", "") } else { Attr::none() }
253}
254
255pub fn reset_on_success(enabled: bool) -> Attr {
258 if enabled { Attr::new("data-nr-reset", "") } else { Attr::none() }
259}
260
261pub fn action_result(key: impl AttrText) -> Attr {
266 Attr::new("data-nr-result", key.into_attr_text())
267}
268
269pub fn scroll(enabled: bool) -> Attr {
271 if enabled { Attr::none() } else { Attr::new("data-nr-scroll", "false") }
272}
273
274pub fn type_(value: impl AttrText) -> Attr {
276 Attr::new("type", value.into_attr_text())
277}
278
279pub fn for_(value: impl AttrText) -> Attr {
281 Attr::new("for", value.into_attr_text())
282}
283
284pub fn r#type(value: impl AttrText) -> Attr {
286 type_(value)
287}
288
289pub fn r#for(value: impl AttrText) -> Attr {
291 for_(value)
292}
293
294pub 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}