tablo-core 0.7.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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
//! Record forms: the typed value a form submission parses into, and the write
//! that stores it.
//!
//! Declares one `RecordForm` struct with one field per written model column.
//! The struct is the form's one source of truth: it parses every key, and a
//! field's blank answer decides whether its control is required. Completes
//! unposted keys from the stored record and writes only named fields plus model
//! defaults.
//!
//! ```no_run
//! #[derive(Debug, Clone, toasty::Model, tablo_core::ModelColumns)]
//! struct User {
//!     #[key]
//!     #[auto]
//!     id: uuid::Uuid,
//!     name: String,
//!     age: i64,
//! }
//!
//! #[derive(tablo_core::RecordForm)]
//! #[form(model = User)]
//! struct UserForm {
//!     name: String,
//!     #[form(blank = 0)]
//!     age: i64,
//! }
//!
//! // A column type toasty stores but the form edge cannot spell.
//! #[derive(Debug, Clone, toasty::Model, tablo_core::ModelColumns)]
//! struct Tagged {
//!     #[key]
//!     #[auto]
//!     id: uuid::Uuid,
//!     tags: Vec<String>,
//! }
//! ```
//!
//! # Compile-time refusals
//!
//! The derive refuses, at compile time:
//!
//! - a field the model does not have;
//! - a type the model's field does not have, such as `i32` for an `i64` column;
//! - a bare choice, which would offer nothing: a foreign key names its source with
//!   `#[form(relationship = ..)]`;
//! - `relationship` and `file` on one field, which each pick the control;
//! - a scalar type the form edge cannot spell, such as `Vec<String>`;
//! - a many-to-many field whose keys are not its source's primary key;
//! - `optional` on a type with no empty value;
//! - `embed` on a type that is not an [`EmbeddedForm`](crate::EmbeddedForm).

mod values;

use std::{collections::HashSet, fmt::Debug, hash::Hash};

use toasty::{Executor, schema::Model};
use topcoat::context::Cx;
pub use values::{FormValue, FormValues};

use crate::{
    schema::{FieldResolver, OptionSource, Schema, TypedValue},
    table::column::Includes,
};

/// A type one form key reads and writes: `String`, every [`TypedValue`] type,
/// every enum deriving [`Options`](crate::Options), and an `Option` of any of them.
///
/// The value the parse sees is trimmed and non-empty; an empty submission is the
/// record-form field's **blank answer** instead, and a field with none is required.
///
/// A text field binds a path of any `FormScalar` type
/// ([`Field::text`](crate::Field::text)), and the form derives read and write
/// every field that is not `#[form(embed)]` through it.
#[diagnostic::on_unimplemented(
    message = "`{Self}` is not a form scalar",
    label = "a form field of this type has no text spelling",
    note = "a form scalar is `String`, a `TypedValue` type, an `Options` enum, or an `Option` of \
            one; implement `TypedValue` for an app type, derive `Options` for a unit enum, or \
            mark an `EmbeddedForm` value `#[form(embed)]`"
)]
pub trait FormScalar: Sized {
    /// The `type` attribute of the text control that edits it.
    const INPUT_TYPE: &'static str = "text";

    /// The control's `step` attribute, when its input type takes one.
    const STEP: Option<&'static str> = None;

    /// The control's `value` for a stored value's form spelling.
    fn input_value(stored: &str) -> String {
        stored.to_string()
    }

    /// Parse a trimmed, non-empty submission, or return the error message.
    fn parse_form(value: &str) -> std::result::Result<Self, String>;

    /// The form spelling of a stored value.
    fn to_form(&self) -> String;

    /// What a column cell and a group header read: the form spelling, or an
    /// `Options` enum's label.
    fn to_label(&self) -> String {
        self.to_form()
    }
}

impl FormScalar for String {
    fn parse_form(value: &str) -> std::result::Result<Self, String> {
        Ok(value.to_string())
    }

    fn to_form(&self) -> String {
        self.clone()
    }
}

impl<T: TypedValue> FormScalar for T {
    const INPUT_TYPE: &'static str = T::INPUT_TYPE;
    const STEP: Option<&'static str> = T::STEP;

    fn input_value(stored: &str) -> String {
        T::input_value(stored)
    }

