tablo-core 0.9.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
//! [`TextColumn`]: one field rendered as text, searchable on a string field, and the escaped
//! `LIKE` pattern its search builds.

use std::sync::Arc;

use derive_where::derive_where;
use toasty::stmt::{Expr, OrderByExpr};
use topcoat::{context::Cx, icon::IconData, view::*};

use super::{
    Column, ColumnBase, ColumnWidth, ReadFn,
    cell::{TextCell, text_cell},
    sort_order,
};
use crate::{
    Lens, Text,
    display::{Alignment, Color, Currency, FontWeight, Numeric},
    values::FormScalar,
};

/// A column of one field, rendered as text and bound through a [`Lens`] for sorting and search.
///
/// ```rust
/// # #[derive(Debug, Clone, toasty::Model, tablo_core::ModelColumns)]
/// # struct User {
/// #     #[key] #[auto] id: uuid::Uuid,
/// #     name: String,
/// #     email: String,
/// #     age: i64,
/// # }
/// tablo_core::TextColumn::new(tablo_core::lens!(User.name))
///     .searchable()
///     .sortable();
/// tablo_core::TextColumn::new(tablo_core::lens!(User.age))
///     .sortable()
///     .format(|age| format!("{age} years"));
/// ```
///
/// The cell is the value's [`FormScalar::to_label`], an [`Options`](crate::Options) enum's label
/// or any other type's form spelling, unless [`format`](Self::format) says otherwise. Only a
/// string field is [`searchable`](Self::searchable).
///
/// [`sortable`](Self::sortable) orders by the stored column, so a type a driver stores as text
/// sorts by its spelling: a decimal column on SQLite, MySQL or Turso lists `10.00`, `100`, `9.50`.
/// The [`ModelColumns`](derive@crate::ModelColumns) derive leaves a type that is not
/// [`SORTABLE`](crate::extend::TypedValue::SORTABLE) unsortable.
///
/// A column presents its value as a [`badge`](Self::badge), in a [`color`](Self::color), with a
/// muted [`description`](Self::description) line under it, or as a right-aligned
/// [`numeric`](Self::numeric) or [`money`](Self::money) amount:
///
/// ```rust
/// # #[derive(Debug, Clone, toasty::Model, tablo_core::ModelColumns)]
/// # struct Order {
/// #     #[key] #[auto] id: uuid::Uuid,
/// #     number: String,
/// #     customer: String,
/// #     status: Status,
/// #     total_cents: i64,
/// # }
/// # #[derive(Debug, Clone, Copy, PartialEq, Eq, toasty::Embed, tablo_core::Options)]
/// # enum Status { #[option(color = "warning")] Pending, #[option(color = "success")] Paid }
/// use tablo_core::{Currency, TextColumn, lens};
///
/// TextColumn::new(lens!(Order.number)).description(|order: &Order| order.customer.clone());
/// TextColumn::new(lens!(Order.status)).badge();
/// TextColumn::new(lens!(Order.total_cents)).money(Currency::USD.minor_units());
/// ```
///
/// A cell also links to a [`url`](Self::url), shows a [`tooltip`](Self::tooltip), cuts a long
/// value to a [`limit`](Self::limit), offers a [`copyable`](Self::copyable) button, shows an
/// [`icon`](Self::icon) before the value, and a [`placeholder`](Self::placeholder) for an empty
/// one:
///
/// ```rust
/// # #[derive(Debug, Clone, toasty::Model, tablo_core::ModelColumns)]
/// # struct User { #[key] #[auto] id: uuid::Uuid, email: String, bio: String, phone: String }
/// use tablo_core::{Reads, TextColumn, lens};
///
/// TextColumn::new(lens!(User.email))
///     .url(|user: &User| Some(format!("mailto:{}", user.email)))
///     .reading(Reads::nothing())
///     .copyable();
/// TextColumn::new(lens!(User.bio)).limit(40);
/// TextColumn::new(lens!(User.phone)).placeholder("No phone");
/// ```
///
/// A closure over the row, a [`description`](Self::description), a [`url`](Self::url), a
/// [`tooltip`](Self::tooltip) or a [`money_by`](Self::money_by), may read any field, so a
/// resource that [restricts a field](crate::ResourceDef::field_access) refuses the column until
/// [`reading`](Self::reading) declares the ones they read.
#[derive_where(Clone, Debug)]
pub struct TextColumn<M, T> {
    lens: Lens<M, T>,
    base: ColumnBase,
    #[derive_where(skip(Debug))]
    format: FormatFn<M, T>,
    /// The `LIKE` predicate for a search pattern, when [`searchable`](Self::searchable).
    #[derive_where(skip(Debug))]
    search: Option<SearchFn>,
    sortable: bool,
    /// The value's color: its own, an `Options` enum's, unless [`color`](Self::color) says
    /// otherwise.
    #[derive_where(skip(Debug))]
    color: ColorFn<T>,
    /// Whether the color tints the text, which only a declared [`color`](Self::color) does.
    tinted: bool,
    badge: bool,
    /// Whether the digits take equal widths, so a column of amounts lines up.
    tabular: bool,
    weight: FontWeight,
    alignment: Alignment,
    #[derive_where(skip(Debug))]
    description: Option<RowFn<M, String>>,
    /// The value's icon: its own, an `Options` enum's, unless [`icon`](Self::icon) says
    /// otherwise.
    #[derive_where(skip(Debug))]
    icon: ReadFn<T, Option<IconData>>,
    #[derive_where(skip(Debug))]
    url: Option<RowFn<M, Option<String>>>,
    new_tab: bool,
    #[derive_where(skip(Debug))]
    tooltip: Option<RowFn<M, Option<String>>>,
    limit: Option<usize>,
    copyable: bool,
    placeholder: Option<Text>,
    /// Whether a closure over the row reads beyond the column's field.
    reads_row: bool,
    /// The fields the closures over the row read, when declared.
    row_reads: Option<crate::lens::Reads<M>>,
}

