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
//! A declared [`Table`] together with what one request wires onto it.

use std::{ops::Deref, sync::Arc};

use topcoat::{context::Cx, icon::IconData};

use super::TableSignals;
use crate::{
    Color,
    resource::Trashed,
    schema::Schema,
    table::{BoxColumn, ColumnChoice, Table, TableState},
};

/// Per-record action policy reads which row actions one model instance allows.
pub(crate) type RowPolicy<M> = Arc<dyn Fn(&M) -> RowActions + Send + Sync>;

/// Why a row action's button shows disabled on one record, if it does.
pub(crate) type DisabledReason<M> = Arc<dyn Fn(&M) -> Option<String> + Send + Sync>;

/// The text and icon of a row action's button on one record, which the record's state may change.
pub(crate) type RecordFace<M> = Arc<dyn Fn(&M) -> (String, Option<IconData>) + Send + Sync>;

/// Which row actions one record may use.
///
/// A denied action emits no link, and a row denied `delete` renders no bulk checkbox.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct RowActions {
    /// Whether the row renders its `View` link.
    pub view: bool,
    /// Whether the row renders its `Edit` link.
    pub edit: bool,
    /// Whether the row renders its `Delete` link and an enabled bulk checkbox.
    pub delete: bool,
}

impl RowActions {
    /// Every action allowed.
    pub const ALL: Self = Self {
        view: true,
        edit: true,
        delete: true,
    };
}

/// The action chrome a resource declares.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct TableChrome {
    /// Whether the row renders a Delete action (which also enables bulk).
    pub(crate) delete: bool,
    /// Whether the row renders an Edit action.
    pub(crate) edit: bool,
    /// Whether the row renders a View action.
    pub(crate) view: bool,
    /// Whether the table renders the resource's custom actions.
    pub(crate) actions: bool,
}

/// One custom [`Action`](crate::resource::Action) as a table renders it.
pub(crate) struct TableAction<M> {
    pub(crate) name: &'static str,
    pub(crate) label: String,
    pub(crate) row: bool,
    pub(crate) bulk: bool,
    /// Whether the action confirms: in the confirmation dialog, or in its input dialog.
    pub(crate) confirm: bool,
    /// The question the confirmation dialog asks of one row.
    pub(crate) prompt: String,
    /// The question the confirmation dialog asks of the bulk bar's selection.
    pub(crate) bulk_prompt: String,
    /// The icon before its buttons' label.
    pub(crate) icon: Option<IconData>,
    /// The text and icon of its row button on one record.
    pub(crate) record_face: RecordFace<M>,
    /// The hint its row buttons show on hover.
    pub(crate) tooltip: Option<String>,
    /// The colour its buttons are tinted in.
    pub(crate) color: Color,
    /// The action's input form, when it asks for one: its buttons open the input's dialog.
    pub(crate) input: Option<fn() -> Schema>,
    /// The records it takes: the live ones, or a soft-deleting resource's trashed ones.
    pub(crate) trashed: Trashed,
    pub(crate) allowed: Arc<dyn Fn(&M) -> bool + Send + Sync>,
    /// Why its row button shows disabled on a record it does not allow, if it does.
    pub(crate) disabled: DisabledReason<M>,
}

/// What a table's editable cells need beside the edit route, which the panel wires from the
/// resource and the request.
pub(crate) struct CellEdits<M> {
    /// Whether the request may change the form key a column names: its field access neither hides
    /// nor locks it.
    pub(crate) changes: Arc<dyn Fn(&str) -> bool + Send + Sync>,
    /// The record's version, which a cell posts so the save refuses a stale one.
    pub(crate) version: fn(&M) -> Option<u64>,
}

/// What a request wires onto a declared table: the action URLs its rows and bulk bar link to,
/// and which actions each row allows.
///
/// The panel builds it per request from the mounted resource and the request's policy, so the
/// declaration itself carries none of it.
pub(crate) struct Wiring<M> {
    row_policy: Option<RowPolicy<M>>,
    delete_prefix: Option<String>,
    edit_prefix: Option<String>,
    /// What the editable cells post, once the edit route is wired.
    cell_edits: Option<CellEdits<M>>,
    view_prefix: Option<String>,
    bulk_delete: bool,
    /// The custom actions and the list URL their routes hang off.
    custom_actions: Vec<TableAction<M>>,
    actions_prefix: Option<String>,
    /// Where a write this table's row and bulk actions start lands.
    return_to: Option<String>,
    /// Whether the bulk bar offers every record the list's query selects: only the resource's
    /// own list, whose query its bulk routes re-run.
    select_matching: bool,
    /// The prefix the table's URL parameters carry.
    prefix: Option<String>,
    /// The reader's choice of toggleable columns.
    choice: ColumnChoice,
    /// Where the column picker posts a new choice; `None` renders no picker.
    columns_url: Option<String>,
}