    fn parse_form(value: &str) -> std::result::Result<Self, String> {
        T::parse_input(value).ok_or_else(|| format!("`{value}` is not a valid {}", T::NOUN))
    }

    fn to_form(&self) -> String {
        self.to_string()
    }
}

/// A form scalar whose `Option` is one too: every [`TypedValue`] type, and every enum deriving
/// [`Options`](crate::Options), which implements it.
#[doc(hidden)]
pub trait NullableScalar: FormScalar {}

impl<T: TypedValue> NullableScalar for T {}

impl<T: NullableScalar> FormScalar for Option<T> {
    const INPUT_TYPE: &'static str = T::INPUT_TYPE;
    const STEP: Option<&'static str> = T::STEP;

    fn input_value(stored: &str) -> String {
        T::input_value(stored)
    }

    fn parse_form(value: &str) -> std::result::Result<Self, String> {
        T::parse_form(value).map(Some)
    }

    fn to_form(&self) -> String {
        self.as_ref().map(T::to_form).unwrap_or_default()
    }

    fn to_label(&self) -> String {
        self.as_ref().map(T::to_label).unwrap_or_default()
    }
}

impl FormScalar for Option<String> {
    fn parse_form(value: &str) -> std::result::Result<Self, String> {
        Ok(Some(value.to_string()))
    }

    fn to_form(&self) -> String {
        self.clone().unwrap_or_default()
    }
}

/// Compiles only for a form scalar: the form derives call it, spanned on a
/// field's type, so a field of another type fails there.
#[doc(hidden)]
pub fn assert_form_scalar<T: FormScalar>() {}

/// Why a key was refused.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum FieldErrorKind {
    /// Posted empty, and the field has no blank answer. The form renders
    /// "{label} is required" under the control.
    Required,
    /// Posted a value the field refuses, with the sentence the form renders.
    Invalid(String),
}

/// One key a submission was refused under: a form key, or a record form's
/// field enum in [`Resource::validate_record`](crate::Resource::validate_record).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FieldError<K = String> {
    /// What the error renders under.
    pub key: K,
    /// Why the key was refused.
    pub kind: FieldErrorKind,
}

impl<K> FieldError<K> {
    /// `key` was posted empty and has no blank answer.
    pub fn required(key: impl Into<K>) -> Self {
        Self {
            key: key.into(),
            kind: FieldErrorKind::Required,
        }
    }

    /// `key` carried a value it refuses; `message` says why.
    pub fn invalid(key: impl Into<K>, message: impl Into<String>) -> Self {
        Self {
            key: key.into(),
            kind: FieldErrorKind::Invalid(message.into()),
        }
    }

    /// The sentence the form renders under the control labelled `label`.
    pub fn message(&self, label: &str) -> String {
        match &self.kind {
            FieldErrorKind::Required => format!("{label} is required"),
            FieldErrorKind::Invalid(message) => message.clone(),
        }
    }
}

/// The refusal of a key holding another shape than its parse reads: a list or rows where it reads
/// text, or text where it reads a list. Only a schema whose controls disagree with its parse
/// holds one.
pub(crate) fn unreadable(key: &str) -> FieldError {
    FieldError::invalid(key, "The value could not be read")
}

/// Read one scalar from a completed submission.
///
/// Trims the value; an empty one is `blank`, the field's blank answer, or
/// refuses as [`FieldErrorKind::Required`] when it has none.
pub fn parse_scalar<T: FormScalar>(
    key: &str,
    values: &FormValues,
    blank: Option<T>,
) -> std::result::Result<T, FieldError> {
    let raw = match values.get(key) {
        None => "",
        Some(FormValue::Text(text)) => text.trim(),
        Some(_) => return Err(unreadable(key)),
    };
    if raw.is_empty() {
        return blank.ok_or_else(|| FieldError::required(key));
    }
    T::parse_form(raw).map_err(|message| FieldError::invalid(key, message))
}

/// Read a password from a completed submission: required as [`parse_scalar`] reads a `String`,
/// but kept as typed, with its outer spaces, since a login compares the password untrimmed.
pub fn parse_password(
    key: &str,
    values: &FormValues,
    blank: Option<String>,
) -> std::result::Result<String, FieldError> {
    parse_scalar::<String>(key, values, blank)?;
    Ok(values.text(key).unwrap_or_default().to_string())
}

