Skip to main content

tablo_core/
form.rs

1//! Record forms: the typed value a form submission parses into, and the write
2//! that stores it.
3//!
4//! Declares one `RecordForm` struct with one field per written model column.
5//! The struct is the form's one source of truth: it parses every key, and a
6//! field's blank answer decides whether its control is required. Completes
7//! unposted keys from the stored record and writes only named fields plus model
8//! defaults.
9//!
10//! ```no_run
11//! #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
12//! struct User {
13//!     #[key]
14//!     #[auto]
15//!     id: uuid::Uuid,
16//!     name: String,
17//!     age: i64,
18//! }
19//!
20//! #[derive(tablo_core::RecordForm)]
21//! #[form(model = User)]
22//! struct UserForm {
23//!     name: String,
24//!     #[form(blank = 0)]
25//!     age: i64,
26//! }
27//!
28//! // A column type toasty stores but the form edge cannot spell.
29//! #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
30//! struct Tagged {
31//!     #[key]
32//!     #[auto]
33//!     id: uuid::Uuid,
34//!     tags: Vec<String>,
35//! }
36//! ```
37//!
38//! # Compile-time refusals
39//!
40//! The derive refuses, at compile time:
41//!
42//! - a field the model does not have;
43//! - a type the model's field does not have, such as `i32` for an `i64` column;
44//! - a bare choice, which would offer nothing: a foreign key names its source with
45//!   `#[form(relationship = ..)]`;
46//! - `relationship` and `file` on one field, which each pick the control;
47//! - a scalar type the form edge cannot spell, such as `Vec<String>`;
48//! - a many-to-many field whose keys are not its source's primary key;
49//! - `optional` on a type with no empty value;
50//! - `embed` on a type that is not an [`EmbeddedForm`](crate::EmbeddedForm).
51
52use std::{collections::HashSet, fmt::Debug, hash::Hash};
53
54use toasty::{Executor, schema::Model};
55use topcoat::context::Cx;
56
57#[doc(hidden)]
58pub use crate::schema::input::required_input;
59use crate::{
60    column::Includes,
61    schema::{OptionSource, Schema},
62};
63// A record form's values, scalars and errors sit below `schema`, which reads and renders them,
64// and a form input is a schema's parse; both are re-exported here, where a record form names
65// them.
66pub use crate::{
67    schema::input::FormInput,
68    values::{
69        FieldError, FieldErrors, FormField, FormFields, FormScalar, FormValue, FormValues,
70        NullableScalar, assert_form_scalar, parse_list, parse_password, parse_scalar,
71    },
72};
73
74impl<F: RecordForm> crate::schema::EditsRecords for F {}
75
76/// The hidden control the edit form carries the record's [`PanelModel::version`] in.
77///
78/// [`PanelModel::version`]: crate::PanelModel::version
79pub(crate) const VERSION_FIELD: &str = "record_version";
80
81/// The name of the create form's second submit button, which saves and lands on a fresh create
82/// form rather than the list.
83pub(crate) const ANOTHER_FIELD: &str = "create_another";
84
85/// The form key of the many-to-many field `path`, a `#[has_many(via = ..)]` list of `R`'s
86/// records, holding their keys of type `K`: the derive calls it, so a field whose type is not
87/// `Vec<K>` of the related model's key, or whose source is not that model's, fails to compile.
88#[doc(hidden)]
89pub fn links_key<M, R, K>(
90    path: impl Into<toasty::stmt::Path<M, toasty::stmt::List<R::Model>>>,
91) -> String
92where
93    M: Model,
94    R: OptionSource,
95    R::Model: Model<PrimaryKey = K>,
96    K: FormScalar,
97{
98    crate::schema::form_key(path.into())
99}
100
101/// `includes` and the include loading the many-to-many field `path`, which
102/// [`RecordForm::hydrate`] reads.
103#[doc(hidden)]
104pub fn links_include<M, R>(
105    includes: Includes<M>,
106    path: impl Into<toasty::stmt::Path<M, toasty::stmt::List<R::Model>>>,
107) -> Includes<M>
108where
109    M: Model,
110    R: OptionSource,
111{
112    includes.with(path.into())
113}
114
115/// The keys of the records a many-to-many field holds, as its form key carries them, or `None`
116/// when the record was loaded without them.
117#[doc(hidden)]
118pub fn write_links<T>(records: &toasty::Deferred<Vec<T>>) -> Option<FormValue>
119where
120    T: Model + toasty::stmt::IntoExpr<T>,
121{
122    (!records.is_unloaded()).then(|| {
123        FormValue::List(
124            records
125                .get()
126                .iter()
127                .map(crate::toasty_compat::pk::pk_text)
128                .collect(),
129        )
130    })
131}
132
133/// The typed value a resource's form submission parses into.
134///
135/// Derive it from a model with [`tablo_core::ModelForm`](crate::ModelForm) or from a struct with
136/// [`tablo_core::RecordForm`](crate::RecordForm); a hand-written impl is what the derives expand
137/// to.
138///
139/// Its [`FormFields`] are one variant per form field, the key [`Posted`] and a refusal use, whose
140/// bound form keys are [`Self::fields`]'.
141pub trait RecordForm:
142    FormFields<Field: Copy + Eq + Hash + Debug + Send + Sync + 'static> + Sized + Send + 'static
143{
144    /// The model the form writes.
145    type Model: Model + toasty::stmt::IntoExpr<Self::Model> + Send + Sync + 'static;
146
147    /// Every field, in declaration order, with the keys it binds.
148    fn fields() -> Vec<FormField<Self::Field>>;
149
150    /// The control the form renders `field` with when its [`form`](crate::ResourceDef::form)
151    /// does not place it: what `controls()` hands over for the field, as a one-control schema.
152    ///
153    /// A resource's form renders every field it does not place after the ones it does, in
154    /// declaration order, so a resource that declares no form renders one control per field.
155    fn control(field: Self::Field) -> Schema<Self>;
156
157    /// The relations [`hydrate`](Self::hydrate) reads off the record: each many-to-many field's,
158    /// which the edit page and the edit's write load the record with.
159    fn includes() -> Includes<Self::Model> {
160        Includes::new()
161    }
162
163    /// The stored record as the form spells it.
164    fn hydrate(cx: &Cx, record: &Self::Model) -> FormValues;
165
166    /// The records each many-to-many field holds, as their keys' form spelling: what
167    /// [`write_create`](crate::resource::write_create) links a new record to, and what
168    /// [`write_update`](crate::resource::write_update) leaves a posted field's record linked to.
169    fn links(&self) -> Vec<(Self::Field, Vec<String>)> {
170        Vec::new()
171    }
172
173    /// Parse a completed submission: the form's only presence and type check.
174    ///
175    /// # Errors
176    ///
177    /// Every key that failed, each once, under one of [`Self::fields`]' keys.
178    fn parse(cx: &Cx, values: &FormValues) -> std::result::Result<Self, Vec<FieldError>>;
179
180    /// The create builder with every field set.
181    fn into_create(self) -> <Self::Model as Model>::Create;
182
183    /// The instance update builder with one assignment per named field, or
184    /// `None` when no field is named.
185    ///
186    /// `None` is what keeps a submission that names no field from building an
187    /// empty update, which toasty refuses with an assertion.
188    fn into_update<'a>(
189        self,
190        record: &'a mut Self::Model,
191        named: &HashSet<Self::Field>,
192    ) -> Option<<Self::Model as Model>::Update<'a>>;
193
194    /// Execute a builder [`Self::into_update`] returned.
195    ///
196    /// Toasty's instance update builder implements no trait that carries
197    /// `exec`, so the generic write reaches it through the form.
198    fn exec_update<'a>(
199        update: <Self::Model as Model>::Update<'a>,
200        ex: &'a mut dyn Executor,
201    ) -> impl Future<Output = toasty::Result<()>> + Send + 'a;
202
203    /// Whether the resource naming this form has create and edit pages.
204    ///
205    /// [`Panel::resource`](crate::Panel::resource) registers the create, edit,
206    /// and options routes only when this holds. [`NoForm`] sets it to `false`.
207    const HAS_FORM: bool = true;
208}
209
210/// The record form of a resource with no create or edit page.
211///
212/// A list-only resource names it as [`Resource::Form`](crate::Resource::Form):
213/// `type Form = NoForm<Self::Model>;`. [`fields`](RecordForm::fields) and
214/// [`hydrate`](RecordForm::hydrate) are empty and
215/// [`into_update`](RecordForm::into_update) answers `None`. No route parses or
216/// writes it, so [`parse`](RecordForm::parse) and
217/// [`into_create`](RecordForm::into_create) panic naming the model, and the
218/// future [`exec_update`](RecordForm::exec_update) returns panics when polled.
219pub struct NoForm<M>(std::marker::PhantomData<fn() -> M>);
220
221impl<M: Model + toasty::stmt::IntoExpr<M> + Send + Sync + 'static> NoForm<M> {
222    fn unreachable() -> ! {
223        panic!("`NoForm<{}>` has no form", std::any::type_name::<M>())
224    }
225}
226
227impl<M> FormFields for NoForm<M> {
228    type Field = std::convert::Infallible;
229    type Keys = ();
230
231    fn keys() -> Self::Keys {}
232}
233
234impl<M: Model + toasty::stmt::IntoExpr<M> + Send + Sync + 'static> RecordForm for NoForm<M> {
235    type Model = M;
236
237    const HAS_FORM: bool = false;
238
239    fn fields() -> Vec<FormField<Self::Field>> {
240        Vec::new()
241    }
242
243    fn control(field: Self::Field) -> Schema<Self> {
244        match field {}
245    }
246
247    fn hydrate(_cx: &Cx, _record: &M) -> FormValues {
248        FormValues::new()
249    }
250
251    fn parse(_cx: &Cx, _values: &FormValues) -> std::result::Result<Self, Vec<FieldError>> {
252        Self::unreachable()
253    }
254
255    fn into_create(self) -> M::Create {
256        Self::unreachable()
257    }
258
259    fn into_update<'a>(
260        self,
261        _record: &'a mut M,
262        _named: &HashSet<Self::Field>,
263    ) -> Option<M::Update<'a>> {
264        None
265    }
266
267    fn exec_update<'a>(
268        update: M::Update<'a>,
269        ex: &'a mut dyn Executor,
270    ) -> impl Future<Output = toasty::Result<()>> + Send + 'a {
271        // `into_update` answers `None`, so no builder reaches here. The
272        // builder is not known to be `Send`, so the future must not hold it.
273        drop((update, ex));
274        async { Self::unreachable() }
275    }
276}
277
278/// An edit submission: the parsed form, and the fields the submission named.
279///
280/// Derefs to the form, so a record fn reads `posted.author_id` — the posted
281/// value, or the stored one when the submission did not name the field.
282pub struct Posted<F: RecordForm> {
283    form: F,
284    named: HashSet<F::Field>,
285}
286
287impl<F: RecordForm> Posted<F> {
288    /// A posted form that names `named`.
289    pub fn new(form: F, named: impl IntoIterator<Item = F::Field>) -> Self {
290        Self {
291            form,
292            named: named.into_iter().collect(),
293        }
294    }
295
296    /// Whether the submission named `field`: `posted.named(|f| f.post_id)`.
297    pub fn named(&self, pick: impl FnOnce(F::Keys) -> F::Field) -> bool {
298        self.names(pick(F::keys()))
299    }
300
301    /// Whether the submission named the field `field` is the variant of.
302    pub(crate) fn names(&self, field: F::Field) -> bool {
303        self.named.contains(&field)
304    }
305
306    /// The update builder assigning every named field, or `None` when the
307    /// submission named none. See [`RecordForm::into_update`].
308    pub fn into_update(self, record: &mut F::Model) -> Option<<F::Model as Model>::Update<'_>> {
309        self.form.into_update(record, &self.named)
310    }
311}
312
313impl<F: RecordForm> std::ops::Deref for Posted<F> {
314    type Target = F;
315
316    fn deref(&self) -> &F {
317        &self.form
318    }
319}