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
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
//! The choice control: a `<select>` over static options or a relationship's
//! rows, with an optional filter input, or a checkbox per option when the choice takes several.

use tablo_ui::{input as ui_input, select as ui_select};
use toasty::stmt::Expr;
use topcoat::{Result, context::Cx, view::*};

use super::{
    super::relationship::{
        MAX_RELATIONSHIP_OPTIONS, OptionLoadError, OptionSource, RelatedCheck,
        RelationshipCheckFuture, RelationshipChecker, RelationshipLoadFuture, RelationshipLoader,
        RelationshipSearchLoader, related_record_check, related_records, related_records_search,
    },
    Field, FieldChrome, Placement, render_field,
};
use crate::form::decode_list;

mod multiple;

/// What a choice field declares beyond presence.
#[derive(Clone, Default)]
pub(crate) struct ChoiceControl {
    pub(super) searchable: bool,
    /// Whether this is an embedded enum's variant control.
    pub(super) discriminant: bool,
    /// Static `(value, label)` options.
    pub(super) options: Vec<(String, String)>,
    pub(super) relationship: Option<Relationship>,
    /// The field whose value narrows the relationship's rows, set by `depends_on`.
    pub(super) parent: Option<Parent>,
    /// Whether the choice takes several options, set by `multiple`: its key then holds a list.
    pub(super) multiple: bool,
}

/// What narrows a dependent choice's options: the related rows whose column equals the value the
/// field `watched` posts.
#[derive(Clone)]
pub(crate) struct Parent {
    pub(super) watched: String,
    /// The model the column belongs to, which must be the relationship's source model.
    pub(super) model: std::any::TypeId,
    /// The predicate selecting the rows for a trimmed, non-empty parent value, or `None` when the
    /// column's type does not parse it.
    pub(super) scope: ParentScope,
}

/// A dependent choice's predicate for one parent value.
pub(crate) type ParentScope = std::sync::Arc<dyn Fn(&str) -> Option<Expr<bool>> + Send + Sync>;

/// The rows a dependent choice offers for one parent value.
enum Scope {
    /// Not a dependent choice: every row.
    All,
    /// The rows the predicate selects.
    Within(Expr<bool>),
    /// A blank parent, or one the column does not parse: no row.
    Nothing,
}

/// A relationship's three loaders: the bounded option load, the server-side
/// search, and the targeted existence check past the cap.
#[derive(Clone)]
pub(crate) struct Relationship {
    load: RelationshipLoader,
    search: RelationshipSearchLoader,
    check: RelationshipChecker,
    /// The source's type, named in declaration errors.
    source: &'static str,
    /// The source's model, which a dependent choice's column must belong to.
    model: std::any::TypeId,
    /// The source's model in the app schema, which a many-to-many field's target must be.
    model_id: crate::toasty_compat::model::ModelId,
    /// Whether the request's panel can load from the source.
    available: fn(&Cx) -> bool,
    /// The source model when its rows are tenant-owned, so a key the write
    /// re-checks cannot name another tenant's row.
    tenant_scoped_model: fn(&Cx) -> Option<crate::toasty_compat::model::ModelId>,
    /// Whether the source's primary key is composite, which no option value can spell.
    composite: bool,
}

/// One `<option>` with its value and label.
pub(crate) fn option_view<'a>(
    cx: &'a Cx,
    value: String,
    label: String,
    selected: bool,
) -> BoxView<'a> {
    view! { cx => <option value=(value) selected=(selected)>(label)</option> }.boxed()
}

