Skip to main content

tablo_core/panel/list/
wiring.rs

1//! A declared [`Table`] together with what one request wires onto it.
2
3use std::{ops::Deref, sync::Arc};
4
5use topcoat::{context::Cx, icon::IconData};
6
7use super::TableSignals;
8use crate::{
9    Color,
10    resource::{InputSpec, Trashed},
11    table::{BoxColumn, ColumnChoice, Table, TableState},
12};
13
14/// Per-record action policy reads which row actions one model instance allows.
15pub(crate) type RowPolicy<M> = Arc<dyn Fn(&M) -> RowActions + Send + Sync>;
16
17/// Why a row action's button shows disabled on one record, if it does.
18pub(crate) type DisabledReason<M> = Arc<dyn Fn(&M) -> Option<String> + Send + Sync>;
19
20/// The text and icon of a row action's button on one record, which the record's state may change.
21pub(crate) type RecordFace<M> = Arc<dyn Fn(&M) -> (String, Option<IconData>) + Send + Sync>;
22
23/// Which row actions one record may use.
24///
25/// A denied action emits no link, and a row denied `delete` renders no bulk checkbox.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub(crate) struct RowActions {
28    /// Whether the row renders its `View` link.
29    pub view: bool,
30    /// Whether the row renders its `Edit` link.
31    pub edit: bool,
32    /// Whether the row renders its `Delete` link and an enabled bulk checkbox.
33    pub delete: bool,
34}
35
36impl RowActions {
37    /// Every action allowed.
38    pub const ALL: Self = Self {
39        view: true,
40        edit: true,
41        delete: true,
42    };
43}
44
45/// The action chrome a resource declares.
46#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
47pub(crate) struct TableChrome {
48    /// Whether the row renders a Delete action (which also enables bulk).
49    pub(crate) delete: bool,
50    /// Whether the row renders an Edit action.
51    pub(crate) edit: bool,
52    /// Whether the row renders a View action.
53    pub(crate) view: bool,
54    /// Whether the table renders the resource's custom actions.
55    pub(crate) actions: bool,
56}
57
58/// One custom [`Action`](crate::resource::Action) as a table renders it.
59pub(crate) struct TableAction<M> {
60    pub(crate) name: &'static str,
61    pub(crate) label: String,
62    pub(crate) row: bool,
63    pub(crate) bulk: bool,
64    /// Whether the action confirms: in the confirmation dialog, or in its input dialog.
65    pub(crate) confirm: bool,
66    /// The question the confirmation dialog asks of one row.
67    pub(crate) prompt: String,
68    /// The question the confirmation dialog asks of the bulk bar's selection.
69    pub(crate) bulk_prompt: String,
70    /// The icon before its buttons' label.
71    pub(crate) icon: Option<IconData>,
72    /// The text and icon of its row button on one record.
73    pub(crate) record_face: RecordFace<M>,
74    /// The hint its row buttons show on hover.
75    pub(crate) tooltip: Option<String>,
76    /// The colour its buttons are tinted in.
77    pub(crate) color: Color,
78    /// The action's input form, when it asks for one: its buttons open the input's dialog.
79    pub(crate) input: Option<InputSpec>,
80    /// The records it takes: the live ones, or a soft-deleting resource's trashed ones.
81    pub(crate) trashed: Trashed,
82    pub(crate) allowed: Arc<dyn Fn(&M) -> bool + Send + Sync>,
83    /// Why its row button shows disabled on a record it does not allow, if it does.
84    pub(crate) disabled: DisabledReason<M>,
85}
86
87/// What a table's editable cells need beside the edit route, which the panel wires from the
88/// resource and the request.
89pub(crate) struct CellEdits<M> {
90    /// Whether the request may change the form key a column names: its field access neither hides
91    /// nor locks it.
92    pub(crate) changes: Arc<dyn Fn(&str) -> bool + Send + Sync>,
93    /// The record's version, which a cell posts so the save refuses a stale one.
94    pub(crate) version: fn(&M) -> Option<u64>,
95}
96
97/// What a request wires onto a declared table: the action URLs its rows and bulk bar link to,
98/// and which actions each row allows.
99///
100/// The panel builds it per request from the mounted resource and the request's policy, so the
101/// declaration itself carries none of it.
102pub(crate) struct Wiring<M> {
103    row_policy: Option<RowPolicy<M>>,
104    delete_prefix: Option<String>,
105    edit_prefix: Option<String>,
106    /// What the editable cells post, once the edit route is wired.
107    cell_edits: Option<CellEdits<M>>,
108    view_prefix: Option<String>,
109    bulk_delete: bool,
110    /// The custom actions and the list URL their routes hang off.
111    custom_actions: Vec<TableAction<M>>,
112    actions_prefix: Option<String>,
113    /// Where a write this table's row and bulk actions start lands.
114    return_to: Option<String>,
115    /// Whether the bulk bar offers every record the list's query selects: only the resource's
116    /// own list, whose query its bulk routes re-run.
117    select_matching: bool,
118    /// The prefix the table's URL parameters carry.
119    prefix: Option<String>,
120    /// The reader's choice of toggleable columns.
121    choice: ColumnChoice,
122    /// Where the column picker posts a new choice; `None` renders no picker.
123    columns_url: Option<String>,
124}
125
126impl<M> Default for Wiring<M> {
127    fn default() -> Self {
128        Self {
129            row_policy: None,
130            delete_prefix: None,
131            edit_prefix: None,
132            cell_edits: None,
133            view_prefix: None,
134            bulk_delete: false,
135            custom_actions: Vec::new(),
136            actions_prefix: None,
137            return_to: None,
138            select_matching: false,
139            prefix: None,
140            choice: ColumnChoice::default(),
141            columns_url: None,
142        }
143    }
144}
145
146/// A declared [`Table`] with one request's actions and policy wired on: what the list page
147/// renders.
148///
149/// [`wired_table`](crate::panel::wired_table) returns the panel's for a resource. It reads as
150/// its [`Table`] for loading a [`TablePage`](crate::TablePage).
151pub struct WiredTable<M> {
152    table: Arc<Table<M>>,
153    pub(super) wiring: Wiring<M>,
154}
155
156impl<M> Deref for WiredTable<M> {
157    type Target = Table<M>;
158
159    fn deref(&self) -> &Table<M> {
160        &self.table
161    }
162}
163
164impl<M> std::fmt::Debug for WiredTable<M> {
165    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
166        let wiring = &self.wiring;
167        f.debug_struct("WiredTable")
168            .field("table", &self.table)
169            .field("row_policy", &wiring.row_policy.is_some())
170            .field("delete_prefix", &wiring.delete_prefix)
171            .field("edit_prefix", &wiring.edit_prefix)
172            .field("cell_edits", &wiring.cell_edits.is_some())
173            .field("view_prefix", &wiring.view_prefix)
174            .field("bulk_delete", &wiring.bulk_delete)
175            .field(
176                "custom_actions",
177                &wiring
178                    .custom_actions
179                    .iter()
180                    .map(|a| a.name)
181                    .collect::<Vec<_>>(),
182            )
183            .field("return_to", &wiring.return_to)
184            .field("prefix", &wiring.prefix)
185            .field("choice", &wiring.choice)
186            .field("columns_url", &wiring.columns_url)
187            .finish()
188    }
189}
190
191impl<M> WiredTable<M> {
192    /// `table` with nothing wired: no actions.
193    pub(crate) fn new(table: Arc<Table<M>>) -> Self {
194        Self {
195            table,
196            wiring: Wiring::default(),
197        }
198    }
199
200    /// Declare the per-record action policy.
201    pub(crate) fn row_actions(
202        mut self,
203        policy: impl Fn(&M) -> RowActions + Send + Sync + 'static,
204    ) -> Self {
205        self.wiring.row_policy = Some(Arc::new(policy));
206        self
207    }
208
209    /// Enable the row-level `Delete` action.
210    pub(crate) fn with_delete(mut self, prefix: String) -> Self {
211        if self.is_addressable() {
212            self.wiring.delete_prefix = Some(prefix);
213        }
214        self
215    }
216
217    /// Enable the row-level `Edit` action.
218    pub(crate) fn with_edit(mut self, prefix: String) -> Self {
219        if self.is_addressable() {
220            self.wiring.edit_prefix = Some(prefix);
221        }
222        self
223    }
224
225    /// Let the editable columns edit their field in a cell, on a row whose record the policy
226    /// lets the user edit, for a key `changes` says the user may change. The edit route must be
227    /// wired too.
228    pub(crate) fn editing_cells(
229        mut self,
230        changes: impl Fn(&str) -> bool + Send + Sync + 'static,
231        version: fn(&M) -> Option<u64>,
232    ) -> Self {
233        if self.is_addressable() {
234            self.wiring.cell_edits = Some(CellEdits {
235                changes: Arc::new(changes),
236                version,
237            });
238        }
239        self
240    }
241
242    /// Enable the row-level `View` action.
243    pub(crate) fn with_view(mut self, prefix: String) -> Self {
244        if self.is_addressable() {
245            self.wiring.view_prefix = Some(prefix);
246        }
247        self
248    }
249
250    /// Enable bulk selection with the `BulkDelete` action.
251    pub(crate) fn with_bulk_delete(mut self, enabled: bool) -> Self {
252        self.wiring.bulk_delete = enabled;
253        self
254    }
255
256    /// Wire the resource's custom actions.
257    pub(crate) fn with_custom_actions(
258        mut self,
259        prefix: String,
260        actions: Vec<TableAction<M>>,
261    ) -> Self {
262        if self.is_addressable() {
263            self.wiring.actions_prefix = Some(prefix);
264            self.wiring.custom_actions = actions;
265        }
266        self
267    }
268
269    /// Show the columns `choice` shows, and let the reader post a new choice to `url`. A choice
270    /// hiding every column would leave no table to read, so the defaults show instead.
271    pub(crate) fn with_column_choice(mut self, choice: ColumnChoice, url: Option<String>) -> Self {
272        let shows_any = self
273            .declared_columns()
274            .iter()
275            .any(|col| choice.shows(col.name(), col.toggle()));
276        if shows_any {
277            self.wiring.choice = choice;
278        }
279        self.wiring.columns_url = url;
280        self
281    }
282
283    /// Let the bulk bar select every record the list's query selects. The bulk routes re-run the
284    /// resource's own list query, so only its list page, never a relation table or a page that
285    /// owns its query, offers it.
286    pub(crate) fn selecting_matching(mut self) -> Self {
287        self.wiring.select_matching = true;
288        self
289    }
290
291    /// Send the writes this table starts back to `url`.
292    pub(crate) fn returning_to(mut self, url: String) -> Self {
293        self.wiring.return_to = Some(url);
294        self
295    }
296
297    /// Spell the table's URL parameters `{prefix}.{name}`, so a page renders several tables and
298    /// each keeps its own state and browser controls.
299    #[must_use]
300    pub fn prefixed(mut self, prefix: impl Into<String>) -> Self {
301        self.wiring.prefix = Some(prefix.into());
302        self
303    }
304
305    /// Keeps the delete and the custom actions that take some of the records `shown` admits, so
306    /// the bulk bar of a list showing only trashed records offers what a trashed record takes.
307    pub(crate) fn taking(mut self, shown: Trashed) -> Self {
308        // Some record, live or trashed, is both shown and taken.
309        let overlaps = |taken: Trashed| {
310            [false, true]
311                .into_iter()
312                .any(|trashed| shown.admits(trashed) && taken.admits(trashed))
313        };
314        self.wiring
315            .custom_actions
316            .retain(|action| overlaps(action.trashed));
317        if !overlaps(Trashed::Without) {
318            self.wiring.bulk_delete = false;
319        }
320        self
321    }
322
323    /// The table's signals and the list state they hold. Creates the signals, so it carries
324    /// [`topcoat::runtime::signal`]'s contract: call it while a page body runs.
325    pub(crate) fn browser_state(&self, cx: &Cx) -> (TableSignals, TableState) {
326        let prefix = self.wiring.prefix.as_deref();
327        let signals = TableSignals::new(cx, prefix);
328        let state = self.normalize_state(&signals.state(prefix));
329        (signals, state)
330    }
331
332    /// Which row actions `record` allows.
333    pub(crate) fn actions_for(&self, record: &M) -> RowActions {
334        self.wiring
335            .row_policy
336            .as_ref()
337            .map_or(RowActions::ALL, |policy| policy(record))
338    }
339
340    /// Whether the reader's choice shows `col`.
341    pub(super) fn shows(&self, col: &BoxColumn<M>) -> bool {
342        self.wiring.choice.shows(col.name(), col.toggle())
343    }
344
345    /// The declared columns the reader's choice shows, in declaration order.
346    pub(super) fn visible_columns(&self) -> impl Iterator<Item = &BoxColumn<M>> {
347        self.declared_columns().iter().filter(|col| self.shows(col))
348    }
349
350    /// The prefix the table's URL parameters and DOM ids carry, if any.
351    pub(super) fn prefix(&self) -> Option<&str> {
352        self.wiring.prefix.as_deref()
353    }
354
355    /// Where the column picker posts, when the table renders one.
356    pub(super) fn columns_url(&self) -> Option<&str> {
357        self.wiring.columns_url.as_deref()
358    }
359
360    pub(super) fn return_to(&self) -> Option<&str> {
361        self.wiring.return_to.as_deref()
362    }
363
364    pub(super) fn select_matching(&self) -> bool {
365        self.wiring.select_matching && self.wiring.prefix.is_none()
366    }
367
368    pub(super) fn delete_prefix(&self) -> Option<&str> {
369        self.wiring.delete_prefix.as_deref()
370    }
371
372    pub(super) fn edit_prefix(&self) -> Option<&str> {
373        self.wiring.edit_prefix.as_deref()
374    }
375
376    /// What the editable cells post, when the edit route is wired.
377    pub(super) fn cell_edits(&self) -> Option<&CellEdits<M>> {
378        self.wiring
379            .cell_edits
380            .as_ref()
381            .filter(|_| self.wiring.edit_prefix.is_some())
382    }
383
384    pub(super) fn view_prefix(&self) -> Option<&str> {
385        self.wiring.view_prefix.as_deref()
386    }
387
388    pub(super) fn actions_prefix(&self) -> Option<&str> {
389        self.wiring.actions_prefix.as_deref()
390    }
391
392    pub(super) fn row_custom_actions(&self) -> impl Iterator<Item = &TableAction<M>> {
393        self.wiring
394            .custom_actions
395            .iter()
396            .filter(|a| a.row && self.wiring.actions_prefix.is_some())
397    }
398
399    pub(super) fn bulk_custom_actions(&self) -> impl Iterator<Item = &TableAction<M>> {
400        self.wiring
401            .custom_actions
402            .iter()
403            .filter(|a| a.bulk && self.wiring.actions_prefix.is_some())
404    }
405
406    pub(super) fn bulk_delete_enabled(&self) -> bool {
407        self.wiring.bulk_delete && self.wiring.delete_prefix.is_some()
408    }
409}
410
411#[cfg(test)]
412impl<M> Table<M> {
413    /// This table with nothing wired yet, for a test that wires it by hand.
414    pub(crate) fn wired(self) -> WiredTable<M> {
415        WiredTable::new(Arc::new(self))
416    }
417}