/// The values a multiple choice holds, as its one form key carries them: what a record form
/// hydrates a many-to-many field with, and what a hand-written one writes.
pub fn write_list<'a, T: FormScalar + 'a>(values: impl IntoIterator<Item = &'a T>) -> FormValue {
    FormValue::List(values.into_iter().map(T::to_form).collect())
}

/// Read the values a multiple choice posted, none when it posted nothing: what a record form's
/// parse reads a many-to-many field with.
///
/// # Errors
///
/// A value `T` refuses, or a key holding no list, under `key`.
pub fn parse_list<T: FormScalar>(
    key: &str,
    values: &FormValues,
) -> std::result::Result<Vec<T>, FieldError> {
    let items: &[String] = match values.get(key) {
        None => &[],
        Some(FormValue::List(items)) => items,
        Some(_) => return Err(unreadable(key)),
    };
    items
        .iter()
        .map(|item| T::parse_form(item).map_err(|message| FieldError::invalid(key, message)))
        .collect()
}

/// The form key of the many-to-many field `path`, a `#[has_many(via = ..)]` list of `R`'s
/// records, holding their keys of type `K`: the derive calls it, so a field whose type is not
/// `Vec<K>` of the related model's key, or whose source is not that model's, fails to compile.
#[doc(hidden)]
pub fn links_key<M, R, K>(
    path: impl Into<toasty::stmt::Path<M, toasty::stmt::List<R::Model>>>,
) -> String
where
    M: Model,
    R: OptionSource,
    R::Model: Model<PrimaryKey = K>,
    K: FormScalar,
{
    crate::schema::form_key(path.into())
}

/// `includes` and the include loading the many-to-many field `path`, which
/// [`RecordForm::hydrate`] reads.
#[doc(hidden)]
pub fn links_include<M, R>(
    includes: Includes<M>,
    path: impl Into<toasty::stmt::Path<M, toasty::stmt::List<R::Model>>>,
) -> Includes<M>
where
    M: Model,
    R: OptionSource,
{
    includes.with(path.into())
}

/// The keys of the records a many-to-many field holds, as its form key carries them, or `None`
/// when the record was loaded without them.
#[doc(hidden)]
pub fn write_links<T>(records: &toasty::Deferred<Vec<T>>) -> Option<FormValue>
where
    T: Model + toasty::stmt::IntoExpr<T>,
{
    (!records.is_unloaded()).then(|| {
        FormValue::List(
            records
                .get()
                .iter()
                .map(crate::toasty_compat::pk::pk_text)
                .collect(),
        )
    })
}

/// One record-form field and the form keys it binds.
#[derive(Debug, Clone)]
pub struct FormField<K> {
    /// The field, as the form's field enum names it.
    pub field: K,
    /// The Rust field name, for build-time refusals.
    pub name: &'static str,
    /// The keys the field binds: one for a scalar, every key of an embedded
    /// value (an enum's discriminant first). An error on the field renders
    /// under the first.
    pub keys: Vec<String>,
    /// The keys with no blank answer, which an empty submission refuses: the
    /// panel renders their controls required.
    pub required: Vec<String>,
}