impl Relationship {
    /// The loaders for source `R`, projecting each row to its primary key and `label`.
    pub(super) fn new<R>(label: impl Fn(&Cx, &R::Model) -> String + Send + Sync + 'static) -> Self
    where
        R: OptionSource + 'static,
    {
        let project = std::sync::Arc::new(move |cx: &Cx, record: &R::Model| {
            (crate::toasty_compat::pk::pk_text(record), label(cx, record))
        });
        let search_project = project.clone();
        let load = std::sync::Arc::new(move |cx: &Cx| {
            let project = project.clone();
            let cx = cx.clone();
            Box::pin(async move {
                let records = related_records::<R>(&cx, crate::tenancy::tenant_id(&cx))
                    .await
                    .map_err(|error| error.clone())?;
                Ok(records.iter().map(|record| project(&cx, record)).collect())
            }) as RelationshipLoadFuture
        }) as RelationshipLoader;
        let search = std::sync::Arc::new(move |cx: &Cx, q: String, scope: Option<Expr<bool>>| {
            let project = search_project.clone();
            let cx = cx.clone();
            Box::pin(async move {
                let records = related_records_search::<R>(&cx, q, scope)
                    .await
                    .map_err(|error| error.clone())?;
                Ok(records.iter().map(|record| project(&cx, record)).collect())
            }) as RelationshipLoadFuture
        }) as RelationshipSearchLoader;
        let check = std::sync::Arc::new(check_record::<R>) as RelationshipChecker;
        Self {
            load,
            search,
            check,
            source: std::any::type_name::<R>(),
            model: std::any::TypeId::of::<R::Model>(),
            model_id: <R::Model as toasty::schema::Model>::id(),
            available: R::available,
            tenant_scoped_model: |cx| {
                R::requires_tenant(cx).then(<R::Model as toasty::schema::Model>::id)
            },
            composite: crate::toasty_compat::pk::pk_is_composite::<R::Model>(),
        }
    }
}

fn check_record<'a, R>(
    cx: &'a Cx,
    value: String,
    scope: Option<Expr<bool>>,
    ex: &'a mut dyn toasty::Executor,
) -> RelationshipCheckFuture<'a>
where
    R: OptionSource,
{
    Box::pin(related_record_check::<R>(cx, value, scope, ex))
}

impl ChoiceControl {
    pub(crate) fn is_searchable(&self) -> bool {
        self.searchable
    }

    /// The label of the static option storing `value`.
    pub(crate) fn label_of(&self, value: &str) -> Option<&str> {
        self.options
            .iter()
            .find(|(stored, _)| stored == value)
            .map(|(_, label)| label.as_str())
    }

    /// Whether the choice declares neither options nor a relationship: its `<select>` offers
    /// nothing, and validation, with no option to check against, would accept any value.
    pub(crate) fn offers_nothing(&self) -> bool {
        self.options.is_empty() && self.relationship.is_none()
    }

    pub(crate) fn is_relationship(&self) -> bool {
        self.relationship.is_some()
    }

    /// Whether the choice takes several options.
    pub(crate) fn is_multiple(&self) -> bool {
        self.multiple
    }

    /// The relationship's source model in the app schema.
    pub(crate) fn source_model(&self) -> Option<crate::toasty_compat::model::ModelId> {
        self.relationship
            .as_ref()
            .map(|relationship| relationship.model_id)
    }

    /// The key of the field whose value narrows a dependent choice's options.
    pub(crate) fn parent_key(&self) -> Option<&str> {
        self.parent.as_ref().map(|parent| parent.watched.as_str())
    }

    /// Whether `depends_on` names a column of another model than the relationship's source, or
    /// the choice has no relationship to narrow.
    pub(crate) fn misdeclared_parent(&self) -> bool {
        self.parent.as_ref().is_some_and(|parent| {
            self.relationship
                .as_ref()
                .is_none_or(|relationship| relationship.model != parent.model)
        })
    }

    /// The rows the choice offers while its parent posts `parent`.
    fn scope(&self, parent: Option<&str>) -> Scope {
        let Some(declared) = &self.parent else {
            return Scope::All;
        };
        let value = parent.unwrap_or("").trim();
        if value.is_empty() {
            return Scope::Nothing;
        }
        match (declared.scope)(value) {
            Some(expr) => Scope::Within(expr),
            None => Scope::Nothing,
        }
    }

    /// Whether the options come from a model with a composite primary key.
    pub(crate) fn has_composite_source(&self) -> bool {
        self.relationship
            .as_ref()
            .is_some_and(|relationship| relationship.composite)
    }

    /// The model the options come from, when its rows are tenant-owned.
    pub(crate) fn tenant_scoped_model(
        &self,
        cx: &Cx,
    ) -> Option<crate::toasty_compat::model::ModelId> {
        self.relationship
            .as_ref()
            .and_then(|relationship| (relationship.tenant_scoped_model)(cx))
    }

