tablo_core/values/error.rs
1//! [`FieldError`] and [`FieldErrors`]: the keys a submission was refused under, and why;
2//! [`FormFields`]: how an app names the field it refuses.
3
4use std::collections::HashSet;
5
6use derive_where::derive_where;
7
8use crate::Text;
9
10/// The fields a submission's errors name: a record form's or a form input's, or the panel's own
11/// form keys (`String`).
12///
13/// The [`RecordForm`](derive@crate::RecordForm), [`ModelForm`](derive@crate::ModelForm) and
14/// [`FormInput`](derive@crate::FormInput) derives implement it, so an app keys its errors by its
15/// form, `FieldErrors<UserForm>`, and picks a field by its name, `errors.add(|f| f.age, ..)`.
16/// The field enum the derive writes, `UserFormField`, is the transport: the key the panel posts
17/// and renders an error under, which an app's code never needs to spell.
18pub trait FormFields {
19 /// What an error names: one variant per field, or a form key.
20 type Field;
21
22 /// One key per field, named like the field, which an error picks a field from: the derive
23 /// writes `UserFormKeys`, holding `age: UserFormField::Age`; a form with no field has `()`.
24 type Keys;
25
26 /// The keys.
27 fn keys() -> Self::Keys;
28}
29
30/// The panel's own errors, keyed by the form key they render under.
31impl FormFields for String {
32 type Field = String;
33 type Keys = ();
34
35 fn keys() -> Self::Keys {}
36}
37
38/// Why a key was refused.
39#[derive(Debug, Clone, PartialEq, Eq)]
40#[non_exhaustive]
41pub enum FieldErrorKind {
42 /// Posted empty, and the field has no blank answer. The form renders
43 /// "{label} is required" under the control.
44 Required,
45 /// Posted a value the field refuses, with the sentence the form renders.
46 Invalid(Text),
47}
48
49/// One key a submission was refused under: a form key, or the field enum of the form a
50/// [`FieldErrors`] is keyed by.
51#[derive(Debug, Clone, PartialEq, Eq)]
52#[non_exhaustive]
53pub struct FieldError<K = String> {
54 /// What the error renders under.
55 pub key: K,
56 /// Why the key was refused.
57 pub kind: FieldErrorKind,
58}
59
60impl<K> FieldError<K> {
61 /// `key` was posted empty and has no blank answer.
62 pub fn required(key: impl Into<K>) -> Self {
63 Self {
64 key: key.into(),
65 kind: FieldErrorKind::Required,
66 }
67 }
68
69 /// `key` carried a value it refuses; `message` says why.
70 pub fn invalid(key: impl Into<K>, message: impl Into<Text>) -> Self {
71 Self {
72 key: key.into(),
73 kind: FieldErrorKind::Invalid(message.into()),
74 }
75 }
76
77 /// The sentence the form renders under the control labelled `label`.
78 pub fn message(&self, label: impl Into<Text>) -> Text {
79 match &self.kind {
80 FieldErrorKind::Required => crate::text!("tablo-field-required", label = label),
81 FieldErrorKind::Invalid(message) => message.clone(),
82 }
83 }
84}
85
86/// The refusal of a key holding another shape than its parse reads: a list or rows where it reads
87/// text, or text where it reads a list. Only a schema whose controls disagree with its parse
88/// holds one.
89pub(crate) fn unreadable(key: &str) -> FieldError {
90 FieldError::invalid(key, Text::message("tablo-field-unreadable"))
91}
92
93/// A refused submission, keyed by the form whose fields it names.
94///
95/// [`Resource::validate_record`](crate::Resource::validate_record) answers a
96/// `FieldErrors<UserForm>`, keyed by its record form, so an error always names a field the form
97/// renders; one on an embedded value renders under its first control. An error picks its field
98/// off the form's keys:
99///
100/// ```rust
101/// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
102/// # struct User { #[key] #[auto] id: uuid::Uuid, age: i64 }
103/// # #[derive(Debug, Clone, tablo_core::RecordForm)]
104/// # #[form(model = User)]
105/// # struct UserForm { age: i64 }
106/// use tablo_core::FieldErrors;
107///
108/// fn validate(form: &UserForm) -> FieldErrors<UserForm> {
109/// let mut errors = FieldErrors::<UserForm>::new();
110/// if form.age < 0 {
111/// errors.add(|f| f.age, "Age must be zero or more");
112/// }
113/// errors
114/// }
115/// ```
116///
117/// The panel keys every error by the form key it renders under (`FieldErrors`, keyed by
118/// `String`), and [`Source::form`] reads them back when a schema renders.
119///
120/// [`Source::form`]: crate::Source::form
121#[derive_where(Debug, Clone; F::Field)]
122pub struct FieldErrors<F: FormFields = String> {
123 errors: Vec<FieldError<F::Field>>,
124}
125
126impl<F: FormFields> Default for FieldErrors<F> {
127 fn default() -> Self {
128 Self { errors: Vec::new() }
129 }
130}
131
132impl<F: FormFields> FieldErrors<F> {
133 /// No errors.
134 pub fn new() -> Self {
135 Self::default()
136 }
137
138 /// Refuse the field `pick` picks off the form's keys with `message`:
139 /// `errors.add(|f| f.age, "Age must be zero or more")`.
140 pub fn add(&mut self, pick: impl FnOnce(F::Keys) -> F::Field, message: impl Into<Text>) {
141 self.add_field(pick(F::keys()), message);
142 }
143
144 /// Refuse `field` with `message`, the field named directly: the panel's own errors name a
145 /// form key, `errors.add_field("email", ..)`.
146 pub fn add_field(&mut self, field: impl Into<F::Field>, message: impl Into<Text>) {
147 self.errors.push(FieldError::invalid(field.into(), message));
148 }
149
150 /// Refuse `error`'s key with `error`.
151 pub fn push(&mut self, error: FieldError<F::Field>) {
152 self.errors.push(error);
153 }
154
155 /// Whether nothing was refused.
156 pub fn is_empty(&self) -> bool {
157 self.errors.is_empty()
158 }
159
160 /// Every error, in the order it was added.
161 pub fn iter(&self) -> impl Iterator<Item = &FieldError<F::Field>> {
162 self.errors.iter()
163 }
164
165 /// Append `other`'s errors after these.
166 pub fn extend(&mut self, other: Self) {
167 self.errors.extend(other.errors);
168 }
169
170 /// These errors, each keyed by the form key `key` gives its field.
171 pub(crate) fn keyed(self, key: fn(F::Field) -> &'static str) -> FieldErrors {
172 let mut keyed = FieldErrors::new();
173 for error in self {
174 keyed.push(FieldError {
175 key: key(error.key).to_string(),
176 kind: error.kind,
177 });
178 }
179 keyed
180 }
181}
182
183impl<F: FormFields> IntoIterator for FieldErrors<F> {
184 type Item = FieldError<F::Field>;
185 type IntoIter = std::vec::IntoIter<FieldError<F::Field>>;
186
187 fn into_iter(self) -> Self::IntoIter {
188 self.errors.into_iter()
189 }
190}
191
192impl FieldErrors {
193 /// Whether any error renders under `key`.
194 pub fn contains_key(&self, key: &str) -> bool {
195 self.errors.iter().any(|error| error.key == key)
196 }
197
198 /// The error `key` renders: the first one added.
199 pub fn first(&self, key: &str) -> Option<&FieldError> {
200 self.errors.iter().find(|error| error.key == key)
201 }
202
203 /// Take `other`'s errors, dropping this collection's own errors under every
204 /// key `other` names.
205 ///
206 /// A source that owns a key answers for it: a rejected upload replaces the
207 /// error the emptied control would otherwise report.
208 pub(crate) fn replace(&mut self, other: Self) {
209 let owned: HashSet<&str> = other
210 .errors
211 .iter()
212 .map(|error| error.key.as_str())
213 .collect();
214 self.errors
215 .retain(|kept| !owned.contains(kept.key.as_str()));
216 self.errors.extend(other.errors);
217 }
218}