lumen_dioxus/inputs/
settings_row.rs1use dioxus::prelude::*;
6
7use crate::class::compose;
8use crate::hooks::use_unique_id;
9
10const MAX_ID_LENGTH: usize = 256;
12const FALLBACK_PREFIX: &str = "ui-settings-row";
14
15#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct SettingsRowControlProps {
20 pub id: String,
22 pub aria_labelledby: String,
25 pub aria_describedby: Option<String>,
27}
28
29fn is_js_whitespace(character: char) -> bool {
32 (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
33}
34
35fn normalize_element_id(value: Option<&str>) -> Option<String> {
38 let value = value?;
39
40 if value.encode_utf16().take(MAX_ID_LENGTH + 1).count() > MAX_ID_LENGTH {
41 return None;
42 }
43
44 let trimmed = value.trim_matches(is_js_whitespace);
45
46 if trimmed.is_empty() || trimmed.chars().any(is_js_whitespace) {
47 return None;
48 }
49
50 Some(trimmed.to_string())
51}
52
53#[derive(Debug, PartialEq, Eq)]
55struct SettingsRowIds {
56 control: Option<String>,
57 label: String,
58 description: String,
59}
60
61impl SettingsRowIds {
62 fn resolve(control_id: Option<&str>, fallback_prefix: &str) -> Self {
65 let control = normalize_element_id(control_id);
66 let prefix = control
67 .clone()
68 .or_else(|| normalize_element_id(Some(fallback_prefix)))
69 .unwrap_or_else(|| FALLBACK_PREFIX.to_string());
70
71 Self {
72 control,
73 label: format!("{prefix}-label"),
74 description: format!("{prefix}-description"),
75 }
76 }
77}
78
79#[derive(Props, Clone, PartialEq)]
81pub struct SettingsRowProps {
82 #[props(into)]
84 pub label: String,
85 #[props(into)]
87 pub description: Option<String>,
88 #[props(into)]
91 pub control_id: Option<String>,
92 #[props(into)]
94 pub id: Option<String>,
95 pub leading: Option<Element>,
97 pub control: Option<Callback<SettingsRowControlProps, Element>>,
100 #[props(into)]
102 pub class: Option<String>,
103 #[props(extends = GlobalAttributes, extends = div)]
105 pub attributes: Vec<Attribute>,
106 pub children: Element,
108}
109
110#[component]
113pub fn SettingsRow(props: SettingsRowProps) -> Element {
114 let generated = use_unique_id();
115 let prefix = props.id.clone().unwrap_or(generated);
116 let ids = SettingsRowIds::resolve(props.control_id.as_deref(), &prefix);
117 let description = props
118 .description
119 .clone()
120 .filter(|description| !description.trim().is_empty());
121 let (control, control_id) = if let Some(render) = props.control {
122 let control_id = ids
123 .control
124 .clone()
125 .unwrap_or_else(|| format!("{prefix}-control"));
126 let control = render.call(SettingsRowControlProps {
127 id: control_id.clone(),
128 aria_labelledby: ids.label.clone(),
129 aria_describedby: description.as_ref().map(|_| ids.description.clone()),
130 });
131
132 (Some(control), Some(control_id))
133 } else {
134 let has_children = props.children != VNode::empty();
135
136 (has_children.then_some(props.children), ids.control.clone())
137 };
138 let class = compose([Some("ui-settings-row"), props.class.as_deref()]);
139
140 rsx! {
141 div {
142 class,
143 "data-slot": "settings-row",
144 id: props.id,
145 ..props.attributes,
146 if let Some(leading) = props.leading {
147 div { class: "ui-settings-row__leading", "data-slot": "settings-row-leading", {leading} }
148 }
149 div { class: "ui-settings-row__content", "data-slot": "settings-row-content",
150 if let Some(control_id) = control_id {
151 label {
152 class: "ui-settings-row__label",
153 "data-slot": "settings-row-label",
154 id: ids.label,
155 r#for: control_id,
156 "{props.label}"
157 }
158 } else {
159 span {
160 class: "ui-settings-row__label",
161 "data-slot": "settings-row-label",
162 id: ids.label,
163 "{props.label}"
164 }
165 }
166 if let Some(description) = description {
167 p {
168 class: "ui-settings-row__description",
169 "data-slot": "settings-row-description",
170 id: ids.description,
171 "{description}"
172 }
173 }
174 }
175 if let Some(control) = control {
176 div { class: "ui-settings-row__control", "data-slot": "settings-row-control", {control} }
177 }
178 }
179 }
180}
181
182#[cfg(test)]
183mod tests {
184 use super::{SettingsRowIds, normalize_element_id};
185
186 #[test]
187 fn ids_derive_from_a_valid_control_id() {
188 assert_eq!(
189 SettingsRowIds::resolve(Some(" theme "), "row"),
190 SettingsRowIds {
191 control: Some("theme".to_string()),
192 label: "theme-label".to_string(),
193 description: "theme-description".to_string(),
194 }
195 );
196 }
197
198 #[test]
199 fn invalid_control_ids_fall_back_to_the_prefix() {
200 for invalid in ["", " ", "two words", "tab\tid", "bom\u{feff}id"] {
201 let ids = SettingsRowIds::resolve(Some(invalid), "row");
202
203 assert_eq!(ids.control, None, "{invalid:?}");
204 assert_eq!(ids.label, "row-label");
205 }
206
207 assert_eq!(
208 SettingsRowIds::resolve(None, "bad prefix").label,
209 "ui-settings-row-label"
210 );
211 assert_eq!(
212 normalize_element_id(Some("next\u{85}line")).as_deref(),
213 Some("next\u{85}line"),
214 "JavaScript does not treat U+0085 as whitespace"
215 );
216 }
217
218 #[test]
219 fn long_ids_are_rejected_in_linear_time() {
220 let long = "a".repeat(257);
221 let spaced = format!("{} b", "a".repeat(100_000));
222
223 assert_eq!(
224 normalize_element_id(Some(&"a".repeat(256))).map(|id| id.len()),
225 Some(256)
226 );
227 assert_eq!(normalize_element_id(Some(&long)), None);
228 assert_eq!(normalize_element_id(Some(&spaced)), None);
229 }
230}