    /// The option source's type when the request's panel cannot load from it.
    pub(crate) fn unavailable_source(&self, cx: &Cx) -> Option<&'static str> {
        self.relationship
            .as_ref()
            .filter(|relationship| !(relationship.available)(cx))
            .map(|relationship| relationship.source)
    }

    /// Searches options server-side among those the parent value `parent` offers, answering
    /// `Overflow` past the option cap.
    pub(crate) async fn search_options(
        &self,
        cx: &Cx,
        q: &str,
        parent: Option<&str>,
    ) -> Result<Vec<(String, String)>, OptionLoadError> {
        let Some(relationship) = &self.relationship else {
            return Ok(self.options.clone());
        };
        match self.scope(parent) {
            Scope::All => (relationship.search)(cx, q.to_string(), None).await,
            Scope::Within(scope) => (relationship.search)(cx, q.to_string(), Some(scope)).await,
            Scope::Nothing => Ok(Vec::new()),
        }
    }

    /// The options the choice offers while its parent posts `parent`: a dependent choice's bounded
    /// head of the rows its parent selects.
    async fn load_options(
        &self,
        cx: &Cx,
        parent: Option<&str>,
    ) -> Result<Vec<(String, String)>, OptionLoadError> {
        match (&self.relationship, self.scope(parent)) {
            (Some(relationship), Scope::All) => (relationship.load)(cx).await,
            (Some(relationship), Scope::Within(scope)) => {
                (relationship.search)(cx, String::new(), Some(scope)).await
            }
            (Some(_), Scope::Nothing) => Ok(Vec::new()),
            (None, _) => Ok(self.options.clone()),
        }
    }

    /// Checks whether a non-empty `value` matches an option the parent value `parent` offers, or
    /// for a multiple choice, whether each value its list holds does, but the ones the stored list
    /// `stored` holds already: keeping a link changes nothing, so it holds past the option cap.
    pub(super) async fn validate_exists(
        &self,
        cx: &Cx,
        label: &str,
        value: &str,
        parent: Option<&str>,
        stored: Option<&str>,
    ) -> Vec<String> {
        if !self.multiple {
            return self.validate_one(cx, label, value, parent).await;
        }
        let keys = match chosen(label, value) {
            Ok(keys) => keys,
            Err(message) => return vec![message],
        };
        let held = stored.and_then(decode_list).unwrap_or_default();
        for key in keys.into_iter().filter(|key| !held.contains(key)) {
            let errors = self.validate_one(cx, label, &key, parent).await;
            if !errors.is_empty() {
                return errors;
            }
        }
        Vec::new()
    }

    /// Checks whether a non-empty `value` matches an option the parent value `parent` offers.
    async fn validate_one(
        &self,
        cx: &Cx,
        label: &str,
        value: &str,
        parent: Option<&str>,
    ) -> Vec<String> {
        let trimmed = value.trim();
        if trimmed.is_empty() {
            return Vec::new();
        }
        let Some(relationship) = &self.relationship else {
            if !self.options.is_empty() && !self.options.iter().any(|(v, _)| v == trimmed) {
                return vec![format!("{label} is invalid")];
            }
            return Vec::new();
        };
        let scope = match self.scope(parent) {
            Scope::All => None,
            Scope::Within(scope) => Some(scope),
            Scope::Nothing => return vec![format!("{label} is invalid")],
        };
        let failure = match self.load_options(cx, parent).await {
            Ok(opts) if opts.iter().any(|(v, _)| v == trimmed) => return Vec::new(),
            Ok(_) => "is invalid",
            Err(OptionLoadError::Denied) => "is not available",
            Err(OptionLoadError::Overflow) if self.searchable => {
                let mut db = crate::db::db(cx);
                match (relationship.check)(cx, trimmed.to_string(), scope, &mut db).await {
                    Ok(RelatedCheck::FoundViewable) => return Vec::new(),
                    Ok(RelatedCheck::FoundHidden | RelatedCheck::NotFound) => "is invalid",
                    Err(error) => load_failure(&error),
                }
            }
            Err(error) => load_failure(&error),
        };
        vec![format!("{label} {failure}")]
    }

    /// Re-checks a submitted relationship key in the write's transaction, among the rows the
    /// parent value `parent` selects, or for a multiple choice, each key its list holds but the
    /// stored list `stored` does not.
    pub(super) async fn recheck(
        &self,
        cx: &Cx,
        label: &str,
        value: &str,
        parent: Option<&str>,
        stored: Option<&str>,
        ex: &mut dyn toasty::Executor,
    ) -> Vec<String> {
        if !self.multiple {
            return self.recheck_one(cx, label, value, parent, ex).await;
        }
        let keys = match chosen(label, value) {
            Ok(keys) => keys,
            Err(message) => return vec![message],
        };
        let held = stored.and_then(decode_list).unwrap_or_default();
        for key in keys.into_iter().filter(|key| !held.contains(key)) {
            let errors = self.recheck_one(cx, label, &key, parent, &mut *ex).await;
            if !errors.is_empty() {
                return errors;
            }
        }
        Vec::new()
    }

    /// Re-checks one submitted relationship key in the write's transaction, among the rows the
    /// parent value `parent` selects.
    async fn recheck_one(
        &self,
        cx: &Cx,
        label: &str,
        value: &str,
        parent: Option<&str>,
        ex: &mut dyn toasty::Executor,
    ) -> Vec<String> {
        let trimmed = value.trim();
        let Some(relationship) = &self.relationship else {
            return Vec::new();
        };
        if trimmed.is_empty() {
            return Vec::new();
        }
        let scope = match self.scope(parent) {
            Scope::All => None,
            Scope::Within(scope) => Some(scope),
            Scope::Nothing => return vec![format!("{label} is invalid")],
        };
        let failure = match (relationship.check)(cx, trimmed.to_string(), scope, ex).await {
            Ok(RelatedCheck::FoundViewable) => return Vec::new(),
            Ok(RelatedCheck::FoundHidden | RelatedCheck::NotFound) => "is invalid",
            Err(error) => load_failure(&error),
        };
        vec![format!("{label} {failure}")]
    }

    /// `value`, a multiple choice's list, with each key of the stored list `stored` it drops that
    /// the user cannot view in the request's tenant put back: a submission unlinks only the
    /// records its form could offer.
    pub(super) async fn keep_unseen(
        &self,
        cx: &Cx,
        value: &str,
        stored: &str,
        ex: &mut dyn toasty::Executor,
    ) -> Option<String> {
        let relationship = self.relationship.as_ref().filter(|_| self.multiple)?;
        let mut keys = decode_list(value)?;
        let dropped: Vec<String> = decode_list(stored)?
            .into_iter()
            .filter(|key| !keys.contains(key))
            .collect();
        let before = keys.len();
        for key in dropped {
            // A failed check keeps the link: only a record the user may view is unlinked.
            let seen = matches!(
                (relationship.check)(cx, key.clone(), None, &mut *ex).await,
                Ok(RelatedCheck::FoundViewable)
            );
            if !seen {
                keys.push(key);
            }
        }
        (keys.len() != before).then(|| crate::form::encode_list(&keys))
    }
}