/// A searchable column's predicate for an escaped `LIKE` pattern.
type SearchFn = Arc<dyn Fn(String) -> Expr<bool> + Send + Sync>;

/// A column's color for a value.
type ColorFn<T> = ReadFn<T, Option<Color>>;

/// A closure over the row.
type RowFn<M, V> = ReadFn<M, V>;

/// A column's spelling of its value, which may read the rest of the row.
type FormatFn<M, T> = Arc<dyn Fn(&Cx, &M, &T) -> Text + Send + Sync>;

/// The escape character a search or filter pattern declares to `LIKE`.
pub(crate) const LIKE_ESCAPE: char = '\\';

/// `term` with `LIKE`'s wildcards and the escape character escaped, so it matches only itself.
pub(crate) fn escape_like(term: &str) -> String {
    let mut escaped = String::with_capacity(term.len());
    for c in term.chars() {
        if c == LIKE_ESCAPE || c == '%' || c == '_' {
            escaped.push(LIKE_ESCAPE);
        }
        escaped.push(c);
    }
    escaped
}

/// Wrap `term` as a `LIKE` pattern matching it anywhere in the column.
pub(super) fn escape_like_pattern(term: &str) -> String {
    format!("%{}%", escape_like(term))
}

/// Escaped substring predicate for `lens` matching `term`.
pub fn contains_expr<M, T>(lens: &Lens<M, T>, term: &str) -> Option<Expr<bool>>
where
    M: toasty::schema::Model,
    T: toasty::schema::Field<Inner = String>,
{
    let trimmed = term.trim();
    (!trimmed.is_empty()).then(|| {
        lens.path()
            .clone()
            .like_with_escape(escape_like_pattern(trimmed), LIKE_ESCAPE)
    })
}

