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

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::OptionLoadError, Field, Placement, Posting, render_field};
use crate::values::FormValue;

mod check;
mod create;
mod listed;
mod relationship;

pub(crate) use listed::Layout;
pub(crate) use relationship::Relationship;

/// 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, crate::Text)>,
    pub(super) relationship: Option<Relationship>,
    /// The field whose value narrows the relationship's rows, set by `depends_on`.
    pub(super) parent: Option<Parent>,
    /// The predicate narrowing the relationship's rows whatever the form posts, set by
    /// `options_where`.
    pub(super) filter: Option<OptionFilter>,
    /// Whether the choice takes several options, set by `multiple`: its key then holds a list.
    pub(super) multiple: bool,
    /// How many options a multiple choice takes, set by `min_items` and `max_items`.
    pub(super) bounds: super::Items,
    /// How the options render, set by `radio` and `buttons`.
    pub(super) layout: Layout,
    /// Whether the choice offers to create a related record, set by `creatable`.
    pub(super) creatable: bool,
    /// Whether the choice takes values its options do not offer, set by `tags`: its options are
    /// suggestions, and a text input adds any value.
    pub(super) tags: 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 name of the field the column is, when it names one.
    pub(super) column: Option<String>,
    /// 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 predicate an `options_where` choice narrows its rows by, built for each request.
pub(crate) type OptionFilter = std::sync::Arc<dyn Fn(&Cx) -> Expr<bool> + Send + Sync>;

/// The rows a choice offers for one parent value.
enum Scope {
    /// Neither a dependent nor a filtered 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,
}

