tablo_core/table.rs
1//! A resource's list view: the [`Table`] builder and its columns and filters, the URL state a list
2//! reads, query planning (`filter_expr`/`search_expr`/`order_bys_for`), the page a table loads, and
3//! CSV export.
4//!
5//! A column renders its own cell and a filter its own control. What a request wires onto a table
6//! and the list page around it belong to the panel: [`WiredTable`](crate::panel::WiredTable).
7
8use std::{num::NonZeroUsize, sync::Arc};
9
10use derive_where::derive_where;
11use toasty::stmt::List;
12use topcoat::context::Cx;
13
14use self::filter::BoxFilter;
15pub(crate) use self::{applied::ignored_reason, choice::ColumnChoice};
16use crate::DeclarationErrorKind;
17pub(crate) use crate::column::{BoxColumn, Column, include_relations, restrict_relations};
18
19mod applied;
20mod choice;
21mod export;
22pub(crate) mod filter;
23mod group;
24mod mask;
25pub(crate) mod model;
26mod page;
27mod row_color;
28mod row_link;
29mod search;
30mod sort;
31mod state;
32mod summary;
33mod tab;
34
35use self::sort::FieldOrder;
36pub use self::{
37 filter::{
38 DateFilter, FilterValue, IntoFilters, NumberFilter, PresenceFilter, QueryFilter,
39 SelectFilter, TernaryFilter, TextFilter, TextMatch,
40 },
41 model::{FieldColumn, PanelModel},
42 page::{DEFAULT_PAGE_SIZE, DEFAULT_PER_PAGE_OPTIONS, PagePosition, Pagination, TablePage},
43 row_link::RowLink,
44 state::{Cursor, Sort, TableState},
45 summary::Summary,
46 tab::ListTab,
47};
48pub(crate) use self::{
49 group::GroupDef,
50 state::{bulk_key, bulk_token, group_header_dom_id, query_of, request_query, row_dom_id},
51};
52pub(crate) use crate::{
53 column::{ColumnToggle, ColumnWidth, IntoColumns, contains_expr},
54 display::Alignment,
55};
56
57/// Where a table puts a row's actions: its custom actions, View, Edit and Delete.
58///
59/// ```rust
60/// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
61/// # struct Post { #[key] #[auto] id: uuid::Uuid, title: String }
62/// use tablo_core::{ActionLayout, Table, TextColumn, lens};
63///
64/// Table::new(TextColumn::new(lens!(Post.title))).action_layout(ActionLayout::Menu);
65/// ```
66#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
67#[non_exhaustive]
68pub enum ActionLayout {
69 /// Side by side at the end of the row: View, Edit and Delete as icons, a custom action by its
70 /// label.
71 #[default]
72 Inline,
73 /// In a menu behind one button at the end of the row, Delete last.
74 Menu,
75}
76
77/// Table description of a `Resource`'s list view declaring columns and how they map to queries.
78///
79/// A clone shares every column, filter and projection.
80///
81/// The list keeps its whole state in the URL: `?tab=` picks a [tab](ListTab), `?q=` searches,
82/// `?sort=` and `?dir=` sort, `?page=`, `?per_page=`, `?after=` and `?before=` page,
83/// `?f.<name>=` filters and `?group_by=` groups. Each row is keyed by its record's primary key,
84/// which the action URLs and bulk checkboxes carry; a composite key has no URL form, so its rows
85/// render without row actions or bulk selection.
86///
87/// - Search matches a row any searchable column contains the term in. It escapes `%` and `_`, trims
88/// the term and caps it at 128 characters, and matches case-insensitively: PostgreSQL runs it as
89/// `ILIKE`, SQLite (for ASCII) and MySQL (under its default collations) as `LIKE`.
90/// - Without a `?sort=` naming a sortable column, the rows sort by the
91/// [`default_sort`](Self::default_sort), else by the first sortable column, ascending. The
92/// primary key breaks ties, so a sort over duplicate values pages deterministically, and a page
93/// number past the last page reads as the last.
94/// - A filter that cannot apply, an unknown name, a value the filter rejects or one past the
95/// limits, is never dropped silently: the list shows a warning banner naming it, and the export
96/// answers 400. At most 32 filters apply, each with at most 64 values and parts, each name, part
97/// and value at most 256 bytes. Active filters combine with AND.
98/// - `?group_by=` groups the rows by one of the table's [groupings](Self::group_by), which orders
99/// them by its field ahead of the sort, so a group runs on across pages; one the table does not
100/// declare is ignored.
101/// - The list updates in place: a search, filter, sort or page reruns the page through the runtime,
102/// keeping focus and scroll, and without JavaScript its links and its search form load the page.
103/// A table that fails to load shows an error state with a retry link in place of the rows.
104///
105/// When the policy allows `DeleteAny`, or `RunAny` for an action placed on the bulk bar, the list
106/// adds a checkbox column and a bulk bar; a row that no delete or bulk action allows gets no
107/// checkbox. A bulk delete takes at most [`Limits::bulk_records`](crate::Limits::bulk_records), 400
108/// by default, runs in one transaction and skips the
109/// records the policy refuses `Delete`. Both deletes ask first through a confirmation dialog,
110/// which needs JavaScript; a POST not confirmed through it answers 400. Each lands back on the
111/// list as it was left.
112///
113/// # Export
114///
115/// `GET {list}/-/export` returns the list as a CSV file named `{slug}.csv`, with the current
116/// search, filters and sort applied and the relations the columns include loaded: the rows the
117/// list shows, each of them, whatever the policy answers `View` of it. It delivers at most
118/// [`Limits::export_rows`](crate::Limits::export_rows), 10,000 by default, and answers 413 rather
119/// than a truncated file when more match. It writes each column's formatted value, a date column's
120/// stored value, and escapes a cell a spreadsheet would read as a formula; `?bom=1` prefixes the
121/// file with a byte-order mark for Excel.
122///
123/// The policy is asked [`Export`](crate::Ability::Export) with `ViewAny`: refused, the list
124/// shows no Export button and the route answers 403. [`without_export`](Self::without_export)
125/// takes the button and the route away for every user.
126#[derive_where(Clone)]
127pub struct Table<M> {
128 columns: Vec<BoxColumn<M>>,
129 /// Misdeclarations a builder recorded ([`Self::declaration_errors`]).
130 misdeclared: Vec<DeclarationErrorKind>,
131 filters: Vec<BoxFilter<M>>,
132 groupings: Vec<GroupDef<M>>,
133 row_color: row_color::RowColor<M>,
134 row_links: Vec<RowLink<M>>,
135 tabs: Vec<ListTab<M>>,
136 summaries: Vec<Summary<M>>,
137 /// A row's key: its record's primary key, as its action URLs carry it.
138 key: fn(&M) -> String,
139 /// Whether a row's key resolves as a URL id; a composite key does not, so its rows carry no
140 /// action.
141 addressable: bool,
142 page_size: NonZeroUsize,
143 pagination: Pagination,
144 action_layout: ActionLayout,
145 /// The page sizes `?per_page=` may ask for, sorted; empty offers no choice.
146 per_page_options: Vec<usize>,
147 /// The sort a request naming no sortable column reads.
148 default_sort: Option<Sort>,
149 /// The field a [`default_sort`](Self::default_sort) orders by, which no sortable column
150 /// need show.
151 default_field: Option<FieldOrder>,
152 hide_search: bool,
153 hide_filter_menu: bool,
154 /// Whether the filter menu applies its controls only on its Apply button.
155 deferred_filters: bool,
156 /// Whether the list serves its CSV export.
157 exports: bool,
158}
159
160impl<M> std::fmt::Debug for Table<M> {
161 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
162 f.debug_struct("Table")
163 .field(
164 "columns",
165 &self.columns.iter().map(|c| c.name()).collect::<Vec<_>>(),
166 )
167 .field("filters", &self.filters.len())
168 .field(
169 "groupings",
170 &self
171 .groupings
172 .iter()
173 .map(GroupDef::name)
174 .collect::<Vec<_>>(),
175 )
176 .field(
177 "tabs",
178 &self.tabs.iter().map(ListTab::key).collect::<Vec<_>>(),
179 )
180 .field("page_size", &self.page_size)
181 .field("pagination", &self.pagination)
182 .field("default_sort", &self.default_sort)
183 .field("hide_search", &self.hide_search)
184 .field("hide_filter_menu", &self.hide_filter_menu)
185 .field("deferred_filters", &self.deferred_filters)
186 .field("exports", &self.exports)
187 .finish()
188 }
189}
190
191impl<M> Table<M> {
192 /// Declare a table of `cols`.
193 ///
194 /// Each row is keyed by its record's primary key, which the row's action URLs carry.
195 pub fn new(cols: impl IntoColumns<M>) -> Self
196 where
197 M: toasty::schema::Model + toasty::stmt::IntoExpr<M>,
198 {
199 Self {
200 columns: cols.into_columns(),
201 misdeclared: Vec::new(),
202 filters: Vec::new(),
203 groupings: Vec::new(),
204 row_color: row_color::RowColor::default(),
205 row_links: Vec::new(),
206 tabs: Vec::new(),
207 summaries: Vec::new(),
208 key: crate::toasty_compat::pk::pk_text::<M>,
209 addressable: !crate::toasty_compat::pk::pk_is_composite::<M>(),
210 page_size: DEFAULT_PAGE_SIZE,
211 pagination: Pagination::default(),
212 action_layout: ActionLayout::default(),
213 per_page_options: DEFAULT_PER_PAGE_OPTIONS.to_vec(),
214 default_sort: None,
215 default_field: None,
216 hide_search: false,
217 hide_filter_menu: false,
218 deferred_filters: false,
219 exports: true,
220 }
221 }
222
223 /// Append `column` after the declared ones.
224 pub fn column(mut self, column: impl Column<M> + 'static) -> Self {
225 self.columns.push(Arc::new(column));
226 self
227 }
228
229 /// Append `filters` after the declared ones, such as those a field's `#[columns(filter)]`
230 /// declares.
231 pub fn filters(mut self, filters: impl IntoFilters<M>) -> Self
232 where
233 M: toasty::schema::Model,
234 {
235 self.filters.extend(filters.into_filters());
236 self
237 }
238
239 /// Whether a reader may hide or show any of the columns.
240 pub(crate) fn has_toggleable_columns(&self) -> bool {
241 self.columns.iter().any(|c| c.toggle().is_toggleable())
242 }
243
244 /// The declared columns, in order.
245 pub(crate) fn declared_columns(&self) -> &[BoxColumn<M>] {
246 &self.columns
247 }
248
249 /// This table with only the columns `names` names, in that order, and no default sort on a
250 /// column it drops. A name it declares no column for picks none.
251 pub(crate) fn only(&self, names: &[String]) -> Self {
252 let mut table = self.clone();
253 table.columns = names
254 .iter()
255 .filter_map(|name| self.columns.iter().find(|column| column.name() == name))
256 .cloned()
257 .collect();
258 if table
259 .default_sort
260 .as_ref()
261 .is_some_and(|sort| !table.orders_by(sort))
262 {
263 table.default_sort = None;
264 }
265 table
266 }
267
268 /// Appends `filter` after the declared ones.
269 pub(crate) fn push_filter(&mut self, filter: BoxFilter<M>) {
270 self.filters.push(filter);
271 }
272
273 /// The declared filters, in order.
274 pub(crate) fn declared_filters(&self) -> &[BoxFilter<M>] {
275 &self.filters
276 }
277
278 /// Include every relation this table's columns declare, once each.
279 pub(crate) fn include_relations(
280 &self,
281 query: toasty::stmt::Query<List<M>>,
282 ) -> toasty::stmt::Query<List<M>>
283 where
284 M: toasty::schema::Model,
285 {
286 include_relations(query, &self.columns)
287 }
288
289 /// Whether [`Self::include_relations`] adds an include.
290 pub(crate) fn includes_relations(&self) -> bool {
291 self.columns
292 .iter()
293 .any(|column| !column.includes().into_vec().is_empty())
294 }
295
296 /// Have each closure over the row that declares it reads none of the row's relations, its row
297 /// color, its row links and its columns, read `bare(row)`, a copy of the row without them, when
298 /// a column loads one: the page's loads then cannot reach the closure.
299 pub(crate) fn read_bare(&mut self, bare: fn(&M) -> M)
300 where
301 M: toasty::schema::Model + 'static,
302 {
303 if !self.includes_relations() {
304 return;
305 }
306 self.bare_row_color(bare);
307 self.bare_row_links(bare);
308 self.columns = std::mem::take(&mut self.columns)
309 .into_iter()
310 .map(|column| crate::column::bare_column(column, bare))
311 .collect();
312 }
313
314 /// Check which related records `rows`, loaded through [`Self::include_relations`], hold that
315 /// the columns' sources show the user.
316 pub(crate) async fn restrict_relations(
317 &self,
318 cx: &topcoat::context::Cx,
319 rows: &[M],
320 ex: &mut dyn toasty::Executor,
321 ) -> topcoat::Result<()> {
322 restrict_relations(cx, &self.columns, rows, ex).await
323 }
324
325 /// Page through the rows as `pagination` says; [`Pagination::Pages`] by default.
326 pub fn pagination(mut self, pagination: Pagination) -> Self {
327 self.pagination = pagination;
328 self
329 }
330
331 /// Put a row's actions where `layout` says; [`ActionLayout::Inline`] by default.
332 pub fn action_layout(mut self, layout: ActionLayout) -> Self {
333 self.action_layout = layout;
334 self
335 }
336
337 /// The page sizes a reader may pick, beside the table's own; none offers no choice.
338 /// [`DEFAULT_PER_PAGE_OPTIONS`] by default. A cursor table offers none.
339 pub fn per_page_options(mut self, options: impl IntoIterator<Item = usize>) -> Self {
340 self.per_page_options = options.into_iter().filter(|size| *size > 0).collect();
341 self
342 }
343
344 /// Show `size` rows a page; [`DEFAULT_PAGE_SIZE`] by default.
345 pub fn page_size(mut self, size: usize) -> Self {
346 match NonZeroUsize::new(size) {
347 Some(size) => self.page_size = size,
348 None => self.misdeclared.push(DeclarationErrorKind::ZeroPageSize),
349 }
350 self
351 }
352
353 /// The columns and filters reading a source the context's panel cannot load from.
354 pub(crate) fn unavailable_sources(
355 &self,
356 cx: &topcoat::context::Cx,
357 ) -> Vec<DeclarationErrorKind> {
358 let mut errors = crate::column::unavailable_sources(cx, self.columns.iter().map(|c| &**c));
359 errors.extend(self.filters.iter().filter_map(|filter| {
360 filter.internals().unavailable_source(cx).map(|source| {
361 DeclarationErrorKind::UnregisteredOptionSource {
362 field: filter.name().to_string(),
363 source,
364 }
365 })
366 }));
367 errors
368 }
369
370 /// What is wrong with this declaration.
371 pub fn declaration_errors(&self) -> Vec<DeclarationErrorKind> {
372 let mut errors = self.misdeclared.clone();
373 errors.extend(self.grouping_errors());
374 errors.extend(self.tab_errors());
375 if self.columns.is_empty() {
376 errors.push(DeclarationErrorKind::NoColumns);
377 }
378 if let Some(sort) = &self.default_sort
379 && !self.orders_by(sort)
380 {
381 errors.push(DeclarationErrorKind::UnsortableDefaultSort {
382 column: sort.column.clone(),
383 });
384 }
385 let mut seen = std::collections::HashSet::with_capacity(self.columns.len());
386 for column in &self.columns {
387 match column.internals().misdeclared() {
388 Some(error) => errors.push(error),
389 None if !seen.insert(column.name()) => {
390 errors.push(DeclarationErrorKind::DuplicateColumn {
391 name: column.name().to_string(),
392 });
393 }
394 None => {}
395 }
396 }
397 let mut seen = std::collections::HashSet::with_capacity(self.filters.len());
398 for filter in &self.filters {
399 match filter.internals().misdeclared() {
400 Some(error) => errors.push(error),
401 None if filter.name().contains('.') => {
402 errors.push(DeclarationErrorKind::DottedFilterName {
403 name: filter.name().to_string(),
404 });
405 }
406 None if !seen.insert(filter.name()) => {
407 errors.push(DeclarationErrorKind::DuplicateFilter {
408 name: filter.name().to_string(),
409 });
410 }
411 None => {}
412 }
413 }
414 errors
415 }
416
417 /// The rows a page shows, as [`Self::page_size`] set them.
418 pub fn per_page(&self) -> usize {
419 self.page_size.get()
420 }
421
422 /// How the table pages.
423 pub(crate) fn pagination_mode(&self) -> Pagination {
424 self.pagination
425 }
426
427 /// Where the table puts a row's actions.
428 pub(crate) fn row_action_layout(&self) -> ActionLayout {
429 self.action_layout
430 }
431
432 /// The page sizes the reader may pick, sorted, the table's own among them; empty when it
433 /// offers no choice.
434 pub(crate) fn page_sizes(&self) -> Vec<usize> {
435 if self.per_page_options.is_empty() || self.pagination == Pagination::Cursor {
436 return Vec::new();
437 }
438 let mut sizes = self.per_page_options.clone();
439 sizes.push(self.per_page());
440 sizes.sort_unstable();
441 sizes.dedup();
442 sizes
443 }
444
445 /// The page size `state` reads at: its `?per_page=` when the table offers it, else the
446 /// table's own.
447 pub(crate) fn page_size_for(&self, state: &TableState) -> usize {
448 state
449 .per_page
450 .and_then(|asked| usize::try_from(asked).ok())
451 .filter(|asked| self.page_sizes().contains(asked))
452 .unwrap_or_else(|| self.per_page())
453 }
454
455 /// The key of `record`'s row: its primary key's URL id.
456 pub(crate) fn key_of(&self, record: &M) -> String {
457 (self.key)(record)
458 }
459
460 /// Each column's name, label and text for `record`, as the export spells them.
461 pub(crate) fn spell(&self, cx: &Cx, record: &M) -> Vec<(String, crate::Text, String)> {
462 self.columns
463 .iter()
464 .map(|column| {
465 (
466 column.name().to_string(),
467 column.label(),
468 column.text(cx, record),
469 )
470 })
471 .collect()
472 }
473
474 /// Whether a row's key resolves as a URL id, so its record's actions have a route.
475 pub(crate) fn is_addressable(&self) -> bool {
476 self.addressable
477 }
478
479 /// Render no search toolbar in the table.
480 pub fn hide_search(mut self) -> Self {
481 self.hide_search = true;
482 self
483 }
484
485 /// Render no filter menu in the table's toolbar.
486 pub fn hide_filter_menu(mut self) -> Self {
487 self.hide_filter_menu = true;
488 self
489 }
490
491 /// Apply the filter menu's controls only when its Apply button is pressed, rather than as each
492 /// one changes, so a reader sets several filters before the list reruns once. A search, a
493 /// sort or a tab applies the controls as they stand too, since the toolbar's form carries
494 /// them.
495 pub fn deferred_filters(mut self) -> Self {
496 self.deferred_filters = true;
497 self
498 }
499
500 /// Serve no CSV export: the list shows no Export button and `{list}/-/export` answers 404,
501 /// whatever the policy answers [`Export`](crate::Ability::Export).
502 pub fn without_export(mut self) -> Self {
503 self.exports = false;
504 self
505 }
506
507 /// Whether the list serves its CSV export.
508 pub(crate) fn exports(&self) -> bool {
509 self.exports
510 }
511
512 /// Whether the filter menu applies its controls only on its Apply button.
513 pub(crate) fn filters_deferred(&self) -> bool {
514 self.deferred_filters
515 }
516
517 /// Apply this table's declaration to `query`: [`Self::narrow`], then the ordering.
518 pub(crate) fn apply_declaration(
519 &self,
520 cx: &Cx,
521 db: &toasty::Db,
522 query: toasty::stmt::Query<List<M>>,
523 state: &TableState,
524 refused: &[String],
525 ) -> toasty::stmt::Query<List<M>>
526 where
527 M: toasty::schema::Model,
528 {
529 self.order(self.narrow(cx, db, query, state, refused), state)
530 }
531
532 /// Narrow `query` to the rows `state`'s tab, search and filters select, but the `refused`
533 /// filters, unordered: what a count reads.
534 pub(crate) fn narrow(
535 &self,
536 cx: &Cx,
537 db: &toasty::Db,
538 query: toasty::stmt::Query<List<M>>,
539 state: &TableState,
540 refused: &[String],
541 ) -> toasty::stmt::Query<List<M>>
542 where
543 M: toasty::schema::Model,
544 {
545 self.narrow_tab(self.narrow_untabbed(cx, db, query, state, refused), state)
546 }
547
548 /// [`Self::narrow`] but the tab: what a tab's badge counts within.
549 fn narrow_untabbed(
550 &self,
551 cx: &Cx,
552 db: &toasty::Db,
553 mut query: toasty::stmt::Query<List<M>>,
554 state: &TableState,
555 refused: &[String],
556 ) -> toasty::stmt::Query<List<M>>
557 where
558 M: toasty::schema::Model,
559 {
560 if let Some(term) = &state.search
561 && let Some(expr) = self.search_expr(term)
562 {
563 query = query.filter(crate::toasty_compat::case_insensitive_search(db, expr));
564 }
565 if let Some(expr) = self.filter_expr(cx, state, refused) {
566 query = query.filter(expr);
567 }
568 query
569 }
570
571 /// Whether the declaration enables a filter menu.
572 pub(crate) fn filter_menu_enabled(&self) -> bool {
573 !self.hide_filter_menu && !self.filters.is_empty()
574 }
575}
576
577#[cfg(test)]
578mod tests;