/// The keys a multiple choice's `value` holds, or the error refusing it: a value that is no list,
/// or one choosing more options than a choice loads.
fn chosen(label: &str, value: &str) -> std::result::Result<Vec<String>, String> {
    let keys = decode_list(value).ok_or_else(|| format!("{label} is invalid"))?;
    if keys.len() > MAX_RELATIONSHIP_OPTIONS {
        return Err(format!(
            "{label} takes at most {MAX_RELATIONSHIP_OPTIONS} choices"
        ));
    }
    Ok(keys)
}

/// The wording of a failed option load.
fn load_failure(error: &OptionLoadError) -> &'static str {
    match error {
        OptionLoadError::Denied => "is not available",
        OptionLoadError::LoadFailed | OptionLoadError::Overflow => "could not load options, retry",
        OptionLoadError::Misdeclared => "could not load options",
    }
}

impl Field {
    /// Renders a choice field's select with the DOM id `id`, offering what its parent's value
    /// selects.
    pub(super) async fn render_choice<'a>(
        &self,
        choice: &ChoiceControl,
        cx: &'a Cx,
        value: Option<&str>,
        error: Option<&str>,
        id: String,
        placement: Placement<'_>,
    ) -> Result<BoxView<'a>> {
        if choice.multiple {
            return self.render_choices(choice, cx, value, error, id).await;
        }
        let parent = placement.parent;
        let name = self.name().to_string();
        let required = self.required;
        let searchable = choice.searchable;
        let current = value.unwrap_or("").trim().to_string();
        let loaded = choice.load_options(cx, parent).await;
        // A denial hides the stored label and fails closed.
        // A failed load keeps the stored key selectable.
        let denied = matches!(&loaded, Err(OptionLoadError::Denied));
        let overflowed = matches!(&loaded, Err(OptionLoadError::Overflow));
        let overflow_searchable = overflowed && searchable && choice.is_relationship();
        let keep_current_value = matches!(
            &loaded,
            Err(OptionLoadError::LoadFailed)
                | Err(OptionLoadError::Overflow)
                | Err(OptionLoadError::Misdeclared)
        );
        let mut options = loaded.unwrap_or_default();
        if keep_current_value && !current.is_empty() && !options.iter().any(|(v, _)| v == &current)
        {
            options.push((current.clone(), current.clone()));
        }
        let chrome = FieldChrome::new(
            id.clone(),
            error,
            denied.then(|| format!("{} is not available", self.label_str())),
        );
        let mut option_views: Vec<BoxView<'a>> = vec![option_view(
            cx,
            String::new(),
            "-- Select --".to_string(),
            current.is_empty(),
        )];
        for (val, lab) in &options {
            option_views.push(option_view(cx, val.clone(), lab.clone(), current == *val));
        }
        let list_id = format!("{id}-options-list");
        let filter_label = format!("Filter {} options", self.label_str());
        // A dependent choice fetches its options again when its parent changes, and a searchable
        // one fetches as the user types past the cap.
        let dependent = choice.parent_key().map(str::to_string);
        let parent_value = dependent
            .as_ref()
            .map(|_| parent.unwrap_or("").trim().to_string());
        let options_field = (overflow_searchable || dependent.is_some()).then(|| name.clone());
        let options_server = overflow_searchable.then_some("true");
        let options_url = options_field
            .as_ref()
            .and(placement.options)
            .map(str::to_string);
        let overflow_hint = "Too many options — type to search".to_string();
        // A searchable dependent choice may overflow after its parent changes, so it always
        // renders the hint, hidden until then.
        let hint = overflow_searchable || (searchable && choice.parent_key().is_some());
        let hint_hidden = !overflow_searchable;
        let aria_invalid = chrome.aria_invalid();
        let described_by = chrome.described_by();
        let control = view! {
            cx =>
            if searchable {
                <div class="relative" data-options-combobox="">
                    ui_input(
                        attrs: attributes! {
                            type="search"
                            role="combobox"
                            aria-expanded="false"
                            aria-controls=(list_id.clone())
                            aria-autocomplete="list"
                            aria-label=(filter_label.clone())
                            placeholder="Filter…"
                            data-options-filter=""
                            class="h-9"
                            autocomplete="off"
                        }
                    )
                    <ul
                        id=(list_id.clone())
                        data-options-list=""
                        role="listbox"
                        aria-label=(filter_label.clone())
                        hidden=""
                        class="absolute z-20 mt-1 max-h-60 w-full overflow-y-auto rounded-lg border border-border bg-popover p-1 text-sm text-popover-foreground shadow-sm"
                    ></ul>
                </div>
            }
            if hint {
                <div
                    class="text-xs text-muted-foreground"
                    data-options-hint=""
                    hidden=(hint_hidden)
                >
                    (overflow_hint)
                </div>
            }
            ui_select(
                attrs: attributes! {
                    id=(id)
                    name=(name.clone())
                    required=(required)
                    aria-required=(required.then_some("true"))
                    aria-invalid=(aria_invalid)
                    aria-describedby=(described_by)
                },
                for opt in option_views {
                    (opt)
                }
            )
        }
        .boxed();
        render_field(
            cx,
            &chrome,
            self.label_str(),
            required,
            attributes! {
                cx =>
                data-select-filterable=""
                data-options-field=(options_field)
                data-options-url=(options_url)
                data-options-server=(options_server)
                data-options-parent=(dependent)
                data-options-parent-value=(parent_value)
            },
            control,
        )
    }
}

#[cfg(test)]
mod tests;