1use dioxus::prelude::*;
4
5use crate::class::{Glass, compose};
6
7#[derive(Clone, Debug, PartialEq)]
9struct FieldContext {
10 control_id: Option<String>,
11 invalid: bool,
12}
13
14impl FieldContext {
15 fn error_id(&self) -> Option<String> {
16 self.control_id.as_ref().map(|id| format!("{id}-error"))
17 }
18}
19
20fn use_field() -> Option<FieldContext> {
21 try_use_context::<Signal<FieldContext>>().map(|field| field.read().clone())
22}
23
24pub(crate) fn use_field_control_aria() -> (Option<&'static str>, Option<String>) {
27 match use_field() {
28 Some(field) if field.invalid => (Some("true"), field.error_id()),
29 _ => (None, None),
30 }
31}
32
33pub(crate) fn merge_described_by(
36 attributes: &mut Vec<Attribute>,
37 field_error: Option<&str>,
38) -> Option<String> {
39 let own = attributes
40 .iter()
41 .position(|attribute| attribute.name == "aria-describedby")
42 .and_then(|index| match attributes.remove(index).value {
43 dioxus::dioxus_core::AttributeValue::Text(text) => Some(text),
44 _ => None,
45 });
46 let mut ids: Vec<&str> = Vec::new();
47
48 for id in own
49 .as_deref()
50 .into_iter()
51 .chain(field_error)
52 .flat_map(str::split_whitespace)
53 {
54 if !ids.contains(&id) {
55 ids.push(id);
56 }
57 }
58
59 (!ids.is_empty()).then(|| ids.join(" "))
60}
61
62#[derive(Props, Clone, PartialEq)]
64pub struct LabelProps {
65 #[props(into)]
67 pub class: Option<String>,
68 #[props(extends = GlobalAttributes, extends = label)]
70 pub attributes: Vec<Attribute>,
71 pub children: Element,
73}
74
75#[component]
77pub fn Label(props: LabelProps) -> Element {
78 let class = compose([Some("ui-label"), props.class.as_deref()]);
79
80 rsx! {
81 label { class, ..props.attributes, {props.children} }
82 }
83}
84
85#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
87#[non_exhaustive]
88pub enum ControlSize {
89 #[default]
91 Default,
92 Sm,
94 Lg,
96}
97
98impl ControlSize {
99 fn input_class(self) -> Option<&'static str> {
100 match self {
101 Self::Default => None,
102 Self::Sm => Some("ui-input--sm"),
103 Self::Lg => Some("ui-input--lg"),
104 }
105 }
106}
107
108#[derive(Props, Clone, PartialEq)]
110pub struct InputProps {
111 #[props(default = "text".to_string(), into)]
113 pub r#type: String,
114 #[props(default)]
116 pub visual_size: ControlSize,
117 #[props(into)]
119 pub class: Option<String>,
120 pub oninput: Option<EventHandler<FormEvent>>,
122 pub onchange: Option<EventHandler<FormEvent>>,
124 #[props(extends = GlobalAttributes, extends = input)]
126 pub attributes: Vec<Attribute>,
127}
128
129#[component]
131pub fn Input(mut props: InputProps) -> Element {
132 let (aria_invalid, field_error) = use_field_control_aria();
133 let aria_describedby = merge_described_by(&mut props.attributes, field_error.as_deref());
134 let class = compose([
135 Some("ui-input"),
136 props.visual_size.input_class(),
137 props.class.as_deref(),
138 ]);
139 let (oninput, onchange) = (props.oninput, props.onchange);
140
141 rsx! {
142 input {
143 aria_describedby,
144 aria_invalid,
145 class,
146 r#type: props.r#type,
147 oninput: move |event| {
148 if let Some(handler) = oninput {
149 handler.call(event);
150 }
151 },
152 onchange: move |event| {
153 if let Some(handler) = onchange {
154 handler.call(event);
155 }
156 },
157 ..props.attributes,
158 }
159 }
160}
161
162#[derive(Props, Clone, PartialEq)]
164pub struct TextareaProps {
165 #[props(default = 4)]
167 pub rows: u32,
168 #[props(into)]
170 pub class: Option<String>,
171 pub oninput: Option<EventHandler<FormEvent>>,
173 #[props(extends = GlobalAttributes, extends = textarea)]
175 pub attributes: Vec<Attribute>,
176}
177
178#[component]
180pub fn Textarea(mut props: TextareaProps) -> Element {
181 let (aria_invalid, field_error) = use_field_control_aria();
182 let aria_describedby = merge_described_by(&mut props.attributes, field_error.as_deref());
183 let class = compose([Some("ui-textarea"), props.class.as_deref()]);
184 let oninput = props.oninput;
185
186 rsx! {
187 textarea {
188 aria_describedby,
189 aria_invalid,
190 class,
191 rows: "{props.rows}",
192 oninput: move |event| {
193 if let Some(handler) = oninput {
194 handler.call(event);
195 }
196 },
197 ..props.attributes,
198 }
199 }
200}
201
202#[derive(Props, Clone, PartialEq)]
204pub struct FieldProps {
205 #[props(into)]
207 pub control_id: Option<String>,
208 #[props(into)]
210 pub described_by: Option<String>,
211 #[props(into)]
213 pub aria_describedby: Option<String>,
214 #[props(default)]
216 pub invalid: bool,
217 #[props(default, into)]
219 pub glass: Glass,
220 #[props(into)]
222 pub class: Option<String>,
223 #[props(extends = GlobalAttributes, extends = div)]
225 pub attributes: Vec<Attribute>,
226 pub children: Element,
228}
229
230#[component]
235pub fn Field(props: FieldProps) -> Element {
236 let context = FieldContext {
237 control_id: props.control_id.clone(),
238 invalid: props.invalid,
239 };
240 let mut shared = use_context_provider(|| Signal::new(context.clone()));
241
242 use_effect(use_reactive((&context,), move |(context,)| {
243 if *shared.peek() != context {
244 shared.set(context);
245 }
246 }));
247
248 let glass = props.glass.class("ui-field");
249 let class = compose([Some("ui-field"), glass.as_deref(), props.class.as_deref()]);
250 let field_described_by = Some(compose([
251 props.aria_describedby.as_deref(),
252 props.described_by.as_deref(),
253 ]))
254 .filter(|ids| !ids.is_empty());
255
256 rsx! {
257 div {
258 aria_describedby: props.aria_describedby,
259 class,
260 "data-invalid": props.invalid.then_some("true"),
261 "data-ui-field": "true",
262 "data-ui-field-control": props.control_id,
263 "data-ui-field-describedby": field_described_by,
264 ..props.attributes,
265 {props.children}
266 }
267 }
268}
269
270#[derive(Props, Clone, PartialEq)]
272pub struct FieldErrorProps {
273 #[props(into)]
275 pub message: Option<String>,
276 #[props(into)]
278 pub class: Option<String>,
279 #[props(extends = GlobalAttributes, extends = p)]
281 pub attributes: Vec<Attribute>,
282}
283
284#[component]
286pub fn FieldError(props: FieldErrorProps) -> Element {
287 let id = use_field().and_then(|field| field.error_id());
288 let class = compose([Some("ui-field-error"), props.class.as_deref()]);
289 let hidden = props.message.as_deref().is_none_or(str::is_empty);
290
291 rsx! {
292 p {
293 class,
294 "data-ui-field-error": "true",
295 hidden,
296 id,
297 ..props.attributes,
298 if let Some(message) = props.message {
299 "{message}"
300 }
301 }
302 }
303}
304
305#[derive(Props, Clone, PartialEq)]
307pub struct CheckboxProps {
308 pub checked: Option<bool>,
310 #[props(default)]
312 pub default_checked: bool,
313 #[props(default)]
316 pub indeterminate: bool,
317 #[props(default)]
319 pub disabled: bool,
320 #[props(into)]
322 pub name: Option<String>,
323 #[props(default = "on".to_string(), into)]
325 pub value: String,
326 pub onchange: Option<EventHandler<bool>>,
328 #[props(into)]
330 pub class: Option<String>,
331 #[props(extends = GlobalAttributes, extends = button)]
334 pub attributes: Vec<Attribute>,
335}
336
337fn checked_control(base: &'static str, role: &'static str, mut props: CheckboxProps) -> Element {
338 let mut internal = use_signal(|| props.default_checked);
339 let controlled = props.checked;
340 let checked = controlled.unwrap_or_else(|| *internal.read());
341 let aria_checked = match (props.indeterminate, checked) {
342 (true, _) => "mixed",
343 (false, true) => "true",
344 (false, false) => "false",
345 };
346 let (aria_invalid, field_error) = use_field_control_aria();
347 let aria_describedby = merge_described_by(&mut props.attributes, field_error.as_deref());
348 let class = compose([Some(base), props.class.as_deref()]);
349 let onchange = props.onchange;
350 let disabled = props.disabled;
351 let indeterminate = props.indeterminate;
352 let submitted = props.name.filter(|_| checked && !indeterminate);
353
354 rsx! {
355 button {
356 aria_checked,
357 aria_describedby,
358 aria_invalid,
359 class,
360 disabled,
361 role,
362 r#type: "button",
363 onclick: move |_| {
364 if disabled {
365 return;
366 }
367
368 let next = indeterminate || !checked;
369
370 if controlled.is_none() {
371 internal.set(next);
372 }
373
374 if let Some(handler) = onchange {
375 handler.call(next);
376 }
377 },
378 ..props.attributes,
379 }
380 if let Some(name) = submitted {
381 input { r#type: "hidden", name, value: props.value }
382 }
383 }
384}
385
386pub type SwitchProps = CheckboxProps;
388
389#[component]
394pub fn Checkbox(props: CheckboxProps) -> Element {
395 checked_control("ui-checkbox", "checkbox", props)
396}
397
398#[component]
400pub fn Switch(props: SwitchProps) -> Element {
401 checked_control("ui-switch", "switch", props)
402}