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