impl<M> Default for Wiring<M> {
    fn default() -> Self {
        Self {
            row_policy: None,
            delete_prefix: None,
            edit_prefix: None,
            cell_edits: None,
            view_prefix: None,
            bulk_delete: false,
            custom_actions: Vec::new(),
            actions_prefix: None,
            return_to: None,
            select_matching: false,
            prefix: None,
            choice: ColumnChoice::default(),
            columns_url: None,
        }
    }
}

/// A declared [`Table`] with one request's actions and policy wired on: what the list page
/// renders.
///
/// [`wired_table`](crate::panel::wired_table) returns the panel's for a resource. It reads as
/// its [`Table`] for loading a [`TablePage`](crate::TablePage).
pub struct WiredTable<M> {
    table: Arc<Table<M>>,
    pub(super) wiring: Wiring<M>,
}

impl<M> Deref for WiredTable<M> {
    type Target = Table<M>;

    fn deref(&self) -> &Table<M> {
        &self.table
    }
}

impl<M> std::fmt::Debug for WiredTable<M> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let wiring = &self.wiring;
        f.debug_struct("WiredTable")
            .field("table", &self.table)
            .field("row_policy", &wiring.row_policy.is_some())
            .field("delete_prefix", &wiring.delete_prefix)
            .field("edit_prefix", &wiring.edit_prefix)
            .field("cell_edits", &wiring.cell_edits.is_some())
            .field("view_prefix", &wiring.view_prefix)
            .field("bulk_delete", &wiring.bulk_delete)
            .field(
                "custom_actions",
                &wiring
                    .custom_actions
                    .iter()
                    .map(|a| a.name)
                    .collect::<Vec<_>>(),
            )
            .field("return_to", &wiring.return_to)
            .field("prefix", &wiring.prefix)
            .field("choice", &wiring.choice)
            .field("columns_url", &wiring.columns_url)
            .finish()
    }
}

impl<M> WiredTable<M> {
    /// `table` with nothing wired: no actions.
    pub(crate) fn new(table: Arc<Table<M>>) -> Self {
        Self {
            table,
            wiring: Wiring::default(),
        }
    }

    /// Declare the per-record action policy.
    pub(crate) fn row_actions(
        mut self,
        policy: impl Fn(&M) -> RowActions + Send + Sync + 'static,
    ) -> Self {
        self.wiring.row_policy = Some(Arc::new(policy));
        self
    }

    /// Enable the row-level `Delete` action.
    pub(crate) fn with_delete(mut self, prefix: String) -> Self {
        if self.is_addressable() {
            self.wiring.delete_prefix = Some(prefix);
        }
        self
    }

    /// Enable the row-level `Edit` action.
    pub(crate) fn with_edit(mut self, prefix: String) -> Self {
        if self.is_addressable() {
            self.wiring.edit_prefix = Some(prefix);
        }
        self
    }

    /// Let the editable columns edit their field in a cell, on a row whose record the policy
    /// lets the user edit, for a key `changes` says the user may change. The edit route must be
    /// wired too.
    pub(crate) fn editing_cells(
        mut self,
        changes: impl Fn(&str) -> bool + Send + Sync + 'static,
        version: fn(&M) -> Option<u64>,
    ) -> Self {
        if self.is_addressable() {
            self.wiring.cell_edits = Some(CellEdits {
                changes: Arc::new(changes),
                version,
            });
        }
        self
    }

    /// Enable the row-level `View` action.
    pub(crate) fn with_view(mut self, prefix: String) -> Self {
        if self.is_addressable() {
            self.wiring.view_prefix = Some(prefix);
        }
        self
    }

    /// Enable bulk selection with the `BulkDelete` action.
    pub(crate) fn with_bulk_delete(mut self, enabled: bool) -> Self {
        self.wiring.bulk_delete = enabled;
        self
    }

    /// Wire the resource's custom actions.
    pub(crate) fn with_custom_actions(
        mut self,
        prefix: String,
        actions: Vec<TableAction<M>>,
    ) -> Self {
        if self.is_addressable() {
            self.wiring.actions_prefix = Some(prefix);
            self.wiring.custom_actions = actions;
        }
        self
    }

    /// Show the columns `choice` shows, and let the reader post a new choice to `url`. A choice
    /// hiding every column would leave no table to read, so the defaults show instead.
    pub(crate) fn with_column_choice(mut self, choice: ColumnChoice, url: Option<String>) -> Self {
        let shows_any = self
            .declared_columns()
            .iter()
            .any(|col| choice.shows(col.name(), col.toggle()));
        if shows_any {
            self.wiring.choice = choice;
        }
        self.wiring.columns_url = url;
        self
    }