impl<M, T> TextColumn<M, T>
where
    M: toasty::schema::Model,
{
    /// Bind a column to the field `lens` reads, which must be one field of the model.
    pub fn new(lens: Lens<M, T>) -> Self
    where
        T: FormScalar + Send + Sync + 'static,
    {
        Self {
            base: ColumnBase::new(lens.path(), ColumnWidth::Grow),
            lens,
            format: Arc::new(|_, _, value: &T| value.to_label()),
            search: None,
            sortable: false,
            color: Arc::new(T::color),
            tinted: false,
            badge: false,
            tabular: false,
            weight: FontWeight::Normal,
            alignment: Alignment::Start,
            description: None,
            icon: Arc::new(T::icon),
            url: None,
            new_tab: false,
            tooltip: None,
            limit: None,
            copyable: false,
            placeholder: None,
            reads_row: false,
            row_reads: None,
        }
    }

    /// Render the field's value through `format`: a `String`, or a [`Text`] the request's locale
    /// spells.
    pub fn format<L: Into<Text>>(
        mut self,
        format: impl Fn(&T) -> L + Send + Sync + 'static,
    ) -> Self {
        self.format = Arc::new(move |_, _, value| format(value).into());
        self
    }

    /// Show the value as a badge, with a dot in its color: an `Options` enum's
    /// `#[option(color = "…")]`, or the [`color`](Self::color) declared here.
    pub fn badge(mut self) -> Self {
        self.badge = true;
        self
    }

    /// Color the value: its badge's dot, or its text when it is no badge.
    pub fn color(mut self, color: impl Fn(&T) -> Option<Color> + Send + Sync + 'static) -> Self {
        self.color = Arc::new(color);
        self.tinted = true;
        self
    }

    /// Show `description(row)` as a muted line under the value, such as a customer's email under
    /// their name. Search, sort and export read the value alone.
    pub fn description(
        mut self,
        description: impl Fn(&M) -> String + Send + Sync + 'static,
    ) -> Self {
        self.description = Some(Arc::new(description));
        self.reads_row = true;
        self
    }

    /// Link the value to `url(row)`, or show it unlinked when that is `None`. The link takes a
    /// relative URL or an `http`, `https`, `mailto` or `tel` one; any other scheme, such as
    /// `javascript:`, leaves the value unlinked.
    pub fn url(mut self, url: impl Fn(&M) -> Option<String> + Send + Sync + 'static) -> Self {
        self.url = Some(Arc::new(url));
        self.reads_row = true;
        self
    }

    /// Open the [`url`](Self::url) in a new tab.
    pub fn open_url_in_new_tab(mut self) -> Self {
        self.new_tab = true;
        self
    }

    /// Show `tooltip(row)` when the pointer rests on the value.
    pub fn tooltip(
        mut self,
        tooltip: impl Fn(&M) -> Option<String> + Send + Sync + 'static,
    ) -> Self {
        self.tooltip = Some(Arc::new(tooltip));
        self.reads_row = true;
        self
    }

    /// Show at most `chars` characters of the value, then an ellipsis; the whole value shows
    /// when the pointer rests on it, unless a [`tooltip`](Self::tooltip) says otherwise. Search,
    /// sort and export read the whole value.
    pub fn limit(mut self, chars: usize) -> Self {
        self.limit = Some(chars);
        self
    }

    /// Follow the value with a button copying it to the clipboard, which needs JavaScript.
    pub fn copyable(mut self) -> Self {
        self.copyable = true;
        self
    }

    /// Show `placeholder` for an empty value, in place of a dash. An export writes the empty
    /// value.
    pub fn placeholder(mut self, placeholder: impl Into<Text>) -> Self {
        self.placeholder = Some(placeholder.into());
        self
    }

    /// Show `icon(value)` before the value, in its color, replacing a badge's dot.
    pub fn icon(mut self, icon: impl Fn(&T) -> Option<IconData> + Send + Sync + 'static) -> Self {
        self.icon = Arc::new(icon);
        self
    }

    /// Declare the fields the closures over the row read, beside the column's own: the
    /// [`description`](Self::description), [`url`](Self::url), [`tooltip`](Self::tooltip) and
    /// [`money_by`](Self::money_by).
    pub fn reading(mut self, reads: crate::lens::Reads<M>) -> Self {
        self.row_reads = Some(reads);
        self
    }

    /// Render the value in `weight`, such as a product's name in [`FontWeight::Medium`]. A
    /// [`badge`](Self::badge) keeps its own weight.
    pub fn weight(mut self, weight: FontWeight) -> Self {
        self.weight = weight;
        self
    }

    /// Align the header and the cells.
    pub fn align(mut self, alignment: Alignment) -> Self {
        self.alignment = alignment;
        self
    }

    base_builders!(sortable);
}