/// The typed value a resource's form submission parses into.
///
/// Derive it from a model with [`tablo_core::ModelForm`](crate::ModelForm) or from a struct with
/// [`tablo_core::RecordForm`](crate::RecordForm); a hand-written impl is what the derives expand
/// to.
pub trait RecordForm: Sized + Send + 'static {
    /// The model the form writes.
    type Model: Model + toasty::stmt::IntoExpr<Self::Model> + Send + Sync + 'static;

    /// One variant per form field: the key [`Posted`] uses. Its bound form keys
    /// are [`Self::fields`]'.
    type Field: Copy + Eq + Hash + Debug + Send + Sync + 'static;

    /// Every field, in declaration order, with the keys it binds through `resolver`'s app schema.
    fn fields(resolver: &FieldResolver) -> Vec<FormField<Self::Field>>;

    /// The control the form renders `field` with when its [`form`](crate::ResourceDef::form)
    /// does not place it: what `controls()` hands over for the field, as a one-control schema.
    ///
    /// A resource's form renders every field it does not place after the ones it does, in
    /// declaration order, so a resource that declares no form renders one control per field.
    fn control(field: Self::Field) -> Schema<Self>;

    /// The relations [`hydrate`](Self::hydrate) reads off the record: each many-to-many field's,
    /// which the edit page and the edit's write load the record with.
    fn includes() -> Includes<Self::Model> {
        Includes::new()
    }

    /// The stored record as the form spells it.
    fn hydrate(cx: &Cx, record: &Self::Model) -> FormValues;

    /// The records each many-to-many field holds, as their keys' form spelling: what
    /// [`write_create`](crate::resource::write_create) links a new record to, and what
    /// [`write_update`](crate::resource::write_update) leaves a posted field's record linked to.
    fn links(&self) -> Vec<(Self::Field, Vec<String>)> {
        Vec::new()
    }

    /// Parse a completed submission: the form's only presence and type check.
    ///
    /// # Errors
    ///
    /// Every key that failed, each once, under one of [`Self::fields`]' keys.
    fn parse(cx: &Cx, values: &FormValues) -> std::result::Result<Self, Vec<FieldError>>;

    /// The create builder with every field set.
    fn into_create(self) -> <Self::Model as Model>::Create;

    /// The instance update builder with one assignment per named field, or
    /// `None` when no field is named.
    ///
    /// `None` is what keeps a submission that names no field from building an
    /// empty update, which toasty refuses with an assertion.
    fn into_update<'a>(
        self,
        record: &'a mut Self::Model,
        named: &HashSet<Self::Field>,
    ) -> Option<<Self::Model as Model>::Update<'a>>;

    /// Execute a builder [`Self::into_update`] returned.
    ///
    /// Toasty's instance update builder implements no trait that carries
    /// `exec`, so the generic write reaches it through the form.
    fn exec_update<'a>(
        update: <Self::Model as Model>::Update<'a>,
        ex: &'a mut dyn Executor,
    ) -> impl Future<Output = toasty::Result<()>> + Send + 'a;

    /// Whether the resource naming this form has create and edit pages.
    ///
    /// [`Panel::resource`](crate::Panel::resource) registers the create, edit,
    /// and options routes only when this holds. [`NoForm`] sets it to `false`.
    const HAS_FORM: bool = true;
}

/// The record form of a resource with no create or edit page.
///
/// A list-only resource names it as [`Resource::Form`](crate::Resource::Form):
/// `type Form = NoForm<Self::Model>;`. [`fields`](RecordForm::fields) and
/// [`hydrate`](RecordForm::hydrate) are empty and
/// [`into_update`](RecordForm::into_update) answers `None`. No route parses or
/// writes it, so [`parse`](RecordForm::parse) and
/// [`into_create`](RecordForm::into_create) panic naming the model, and the
/// future [`exec_update`](RecordForm::exec_update) returns panics when polled.
pub struct NoForm<M>(std::marker::PhantomData<fn() -> M>);

impl<M: Model + toasty::stmt::IntoExpr<M> + Send + Sync + 'static> NoForm<M> {
    fn unreachable() -> ! {
        panic!("`NoForm<{}>` has no form", std::any::type_name::<M>())
    }
}

impl<M: Model + toasty::stmt::IntoExpr<M> + Send + Sync + 'static> RecordForm for NoForm<M> {
    type Model = M;
    type Field = std::convert::Infallible;

    const HAS_FORM: bool = false;

    fn fields(_resolver: &FieldResolver) -> Vec<FormField<Self::Field>> {
        Vec::new()
    }

    fn control(field: Self::Field) -> Schema<Self> {
        match field {}
    }

    fn hydrate(_cx: &Cx, _record: &M) -> FormValues {
        FormValues::new()
    }

    fn parse(_cx: &Cx, _values: &FormValues) -> std::result::Result<Self, Vec<FieldError>> {
        Self::unreachable()
    }

    fn into_create(self) -> M::Create {
        Self::unreachable()
    }

    fn into_update<'a>(
        self,
        _record: &'a mut M,
        _named: &HashSet<Self::Field>,
    ) -> Option<M::Update<'a>> {
        None
    }

    fn exec_update<'a>(
        update: M::Update<'a>,
        ex: &'a mut dyn Executor,
    ) -> impl Future<Output = toasty::Result<()>> + Send + 'a {
        // `into_update` answers `None`, so no builder reaches here. The
        // builder is not known to be `Send`, so the future must not hold it.
        drop((update, ex));
        async { Self::unreachable() }
    }
}

