1mod 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
42pub(crate) const COLUMN_FIELD: &str = "column";
44
45pub(crate) const RESET_FIELD: &str = "reset";
47
48pub(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
62pub(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
72pub(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
87pub(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
114pub 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
128pub(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
136pub(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
145pub(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 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 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
189fn 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 if wired.is_empty() {
247 return table;
248 }
249 table.with_custom_actions(resource.url.clone(), wired)
250}
251
252pub(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
284fn 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
349pub(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 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 let table = table
366 .taking(resource.list_trashed(&state))
367 .selecting_matching();
368 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
442struct ListPage<'a> {
444 header: BoxView<'a>,
445 widgets: BoxView<'a>,
447 skeleton: BoxView<'a>,
449 mode: SuspenseMode,
450 rows: BoxView<'a>,
451}
452
453fn 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
477fn 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
487pub(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
498pub(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;