Skip to main content

tablo_core/panel/
list.rs

1//! Serves each resource's list page, and renders the [`WiredTable`] it and a related table show.
2
3mod render;
4mod shown;
5mod signals;
6mod wiring;
7
8use std::sync::Arc;
9
10use topcoat::{
11    Result,
12    context::Cx,
13    icon::icon,
14    router::{
15        Body,
16        error::{forbidden, see_other},
17        request::original_method,
18    },
19    view::{BoxView, SuspenseMode, ViewExt, attributes, internal::ThenView, suspense, view},
20};
21
22pub(crate) use self::{
23    render::{TAB_ACTIVE_CLASS, TAB_CLASS, TAB_IDLE_CLASS},
24    shown::ShownList,
25    signals::TableSignals,
26    wiring::{RowActions, TableAction, TableChrome},
27};
28pub use self::{shown::list_query, wiring::WiredTable};
29use super::{
30    bar::{ActionBar, header_bar},
31    forms::{parse_form_body, truthy},
32    gate::{gate, landing_url},
33    url::{columns_url, create_page_url, export_url, import_url},
34};
35use crate::{
36    policy::Ability,
37    resource::{Mounted, Places, Resource},
38    table::{ColumnChoice, Table, TablePage, TableState},
39    topcoat_compat::async_page,
40};
41
42/// The field each checked box of the column picker posts a column's name under.
43pub(crate) const COLUMN_FIELD: &str = "column";
44
45/// The field the column picker's Reset posts, restoring every column's default.
46pub(crate) const RESET_FIELD: &str = "reset";
47
48/// Returns the retry link for a failed table load, dropping pagination for cursor failures and
49/// keeping it otherwise.
50pub(crate) fn retry_url_for_error(
51    state: &TableState,
52    error: &topcoat::Error,
53    path: &str,
54) -> String {
55    if crate::error::TabloError::is_cursor(error) {
56        state.first_page(path)
57    } else {
58        state.list_url(path)
59    }
60}
61
62/// Derives the action chrome a resource's declarations imply.
63pub(crate) fn declared_chrome<R: Resource>(cx: &Cx, resource: &Mounted<R>) -> TableChrome {
64    TableChrome {
65        delete: resource.can(cx, Ability::DeleteAny),
66        edit: resource.pages.edit,
67        view: resource.viewed(),
68        actions: true,
69    }
70}
71
72/// `table` showing the columns the request's user chose for `R`'s list, its picker posting to the
73/// list's column route while a signed-in user may keep a choice.
74pub(crate) async fn choose_columns<R: Resource>(
75    cx: &Cx,
76    resource: &Mounted<R>,
77    table: WiredTable<R::Model>,
78) -> WiredTable<R::Model> {
79    if !table.has_toggleable_columns() {
80        return table;
81    }
82    let choice = crate::auth::load_choice(cx, &resource.slug).await;
83    let url = crate::auth::signed_in(cx).then(|| columns_url(&resource.url));
84    table.with_column_choice(choice, url)
85}
86
87/// The column picker's POST, `{list}/-/columns`: stores the signed-in user's choice of `R`'s
88/// toggleable columns, the boxes it checks under [`COLUMN_FIELD`], or the defaults with
89/// [`RESET_FIELD`], and lands back where the picker was.
90pub(crate) fn resource_columns<R: Resource>(cx: &Cx, body: Body) -> BoxView<'_> {
91    async_page(async move {
92        let resource = gate::<R>(cx)?;
93        if !resource.can(cx, Ability::ViewAny) {
94            return Err(forbidden().into());
95        }
96        let parts = parse_form_body(cx, body).await?;
97        crate::csrf::verify(cx, parts.last(crate::csrf::FIELD_NAME))?;
98        let choice = if parts.last(RESET_FIELD).is_some_and(truthy) {
99            ColumnChoice::default()
100        } else {
101            let checked: Vec<&str> = parts
102                .pairs
103                .iter()
104                .filter(|(name, _)| name == COLUMN_FIELD)
105                .map(|(_, value)| value.as_str())
106                .collect();
107            ColumnChoice::checked(resource.table_for(cx).declared_columns(), &checked)
108        };
109        crate::auth::save_choice(cx, &resource.slug, &choice).await?;
110        Err::<(), _>(see_other(landing_url(cx, &resource.url)).into())
111    })
112}
113
114/// Returns the panel's list table for `R`, with the request's row actions wired on, for a page
115/// that owns its table; render it over the page's own query with
116/// [`WiredTable::render`](WiredTable::render).
117///
118/// # Errors
119///
120/// A declaration error when the context's panel does not mount `R`.
121pub fn wired_table<R: Resource>(
122    cx: &topcoat::context::Cx,
123) -> topcoat::Result<WiredTable<R::Model>> {
124    let resource = crate::resource::require_mounted::<R>(cx)?;
125    Ok(wire_table_actions(cx, &resource))
126}
127
128/// Wires `R`'s delete, bulk, edit, view, and custom actions onto the table.
129pub(crate) fn wire_table_actions<R: Resource>(
130    cx: &Cx,
131    resource: &Arc<Mounted<R>>,
132) -> WiredTable<R::Model> {
133    wire_table(cx, resource, declared_chrome(cx, resource))
134}
135
136/// Wires `chrome`'s affordances onto `R`'s table.
137pub(crate) fn wire_table<R: Resource>(
138    cx: &Cx,
139    resource: &Arc<Mounted<R>>,
140    chrome: TableChrome,
141) -> WiredTable<R::Model> {
142    wire_table_over(cx, resource, resource.table_for(cx), chrome)
143}
144
145/// Wires `chrome`'s affordances onto `table`, a narrowing of `R`'s table for the request.
146pub(crate) fn wire_table_over<R: Resource>(
147    cx: &Cx,
148    resource: &Arc<Mounted<R>>,
149    table: Arc<Table<R::Model>>,
150    chrome: TableChrome,
151) -> WiredTable<R::Model> {
152    let mut table = WiredTable::new(table);
153    let (policy_cx, policy) = (cx.clone(), Arc::clone(resource));
154    table = table.row_actions(move |record| {
155        // Every route pairs its predicate with `View`; a trashed record is restored before it is
156        // edited or deleted again.
157        let view = policy.can(&policy_cx, Ability::View(record));
158        let live = view && !policy.is_trashed(record);
159        RowActions {
160            view,
161            edit: live && policy.can(&policy_cx, Ability::Update(record)),
162            delete: live && policy.can(&policy_cx, Ability::Delete(record)),
163        }
164    });
165    if chrome.delete {
166        table = table
167            .with_delete(resource.url.clone())
168            .with_bulk_delete(true);
169    }
170    if chrome.edit {
171        // A cell posts its field to the edit route, which refuses a key the user may not change.
172        // A widget's table or a custom page may render it before anything else set the token.
173        crate::csrf::ensure_token(cx);
174        let mask = resource.form_mask(cx);
175        table = table.with_edit(resource.url.clone()).editing_cells(
176            move |key| mask.writes(key).is_none(),
177            <R::Model as crate::PanelModel>::version,
178        );
179    }
180    if chrome.view {
181        table = table.with_view(resource.url.clone());
182    }
183    if chrome.actions {
184        table = wire_custom_actions(cx, resource, table);
185    }
186    table
187}
188
189/// Attaches the custom actions of `R` its policy allows `RunAny`, each gated per record by `View`
190/// and the entry's per-record check: `Run` and the action's `can_run`, on a live record; a
191/// soft-deleting resource's restore and force delete, on a trashed one.
192fn wire_custom_actions<R: Resource>(
193    cx: &Cx,
194    resource: &Arc<Mounted<R>>,
195    table: WiredTable<R::Model>,
196) -> WiredTable<R::Model> {
197    let wired: Vec<_> = resource
198        .actions
199        .entries()
200        .iter()
201        .filter(|action| resource.can(cx, action.resource_wide))
202        .map(|action| {
203            let action = Arc::new(action.clone());
204            let (face, allow, refuse) = (
205                Arc::clone(&action),
206                Arc::clone(&action),
207                Arc::clone(&action),
208            );
209            let (policy_cx, policy) = (cx.clone(), Arc::clone(resource));
210            let face_cx = cx.clone();
211            let (reason_cx, reasons) = (cx.clone(), Arc::clone(resource));
212            TableAction {
213                name: action.name,
214                label: (action.label)().localize(cx),
215                row: action.places.contains(Places::ROW),
216                bulk: action.places.contains(Places::BULK),
217                confirm: action.confirm,
218                prompt: (action.prompt)(false).localize(cx),
219                bulk_prompt: (action.prompt)(true).localize(cx),
220                icon: (action.icon)(),
221                tooltip: (action.tooltip)().map(|text| text.localize(cx)),
222                record_face: Arc::new(move |record: &R::Model| {
223                    (
224                        (face.label_for)(&face_cx, record).localize(&face_cx),
225                        (face.icon_for)(&face_cx, record),
226                    )
227                }),
228                color: action.color,
229                input: action.input.takes_input.then_some(action.input),
230                trashed: action.trashed,
231                allowed: Arc::new(move |record: &R::Model| {
232                    policy.can(&policy_cx, Ability::View(record))
233                        && allow.allows(&policy, &policy_cx, record)
234                }),
235                disabled: Arc::new(move |record: &R::Model| {
236                    if !reasons.can(&reason_cx, Ability::View(record)) {
237                        return None;
238                    }
239                    let reason = refuse.disabled_on(&reasons, &reason_cx, record)?;
240                    Some(reason.localize(&reason_cx))
241                }),
242            }
243        })
244        .collect();
245    // A table wired with no action would still render the write form and its dialog.
246    if wired.is_empty() {
247        return table;
248    }
249    table.with_custom_actions(resource.url.clone(), wired)
250}
251
252/// Renders the branded in-region table failure of the resource at `slug` with a cursor-aware
253/// retry link.
254pub(crate) fn table_error_view<'a>(
255    cx: &'a Cx,
256    slug: &str,
257    plural_label: &crate::Text,
258    state: &TableState,
259    error: &topcoat::Error,
260    path: &str,
261) -> BoxView<'a> {
262    tracing::error!(resource = slug, error = %error, "table load failed");
263    let title = crate::t!(cx, "tablo-list-failed", label = plural_label);
264    let retry_url = retry_url_for_error(state, error, path);
265    view! {
266        tablo_ui::error_state(
267            title: title,
268            detail: crate::t!(cx, "tablo-list-failed-description"),
269            action: Some(
270                view! {
271                    <a (crate::navigation::runtime_link(cx, &retry_url))>
272                        (crate::t!(cx, "tablo-list-retry"))
273                    </a>
274                }
275                    .boxed()
276                    .into(),
277            ),
278            attrs: attributes! { role="alert" }
279        )
280    }
281    .boxed()
282}
283
284/// Renders the list page header titled `plural_label`, with the header `actions`, a CSV export
285/// link to `export_url`, an Import link to `import_url` and a Create link to `create_url`.
286fn list_header<'a>(
287    cx: &'a Cx,
288    plural_label: &crate::Text,
289    label: &crate::Text,
290    actions: ActionBar,
291    create_url: Option<String>,
292    import_url: Option<String>,
293    export_url: Option<String>,
294) -> BoxView<'a> {
295    let actions = actions.render(cx);
296    let title = plural_label.clone();
297    let create_label = crate::t!(cx, "tablo-form-create-title", label = label);
298    let outline =
299        tablo_ui::button_variants(tablo_ui::ButtonVariant::Outline, tablo_ui::ButtonSize::Md);
300    let export_class = outline.clone();
301    view! {
302        tablo_ui::page_header(
303            tablo_ui::page_title((title))
304            tablo_ui::page_actions(
305                (actions)
306                if let Some(url) = export_url {
307                    <a
308                        href=(url)
309                        class=(export_class)
310                        data-slot="button"
311                        data-tone="outline"
312                    >
313                        icon(data: tablo_ui::icons::DOWNLOAD)
314                        (crate::t!(cx, "tablo-list-export"))
315                    </a>
316                }
317                if let Some(url) = import_url {
318                    <a
319                        (crate::navigation::runtime_link(cx, &url))
320                        class=(outline)
321                        data-slot="button"
322                        data-tone="outline"
323                    >
324                        icon(data: tablo_ui::icons::UPLOAD)
325                        (crate::t!(cx, "tablo-list-import"))
326                    </a>
327                }
328                if let Some(url) = create_url {
329                    <a
330                        id="tablo-header-create"
331                        (crate::navigation::runtime_link(cx, &url))
332                        class=(tablo_ui::button_variants(
333                            tablo_ui::ButtonVariant::Primary,
334                            tablo_ui::ButtonSize::Md,
335                        ))
336                        data-slot="button"
337                        data-tone="primary"
338                    >
339                        icon(data: tablo_ui::icons::PLUS)
340                        (create_label)
341                    </a>
342                }
343            )
344        )
345    }
346    .boxed()
347}
348
349/// Serves the list page every declared [`Resource`] gets at `{prefix}/{slug}`.
350///
351/// The page reads the table's state from its signals, so a change in the browser reruns it in
352/// place; a rerun waits for the rows instead of flashing the skeleton.
353pub(crate) fn resource_list<R: Resource>(cx: &Cx, _body: Body) -> BoxView<'_> {
354    async_page(async move {
355        let resource = gate::<R>(cx)?;
356        if !resource.can(cx, Ability::ViewAny) {
357            return Err(forbidden().into());
358        }
359        crate::csrf::ensure_token(cx);
360        // Normalizes once per request.
361        let table = choose_columns(cx, &resource, wire_table_actions(cx, &resource)).await;
362        let (signals, state) = table.browser_state(cx);
363        ShownList::record::<R>(cx, &state);
364        // The bulk bar offers what the rows the trash control shows can take.
365        let table = table
366            .taking(resource.list_trashed(&state))
367            .selecting_matching();
368        // A write lands back on the list as the reader left it.
369        let back = state.without_cursor(&resource.url);
370        let badges = resource.header_action_badges(cx).await;
371        let mut actions = header_bar(
372            cx,
373            &resource.url,
374            &resource.header_actions,
375            |action| {
376                resource.can(
377                    cx,
378                    Ability::RunHeader {
379                        action: action.name,
380                    },
381                )
382            },
383            &badges,
384        );
385        let table = if back == resource.url {
386            table
387        } else {
388            actions = actions.returning_to(&back);
389            table.returning_to(back)
390        };
391        let skeleton = table.render_skeleton(cx, &state).await?;
392        let creates = resource.pages.create && resource.can_create(cx);
393        let create_url = creates.then(|| create_page_url(&resource.url));
394        let import_url = (creates && resource.imports).then(|| import_url(&resource.url));
395        let export_url = resource
396            .can(cx, Ability::Export)
397            .then(|| state.first_page(&export_url(&resource.url)));
398        let header = list_header(
399            cx,
400            &resource.plural_label,
401            &resource.label,
402            actions,
403            create_url,
404            import_url,
405            export_url,
406        );
407        let widgets = super::widgets::rendered_grid(cx, &resource.list_widgets).await?;
408        let mode = rerun_suspense_mode(cx);
409        let lazy_rows = ThenView::new(async move {
410            let list_path = &resource.url;
411            let rendered = async {
412                let page = load_table_page(cx, &resource, &table, &state).await?;
413                table
414                    .render_page(cx, page, &state, list_path, &signals)
415                    .await
416            };
417            match rendered.await {
418                Ok(view) => Ok(view),
419                Err(error) => Ok(table_error_view(
420                    cx,
421                    &resource.slug,
422                    &resource.plural_label,
423                    &state,
424                    &error,
425                    list_path,
426                )),
427            }
428        });
429        Ok(list_page(
430            cx,
431            ListPage {
432                header,
433                widgets,
434                skeleton,
435                mode,
436                rows: lazy_rows.boxed(),
437            },
438        ))
439    })
440}
441
442/// What the list page shows, resolved from the resource.
443struct ListPage<'a> {
444    header: BoxView<'a>,
445    /// The [`ResourceDef::list_widget`](crate::ResourceDef::list_widget) grid.
446    widgets: BoxView<'a>,
447    /// What shows while the rows load.
448    skeleton: BoxView<'a>,
449    mode: SuspenseMode,
450    rows: BoxView<'a>,
451}
452
453/// Renders the list page: `header` over the widgets and the `rows`, behind `skeleton` while they
454/// load.
455fn list_page<'a>(cx: &'a Cx, page: ListPage<'a>) -> BoxView<'a> {
456    let ListPage {
457        header,
458        widgets,
459        skeleton,
460        mode,
461        rows,
462    } = page;
463    view! {
464        tablo_ui::page(
465            (header)
466            tablo_ui::page_content(
467                <div class="flex flex-col gap-4">
468                    (widgets)
469                    suspense(fallback: skeleton, mode: mode, (rows))
470                </div>
471            )
472        )
473    }
474    .boxed()
475}
476
477/// How a list's `suspense` loads: streamed behind its skeleton on the first render, and waited
478/// for on a rerun, which updates the page in place.
479fn rerun_suspense_mode(cx: &Cx) -> SuspenseMode {
480    if original_method(cx) == http::Method::POST {
481        SuspenseMode::Wait
482    } else {
483        SuspenseMode::Stream
484    }
485}
486
487/// Loads `R`'s list page for `state` from the tenant-scoped query, admitting the records its
488/// trash control selects.
489pub(crate) async fn load_table_page<R: Resource>(
490    cx: &Cx,
491    resource: &Mounted<R>,
492    table: &Table<R::Model>,
493    state: &TableState,
494) -> Result<TablePage<R::Model>> {
495    TablePage::load(cx, table, resource.list_query(cx, state)?, state).await
496}
497
498/// Loads [`load_table_page`] over the rows `scope` admits.
499pub(crate) async fn load_scoped_page<R: Resource>(
500    cx: &Cx,
501    resource: &Mounted<R>,
502    table: &Table<R::Model>,
503    state: &TableState,
504    scope: toasty::stmt::Expr<bool>,
505) -> Result<TablePage<R::Model>> {
506    let query = resource.list_query(cx, state)?.filter(scope);
507    TablePage::load(cx, table, query, state).await
508}
509
510#[cfg(test)]
511mod tests;