htmx_components/server/
attrs.rs1use std::collections::HashMap;
2
3use super::opt_attrs::opt_attrs;
4
5#[derive(Default)]
6pub struct Attrs {
7 values: HashMap<&'static str, String>,
8 omit: Vec<&'static str>,
9}
10impl Attrs {
11 pub fn omit(&self, fields_to_omit: Vec<&'static str>) -> Self {
12 Self {
13 values: self.values.clone(),
14 omit: fields_to_omit,
15 }
16 }
17 pub fn to_hashmap(&self) -> HashMap<&'static str, String> {
18 let mut hashmap = self.values.clone();
19
20 for field in &self.omit {
21 hashmap.remove(field);
22 }
23
24 hashmap
25 }
26 pub fn to_hashmap_excluding(
27 &self,
28 exclude: Vec<&'static str>,
29 ) -> HashMap<&'static str, String> {
30 let mut hashmap = self.to_hashmap();
31
32 for field in exclude {
33 hashmap.remove(field);
34 }
35
36 hashmap
37 }
38 pub fn with(key: &'static str, value: String) -> Self {
39 Self {
40 values: HashMap::from([(key, value)]),
41 omit: vec![],
42 }
43 }
44 pub fn set(&self, key: &'static str, value: String) -> Self {
45 let mut values = self.values.clone();
46 values.insert(key, value);
47
48 Self {
49 values,
50 omit: self.omit.clone(),
51 }
52 }
53 pub fn set_if(&self, key: &'static str, value: String, condition: bool) -> Self {
54 if condition {
55 self.set(key, value)
56 } else {
57 self.clone()
58 }
59 }
60 pub fn get(&self, key: &'static str) -> Option<&String> {
61 if self.omit.contains(&key) {
62 return None;
63 }
64 self.values.get(key)
65 }
66}
67
68impl Clone for Attrs {
69 fn clone(&self) -> Self {
70 Self {
71 values: self.values.clone(),
72 omit: self.omit.clone(),
73 }
74 }
75}
76
77impl From<HashMap<&'static str, String>> for Attrs {
78 fn from(html_attrs: HashMap<&'static str, String>) -> Self {
79 Self {
80 values: html_attrs,
81 omit: vec![],
82 }
83 }
84}
85
86impl From<Attrs> for String {
87 fn from(attrs: Attrs) -> Self {
88 opt_attrs(attrs.to_hashmap())
89 }
90}