use std::cell::Cell;
use std::future::Future;
use std::pin::Pin;
use std::rc::Rc;
use std::time::Duration;
use dioxus::prelude::*;
use super::dialog::DialogHandle;
use crate::FormErrors;
use crate::class::compose;
use crate::time::sleep;
const DEFAULT_FAILURE_MESSAGE: &str = "Something went wrong. Try again.";
const FOCUS_ERROR_CONTROL: &str = r"
const ids = await dioxus.recv();
if (!Array.isArray(ids)) return false;
for (const id of ids) {
if (typeof id !== 'string') continue;
const control = document.getElementById(id);
if (!(control instanceof HTMLElement) || control.matches(':disabled')) continue;
const owner = control.closest('[data-ui-dialog-form]') ?? control.form;
if (!(owner instanceof HTMLElement) || !owner.matches('[data-ui-dialog-form]')) continue;
control.focus();
if (document.activeElement === control) return true;
}
return false;
";
#[derive(Clone, Debug, Default, PartialEq)]
pub struct DialogFormValues(Vec<(String, FormValue)>);
impl DialogFormValues {
pub fn entries(&self) -> &[(String, FormValue)] {
&self.0
}
pub fn get(&self, name: &str) -> Option<&str> {
self.0.iter().find_map(|(key, value)| match value {
FormValue::Text(text) if key == name => Some(text.as_str()),
_ => None,
})
}
}
impl From<Vec<(String, FormValue)>> for DialogFormValues {
fn from(entries: Vec<(String, FormValue)>) -> Self {
Self(entries)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct DialogFormFailure;
impl<E: std::error::Error> From<E> for DialogFormFailure {
fn from(_: E) -> Self {
Self
}
}
pub type DialogFormResult = Result<FormErrors, DialogFormFailure>;
pub type DialogFormFuture = Pin<Box<dyn Future<Output = DialogFormResult>>>;
#[derive(Clone, Debug, PartialEq)]
pub struct DialogFormState {
pub errors: FormErrors,
pub pending: bool,
pub submit: Callback<()>,
}
#[derive(Clone, Copy)]
pub(crate) struct DialogFormContext {
pending: Signal<bool>,
summary: CopyValue<Option<Rc<MountedData>>>,
}
impl DialogFormContext {
pub(crate) fn is_pending(self) -> bool {
*self.pending.read()
}
pub(crate) fn set_summary(self, summary: Rc<MountedData>) {
let mut stored = self.summary;
stored.set(Some(summary));
}
}
#[derive(Props, Clone, PartialEq)]
pub struct DialogFormProps {
pub submit: Option<Callback<DialogFormValues, DialogFormFuture>>,
pub on_success: Option<EventHandler<()>>,
#[props(default = DEFAULT_FAILURE_MESSAGE.to_string(), into)]
pub failure_message: String,
pub render: Option<Callback<DialogFormState, Element>>,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = form)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
fn failure_errors(message: &str) -> FormErrors {
let message = message.trim();
let message = if message.is_empty() {
DEFAULT_FAILURE_MESSAGE
} else {
message
};
FormErrors {
fields: Vec::new(),
form: vec![message.to_string()],
}
}
fn form_status(pending: bool, errors: &FormErrors) -> &'static str {
if pending {
"submitting"
} else if errors.is_empty() {
"idle"
} else {
"error"
}
}
async fn focus_first_error(control_ids: Vec<String>, summary: Option<Rc<MountedData>>) {
if !control_ids.is_empty() {
let eval = document::eval(FOCUS_ERROR_CONTROL);
if eval.send(control_ids).is_ok() && eval.join::<bool>().await.unwrap_or(false) {
return;
}
}
if let Some(summary) = summary {
let _ = summary.set_focus(true).await;
}
}
#[component]
pub fn DialogForm(props: DialogFormProps) -> Element {
let handle = try_use_context::<DialogHandle>();
let mut errors = use_signal(FormErrors::default);
let mut pending = use_signal(|| false);
let context = use_context_provider(|| DialogFormContext {
pending,
summary: CopyValue::new(None),
});
let lock = use_hook(|| Rc::new(Cell::new(false)));
use_drop({
let lock = lock.clone();
move || {
if lock.get()
&& let Some(handle) = handle
{
handle.release_lock();
}
}
});
let open = handle.map(DialogHandle::is_open);
use_effect(use_reactive((&open,), move |(open,)| {
if open == Some(false) && !*pending.peek() && !errors.peek().is_empty() {
errors.set(FormErrors::default());
}
}));
let failure_message = props.failure_message.clone();
let (submit, on_success) = (props.submit, props.on_success);
let summary = context.summary;
let run = use_callback(move |values: DialogFormValues| {
if *pending.peek() {
return;
}
if !errors.peek().is_empty() {
errors.set(FormErrors::default());
}
let Some(submit) = submit else {
if let Some(handle) = handle {
handle.set_open(false);
}
return;
};
pending.set(true);
lock.set(true);
if let Some(handle) = handle {
handle.set_locked(true);
}
let request = submit.call(values);
let failure = failure_errors(&failure_message);
let lock = lock.clone();
spawn(async move {
let next = match request.await {
Ok(next) => next.normalized(),
Err(DialogFormFailure) => failure,
};
lock.set(false);
if let Some(handle) = handle {
handle.set_locked(false);
}
pending.set(false);
if next.is_empty() {
if let Some(handle) = handle {
handle.set_open(false);
}
if let Some(on_success) = on_success {
on_success.call(());
}
return;
}
let control_ids: Vec<String> = next
.fields
.iter()
.filter_map(|error| error.control_id.clone())
.collect();
errors.set(next);
sleep(Duration::ZERO).await;
let target = Option::clone(&*summary.peek());
focus_first_error(control_ids, target).await;
});
});
let submit_now = use_callback(move |()| run.call(DialogFormValues::default()));
let is_pending = pending();
let current = errors();
let status = form_status(is_pending, ¤t);
let class = compose([Some("ui-form ui-dialog-form"), props.class.as_deref()]);
let has_dialog = handle.is_some();
let content = match props.render {
Some(render) => render.call(DialogFormState {
errors: current,
pending: is_pending,
submit: submit_now,
}),
None => props.children,
};
rsx! {
form {
aria_busy: is_pending.then_some("true"),
class,
"data-slot": "dialog-form",
"data-status": status,
"data-ui-dialog-form": "true",
"data-ui-owner": "dioxus",
method: "dialog",
onsubmit: move |event: FormEvent| {
if submit.is_none() && !has_dialog {
return;
}
event.prevent_default();
run.call(DialogFormValues(event.values()));
},
..props.attributes,
{content}
}
}
}
#[cfg(test)]
mod tests {
use super::{DialogFormValues, FormErrors, failure_errors, form_status};
use dioxus::prelude::FormValue;
#[test]
fn values_read_the_first_text_entry() {
let values = DialogFormValues::from(vec![
("avatar".to_string(), FormValue::File(None)),
("name".to_string(), FormValue::Text("Ada".to_string())),
("name".to_string(), FormValue::Text("Grace".to_string())),
]);
assert_eq!(values.get("name"), Some("Ada"));
assert_eq!(values.get("avatar"), None);
assert_eq!(values.get("missing"), None);
assert_eq!(values.entries().len(), 3);
assert_eq!(DialogFormValues::default().get("name"), None);
}
#[test]
fn blank_failure_messages_fall_back_to_the_default() {
assert_eq!(
failure_errors(" Not saved. ").form,
vec!["Not saved.".to_string()]
);
assert_eq!(
failure_errors(" \n ").form,
vec!["Something went wrong. Try again.".to_string()]
);
assert_eq!(failure_errors("x").fields, Vec::new());
}
#[test]
fn status_prefers_submitting_then_error() {
let errors = FormErrors::from(vec![("form", "Try again.")]);
assert_eq!(form_status(true, &errors), "submitting");
assert_eq!(form_status(false, &errors), "error");
assert_eq!(form_status(false, &FormErrors::default()), "idle");
}
}