tablo-core 0.6.0

The core toolkit types for Tablo, a server-rendered admin toolkit on Topcoat and Toasty.
Documentation
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//! Tablo: a server-rendered admin toolkit on [Topcoat](topcoat) and [Toasty](toasty).
//!
//! A [`Panel`] serves one [`Resource`] per Toasty model. A resource names the model and the
//! [`RecordForm`](derive@RecordForm) struct its create and edit submissions parse into, and
//! declares the rest as one [`ResourceDef`] value: its [`Policy`], which denies by default, and
//! any [`Table`], [`Schema`] or [`Detail`] that arranges or extends what the record form derives.
//! The app mounts the panel on its own Topcoat router with [`RouterBuilderPanelExt::panel`], which
//! builds each def once, binds it to the database schema and checks it first; one router mounts any
//! number of panels at distinct prefixes.
//!
//! ```rust,no_run
//! # use tablo_core::{Allow, Panel, Resource, ResourceDef, RouterBuilderPanelExt};
//! # use toasty::Db;
//! # use topcoat::router::{Router, RouterBuilderDiscoverExt};
//! # fn main() -> topcoat::Result<()> {
//! # #[derive(Debug, Clone, toasty::Model)]
//! # pub struct Book {
//! #     #[key]
//! #     #[auto]
//! #     pub id: uuid::Uuid,
//! #     pub title: String,
//! # }
//! #[derive(tablo_core::RecordForm)]
//! #[form(model = Book)]
//! pub struct BookForm {
//!     pub title: String,
//! }
//!
//! pub struct BookResource;
//!
//! impl Resource for BookResource {
//!     type Model = Book;
//!     type Form = BookForm;
//!
//!     fn declare() -> ResourceDef<Self> {
//!         ResourceDef::new().policy(Allow)
//!     }
//! }
//!
//! # let db: Db = todo!();
//! let router = Router::builder()
//!     .discover()
//!     .app_context(db)
//!     .panel(Panel::new("admin").resource::<BookResource>())?
//!     .build();
//! # let _ = router;
//! # Ok(())
//! # }
//! ```
//!
//! The [user guide](https://y-l.fr/tablo/nightly/guide/) walks through a complete panel and each
//! part of it. [`ResourceDef`] lists everything a resource declares, [`Resource`] the hooks it
//! overrides, and [`Panel`] every builder call.

// The derives emit `tablo_core::` paths; this lets them expand inside this
// crate's own tests too.
extern crate self as tablo_core;

#[doc(hidden)]
pub mod __macro {
    pub use toasty::{
        Executor, Result as DbResult,
        schema::{Embed, Model},
        stmt,
        stmt::{List, Path},
    };
    pub use topcoat::context::Cx;

    pub use crate::{
        Lens,
        detail::Detail,
        extend::{Includes, OptionSource},
        form::{
            FieldError, FormField, FormScalar, NullableScalar, RecordForm, assert_form_scalar,
            links_include, links_key, parse_list, parse_password, parse_scalar, write_links,
        },
        resource::{ActionInput, required_input},
        schema::{
            ChoiceField, CustomField, EmbeddedForm, Field, FieldResolver, FileField, IntoSchema,
            Options, RepeaterField, RepeaterItem, Schema, TextField,
            embedded::{
                Embedded, EmbeddedBuilder, embedded_field, embedded_form, take_leaf, take_value,
            },
            form_key, parse_items,
            tree::Retype,
            write_items,
        },
        table::{
            BooleanColumn, EmbeddedColumn, FileColumn, RelationColumn, RelationLens,
            RepeaterColumn, Table, TextColumn,
        },
        toasty_compat::VariantId,
    };
}
// The toolkit surface: Panel, Resource, Table, Schema, Notification,
// Tenancy, CSRF, and the `Db` glue.
pub mod auth;
pub mod csrf;
pub mod db;
mod declaration;
pub mod detail;
mod error;
pub mod extend;
pub mod form;
mod lens;
mod naming;
pub mod navigation;
pub mod notification;
mod page;
pub mod panel;
pub mod policy;
mod query_term;
pub mod resource;
pub mod schema;
pub mod table;
pub mod tenancy;
#[cfg(test)]
mod test_support;
mod toasty_compat;
mod topcoat_compat;
pub mod upload;

