1use std::cell::Cell;
10use std::future::Future;
11use std::pin::Pin;
12use std::rc::Rc;
13use std::time::Duration;
14
15use dioxus::prelude::*;
16
17use super::dialog::DialogHandle;
18use crate::FormErrors;
19use crate::class::compose;
20use crate::time::sleep;
21
22const DEFAULT_FAILURE_MESSAGE: &str = "Something went wrong. Try again.";
25
26const FOCUS_ERROR_CONTROL: &str = r"
30const ids = await dioxus.recv();
31if (!Array.isArray(ids)) return false;
32for (const id of ids) {
33 if (typeof id !== 'string') continue;
34 const control = document.getElementById(id);
35 if (!(control instanceof HTMLElement) || control.matches(':disabled')) continue;
36 const owner = control.closest('[data-ui-dialog-form]') ?? control.form;
37 if (!(owner instanceof HTMLElement) || !owner.matches('[data-ui-dialog-form]')) continue;
38 control.focus();
39 if (document.activeElement === control) return true;
40}
41return false;
42";
43
44#[derive(Clone, Debug, Default, PartialEq)]
50pub struct DialogFormValues(Vec<(String, FormValue)>);
51
52impl DialogFormValues {
53 pub fn entries(&self) -> &[(String, FormValue)] {
55 &self.0
56 }
57
58 pub fn get(&self, name: &str) -> Option<&str> {
60 self.0.iter().find_map(|(key, value)| match value {
61 FormValue::Text(text) if key == name => Some(text.as_str()),
62 _ => None,
63 })
64 }
65}
66
67impl From<Vec<(String, FormValue)>> for DialogFormValues {
68 fn from(entries: Vec<(String, FormValue)>) -> Self {
69 Self(entries)
70 }
71}
72
73#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
78pub struct DialogFormFailure;
79
80impl<E: std::error::Error> From<E> for DialogFormFailure {
81 fn from(_: E) -> Self {
82 Self
83 }
84}
85
86pub type DialogFormResult = Result<FormErrors, DialogFormFailure>;
89
90pub type DialogFormFuture = Pin<Box<dyn Future<Output = DialogFormResult>>>;
93
94#[derive(Clone, Debug, PartialEq)]
97pub struct DialogFormState {
98 pub errors: FormErrors,
101 pub pending: bool,
104 pub submit: Callback<()>,
107}
108
109#[derive(Clone, Copy)]
113pub(crate) struct DialogFormContext {
114 pending: Signal<bool>,
115 summary: CopyValue<Option<Rc<MountedData>>>,
116}
117
118impl DialogFormContext {
119 pub(crate) fn is_pending(self) -> bool {
121 *self.pending.read()
122 }
123
124 pub(crate) fn set_summary(self, summary: Rc<MountedData>) {
126 let mut stored = self.summary;
127 stored.set(Some(summary));
128 }
129}
130
131#[derive(Props, Clone, PartialEq)]
133pub struct DialogFormProps {
134 pub submit: Option<Callback<DialogFormValues, DialogFormFuture>>,
138 pub on_success: Option<EventHandler<()>>,
140 #[props(default = DEFAULT_FAILURE_MESSAGE.to_string(), into)]
143 pub failure_message: String,
144 pub render: Option<Callback<DialogFormState, Element>>,
147 #[props(into)]
149 pub class: Option<String>,
150 #[props(extends = GlobalAttributes, extends = form)]
152 pub attributes: Vec<Attribute>,
153 pub children: Element,
156}
157
158fn failure_errors(message: &str) -> FormErrors {
160 let message = message.trim();
161 let message = if message.is_empty() {
162 DEFAULT_FAILURE_MESSAGE
163 } else {
164 message
165 };
166
167 FormErrors {
168 fields: Vec::new(),
169 form: vec![message.to_string()],
170 }
171}
172
173fn form_status(pending: bool, errors: &FormErrors) -> &'static str {
175 if pending {
176 "submitting"
177 } else if errors.is_empty() {
178 "idle"
179 } else {
180 "error"
181 }
182}
183
184async fn focus_first_error(control_ids: Vec<String>, summary: Option<Rc<MountedData>>) {
186 if !control_ids.is_empty() {
187 let eval = document::eval(FOCUS_ERROR_CONTROL);
188
189 if eval.send(control_ids).is_ok() && eval.join::<bool>().await.unwrap_or(false) {
190 return;
191 }
192 }
193
194 if let Some(summary) = summary {
195 let _ = summary.set_focus(true).await;
196 }
197}
198
199#[component]
210pub fn DialogForm(props: DialogFormProps) -> Element {
211 let handle = try_use_context::<DialogHandle>();
212 let mut errors = use_signal(FormErrors::default);
213 let mut pending = use_signal(|| false);
214 let context = use_context_provider(|| DialogFormContext {
215 pending,
216 summary: CopyValue::new(None),
217 });
218 let lock = use_hook(|| Rc::new(Cell::new(false)));
220
221 use_drop({
222 let lock = lock.clone();
223
224 move || {
225 if lock.get()
226 && let Some(handle) = handle
227 {
228 handle.release_lock();
229 }
230 }
231 });
232
233 let open = handle.map(DialogHandle::is_open);
235 use_effect(use_reactive((&open,), move |(open,)| {
236 if open == Some(false) && !*pending.peek() && !errors.peek().is_empty() {
237 errors.set(FormErrors::default());
238 }
239 }));
240
241 let failure_message = props.failure_message.clone();
242 let (submit, on_success) = (props.submit, props.on_success);
243 let summary = context.summary;
244 let run = use_callback(move |values: DialogFormValues| {
245 if *pending.peek() {
246 return;
247 }
248
249 if !errors.peek().is_empty() {
250 errors.set(FormErrors::default());
251 }
252
253 let Some(submit) = submit else {
255 if let Some(handle) = handle {
256 handle.set_open(false);
257 }
258
259 return;
260 };
261
262 pending.set(true);
263 lock.set(true);
264
265 if let Some(handle) = handle {
266 handle.set_locked(true);
267 }
268
269 let request = submit.call(values);
270 let failure = failure_errors(&failure_message);
271 let lock = lock.clone();
272
273 spawn(async move {
274 let next = match request.await {
275 Ok(next) => next.normalized(),
276 Err(DialogFormFailure) => failure,
277 };
278
279 lock.set(false);
280
281 if let Some(handle) = handle {
282 handle.set_locked(false);
283 }
284
285 pending.set(false);
286
287 if next.is_empty() {
288 if let Some(handle) = handle {
289 handle.set_open(false);
290 }
291
292 if let Some(on_success) = on_success {
293 on_success.call(());
294 }
295
296 return;
297 }
298
299 let control_ids: Vec<String> = next
300 .fields
301 .iter()
302 .filter_map(|error| error.control_id.clone())
303 .collect();
304
305 errors.set(next);
306 sleep(Duration::ZERO).await;
308 let target = Option::clone(&*summary.peek());
309 focus_first_error(control_ids, target).await;
310 });
311 });
312 let submit_now = use_callback(move |()| run.call(DialogFormValues::default()));
313
314 let is_pending = pending();
315 let current = errors();
316 let status = form_status(is_pending, ¤t);
317 let class = compose([Some("ui-form ui-dialog-form"), props.class.as_deref()]);
318 let has_dialog = handle.is_some();
319 let content = match props.render {
320 Some(render) => render.call(DialogFormState {
321 errors: current,
322 pending: is_pending,
323 submit: submit_now,
324 }),
325 None => props.children,
326 };
327
328 rsx! {
329 form {
330 aria_busy: is_pending.then_some("true"),
331 class,
332 "data-slot": "dialog-form",
333 "data-status": status,
334 "data-ui-dialog-form": "true",
335 "data-ui-owner": "dioxus",
336 method: "dialog",
337 onsubmit: move |event: FormEvent| {
338 if submit.is_none() && !has_dialog {
340 return;
341 }
342
343 event.prevent_default();
344 run.call(DialogFormValues(event.values()));
345 },
346 ..props.attributes,
347 {content}
348 }
349 }
350}
351
352#[cfg(test)]
353mod tests {
354 use super::{DialogFormValues, FormErrors, failure_errors, form_status};
355 use dioxus::prelude::FormValue;
356
357 #[test]
358 fn values_read_the_first_text_entry() {
359 let values = DialogFormValues::from(vec![
360 ("avatar".to_string(), FormValue::File(None)),
361 ("name".to_string(), FormValue::Text("Ada".to_string())),
362 ("name".to_string(), FormValue::Text("Grace".to_string())),
363 ]);
364
365 assert_eq!(values.get("name"), Some("Ada"));
366 assert_eq!(values.get("avatar"), None);
367 assert_eq!(values.get("missing"), None);
368 assert_eq!(values.entries().len(), 3);
369 assert_eq!(DialogFormValues::default().get("name"), None);
370 }
371
372 #[test]
373 fn blank_failure_messages_fall_back_to_the_default() {
374 assert_eq!(
375 failure_errors(" Not saved. ").form,
376 vec!["Not saved.".to_string()]
377 );
378 assert_eq!(
379 failure_errors(" \n ").form,
380 vec!["Something went wrong. Try again.".to_string()]
381 );
382 assert_eq!(failure_errors("x").fields, Vec::new());
383 }
384
385 #[test]
386 fn status_prefers_submitting_then_error() {
387 let errors = FormErrors::from(vec![("form", "Try again.")]);
388
389 assert_eq!(form_status(true, &errors), "submitting");
390 assert_eq!(form_status(false, &errors), "error");
391 assert_eq!(form_status(false, &FormErrors::default()), "idle");
392 }
393}