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