pub use auth::{
    Auth, Authenticator, LoginThrottle, PanelUser, PasswordAuth, Registrar, SignUp, membership,
};
pub use declaration::{
    ActionInputFault, DeclarationError, DeclarationErrorKind, ManyToManyFault, MountError,
    SegmentFault, SignUpFault, Site,
};
pub use detail::{Detail, IntoDetail};
pub use form::{
    FieldError, FieldErrorKind, FieldErrors, FormField, FormScalar, NoForm, Posted, RecordForm,
};
pub use lens::Lens;
pub use navigation::{NavTarget, NavigationItem};
pub use notification::{Notification, NotificationStatus};
pub use page::{Page, header_action_buttons};
pub use panel::{Brand, Panel, PanelHandle, RouterBuilderPanelExt, can_list, url};
pub use policy::{Ability, Allow, Deny, Policy, ReadOnly, when};
pub use resource::{
    Action, ActionInput, Committed, ForeignKey, HeaderAction, HeaderActions, Mutation, Places,
    PublicLink, Relation, Resource, ResourceDef, can, scoped_query, write_create, write_update,
};
pub use schema::{
    ChoiceField, CustomField, EmbeddedForm, Field, FieldResolver, FileField, Grid, Group,
    IntoOptions, IntoSchema, Options, RepeaterField, RepeaterItem, Schema, Section, Source,
    TextField, Toggle, Watched,
};
pub use table::{
    BooleanColumn, ColumnWidth, ComputedColumn, CountColumn, Cursor, DateFilter, EmbeddedColumn,
    FileColumn, IntoColumns, IntoFilters, QueryFilter, RelationColumn, RelationLens,
    RepeaterColumn, SelectFilter, Sort, Table, TablePage, TableState, TernaryFilter, TextColumn,
    ToOneRelation, WiredTable, contains_expr,
};
/// Derives [`ActionInput`](trait@ActionInput) for the typed value an [`Action`] asks for
/// before it runs.
///
/// ```rust
/// # #[derive(Debug, Clone, toasty::Model)]
/// # struct Post { #[key] #[auto] id: uuid::Uuid, status: String }
/// # use tablo_core::{Action, ActionInput, NoForm, Resource};
/// # use topcoat::{Result, context::Cx};
/// # struct PostResource;
/// # impl Resource for PostResource {
/// #     type Model = Post;
/// #     type Form = NoForm<Post>;
/// # }
/// #[derive(tablo_core::ActionInput)]
/// pub struct Rejection {
///     #[form(multiline = 4)]
///     pub reason: String,
///     pub notify_author: bool,
/// }
///
/// struct Reject;
///
/// impl Action<PostResource> for Reject {
///     type Input = Rejection;
///     const NAME: &'static str = "reject";
///
///     async fn run(
///         _cx: &Cx,
///         posts: &[Post],
///         rejection: Rejection,
///         ex: &mut dyn toasty::Executor,
///     ) -> Result<()> {
///         // Store `rejection.reason`, notify when `rejection.notify_author` holds…
///         # let _ = (posts, rejection.reason, rejection.notify_author, ex);
///         Ok(())
///     }
/// }
/// ```
///
/// Each field posts its own name, which no column binds, and renders the control its type
/// picks: a `bool` a checkbox, `#[form(options)]` a choice over the field type's
/// [`Options`](derive@Options), `#[form(options = T)]` one over `T`'s, and any other
/// [`FormScalar`] a text input of the type's input type.
///
/// A field's **blank answer** is its `#[form(blank = ..)]`, `""` for an `#[form(optional)]`
/// `String`, `None` for an `Option`, or `false` for a `bool`. A field with none is required:
/// its control renders required and the parse refuses an empty submission.
///
/// # Per-field attributes
///
/// - `#[form(label = "Reason")]` — the control's label (default: the field name in sentence
///   case).
/// - `#[form(multiline = 4)]` — a `<textarea>` of 4 rows.
/// - `#[form(placeholder = "rust, async")]` — a text input's placeholder.
/// - `#[form(email)]` — a text input that refuses a malformed email address.
/// - `#[form(password)]` — a masked text input on a `String`, read untrimmed, that a refused
///   form renders empty.
/// - `#[form(blank = ..)]`, `#[form(optional)]` — the blank answer.
/// - `#[form(options)]`, `#[form(options = T)]` — a choice. An `Option<T>` field names its
///   options type: `#[form(options = T)]`.
///
/// A generic struct, a tuple struct, an empty struct (name `()` instead), an unknown key, a
/// text input's key with `options` or on a `bool`, `password` with `multiline`, and a field
/// that is not a `FormScalar` are compile errors.
/// [`RouterBuilderPanelExt::panel`] refuses a field named `csrf_token`, `confirm` or `ids`,
/// the keys an action's POST carries besides its input.
///
/// A hand-written impl builds its fields with [`Field::text_input`], [`Field::choice_input`]
/// and [`Field::toggle_input`]; its controls render without the `required` mark, though its
/// `parse` still refuses what it requires.
pub use tablo_macros::ActionInput;
/// Derives `EmbeddedForm` for an embedded struct or enum.
///
/// Builds the schema node and converts the value through that node's keys.
///
/// ```rust,no_run
/// # #[derive(Debug, Clone, toasty::Model)]
/// # struct Post {
/// #     #[key] #[auto] id: uuid::Uuid,
/// #     publication: Publication,
/// # }
/// # use tablo_core::Section;
/// #[derive(Debug, Clone, toasty::Embed, tablo_core::EmbeddedForm)]
/// pub enum Publication {
///     #[column(variant = 1)]
///     Scheduled {
///         #[shared(timestamp)]
///         #[form(label = "Publication timestamp")]
///         scheduled_at: String,
///         scheduled_for: String,
///     },
///     #[column(variant = 2)]
///     Published {
///         #[shared(timestamp)]
///         published_at: String,
///         canonical_url: String,
///     },
/// }
///
/// // form declaration — no field bindings written by hand
/// Section::new("Publication").schema(Publication::form(Post::fields().publication()));
/// ```
///
/// # How a field is classified
///
/// A field marked `#[form(embed)]` is another **embedded value**, delegated to
/// its own `EmbeddedForm`. Every other field is a **scalar**: one column, read
/// and written through `FormScalar` (`String`, a `TypedValue` type, an
/// `Options` enum, or an `Option` of one). A scalar of another type fails to compile at the
/// field, naming the trait. An empty scalar is its blank answer — its declared
/// `#[form(blank = ..)]`, `None` for an `Option`, `false` for a `bool`, `""`
/// for an `#[form(optional)]` `String` — and a scalar with none is required:
/// its control renders required and the parse refuses its key.
///
/// # Which variant an enum reads
///
/// A named discriminant always wins, and an undeclared one is refused;
/// otherwise the first variant, in declaration order, with a **payload of its
/// own** submitted — a `#[shared(..)]` column belongs to several variants and
/// never selects one; otherwise the first variant.
///
/// # Per-field attributes
///
/// - `#[form(embed)]` — a nested `EmbeddedForm` value.
/// - `#[form(label = "Canonical URL")]` — the control's label (default: the field name in
///   sentence case, `canonical_url` → "Canonical url").
/// - `#[form(multiline = 3)]` — a `<textarea>` of 3 rows.
/// - `#[form(blank = ..)]` — what an empty submission reads as.
/// - `#[form(optional)]` on a `String` — an empty submission reads as `""`.
///
/// Anything else in `#[form(..)]` is a compile error, as are `label`, `multiline`, `blank` and
/// `optional` on an embedded value, `blank` or `optional` on an `Option`, and `optional` on a
/// type other than `String`.
pub use tablo_macros::EmbeddedForm;
/// Derive `Options` for a unit-variant enum: the `(value, label)` list a
/// choice field, a select filter and a column share, and the `FormScalar`
/// that posts a variant as its value and reads it as its label.
///
/// ```rust
/// # use tablo_core::Options;
/// #[derive(Debug, Clone, Copy, PartialEq, Eq, toasty::Embed, tablo_core::Options)]
/// pub enum Status {
///     Draft,
///     #[option(label = "Live")]
///     Published,
/// }
///
/// assert_eq!(Status::Published.value(), "published");
/// assert_eq!(Status::Published.label(), "Live");
/// assert_eq!(Status::from_value("draft"), Some(Status::Draft));
/// ```
///
/// Each variant's value is its `snake_case` name and its label that name in
/// sentence case. `#[option(value = "..")]` and `#[option(label = "..")]`
/// override either. A generic enum, a variant with fields, two variants
/// sharing one value or one label, and an unknown key are compile errors.
///
/// The enum, and an `Option` of it, is a form scalar through this derive, so
/// it cannot also implement `TypedValue` or `FormScalar` itself.
pub use tablo_macros::Options;
/// Derive `RecordForm` for the typed value a resource's form writes.
///
/// One field per model column the form writes, named and typed like the
/// model's field. A scalar (`String`, a `TypedValue` type, an `Options` enum,
/// or an `Option` of one) binds the key its control posts; a `#[form(embed)]` field binds
/// every key of an `EmbeddedForm` value and is written whole.
///
/// ```rust
/// # #[derive(Debug, Clone, toasty::Model)]
/// # pub struct User {
/// #     #[key] #[auto] id: uuid::Uuid,
/// #     name: String,
/// #     role: String,
/// #     age: i64,
/// # }
/// #[derive(tablo_core::RecordForm)]
/// #[form(model = User)]
/// pub struct UserForm {
///     pub name: String,
///     #[form(blank = "member")]
///     pub role: String,
///     #[form(blank = 0)]
///     pub age: i64,
/// }
/// ```
///
/// The derive also emits `UserFormField`, one variant per field, which
/// `Posted` and `Resource::validate_record`'s `FieldErrors` key on and
/// `RecordForm::fields` answers with each variant's keys.
/// It emits `UserFormControls`, one control per field chosen from the field —
/// a `bool` is a toggle, `#[form(options = T)]` a choice over `T`'s options,
/// `#[form(options)]` a choice over the field type's options,
/// `#[form(relationship = R)]` a choice over `R`'s records (a multiple choice over a `Vec` of
/// their keys), `#[form(file)]` a file field, `#[form(embed)]` the embedded value's schema,
/// `#[form(repeat)]` a repeater, and any
/// other field a text field — with `controls()` handing them over, typed by the form so only a
/// `Schema<UserForm>` places them, and `RecordForm::control` answering one
/// field's. `RecordForm::table` lists a
/// sortable column per text field, searchable over a `String` or
/// `Option<String>`, an options field by its option's label, and a toggle as
/// yes or no. `RecordForm::detail` shows the same columns, plus a relationship's
/// key, a many-to-many field's records by their titles, a file field as a link, an embedded
/// value leaf by leaf and a repeater's items. A
/// resource's `ResourceDef` defaults its form, table and detail page to them;
/// `ResourceDef::form`, `ResourceDef::table` and `ResourceDef::view` arrange or extend them
/// instead, and a form renders the controls it does not place after the ones it does.
///
/// # Attributes
///
/// - `#[form(model = User)]` on the struct: the model the form writes.
/// - `#[form(blank = <expr>)]` on a scalar: the value an empty submission reads as.
/// - `#[form(optional)]` on a `String`: an empty submission reads as `""`.
/// - `#[form(options)]` on an `Options` enum or an `Option` of one: a choice over its options.
///   Without it, the field is a text field.
/// - `#[form(options = Status)]`: a choice over `Status::options()`.
/// - `#[form(relationship = AuthorResource)]` on a foreign key: a choice over the source's
///   records, each labelled by its `record_title`. The source is any `OptionSource`, which
///   every `Resource` is.
/// - `#[form(relationship = TagResource)]` on a `Vec` of the source's keys, named like the
///   model's `#[has_many(via = joins.target)]` field: a many-to-many field, a multiple choice
///   whose records the write links through the join model, one row each. No record is its
///   blank answer; an edit that does not post it keeps the record's links.
/// - `#[form(file)]` on a `String`: a file field.
/// - `#[form(embed)]` on an `EmbeddedForm` value.
/// - `#[form(repeat)]` on a `#[document]` list of [`RepeaterItem`](derive@RepeaterItem)
///   values: a repeater, a row per item, which the browser adds, removes and moves. No rows is
///   its blank answer.
///
/// A scalar's **blank answer** is its `blank`, `""` for an `optional` `String`, `None` for an
/// `Option`, or `false` for a `bool`. A field with none is required: the panel renders its
/// control required and the parse refuses an empty submission. No control declares presence.
///
/// A generic struct, a tuple struct, an empty struct, a `Deferred<_>` field,
/// `blank` or `optional` on an `Option`, an embedded value or a many-to-many field, `optional`
/// on a type other than `String`, and an unknown key are compile errors. So are a field the
/// model lacks, a type the model's field does not have, a scalar that is not a `FormScalar`,
/// and a many-to-many field whose keys are not its source's primary key.
pub use tablo_macros::RecordForm;
/// Derives [`RepeaterItem`](trait@RepeaterItem) for one item of a repeater: an embedded struct
/// a `#[document]` list stores.
///
/// ```rust
/// #[derive(Debug, Clone, toasty::Embed, tablo_core::RepeaterItem)]
/// pub struct Link {
///     pub label: String,
///     #[form(label = "URL")]
///     pub url: String,
/// }
///
/// #[derive(Debug, Clone, toasty::Model)]
/// pub struct Post {
///     #[key]
///     #[auto]
///     id: uuid::Uuid,
///     #[document]
///     #[default(Vec::<Link>::new())]
///     links: Vec<Link>,
/// }
///
/// #[derive(tablo_core::RecordForm)]
/// #[form(model = Post)]
/// pub struct PostForm {
///     #[form(repeat)]
///     pub links: Vec<Link>,
/// }
/// ```
///
/// Its fields, controls and attributes are an [`ActionInput`](derive@ActionInput)'s: each row
/// posts them under its own prefix (`links.0.url`). An item's blank answers and required
/// fields work the same way, and each row answers to its controls' own rules, such as a choice
/// offering only its options. A repeater takes at most [`MAX_ROWS`](schema::MAX_ROWS) rows.
pub use tablo_macros::RepeaterItem;
pub use tenancy::{Membership, Tenancy, Tenant, TenantColumn, TenantId, require_tenant, tenant_id};
pub use upload::Uploader;