Skip to main content

tablo_core/declaration/
wording.rs

1//! The wording of each [`DeclarationErrorKind`].
2
3use std::fmt;
4
5use super::{
6    DeclarationError, DeclarationErrorKind, fmt_action_input, fmt_field_rule, fmt_many_to_many,
7};
8
9impl fmt::Display for DeclarationError {
10    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11        if let Some(resource) = self.resource {
12            write!(f, "`{resource}`{}: ", self.site)?;
13        }
14        write!(f, "{}", self.kind)
15    }
16}
17
18/// [`DeclarationErrorKind::EmptyDetail`]'s wording.
19const EMPTY_DETAIL: &str = "the view page shows a detail listing no column: declare a `detail` or \
20                            a table, or turn the page off with `without_page(ResourcePage::View)`";
21
22impl fmt::Display for DeclarationErrorKind {
23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        match self {
25            Self::MissingDb => f.write_str(
26                "the router holds no Db: install it with `.with(db)` before mounting the \
27                 panel",
28            ),
29            Self::MissingAuthModels { models } => write!(
30                f,
31                "auth is on, but the Db does not register its shipped models ({models}): build \
32                 the Db from `tablo::models!(…)`, which registers them, or opt out with \
33                 `.auth(Auth::disabled())`",
34                models = models.join(", ")
35            ),
36            Self::ShellAssetsWithoutBundle => f.write_str(
37                "shell_assets need the router's asset bundle: install it with `.assets(..)` \
38                 before mounting the panel",
39            ),
40            Self::NotificationsWithoutAuth => f.write_str(
41                "notifications are for signed-in users: `Panel::notifications` needs auth on",
42            ),
43            Self::MissingAuditModel => f.write_str(
44                "`Panel::audit_log` stores its entries in `AuditEntry`, which the Db does not \
45                 register: build the Db from `tablo::models!(…)`, or add `AuditEntry` to \
46                 `toasty::models!(…)`",
47            ),
48            Self::BrandColor { value } => write!(
49                f,
50                "the brand color `{value}` is no CSS color: spell it `#4f46e5` or \
51                 `oklch(0.55 0.2 260)`",
52            ),
53            Self::ExternalAuthFeature { feature } => write!(
54                f,
55                "`Auth::external` leaves credentials to the host app: drop `{feature}`",
56            ),
57            Self::FileFieldWithoutUploader { field } => write!(
58                f,
59                "file field `{field}` needs an uploader to store its bytes: install one with \
60                 `Panel::uploads`"
61            ),
62            Self::InvalidSegment { .. }
63            | Self::PrefixOverlapsRuntime { .. }
64            | Self::PrefixOverlapsPanel { .. }
65            | Self::EndpointOutsideRuntime { .. }
66            | Self::ServeDirWithoutCatchAll { .. }
67            | Self::ServeDirTwice { .. }
68            | Self::ServeDirTaken { .. } => fmt_route(f, self),
69            Self::ContentSecurityPolicy(fault) => fault.fmt(f),
70            Self::SecondHome => {
71                f.write_str("a home page is already registered: `Panel::home` takes one")
72            }
73            Self::NoRoot => f.write_str(
74                "every resource is hidden from navigation and no home page is registered, so the \
75                 panel's root, where a sign-in lands, leads nowhere: show one resource in the \
76                 sidebar, or register a page with `Panel::home`",
77            ),
78            Self::DuplicateResource => f.write_str(
79                "registered twice: a panel mounts each resource type once, so mount a variant \
80                 under its own type",
81            ),
82            Self::DuplicatePage => f.write_str(
83                "registered twice: a panel mounts each page type once, so mount a variant under \
84                 its own type",
85            ),
86            Self::NotMounted => f.write_str(
87                "not mounted on the context's panel: register it with `Panel::resource`",
88            ),
89            Self::ReservedSlug { slug } => {
90                write!(f, "slug '{slug}' names a route the panel serves itself")
91            }
92            Self::DuplicateSlug { slug } => write!(
93                f,
94                "slug '{slug}' is taken by another resource or page: each needs a distinct `slug()`"
95            ),
96            Self::DuplicateAction { name } => write!(
97                f,
98                "two actions are named '{name}': each needs a distinct `NAME`"
99            ),
100            Self::DuplicateWidget { name } => write!(
101                f,
102                "two widgets are named '{name}': each needs a distinct `WidgetDef::name`"
103            ),
104            Self::MisdeclaredPageFilter { key } => write!(
105                f,
106                "page filter '{key}' shares its key with another, or its key is not ASCII \
107                 letters, digits, `-` and `_`: give each filter a distinct key of those"
108            ),
109            Self::EditableColumn { column, fault } => fault.fmt(f, column),
110            Self::ActionInput { action, fault } => fmt_action_input(f, action, fault),
111            Self::SignUp(fault) => fault.fmt(f),
112            Self::Profile(fault) => fault.fmt(f),
113            Self::Area(fault) => fault.fmt(f),
114            Self::PasswordReset(fault) => fault.fmt(f),
115            Self::EmailVerification(fault) => fault.fmt(f),
116            Self::TenantRegistration(fault) => fault.fmt(f),
117            Self::TenantProfile(fault) => fault.fmt(f),
118            Self::TwoFactor(fault) => fault.fmt(f),
119            Self::AuthMail(fault) => fault.fmt(f),
120            Self::Locale(fault) => fault.fmt(f),
121            Self::DuplicateRelation => {
122                f.write_str("declared twice: each related resource is one relation")
123            }
124            Self::HasOneTab => f.write_str(
125                "a `has_one` relation cannot be a tab: its form edits inside the record's own \
126                 form",
127            ),
128            Self::UnregisteredRelation => f.write_str(
129                "the related resource is not registered on this panel: declare it with \
130                 `Panel::resource`",
131            ),
132            Self::UnregisteredOptionSource { field, source } => write!(
133                f,
134                "field '{field}' takes its options from `{source}`, which this panel does not \
135                 register: declare it with `Panel::resource`"
136            ),
137            Self::UnregisteredLabelSource { column, source } => write!(
138                f,
139                "column '{column}' labels its records by `{source}`, which this panel does not \
140                 register: declare it with `Panel::resource`"
141            ),
142            Self::TraversalLens { steps } => write!(
143                f,
144                "a lens here names one field of its model, not a {steps}-step path"
145            ),
146            Self::UnresolvedLens { model, steps } => write!(
147                f,
148                "lens path {steps:?} resolves to no single column of `{model}`: only embedded \
149                 steps (embedded structs, enum variant fields and `#[document]` fields) bind, not \
150                 relation hops"
151            ),
152            Self::Uncompiled { model, error } => write!(
153                f,
154                "`{model}` compiles to no schema, so its embedded paths name no column: {error}"
155            ),
156            Self::Tenancy { fault } => fault.fmt(f),
157            Self::FieldAccess { fault } => fault.fmt(f),
158            Self::NoColumns => f.write_str(
159                "no column: declare columns with `Table::new(columns)` or in `ResourceDef::table`",
160            ),
161            Self::ZeroPageSize => f.write_str("`Table::page_size` needs a page size of at least 1"),
162            Self::UnsortableDefaultSort { column } => write!(
163                f,
164                "`Table::default_sort_by` sorts on '{column}', but the table declares no sortable column for it"
165            ),
166            Self::DuplicateColumn { name } => write!(
167                f,
168                "two columns are named '{name}': each column needs a distinct name"
169            ),
170            Self::DuplicateFilter { name } => write!(
171                f,
172                "two filters are named '{name}': each filter needs a distinct name"
173            ),
174            Self::DuplicateTab { key } => write!(
175                f,
176                "two list tabs share the key '{key}': each tab needs a distinct key"
177            ),
178            Self::DuplicateGrouping { name } => write!(
179                f,
180                "the table groups by '{name}' twice: declare each grouping once"
181            ),
182            Self::DottedFilterName { name } => write!(f, "filter name '{name}' holds a '.'"),
183            Self::UnparsedFilterOption { filter, value } => write!(
184                f,
185                "filter '{filter}' offers '{value}', which its field's type does not parse: spell \
186                 each option as the field's form value, or take the type's own with \
187                 `SelectFilter::of`"
188            ),
189            Self::UnparsedTabOption { value } => write!(
190                f,
191                "the option tabs offer '{value}', which the field's type does not parse: spell \
192                 each option as the field's form value"
193            ),
194            Self::DuplicateField { name } => write!(
195                f,
196                "two fields are named '{name}': each input needs a distinct field"
197            ),
198            Self::DisabledWithoutValue { field } => write!(
199                f,
200                "field '{field}' is disabled or hidden on the create form, or a condition can \
201                 disable it, and it is required, so a create cannot fill it: give it a `default` \
202                 (a file field takes none), make it optional, or use `disabled_on_edit`"
203            ),
204            Self::RepeaterLeafModifier { field, leaf } => write!(
205                f,
206                "repeater '{field}' disables its row's '{leaf}' or gives it a default, which a \
207                 row does not apply: disable the repeater's own field instead"
208            ),
209            Self::RepeaterPassword { field, leaf } => write!(
210                f,
211                "repeater '{field}' rows hold password '{leaf}', which an edit never renders \
212                 back, so each save overwrites it: keep the secret out of the item"
213            ),
214            Self::FieldRule { field, fault } => fmt_field_rule(f, field, fault),
215            Self::UnpostedDefault { field, value } => write!(
216                f,
217                "field '{field}' defaults to '{value}', which its control never posts: spell the \
218                 default as the field's form value, a list for a multiple choice"
219            ),
220            Self::UnplacedWatchedField { .. }
221            | Self::HiddenWatchedField { .. }
222            | Self::DisabledWatchedField { .. }
223            | Self::UnpostedConditionValue { .. } => fmt_condition(f, self),
224            Self::MisdeclaredDependentChoice { .. }
225            | Self::UnfilterableChoice { .. }
226            | Self::MultipleDependentChoice { .. }
227            | Self::ListedDependentChoice { .. }
228            | Self::UncreatableChoice { .. }
229            | Self::UnplacedParentField { .. } => fmt_choice(f, self),
230            Self::RequiredConditionalField { field } => write!(
231                f,
232                "field '{field}' is conditional but has no blank answer: a submission that hides \
233                 it posts nothing, so make it an `Option` or give it `#[form(blank = ..)]`"
234            ),
235            Self::MissingControl { field, key } => write!(
236                f,
237                "record-form field `{field}` binds key `{key}`, but no control posts it: \
238                 `RecordForm::control` must render the field's control"
239            ),
240            Self::FormClaimsTenantColumn { field, column } => write!(
241                f,
242                "record-form field `{field}` claims the tenant column `{column}`, which the \
243                 framework stamps on create: drop it from the form"
244            ),
245            Self::FormClaimsSoftDeleteColumn { field, column } => write!(
246                f,
247                "record-form field `{field}` claims the soft-delete column `{column}`, which only \
248                 a delete and a restore write: drop it from the form, or mark it \
249                 `#[form(skip)]` on a `ModelForm`"
250            ),
251            Self::ReservedFormField { field } => write!(
252                f,
253                "form field `{field}` takes a name the form's POST carries itself, so the two \
254                 would read each other's value: rename the field"
255            ),
256            Self::EmptyChoice { field } => write!(
257                f,
258                "choice field `{field}` declares no options and no relationship, so it offers \
259                 nothing to choose: add `.options(..)` or `.relationship::<Source>()`, or \
260                 `#[form(relationship = Source)]` on a record form's field"
261            ),
262            Self::CompositeKeyChoice { field } => write!(
263                f,
264                "`{field}` reads a relationship whose model has a composite primary key, which \
265                 no option value can spell"
266            ),
267            Self::UniqueWithoutIndex { field } => write!(
268                f,
269                "field `{field}` is marked unique, but no unique index covers its column: add \
270                 `#[unique]` (or `#[unique(..)]`) to the model or drop `.unique()`, which would \
271                 otherwise check a rule the database does not enforce"
272            ),
273            Self::OptionalUnique { field } => write!(
274                f,
275                "field `{field}` is marked unique, but its record-form field answers an empty \
276                 submission and its column is not nullable, so every empty submission stores \
277                 the same value: make the field required, or an `Option`"
278            ),
279            Self::CreateColumnsNameTenant { column } => write!(
280                f,
281                "`create_column` names the tenant column `{column}`, which the framework stamps \
282                 on create: drop it there and delegate to `write_create`"
283            ),
284            Self::UnwrittenColumn { column } => write!(
285                f,
286                "nothing writes the non-nullable column `{column}` on create: the record form has \
287                 no such field, toasty fills no `#[default(..)]` for it, and no `create_column` \
288                 names it, so every create would fail at the driver; a resource that creates \
289                 nothing declares `without_page(ResourcePage::Create)`"
290            ),
291            Self::ImportWithoutCreate => write!(
292                f,
293                "`importable` creates each row through the create form, which this resource does \
294                 not serve: it has no record form, or declares `without_page(ResourcePage::Create)`"
295            ),
296            Self::EmptyDetail => f.write_str(EMPTY_DETAIL),
297            Self::RelatedForm(fault) => fault.fmt(f),
298            Self::ManyToMany { field, fault } => fmt_many_to_many(f, field, fault),
299        }
300    }
301}
302
303/// The wording of a choice field's [`DeclarationErrorKind`].
304fn fmt_choice(f: &mut fmt::Formatter<'_>, kind: &DeclarationErrorKind) -> fmt::Result {
305    match kind {
306        DeclarationErrorKind::MisdeclaredDependentChoice { field } => write!(
307            f,
308            "choice '{field}' depends on a column its options do not have: call \
309             `relationship::<R>()` and name a column of `R`'s model in `depends_on`"
310        ),
311        DeclarationErrorKind::UnfilterableChoice { field } => write!(
312            f,
313            "choice '{field}' filters its options but loads none from a relationship: call \
314             `relationship::<R>()` or drop `options_where`"
315        ),
316        DeclarationErrorKind::MultipleDependentChoice { field } => write!(
317            f,
318            "choice '{field}' depends on another field through a multiple choice, which \
319             neither narrows another choice nor is narrowed: drop `depends_on` or `multiple`"
320        ),
321        DeclarationErrorKind::ListedDependentChoice { field } => write!(
322            f,
323            "choice '{field}' depends on another field but renders its options as radios or \
324             buttons, which the browser cannot narrow: drop `depends_on`, or `radio` or \
325             `buttons`"
326        ),
327        DeclarationErrorKind::UncreatableChoice { field } => write!(
328            f,
329            "choice '{field}' is creatable but is not a single select over a resource's \
330             records: drop `creatable`, or declare a single select with \
331             `relationship::<R>()` over a resource `R`, outside a repeater and without \
332             `disabled_when`"
333        ),
334        DeclarationErrorKind::UnplacedParentField { field, parent } => write!(
335            f,
336            "choice '{field}' depends on field '{parent}', which the schema does not place: \
337             place it in the same schema"
338        ),
339        _ => unreachable!("not a choice's error"),
340    }
341}
342
343/// The wording of a condition's [`DeclarationErrorKind`].
344fn fmt_condition(f: &mut fmt::Formatter<'_>, kind: &DeclarationErrorKind) -> fmt::Result {
345    match kind {
346        DeclarationErrorKind::UnplacedWatchedField { field } => write!(
347            f,
348            "a condition watches field '{field}', which the schema does not place: place it \
349             in the same schema"
350        ),
351        DeclarationErrorKind::HiddenWatchedField { field } => write!(
352            f,
353            "a condition watches field '{field}', which a condition hides while the guarded \
354             field or block still shows: place the guarded one inside the block that hides \
355             '{field}'"
356        ),
357        DeclarationErrorKind::DisabledWatchedField { field } => write!(
358            f,
359            "a condition or a dependent choice watches field '{field}', which a condition \
360             disables and so posts nothing: watch another field, or drop `disabled_when` from \
361             '{field}'"
362        ),
363        DeclarationErrorKind::UnpostedConditionValue { field, value } => write!(
364            f,
365            "a condition shows a field while '{field}' posts '{value}', which it never posts: \
366             name one of its option values, or `true` or `false` for a toggle"
367        ),
368        _ => unreachable!("not a condition's error"),
369    }
370}
371
372/// The wording of a route's or a prefix's [`DeclarationErrorKind`].
373fn fmt_route(f: &mut fmt::Formatter<'_>, kind: &DeclarationErrorKind) -> fmt::Result {
374    match kind {
375        DeclarationErrorKind::InvalidSegment {
376            item,
377            segment,
378            fault,
379        } => write!(f, "{item} '{segment}' {fault}"),
380        DeclarationErrorKind::PrefixOverlapsRuntime { prefix } => write!(
381            f,
382            "prefix '{prefix}' overlaps Topcoat's runtime endpoints at '{}'",
383            crate::topcoat_compat::RUNTIME_PREFIX
384        ),
385        DeclarationErrorKind::PrefixOverlapsPanel { other } => write!(
386            f,
387            "the prefix overlaps the panel mounted at '{other}': each panel needs a prefix of \
388             its own"
389        ),
390        DeclarationErrorKind::EndpointOutsideRuntime { path } => write!(
391            f,
392            "endpoint '{path}' is not a shard or procedure under '{}': the panel's prefix or \
393             the app's own layers guard a route elsewhere",
394            crate::topcoat_compat::RUNTIME_PREFIX
395        ),
396        DeclarationErrorKind::ServeDirWithoutCatchAll { path } => write!(
397            f,
398            "serve_dir path '{path}' must end in a catch-all like '/uploads/{{*file}}'"
399        ),
400        DeclarationErrorKind::ServeDirTwice { path } => {
401            write!(f, "serve_dir path '{path}' is declared twice")
402        }
403        DeclarationErrorKind::ServeDirTaken { path, panel } => write!(
404            f,
405            "serve_dir path '{path}' is already served by the panel mounted at '{panel}'"
406        ),
407        _ => unreachable!("not a route's error"),
408    }
409}