use dioxus::prelude::*;
use crate::class::compose;
use crate::hooks::use_unique_id;
const MAX_ID_LENGTH: usize = 256;
const FALLBACK_PREFIX: &str = "ui-settings-row";
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SettingsRowControlProps {
pub id: String,
pub aria_labelledby: String,
pub aria_describedby: Option<String>,
}
fn is_js_whitespace(character: char) -> bool {
(character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
}
fn normalize_element_id(value: Option<&str>) -> Option<String> {
let value = value?;
if value.encode_utf16().take(MAX_ID_LENGTH + 1).count() > MAX_ID_LENGTH {
return None;
}
let trimmed = value.trim_matches(is_js_whitespace);
if trimmed.is_empty() || trimmed.chars().any(is_js_whitespace) {
return None;
}
Some(trimmed.to_string())
}
#[derive(Debug, PartialEq, Eq)]
struct SettingsRowIds {
control: Option<String>,
label: String,
description: String,
}
impl SettingsRowIds {
fn resolve(control_id: Option<&str>, fallback_prefix: &str) -> Self {
let control = normalize_element_id(control_id);
let prefix = control
.clone()
.or_else(|| normalize_element_id(Some(fallback_prefix)))
.unwrap_or_else(|| FALLBACK_PREFIX.to_string());
Self {
control,
label: format!("{prefix}-label"),
description: format!("{prefix}-description"),
}
}
}
#[derive(Props, Clone, PartialEq)]
pub struct SettingsRowProps {
#[props(into)]
pub label: String,
#[props(into)]
pub description: Option<String>,
#[props(into)]
pub control_id: Option<String>,
#[props(into)]
pub id: Option<String>,
pub leading: Option<Element>,
pub control: Option<Callback<SettingsRowControlProps, Element>>,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = div)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
#[component]
pub fn SettingsRow(props: SettingsRowProps) -> Element {
let generated = use_unique_id();
let prefix = props.id.clone().unwrap_or(generated);
let ids = SettingsRowIds::resolve(props.control_id.as_deref(), &prefix);
let description = props
.description
.clone()
.filter(|description| !description.trim().is_empty());
let (control, control_id) = if let Some(render) = props.control {
let control_id = ids
.control
.clone()
.unwrap_or_else(|| format!("{prefix}-control"));
let control = render.call(SettingsRowControlProps {
id: control_id.clone(),
aria_labelledby: ids.label.clone(),
aria_describedby: description.as_ref().map(|_| ids.description.clone()),
});
(Some(control), Some(control_id))
} else {
let has_children = props.children != VNode::empty();
(has_children.then_some(props.children), ids.control.clone())
};
let class = compose([Some("ui-settings-row"), props.class.as_deref()]);
rsx! {
div {
class,
"data-slot": "settings-row",
id: props.id,
..props.attributes,
if let Some(leading) = props.leading {
div { class: "ui-settings-row__leading", "data-slot": "settings-row-leading", {leading} }
}
div { class: "ui-settings-row__content", "data-slot": "settings-row-content",
if let Some(control_id) = control_id {
label {
class: "ui-settings-row__label",
"data-slot": "settings-row-label",
id: ids.label,
r#for: control_id,
"{props.label}"
}
} else {
span {
class: "ui-settings-row__label",
"data-slot": "settings-row-label",
id: ids.label,
"{props.label}"
}
}
if let Some(description) = description {
p {
class: "ui-settings-row__description",
"data-slot": "settings-row-description",
id: ids.description,
"{description}"
}
}
}
if let Some(control) = control {
div { class: "ui-settings-row__control", "data-slot": "settings-row-control", {control} }
}
}
}
}
#[cfg(test)]
mod tests {
use super::{SettingsRowIds, normalize_element_id};
#[test]
fn ids_derive_from_a_valid_control_id() {
assert_eq!(
SettingsRowIds::resolve(Some(" theme "), "row"),
SettingsRowIds {
control: Some("theme".to_string()),
label: "theme-label".to_string(),
description: "theme-description".to_string(),
}
);
}
#[test]
fn invalid_control_ids_fall_back_to_the_prefix() {
for invalid in ["", " ", "two words", "tab\tid", "bom\u{feff}id"] {
let ids = SettingsRowIds::resolve(Some(invalid), "row");
assert_eq!(ids.control, None, "{invalid:?}");
assert_eq!(ids.label, "row-label");
}
assert_eq!(
SettingsRowIds::resolve(None, "bad prefix").label,
"ui-settings-row-label"
);
assert_eq!(
normalize_element_id(Some("next\u{85}line")).as_deref(),
Some("next\u{85}line"),
"JavaScript does not treat U+0085 as whitespace"
);
}
#[test]
fn long_ids_are_rejected_in_linear_time() {
let long = "a".repeat(257);
let spaced = format!("{} b", "a".repeat(100_000));
assert_eq!(
normalize_element_id(Some(&"a".repeat(256))).map(|id| id.len()),
Some(256)
);
assert_eq!(normalize_element_id(Some(&long)), None);
assert_eq!(normalize_element_id(Some(&spaced)), None);
}
}