/// 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! { <option value=(value) selected=(selected)>(label)</option> }.boxed()
}

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<&crate::Text> {
        self.options
            .iter()
            .find(|(stored, _)| stored == value)
            .map(|(_, label)| label)
    }

    /// The static options, each a value and its label.
    pub(crate) fn static_options(&self) -> &[(String, crate::Text)] {
        &self.options
    }

    /// The static options with their labels in the request's locale.
    fn spelled(&self, cx: &Cx) -> Vec<(String, String)> {
        self.options
            .iter()
            .map(|(value, label)| (value.clone(), label.localize(cx)))
            .collect()
    }

    /// Whether the choice offers to create a related record.
    pub(crate) fn is_creatable(&self) -> bool {
        self.creatable
    }

    /// Whether `creatable` asks for what the choice cannot offer: it must be a single, independent
    /// select over a resource's records.
    pub(crate) fn uncreatable(&self) -> bool {
        self.creatable
            && (self.multiple
                || self.layout != Layout::Select
                || self.parent.is_some()
                || self.filter.is_some()
                || !self
                    .relationship
                    .as_ref()
                    .is_some_and(|relationship| relationship.creates))
    }

    /// The related resource's create page, when the choice is creatable and the user
    /// may create there.
    fn create_page(&self, cx: &Cx) -> Option<String> {
        let relationship = self.relationship.as_ref().filter(|_| self.creatable)?;
        (relationship.create_page)(cx)
    }

    /// 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() && !self.tags
    }

    /// Whether the choice takes values its options do not offer.
    pub(crate) fn is_tags(&self) -> bool {
        self.tags
    }

    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
    }

    /// Whether the choice renders an input per option rather than a `<select>`: the browser
    /// cannot fetch its options again, so it cannot depend on another field.
    pub(crate) fn is_listed(&self) -> bool {
        self.multiple || self.layout != Layout::Select
    }

    /// 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 source model's name when the choice's options show records under a label a panel
    /// cannot mask: see [`Relationship::unmasked_model`](super::choice::Relationship).
    pub(crate) fn unmasked_model(
        &self,
        is_mounted: impl Fn(std::any::TypeId) -> bool,
        restricted: impl Fn(crate::toasty_compat::model::ModelId) -> bool,
    ) -> Option<&'static str> {
        self.relationship
            .as_ref()?
            .unmasked_model(is_mounted, restricted)
    }

    /// The field a dependent choice narrows its options by, when `restricts` says a mounted
    /// resource restricts it of the source model: the options would then show which records hold
    /// each value of it.
    pub(crate) fn narrowed_by(
        &self,
        restricts: impl Fn(crate::toasty_compat::model::ModelId, &str) -> bool,
    ) -> Option<&str> {
        let column = self.parent.as_ref()?.column.as_deref()?;
        let model = self.relationship.as_ref()?.model_id;
        restricts(model, column).then_some(column)
    }

    /// 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)
        })
    }

    /// Whether `options_where` narrows a choice that has no relationship to narrow.
    pub(crate) fn misdeclared_filter(&self) -> bool {
        self.filter.is_some() && self.relationship.is_none()
    }

    /// The rows the choice offers while its parent posts `parent`: those its filter selects, among
    /// those of the parent value.
    fn scope(&self, cx: &Cx, parent: Option<&str>) -> Scope {
        let filter = self.filter.as_ref().map(|filter| filter(cx));
        let Some(declared) = &self.parent else {
            return filter.map_or(Scope::All, Scope::Within);
        };
        let value = parent.unwrap_or("").trim();
        if value.is_empty() {
            return Scope::Nothing;
        }
        match ((declared.scope)(value), filter) {
            (Some(expr), Some(filter)) => Scope::Within(expr.and(filter)),
            (Some(expr), None) => 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()
            .and_then(|relationship| relationship.unavailable_source(cx))
    }

    /// 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.spelled(cx));
        };
        match self.scope(cx, 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(cx, 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.spelled(cx)),
        }
    }

    /// `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, or that the choice's filter drops, put back: a
    /// submission unlinks only the records its form could offer.
    pub(super) async fn keep_unseen(
        &self,
        cx: &Cx,
        value: &FormValue,
        stored: &FormValue,
        ex: &mut dyn toasty::Executor,
    ) -> Option<FormValue> {
        let relationship = self.relationship.as_ref().filter(|_| self.multiple)?;
        let mut keys = value.as_list()?.to_vec();
        let dropped: Vec<String> = stored
            .as_list()?
            .iter()
            .filter(|key| !keys.contains(key))
            .cloned()
            .collect();
        let before = keys.len();
        for key in dropped {
            // A failed check keeps the link: only a record the choice could offer is unlinked.
            let filter = self.filter.as_ref().map(|filter| filter(cx));
            let seen = matches!(
                (relationship.check)(cx, key.clone(), filter, &mut *ex).await,
                Ok(true)
            );
            if !seen {
                keys.push(key);
            }
        }
        (keys.len() != before).then_some(FormValue::List(keys))
    }
}

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<&FormValue>,
        error: Option<&crate::values::FieldError>,
        id: String,
        placement: Placement<'_>,
    ) -> Result<BoxView<'a>> {
        let disabled = self.is_disabled_at(&placement);
        let name = placement.name(self.name());
        let posting = || Posting {
            id: id.clone(),
            name: name.clone(),
            disabled,
        };
        if choice.multiple {
            let chosen = value.and_then(FormValue::as_list).unwrap_or_default();
            return self
                .render_choices(choice, cx, chosen, error, posting())
                .await;
        }
        if choice.is_listed() {
            let chosen: Vec<String> = value
                .and_then(FormValue::as_text)
                .map(str::trim)
                .filter(|chosen| !chosen.is_empty())
                .map(str::to_string)
                .into_iter()
                .collect();
            return self
                .render_choices(choice, cx, &chosen, error, posting())
                .await;
        }
        let value = value.and_then(FormValue::as_text);
        let parent = placement.parent;
        let required = self.required && !disabled;
        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 = self.chrome(
            cx,
            id.clone(),
            error,
            denied.then(|| {
                crate::t!(
                    cx,
                    "tablo-field-unavailable",
                    label = self.label().to_owned()
                )
            }),
        );
        let mut option_views: Vec<BoxView<'a>> = vec![option_view(
            cx,
            String::new(),
            crate::t!(cx, "tablo-field-select"),
            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 = crate::t!(
            cx,
            "tablo-field-filter-options",
            label = self.label().to_owned()
        );
        // 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 = crate::t!(cx, "tablo-field-too-many-options");
        // 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 select_id = id.clone();
        let control = view! {
            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=(crate::t!(cx, "tablo-field-filter"))
                            data-options-filter=""
                            class="h-9"
                            autocomplete="off"
                            disabled=(disabled)
                        }
                    )
                    <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)
                    disabled=(disabled)
                    aria-required=(required.then_some("true"))
                    aria-invalid=(aria_invalid)
                    aria-describedby=(described_by)
                },
                for opt in option_views {
                    (opt)
                }
            )
        }
        .boxed();
        // A disabled choice posts nothing, so a record created for it could not become its value.
        let control = match choice.create_page(cx).filter(|_| !disabled) {
            Some(url) => {
                create::with_create_link(cx, control, &select_id, self.label().to_owned(), url)
            }
            None => control,
        };
        render_field(
            cx,
            &chrome,
            &self.label(),
            required,
            attributes! {
                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)
                data-options-empty-text=(crate::t!(cx, "tablo-field-no-options"))
                data-options-unmatched-text=(crate::t!(
                    cx,
                    "tablo-field-no-matching-options",
                ))
                data-options-searching-text=(crate::t!(cx, "tablo-field-searching"))
            },
            control,
        )
    }
}

#[cfg(test)]
mod tests;