    /// Let the bulk bar select every record the list's query selects. The bulk routes re-run the
    /// resource's own list query, so only its list page, never a relation table or a page that
    /// owns its query, offers it.
    pub(crate) fn selecting_matching(mut self) -> Self {
        self.wiring.select_matching = true;
        self
    }

    /// Send the writes this table starts back to `url`.
    pub(crate) fn returning_to(mut self, url: String) -> Self {
        self.wiring.return_to = Some(url);
        self
    }

    /// Spell the table's URL parameters `{prefix}.{name}`, so a page renders several tables and
    /// each keeps its own state and browser controls.
    #[must_use]
    pub fn prefixed(mut self, prefix: impl Into<String>) -> Self {
        self.wiring.prefix = Some(prefix.into());
        self
    }

    /// Keeps the delete and the custom actions that take some of the records `shown` admits, so
    /// the bulk bar of a list showing only trashed records offers what a trashed record takes.
    pub(crate) fn taking(mut self, shown: Trashed) -> Self {
        // Some record, live or trashed, is both shown and taken.
        let overlaps = |taken: Trashed| {
            [false, true]
                .into_iter()
                .any(|trashed| shown.admits(trashed) && taken.admits(trashed))
        };
        self.wiring
            .custom_actions
            .retain(|action| overlaps(action.trashed));
        if !overlaps(Trashed::Without) {
            self.wiring.bulk_delete = false;
        }
        self
    }

    /// The table's signals and the list state they hold. Creates the signals, so it carries
    /// [`topcoat::runtime::signal`]'s contract: call it while a page body runs.
    pub(crate) fn browser_state(&self, cx: &Cx) -> (TableSignals, TableState) {
        let prefix = self.wiring.prefix.as_deref();
        let signals = TableSignals::new(cx, prefix);
        let state = self.normalize_state(&signals.state(prefix));
        (signals, state)
    }

    /// Which row actions `record` allows.
    pub(crate) fn actions_for(&self, record: &M) -> RowActions {
        self.wiring
            .row_policy
            .as_ref()
            .map_or(RowActions::ALL, |policy| policy(record))
    }

    /// Whether the reader's choice shows `col`.
    pub(super) fn shows(&self, col: &BoxColumn<M>) -> bool {
        self.wiring.choice.shows(col.name(), col.toggle())
    }

    /// The declared columns the reader's choice shows, in declaration order.
    pub(super) fn visible_columns(&self) -> impl Iterator<Item = &BoxColumn<M>> {
        self.declared_columns().iter().filter(|col| self.shows(col))
    }

    /// The prefix the table's URL parameters and DOM ids carry, if any.
    pub(super) fn prefix(&self) -> Option<&str> {
        self.wiring.prefix.as_deref()
    }

    /// Where the column picker posts, when the table renders one.
    pub(super) fn columns_url(&self) -> Option<&str> {
        self.wiring.columns_url.as_deref()
    }

    pub(super) fn return_to(&self) -> Option<&str> {
        self.wiring.return_to.as_deref()
    }

    pub(super) fn select_matching(&self) -> bool {
        self.wiring.select_matching && self.wiring.prefix.is_none()
    }

    pub(super) fn delete_prefix(&self) -> Option<&str> {
        self.wiring.delete_prefix.as_deref()
    }

    pub(super) fn edit_prefix(&self) -> Option<&str> {
        self.wiring.edit_prefix.as_deref()
    }

    /// What the editable cells post, when the edit route is wired.
    pub(super) fn cell_edits(&self) -> Option<&CellEdits<M>> {
        self.wiring
            .cell_edits
            .as_ref()
            .filter(|_| self.wiring.edit_prefix.is_some())
    }

    pub(super) fn view_prefix(&self) -> Option<&str> {
        self.wiring.view_prefix.as_deref()
    }

    pub(super) fn actions_prefix(&self) -> Option<&str> {
        self.wiring.actions_prefix.as_deref()
    }

    pub(super) fn row_custom_actions(&self) -> impl Iterator<Item = &TableAction<M>> {
        self.wiring
            .custom_actions
            .iter()
            .filter(|a| a.row && self.wiring.actions_prefix.is_some())
    }

    pub(super) fn bulk_custom_actions(&self) -> impl Iterator<Item = &TableAction<M>> {
        self.wiring
            .custom_actions
            .iter()
            .filter(|a| a.bulk && self.wiring.actions_prefix.is_some())
    }

    pub(super) fn bulk_delete_enabled(&self) -> bool {
        self.wiring.bulk_delete && self.wiring.delete_prefix.is_some()
    }
}

#[cfg(test)]
impl<M> Table<M> {
    /// This table with nothing wired yet, for a test that wires it by hand.
    pub(crate) fn wired(self) -> WiredTable<M> {
        WiredTable::new(Arc::new(self))
    }
}