impl<M, T> TextColumn<M, T>
where
    M: toasty::schema::Model,
    T: Numeric + 'static,
{
    /// Spell the value as a number with `decimals` digits after the point and its thousands
    /// grouped in the request's locale, `12,345.60` in English and `12 345,60` in French, aligned
    /// to the end with equal-width digits.
    pub fn numeric(mut self, decimals: u8) -> Self {
        self.format = Arc::new(move |cx, _, value: &T| {
            value
                .number()
                .map(|number| crate::display::NumberFormat::of(cx).spell(number, decimals))
                .unwrap_or_default()
                .into()
        });
        self.amount()
    }

    /// Spell the value as an amount of `currency` in the request's locale, `$1,234.50` in English
    /// and `1 234,50 $` in French, aligned to the end with equal-width digits.
    pub fn money(mut self, currency: Currency) -> Self {
        self.format = Arc::new(move |cx, _, value: &T| currency.format_in(cx, value).into());
        self.amount()
    }

    /// Spell the value as an amount of the currency `currency(row)` names, such as an order's
    /// own, aligned as [`money`](Self::money) aligns it.
    pub fn money_by(mut self, currency: impl Fn(&M) -> Currency + Send + Sync + 'static) -> Self {
        self.format = Arc::new(move |cx, row, value: &T| currency(row).format_in(cx, value).into());
        self.reads_row = true;
        self.amount()
    }

    /// Align the column as an amount.
    fn amount(mut self) -> Self {
        self.alignment = Alignment::End;
        self.tabular = true;
        self.base.width = ColumnWidth::Auto;
        self
    }
}

impl<M, T> TextColumn<M, T>
where
    M: toasty::schema::Model + Send + Sync + 'static,
    T: toasty::schema::Field<Inner = String> + Send + Sync + 'static,
{
    /// Join the table's search with a substring match on this string field.
    pub fn searchable(mut self) -> Self {
        let path = self.lens.path().clone();
        self.search = Some(Arc::new(move |pattern| {
            path.clone().like_with_escape(pattern, LIKE_ESCAPE)
        }));
        self
    }
}

impl<M, T> Column<M> for TextColumn<M, T>
where
    M: toasty::schema::Model + Send + Sync + 'static,
    T: Send + Sync + 'static,
{
    base_column_methods!(reads);

    fn reads(&self) -> Option<crate::lens::Reads<M>> {
        let own = self.base.reads();
        match (self.reads_row, &self.row_reads) {
            (false, _) => Some(own),
            (true, None) => None,
            (true, Some(declared)) => Some(own.union(declared)),
        }
    }

    fn text(&self, cx: &Cx, row: &M) -> String {
        (self.format)(cx, row, self.lens.read(row)).localize(cx)
    }

    fn cell<'a>(&self, cx: &'a Cx, row: &M) -> BoxView<'a> {
        let value = self.lens.read(row);
        let text = (self.format)(cx, row, value).localize(cx);
        let color = (!text.trim().is_empty())
            .then(|| (self.color)(value))
            .flatten();
        // An icon takes the value's color, as a badge's dot does; only a declared color tints the
        // text.
        let icon = (self.icon)(value).map(|icon| (icon, color));
        let color = color.filter(|_| self.badge || self.tinted);
        text_cell(
            cx,
            TextCell {
                text,
                color,
                badge: self.badge,
                tabular: self.tabular,
                weight: self.weight,
                icon,
                description: self.description.as_ref().map(|describe| describe(row)),
                url: self.url.as_ref().and_then(|url| url(row)),
                new_tab: self.new_tab,
                tooltip: self.tooltip.as_ref().and_then(|tooltip| tooltip(row)),
                limit: self.limit,
                copyable: self.copyable,
                placeholder: self.placeholder.clone(),
            },
        )
    }

    fn alignment(&self) -> Alignment {
        self.alignment
    }

    /// A portable, escaped substring match.
    fn search_expr(&self, term: &str) -> Option<Expr<bool>> {
        let t = term.trim();
        let search = self.search.as_ref()?;
        (!t.is_empty()).then(|| search(escape_like_pattern(t)))
    }

    fn order_by(&self, descending: bool) -> Option<OrderByExpr> {
        self.sortable
            .then(|| sort_order(self.lens.path(), descending))
    }
}

impl<M, T> crate::column::ColumnInternals<M> for TextColumn<M, T>
where
    M: toasty::schema::Model + Send + Sync + 'static,
    T: Send + Sync + 'static,
{
    base_internals!(binding, related);

    /// A closure over the row may reach any relation the page loads, as a computed column's does.
    fn related(&self) -> crate::column::Related {
        if self.reads_row {
            crate::column::Related::Row
        } else {
            crate::column::Related::None
        }
    }
}