use dioxus::prelude::*;
use crate::class::{Glass, compose};
#[derive(Clone, Debug, PartialEq)]
struct FieldContext {
control_id: Option<String>,
invalid: bool,
}
impl FieldContext {
fn error_id(&self) -> Option<String> {
self.control_id.as_ref().map(|id| format!("{id}-error"))
}
}
fn use_field() -> Option<FieldContext> {
try_use_context::<Signal<FieldContext>>().map(|field| field.read().clone())
}
pub(crate) fn use_field_control_aria() -> (Option<&'static str>, Option<String>) {
match use_field() {
Some(field) if field.invalid => (Some("true"), field.error_id()),
_ => (None, None),
}
}
pub(crate) fn merge_described_by(
attributes: &mut Vec<Attribute>,
field_error: Option<&str>,
) -> Option<String> {
let own = attributes
.iter()
.position(|attribute| attribute.name == "aria-describedby")
.and_then(|index| match attributes.remove(index).value {
dioxus::dioxus_core::AttributeValue::Text(text) => Some(text),
_ => None,
});
let mut ids: Vec<&str> = Vec::new();
for id in own
.as_deref()
.into_iter()
.chain(field_error)
.flat_map(str::split_whitespace)
{
if !ids.contains(&id) {
ids.push(id);
}
}
(!ids.is_empty()).then(|| ids.join(" "))
}
#[derive(Props, Clone, PartialEq)]
pub struct LabelProps {
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = label)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
#[component]
pub fn Label(props: LabelProps) -> Element {
let class = compose([Some("ui-label"), props.class.as_deref()]);
rsx! {
label { class, ..props.attributes, {props.children} }
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ControlSize {
#[default]
Default,
Sm,
Lg,
}
impl ControlSize {
fn input_class(self) -> Option<&'static str> {
match self {
Self::Default => None,
Self::Sm => Some("ui-input--sm"),
Self::Lg => Some("ui-input--lg"),
}
}
}
#[derive(Props, Clone, PartialEq)]
pub struct InputProps {
#[props(default = "text".to_string(), into)]
pub r#type: String,
#[props(default)]
pub visual_size: ControlSize,
#[props(into)]
pub class: Option<String>,
pub oninput: Option<EventHandler<FormEvent>>,
pub onchange: Option<EventHandler<FormEvent>>,
#[props(extends = GlobalAttributes, extends = input)]
pub attributes: Vec<Attribute>,
}
#[component]
pub fn Input(mut props: InputProps) -> Element {
let (aria_invalid, field_error) = use_field_control_aria();
let aria_describedby = merge_described_by(&mut props.attributes, field_error.as_deref());
let class = compose([
Some("ui-input"),
props.visual_size.input_class(),
props.class.as_deref(),
]);
let (oninput, onchange) = (props.oninput, props.onchange);
rsx! {
input {
aria_describedby,
aria_invalid,
class,
r#type: props.r#type,
oninput: move |event| {
if let Some(handler) = oninput {
handler.call(event);
}
},
onchange: move |event| {
if let Some(handler) = onchange {
handler.call(event);
}
},
..props.attributes,
}
}
}
#[derive(Props, Clone, PartialEq)]
pub struct TextareaProps {
#[props(default = 4)]
pub rows: u32,
#[props(into)]
pub class: Option<String>,
pub oninput: Option<EventHandler<FormEvent>>,
#[props(extends = GlobalAttributes, extends = textarea)]
pub attributes: Vec<Attribute>,
}
#[component]
pub fn Textarea(mut props: TextareaProps) -> Element {
let (aria_invalid, field_error) = use_field_control_aria();
let aria_describedby = merge_described_by(&mut props.attributes, field_error.as_deref());
let class = compose([Some("ui-textarea"), props.class.as_deref()]);
let oninput = props.oninput;
rsx! {
textarea {
aria_describedby,
aria_invalid,
class,
rows: "{props.rows}",
oninput: move |event| {
if let Some(handler) = oninput {
handler.call(event);
}
},
..props.attributes,
}
}
}
#[derive(Props, Clone, PartialEq)]
pub struct FieldProps {
#[props(into)]
pub control_id: Option<String>,
#[props(into)]
pub described_by: Option<String>,
#[props(into)]
pub aria_describedby: Option<String>,
#[props(default)]
pub invalid: bool,
#[props(default, into)]
pub glass: Glass,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = div)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
#[component]
pub fn Field(props: FieldProps) -> Element {
let context = FieldContext {
control_id: props.control_id.clone(),
invalid: props.invalid,
};
let mut shared = use_context_provider(|| Signal::new(context.clone()));
use_effect(use_reactive((&context,), move |(context,)| {
if *shared.peek() != context {
shared.set(context);
}
}));
let glass = props.glass.class("ui-field");
let class = compose([Some("ui-field"), glass.as_deref(), props.class.as_deref()]);
let field_described_by = Some(compose([
props.aria_describedby.as_deref(),
props.described_by.as_deref(),
]))
.filter(|ids| !ids.is_empty());
rsx! {
div {
aria_describedby: props.aria_describedby,
class,
"data-invalid": props.invalid.then_some("true"),
"data-ui-field": "true",
"data-ui-field-control": props.control_id,
"data-ui-field-describedby": field_described_by,
..props.attributes,
{props.children}
}
}
}
#[derive(Props, Clone, PartialEq)]
pub struct FieldErrorProps {
#[props(into)]
pub message: Option<String>,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = p)]
pub attributes: Vec<Attribute>,
}
#[component]
pub fn FieldError(props: FieldErrorProps) -> Element {
let id = use_field().and_then(|field| field.error_id());
let class = compose([Some("ui-field-error"), props.class.as_deref()]);
let hidden = props.message.as_deref().is_none_or(str::is_empty);
rsx! {
p {
class,
"data-ui-field-error": "true",
hidden,
id,
..props.attributes,
if let Some(message) = props.message {
"{message}"
}
}
}
}
#[derive(Props, Clone, PartialEq)]
pub struct CheckboxProps {
pub checked: Option<bool>,
#[props(default)]
pub default_checked: bool,
#[props(default)]
pub indeterminate: bool,
#[props(default)]
pub disabled: bool,
#[props(into)]
pub name: Option<String>,
#[props(default = "on".to_string(), into)]
pub value: String,
pub onchange: Option<EventHandler<bool>>,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = button)]
pub attributes: Vec<Attribute>,
}
fn checked_control(base: &'static str, role: &'static str, mut props: CheckboxProps) -> Element {
let mut internal = use_signal(|| props.default_checked);
let controlled = props.checked;
let checked = controlled.unwrap_or_else(|| *internal.read());
let aria_checked = match (props.indeterminate, checked) {
(true, _) => "mixed",
(false, true) => "true",
(false, false) => "false",
};
let (aria_invalid, field_error) = use_field_control_aria();
let aria_describedby = merge_described_by(&mut props.attributes, field_error.as_deref());
let class = compose([Some(base), props.class.as_deref()]);
let onchange = props.onchange;
let disabled = props.disabled;
let indeterminate = props.indeterminate;
let submitted = props.name.filter(|_| checked && !indeterminate);
rsx! {
button {
aria_checked,
aria_describedby,
aria_invalid,
class,
disabled,
role,
r#type: "button",
onclick: move |_| {
if disabled {
return;
}
let next = indeterminate || !checked;
if controlled.is_none() {
internal.set(next);
}
if let Some(handler) = onchange {
handler.call(next);
}
},
..props.attributes,
}
if let Some(name) = submitted {
input { r#type: "hidden", name, value: props.value }
}
}
}
pub type SwitchProps = CheckboxProps;
#[component]
pub fn Checkbox(props: CheckboxProps) -> Element {
checked_control("ui-checkbox", "checkbox", props)
}
#[component]
pub fn Switch(props: SwitchProps) -> Element {
checked_control("ui-switch", "switch", props)
}