/// An edit submission: the parsed form, and the fields the submission named.
///
/// Derefs to the form, so a record fn reads `posted.author_id` — the posted
/// value, or the stored one when the submission did not name the field.
pub struct Posted<F: RecordForm> {
    form: F,
    named: HashSet<F::Field>,
}

impl<F: RecordForm> Posted<F> {
    /// A posted form that names `named`.
    pub fn new(form: F, named: impl IntoIterator<Item = F::Field>) -> Self {
        Self {
            form,
            named: named.into_iter().collect(),
        }
    }

    /// Whether the submission named `field`.
    pub fn named(&self, field: F::Field) -> bool {
        self.named.contains(&field)
    }

    /// The update builder assigning every named field, or `None` when the
    /// submission named none. See [`RecordForm::into_update`].
    pub fn into_update(self, record: &mut F::Model) -> Option<<F::Model as Model>::Update<'_>> {
        self.form.into_update(record, &self.named)
    }
}

impl<F: RecordForm> std::ops::Deref for Posted<F> {
    type Target = F;

    fn deref(&self) -> &F {
        &self.form
    }
}

/// A refused submission.
///
/// [`Resource::validate_record`](crate::Resource::validate_record) keys it by the record form's
/// field enum (`FieldErrors<UserFormField>`), so an error always names a field the form renders;
/// one on an embedded value renders under its first control. The panel keys every error by the
/// form key it renders under (`FieldErrors`, keyed by `String`), and [`Source::form`] reads them
/// back when a schema renders.
///
/// [`Source::form`]: crate::Source::form
#[derive(Debug)]
pub struct FieldErrors<K = String> {
    errors: Vec<FieldError<K>>,
}

impl<K> Default for FieldErrors<K> {
    fn default() -> Self {
        Self { errors: Vec::new() }
    }
}

impl<K> FieldErrors<K> {
    /// No errors.
    pub fn new() -> Self {
        Self::default()
    }

    /// Refuse `key` with `message`.
    pub fn add(&mut self, key: impl Into<K>, message: impl Into<String>) {
        self.errors.push(FieldError::invalid(key, message));
    }

    /// Refuse `error`'s key with `error`.
    pub fn push(&mut self, error: FieldError<K>) {
        self.errors.push(error);
    }

    /// Whether nothing was refused.
    pub fn is_empty(&self) -> bool {
        self.errors.is_empty()
    }

    /// Every error, in the order it was added.
    pub fn iter(&self) -> impl Iterator<Item = &FieldError<K>> {
        self.errors.iter()
    }

    /// Append `other`'s errors after these.
    pub fn extend(&mut self, other: Self) {
        self.errors.extend(other.errors);
    }
}

impl<K> IntoIterator for FieldErrors<K> {
    type Item = FieldError<K>;
    type IntoIter = std::vec::IntoIter<FieldError<K>>;

    fn into_iter(self) -> Self::IntoIter {
        self.errors.into_iter()
    }
}

impl FieldErrors {
    /// Whether any error renders under `key`.
    pub fn contains_key(&self, key: &str) -> bool {
        self.errors.iter().any(|error| error.key == key)
    }

    /// The error `key` renders: the first one added.
    pub fn first(&self, key: &str) -> Option<&FieldError> {
        self.errors.iter().find(|error| error.key == key)
    }

    /// Take `other`'s errors, dropping this collection's own errors under every
    /// key `other` names.
    ///
    /// A source that owns a key answers for it: a rejected upload replaces the
    /// error the emptied control would otherwise report.
    pub(crate) fn replace(&mut self, other: Self) {
        let owned: HashSet<&str> = other
            .errors
            .iter()
            .map(|error| error.key.as_str())
            .collect();
        self.errors
            .retain(|kept| !owned.contains(kept.key.as_str()));
        self.errors.extend(other.errors);
    }
}

#[cfg(test)]
mod tests;