Skip to main content

lumen_dioxus/inputs/
error_summary.rs

1//! `ErrorSummary`: a focusable list of a form's validation errors.
2
3use dioxus::prelude::*;
4
5use super::FormErrors;
6use crate::class::compose;
7use crate::overlays::DialogFormContext;
8
9/// The id lumen-react gives a summary without an `id`.
10const DEFAULT_ID: &str = "ui-error-summary";
11
12/// Props for [`ErrorSummary`].
13#[derive(Props, Clone, PartialEq)]
14pub struct ErrorSummaryProps {
15    /// The errors to list: form-level messages first, then field messages. Field messages with a
16    /// `control_id` link to their control. The summary is hidden while there are none.
17    #[props(default, into)]
18    pub errors: FormErrors,
19    /// Heading text. Defaults to `There is a problem`.
20    #[props(default = "There is a problem".to_string(), into)]
21    pub heading: String,
22    /// Id of the summary; the heading id is `{id}-heading`. Defaults to `ui-error-summary`, so
23    /// give each summary on a page its own id.
24    #[props(into)]
25    pub id: Option<String>,
26    /// Extra classes appended after the Lumen class.
27    #[props(into)]
28    pub class: Option<String>,
29    /// Any other `<section>` or global attribute.
30    #[props(extends = GlobalAttributes, extends = section)]
31    pub attributes: Vec<Attribute>,
32}
33
34/// One rendered line: the message and the control it links to.
35struct Line {
36    message: String,
37    control_id: Option<String>,
38}
39
40/// Lists a form's errors under a heading, each linked to its control, so keyboard users can
41/// jump straight to the field. Focus it after a failed submission; it has `tabindex="-1"`. Inside
42/// a [`DialogForm`](crate::DialogForm), the form focuses it when no error control can take focus.
43#[component]
44pub fn ErrorSummary(props: ErrorSummaryProps) -> Element {
45    let dialog_form = try_use_context::<DialogFormContext>();
46    let errors = props.errors.normalized();
47    let lines: Vec<Line> = errors
48        .form
49        .into_iter()
50        .map(|message| Line {
51            message,
52            control_id: None,
53        })
54        .chain(errors.fields.into_iter().map(|error| Line {
55            message: error.message,
56            control_id: error.control_id,
57        }))
58        .collect();
59    let id = props.id.unwrap_or_else(|| DEFAULT_ID.to_string());
60    let heading_id = format!("{id}-heading");
61    let class = compose([Some("ui-error-summary"), props.class.as_deref()]);
62    let hidden = lines.is_empty();
63
64    rsx! {
65        section {
66            aria_labelledby: heading_id.clone(),
67            class,
68            "data-ui-error-summary": "true",
69            hidden,
70            id,
71            tabindex: "-1",
72            onmounted: move |event: MountedEvent| {
73                if let Some(dialog_form) = dialog_form {
74                    dialog_form.set_summary(event.data());
75                }
76            },
77            ..props.attributes,
78            h2 { id: heading_id, "{props.heading}" }
79            ul {
80                for line in lines {
81                    li {
82                        if let Some(control_id) = line.control_id {
83                            a { href: "#{control_id}", "{line.message}" }
84                        } else {
85                            "{line.message}"
86                        }
87                    }
88                }
89            }
90        }
91    }
92}