Skip to main content

lumen_dioxus/inputs/
settings_row.rs

1//! `SettingsRow`: a label and description on the start side with a control on the end side.
2
3// cspell:words feff
4
5use dioxus::prelude::*;
6
7use crate::class::compose;
8use crate::hooks::use_unique_id;
9
10/// The longest id lumen-core accepts.
11const MAX_ID_LENGTH: usize = 256;
12/// The id prefix when neither `control_id` nor `id` is usable.
13const FALLBACK_PREFIX: &str = "ui-settings-row";
14
15/// Attributes a [`SettingsRow`] hands to its `control` render function, so the row names and
16/// describes the control. Spread them on the control, like lumen-react's
17/// `SettingsRowControlProps`.
18#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct SettingsRowControlProps {
20    /// Id for the control. The row's `<label>` points at it.
21    pub id: String,
22    /// Id of the row's label, for controls that `<label for>` cannot name (such as the ARIA-button
23    /// `Switch` and `Checkbox`).
24    pub aria_labelledby: String,
25    /// Id of the row's description, when it has one.
26    pub aria_describedby: Option<String>,
27}
28
29/// JavaScript's whitespace: Unicode white space plus the byte order mark, without the next-line
30/// control that Rust's `char::is_whitespace` also includes.
31fn is_js_whitespace(character: char) -> bool {
32    (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
33}
34
35/// A usable element id: trimmed, not empty, at most 256 UTF-16 units, and without whitespace,
36/// like lumen-core's `normalizeLumenElementId`. Linear and bounded scans only.
37fn 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/// The ids a row derives, like lumen-core's `resolveLumenSettingsRowIds`.
54#[derive(Debug, PartialEq, Eq)]
55struct SettingsRowIds {
56    control: Option<String>,
57    label: String,
58    description: String,
59}
60
61impl SettingsRowIds {
62    /// Derives the label and description ids from `control_id` when it is valid, otherwise from
63    /// `fallback_prefix`.
64    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/// Props for [`SettingsRow`].
80#[derive(Props, Clone, PartialEq)]
81pub struct SettingsRowProps {
82    /// Visible label. It becomes the accessible name of the control.
83    #[props(into)]
84    pub label: String,
85    /// Supporting sentence under the label, with the id `{control_id}-description`.
86    #[props(into)]
87    pub description: Option<String>,
88    /// Id of the control. The label points at it with `for`, and the label and description ids
89    /// derive from it (`{control_id}-label`, `{control_id}-description`).
90    #[props(into)]
91    pub control_id: Option<String>,
92    /// Id of the row. Without a `control_id`, the derived ids use it as their prefix.
93    #[props(into)]
94    pub id: Option<String>,
95    /// Icon or graphic before the text. Mark decorative icons as hidden.
96    pub leading: Option<Element>,
97    /// Renders the control with the ids it needs, like lumen-react's function child. It wins over
98    /// `children`. Without a `control_id`, the control id is `{id}-control`.
99    pub control: Option<Callback<SettingsRowControlProps, Element>>,
100    /// Extra classes appended after the Lumen class.
101    #[props(into)]
102    pub class: Option<String>,
103    /// Any other `<div>` or global attribute.
104    #[props(extends = GlobalAttributes, extends = div)]
105    pub attributes: Vec<Attribute>,
106    /// The control at the end of the row, when it does not use `control`.
107    pub children: Element,
108}
109
110/// A label and description on the start side with a control on the end side. It stacks in
111/// narrow containers.
112#[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}