Skip to main content

ignite_core/
list.rs

1//! The list page's tabs and column badges, as Filament's `getTabs()` on a List page and
2//! `badge()` with `color()` on a text column.
3//!
4//! A [`Tab`] has a key (the value of the list's `tab` query parameter, as Filament's
5//! `#[Url(as: 'tab')]`), a label and a [`ListFilter`]: conditions on the resource's rows, as
6//! Filament's `modifyQueryUsing()`. The panel gives the active tab's filter to the resource's
7//! list query in [`ListQuery::filter`](crate::ListQuery::filter), beside the search and sort,
8//! and shows the number of rows each tab matches beside its label, for the current search.
9//!
10//! ```ignore
11//! RuntimeResource::new("posts", "Posts", "Post", PostData)
12//!     .tab(Tab::make("all"))
13//!     .tab(Tab::make("drafts").where_eq("status", "draft"))
14//!     .badge_color("status", |state| match state {
15//!         "draft" => BadgeColor::Gray,
16//!         "publish" => BadgeColor::Success,
17//!         _ => BadgeColor::Primary,
18//!     });
19//! ```
20
21use std::collections::{BTreeMap, BTreeSet};
22use std::fmt;
23use std::sync::Arc;
24
25use serde_json::Value;
26
27use crate::runtime_resource::Row;
28
29/// One condition of a [`ListFilter`] on a column of the resource's rows. Each value is JSON,
30/// as a runtime resource's [`Row`] holds it: a string, a number, a boolean or `null`.
31#[derive(Debug, Clone, PartialEq, Eq)]
32#[non_exhaustive]
33pub enum FilterCondition {
34    /// `column = value`, as Laravel's `where($column, $value)`. A `null` value is `IS NULL`.
35    Eq(String, Value),
36    /// `column != value`, as Laravel's `where($column, '!=', $value)`. A row whose column is
37    /// NULL does not match, as in SQL. A `null` value is `IS NOT NULL`.
38    Ne(String, Value),
39    /// `column IN (values)`, as Laravel's `whereIn()`. An empty list matches no rows.
40    In(String, Vec<Value>),
41    /// `column IS NULL`, as Laravel's `whereNull()`.
42    Null(String),
43    /// `column IS NOT NULL`, as Laravel's `whereNotNull()`.
44    NotNull(String),
45}
46
47/// Conditions on a resource's rows, all of which a row must meet: the query of a [`Tab`], as
48/// Filament's `modifyQueryUsing()`. An empty filter matches every row.
49///
50/// `#[derive(IgniteResource)]` applies it in its list query. A resource that writes its own
51/// `list` (or a [`RuntimeData`](crate::RuntimeData)) applies it with [`apply`](Self::apply) on
52/// an Orbit query, or [`matches`](Self::matches) on a row, or reads its
53/// [`conditions`](Self::conditions).
54#[derive(Debug, Clone, Default, PartialEq, Eq)]
55pub struct ListFilter {
56    conditions: Vec<FilterCondition>,
57}
58
59impl ListFilter {
60    /// A filter with no conditions: it matches every row.
61    pub fn new() -> Self {
62        ListFilter::default()
63    }
64
65    /// Adds `column = value`.
66    pub fn where_eq(mut self, column: impl Into<String>, value: impl Into<Value>) -> Self {
67        self.conditions
68            .push(FilterCondition::Eq(column.into(), value.into()));
69        self
70    }
71
72    /// Adds `column != value`.
73    pub fn where_ne(mut self, column: impl Into<String>, value: impl Into<Value>) -> Self {
74        self.conditions
75            .push(FilterCondition::Ne(column.into(), value.into()));
76        self
77    }
78
79    /// Adds `column IN (values)`.
80    pub fn where_in<V: Into<Value>>(
81        mut self,
82        column: impl Into<String>,
83        values: impl IntoIterator<Item = V>,
84    ) -> Self {
85        self.conditions.push(FilterCondition::In(
86            column.into(),
87            values.into_iter().map(Into::into).collect(),
88        ));
89        self
90    }
91
92    /// Adds `column IS NULL`.
93    pub fn where_null(mut self, column: impl Into<String>) -> Self {
94        self.conditions.push(FilterCondition::Null(column.into()));
95        self
96    }
97
98    /// Adds `column IS NOT NULL`.
99    pub fn where_not_null(mut self, column: impl Into<String>) -> Self {
100        self.conditions
101            .push(FilterCondition::NotNull(column.into()));
102        self
103    }
104
105    /// Whether the filter has no conditions.
106    pub fn is_empty(&self) -> bool {
107        self.conditions.is_empty()
108    }
109
110    /// The conditions, in the order they were added.
111    pub fn conditions(&self) -> &[FilterCondition] {
112        &self.conditions
113    }
114
115    /// Adds the conditions to an Orbit query, joined with `AND`.
116    pub fn apply<M: orbit_orm::Model>(&self, query: orbit_orm::Query<M>) -> orbit_orm::Query<M> {
117        self.conditions
118            .iter()
119            .fold(query, |query, condition| match condition {
120                FilterCondition::Eq(column, value) => query.where_eq(column, orbit_value(value)),
121                FilterCondition::Ne(column, Value::Null) => query.where_not_null(column),
122                FilterCondition::Ne(column, value) => {
123                    query.where_op(column, orbit_orm::Operator::Ne, orbit_value(value))
124                }
125                FilterCondition::In(column, values) => {
126                    query.where_in(column, values.iter().map(orbit_value))
127                }
128                FilterCondition::Null(column) => query.where_null(column),
129                FilterCondition::NotNull(column) => query.where_not_null(column),
130            })
131    }
132
133    /// Whether `row` meets every condition, as the database would answer: a missing key is
134    /// NULL, and a NULL column is neither equal nor unequal to a value.
135    pub fn matches(&self, row: &Row) -> bool {
136        self.conditions.iter().all(|condition| {
137            let get = |column: &str| row.get(column).filter(|v| !v.is_null());
138            match condition {
139                FilterCondition::Eq(column, Value::Null) | FilterCondition::Null(column) => {
140                    get(column).is_none()
141                }
142                FilterCondition::Ne(column, Value::Null) | FilterCondition::NotNull(column) => {
143                    get(column).is_some()
144                }
145                FilterCondition::Eq(column, value) => get(column) == Some(value),
146                FilterCondition::Ne(column, value) => get(column).is_some_and(|v| v != value),
147                FilterCondition::In(column, values) => {
148                    get(column).is_some_and(|v| values.contains(v))
149                }
150            }
151        })
152    }
153}
154
155/// A JSON value as an Orbit value: arrays and objects as their JSON text.
156fn orbit_value(value: &Value) -> orbit_orm::Value {
157    match value {
158        Value::Null => orbit_orm::Value::Null,
159        Value::Bool(b) => orbit_orm::Value::Bool(*b),
160        Value::Number(n) => match (n.as_i64(), n.as_u64(), n.as_f64()) {
161            (Some(i), _, _) => orbit_orm::Value::Int(i),
162            (None, Some(u), _) => orbit_orm::Value::UInt(u),
163            (None, None, Some(f)) => orbit_orm::Value::Float(f),
164            _ => orbit_orm::Value::Text(n.to_string()),
165        },
166        Value::String(s) => orbit_orm::Value::Text(s.clone()),
167        other => orbit_orm::Value::Text(other.to_string()),
168    }
169}
170
171/// One tab of a resource's list page, as Filament's `Tab::make()` in `getTabs()`: a key, a
172/// label and the conditions the tab's rows meet. The panel shows the number of rows the tab
173/// matches beside its label, as in "Drafts (3)", counted for the current search.
174#[derive(Debug, Clone, PartialEq, Eq)]
175pub struct Tab {
176    /// The tab's key: the value of the list's `tab` query parameter, as Filament's array key
177    /// in `getTabs()`.
178    pub key: String,
179    /// The label. [`make`](Self::make) generates it from the key, as Filament does.
180    pub label: String,
181    /// The conditions the tab's rows meet. An empty filter, as for an "All" tab, matches
182    /// every row.
183    pub filter: ListFilter,
184}
185
186impl Tab {
187    /// A tab with the key `key`, no conditions, and the label Filament generates from the key:
188    /// `_` and `-` become spaces and the first letter is upper case, so `"needs_review"` is
189    /// "Needs review".
190    pub fn make(key: impl Into<String>) -> Self {
191        let key = key.into();
192        let label = generate_label(&key);
193        Tab {
194            key,
195            label,
196            filter: ListFilter::new(),
197        }
198    }
199
200    /// Sets the label, as `Tab::make('Label')`.
201    pub fn label(mut self, label: impl Into<String>) -> Self {
202        self.label = label.into();
203        self
204    }
205
206    /// Sets the tab's conditions, as Filament's `modifyQueryUsing()`.
207    pub fn filter(mut self, filter: ListFilter) -> Self {
208        self.filter = filter;
209        self
210    }
211
212    /// Adds `column = value` to the tab's conditions, as
213    /// `modifyQueryUsing(fn ($query) => $query->where($column, $value))`.
214    pub fn where_eq(mut self, column: impl Into<String>, value: impl Into<Value>) -> Self {
215        self.filter = self.filter.where_eq(column, value);
216        self
217    }
218
219    /// Adds `column != value` to the tab's conditions.
220    pub fn where_ne(mut self, column: impl Into<String>, value: impl Into<Value>) -> Self {
221        self.filter = self.filter.where_ne(column, value);
222        self
223    }
224
225    /// Adds `column IN (values)` to the tab's conditions.
226    pub fn where_in<V: Into<Value>>(
227        mut self,
228        column: impl Into<String>,
229        values: impl IntoIterator<Item = V>,
230    ) -> Self {
231        self.filter = self.filter.where_in(column, values);
232        self
233    }
234
235    /// Adds `column IS NULL` to the tab's conditions.
236    pub fn where_null(mut self, column: impl Into<String>) -> Self {
237        self.filter = self.filter.where_null(column);
238        self
239    }
240
241    /// Adds `column IS NOT NULL` to the tab's conditions.
242    pub fn where_not_null(mut self, column: impl Into<String>) -> Self {
243        self.filter = self.filter.where_not_null(column);
244        self
245    }
246}
247
248/// Filament's `generateTabLabel()`: `_` and `-` become spaces, and the first letter is upper
249/// case.
250fn generate_label(key: &str) -> String {
251    let spaced = key.replace(['_', '-'], " ");
252    let mut chars = spaced.chars();
253    match chars.next() {
254        Some(first) => first.to_uppercase().chain(chars).collect(),
255        None => String::new(),
256    }
257}
258
259/// The tab a list request shows, as Filament's `$activeTab`: the `requested` key when it is
260/// one of `tabs`; with no key, the `default` key when it is one of `tabs`, or the first tab,
261/// as Filament's `getDefaultActiveTab()`. A requested key that is not a tab shows no tab:
262/// the list is not filtered, as Filament ignores an unknown `activeTab`.
263pub fn active_tab<'a>(
264    tabs: &'a [Tab],
265    requested: Option<&str>,
266    default: Option<&str>,
267) -> Option<&'a Tab> {
268    let find = |key: &str| tabs.iter().find(|tab| tab.key == key);
269    match requested.filter(|key| !key.is_empty()) {
270        Some(key) => find(key),
271        None => default.and_then(find).or_else(|| tabs.first()),
272    }
273}
274
275/// The colour of a badge, by the names Filament gives its colours.
276#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
277pub enum BadgeColor {
278    /// A neutral grey, as for a draft.
279    Gray,
280    /// Information, in blue.
281    Info,
282    /// Success, in green.
283    Success,
284    /// A warning, in amber.
285    Warning,
286    /// Danger, in red.
287    Danger,
288    /// The panel's primary colour: a badge's default, as in Filament.
289    Primary,
290}
291
292impl BadgeColor {
293    /// The colour's name, as Filament spells it: `"gray"`, `"info"`, `"success"`,
294    /// `"warning"`, `"danger"` or `"primary"`.
295    pub fn as_str(self) -> &'static str {
296        match self {
297            BadgeColor::Gray => "gray",
298            BadgeColor::Info => "info",
299            BadgeColor::Success => "success",
300            BadgeColor::Warning => "warning",
301            BadgeColor::Danger => "danger",
302            BadgeColor::Primary => "primary",
303        }
304    }
305}
306
307/// How a badge column picks its colour from the cell's state.
308type ColorRule = Arc<dyn Fn(&str) -> BadgeColor + Send + Sync>;
309
310/// One badge column: its colour rule, the column whose cell shows it, and the tabs it shows on.
311#[derive(Clone, Default)]
312struct Badge {
313    color: Option<ColorRule>,
314    inside: Option<String>,
315    tabs: Option<Vec<String>>,
316}
317
318/// The list columns that show their value as a coloured badge, by column key, as Filament's
319/// `TextColumn::make($key)->badge()->color(fn (string $state) => ...)`. A column that is not
320/// listed shows its value as plain text.
321///
322/// A badge can also show inside another column's cell, after its text, instead of in a column
323/// of its own ([`badge_inside`](Self::badge_inside)), such as a post's status beside its
324/// title; and only on some tabs of the list ([`badge_on_tabs`](Self::badge_on_tabs)). The
325/// panel decides both when it renders the page, so the page needs no script for them.
326#[derive(Clone, Default)]
327pub struct ColumnBadges {
328    columns: BTreeMap<String, Badge>,
329}
330
331impl fmt::Debug for ColumnBadges {
332    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
333        f.debug_struct("ColumnBadges")
334            .field("columns", &self.columns.keys().collect::<BTreeSet<_>>())
335            .finish()
336    }
337}
338
339impl ColumnBadges {
340    /// No badge columns.
341    pub fn new() -> Self {
342        ColumnBadges::default()
343    }
344
345    /// Shows the column `column` as a badge in the primary colour, as Filament's `->badge()`
346    /// with no `color()`.
347    pub fn badge(mut self, column: impl Into<String>) -> Self {
348        self.columns.entry(column.into()).or_default().color = None;
349        self
350    }
351
352    /// Shows the column `column` as a badge whose colour `color` picks from the cell's state,
353    /// as Filament's `->badge()->color(fn (string $state): string => match ($state) { ... })`.
354    /// The state is the stored value as text, such as `"draft"`, before a select's or a
355    /// lookup's label replaces it for display.
356    pub fn badge_color(
357        mut self,
358        column: impl Into<String>,
359        color: impl Fn(&str) -> BadgeColor + Send + Sync + 'static,
360    ) -> Self {
361        self.columns.entry(column.into()).or_default().color = Some(Arc::new(color));
362        self
363    }
364
365    /// Shows the badge of the column `column` inside the cell of the column `target`, after
366    /// its text, and not as a column of its own: the list has no column for `column`, even
367    /// when the resource lists it. `column` need not be a list column: its value is read from
368    /// the row. It is a badge in the primary colour unless [`badge_color`](Self::badge_color)
369    /// gives it a colour.
370    pub fn badge_inside(mut self, column: impl Into<String>, target: impl Into<String>) -> Self {
371        self.columns.entry(column.into()).or_default().inside = Some(target.into());
372        self
373    }
374
375    /// Shows the badge of the column `column` only on the list's tabs `tabs`, by key, as a
376    /// Filament column's `visible()` that reads the active tab. On another tab, or on a list
377    /// with no tab active, the badge is not rendered: a badge column is left out of the table,
378    /// heading and all, and a badge inside another cell is left out of the cell.
379    pub fn badge_on_tabs<S: Into<String>>(
380        mut self,
381        column: impl Into<String>,
382        tabs: impl IntoIterator<Item = S>,
383    ) -> Self {
384        self.columns.entry(column.into()).or_default().tabs =
385            Some(tabs.into_iter().map(Into::into).collect());
386        self
387    }
388
389    /// Whether no column is a badge.
390    pub fn is_empty(&self) -> bool {
391        self.columns.is_empty()
392    }
393
394    /// Whether the column `column` is a badge.
395    pub fn is_badge(&self, column: &str) -> bool {
396        self.columns.contains_key(column)
397    }
398
399    /// The colour of the badge of the column `column` for `state`, or `None` when the column
400    /// is not a badge.
401    pub fn color(&self, column: &str, state: &str) -> Option<BadgeColor> {
402        self.columns.get(column).map(|badge| {
403            badge
404                .color
405                .as_ref()
406                .map_or(BadgeColor::Primary, |rule| rule(state))
407        })
408    }
409
410    /// The column whose cell shows the badge of `column`, if it shows inside another cell.
411    pub fn inside_of(&self, column: &str) -> Option<&str> {
412        self.columns.get(column)?.inside.as_deref()
413    }
414
415    /// The badge columns shown inside the cell of `target`, in key order.
416    pub fn inside(&self, target: &str) -> Vec<&str> {
417        self.columns
418            .iter()
419            .filter(|(_, badge)| badge.inside.as_deref() == Some(target))
420            .map(|(column, _)| column.as_str())
421            .collect()
422    }
423
424    /// Whether the badge of `column` shows when the tab `tab` is active (`None` for none): a
425    /// badge without [`badge_on_tabs`](Self::badge_on_tabs) shows on every tab. A column that
426    /// is not a badge shows.
427    pub fn shows_on(&self, column: &str, tab: Option<&str>) -> bool {
428        match self
429            .columns
430            .get(column)
431            .and_then(|badge| badge.tabs.as_ref())
432        {
433            None => true,
434            Some(tabs) => tab.is_some_and(|tab| tabs.iter().any(|key| key == tab)),
435        }
436    }
437}
438
439#[cfg(test)]
440mod tests {
441    use super::*;
442    use serde_json::json;
443
444    fn row(value: Value) -> Row {
445        value.as_object().cloned().unwrap()
446    }
447
448    #[test]
449    fn a_tab_label_is_generated_from_its_key_as_filament_does() {
450        assert_eq!(Tab::make("needs_review").label, "Needs review");
451        assert_eq!(Tab::make("all-posts").label, "All posts");
452        assert_eq!(Tab::make("drafts").label("My drafts").label, "My drafts");
453    }
454
455    #[test]
456    fn the_active_tab_is_the_requested_one_or_the_default_or_the_first() {
457        let tabs = [Tab::make("all"), Tab::make("drafts")];
458        assert_eq!(
459            active_tab(&tabs, Some("drafts"), None).unwrap().key,
460            "drafts"
461        );
462        assert_eq!(active_tab(&tabs, None, None).unwrap().key, "all");
463        assert_eq!(
464            active_tab(&tabs, Some(""), Some("drafts")).unwrap().key,
465            "drafts"
466        );
467        assert_eq!(active_tab(&tabs, None, Some("missing")).unwrap().key, "all");
468        assert!(active_tab(&tabs, Some("missing"), None).is_none());
469        assert!(active_tab(&[], None, None).is_none());
470    }
471
472    #[test]
473    fn a_filter_matches_rows_as_the_database_would() {
474        let draft = row(json!({"status": "draft", "author": null, "id": 3}));
475        let published = row(json!({"status": "publish", "author": 1, "id": 4}));
476        let drafts = ListFilter::new().where_eq("status", "draft");
477        assert!(drafts.matches(&draft));
478        assert!(!drafts.matches(&published));
479        assert!(ListFilter::new().where_null("author").matches(&draft));
480        assert!(ListFilter::new()
481            .where_not_null("author")
482            .matches(&published));
483        assert!(!ListFilter::new().where_ne("author", 2).matches(&draft));
484        assert!(ListFilter::new().where_ne("author", 2).matches(&published));
485        assert!(ListFilter::new().where_in("id", [3, 5]).matches(&draft));
486        assert!(!ListFilter::new()
487            .where_in("id", Vec::<i64>::new())
488            .matches(&draft));
489        assert!(ListFilter::new().matches(&published));
490    }
491
492    #[test]
493    fn a_badge_column_takes_its_colour_from_the_state() {
494        let badges = ColumnBadges::new()
495            .badge("kind")
496            .badge_color("status", |state| match state {
497                "draft" => BadgeColor::Gray,
498                _ => BadgeColor::Success,
499            });
500        assert_eq!(badges.color("status", "draft"), Some(BadgeColor::Gray));
501        assert_eq!(badges.color("status", "publish"), Some(BadgeColor::Success));
502        assert_eq!(badges.color("kind", "x"), Some(BadgeColor::Primary));
503        assert_eq!(badges.color("title", "x"), None);
504        assert_eq!(BadgeColor::Danger.as_str(), "danger");
505    }
506
507    #[test]
508    fn a_badge_shows_inside_another_cell_and_on_its_tabs() {
509        let badges = ColumnBadges::new()
510            .badge_color("status", |_| BadgeColor::Gray)
511            .badge_inside("status", "title")
512            .badge_on_tabs("status", ["all"])
513            .badge("kind");
514        assert_eq!(badges.inside_of("status"), Some("title"));
515        assert_eq!(badges.inside("title"), ["status"]);
516        assert_eq!(badges.inside_of("kind"), None);
517        assert_eq!(badges.color("status", "x"), Some(BadgeColor::Gray));
518        assert!(badges.shows_on("status", Some("all")));
519        assert!(!badges.shows_on("status", Some("drafts")));
520        assert!(!badges.shows_on("status", None));
521        assert!(badges.shows_on("kind", None) && badges.shows_on("title", Some("drafts")));
522        // `badge` after `badge_inside` keeps the place and resets the colour only.
523        let badges = ColumnBadges::new()
524            .badge_inside("status", "title")
525            .badge("status");
526        assert_eq!(badges.inside_of("status"), Some("title"));
527    }
528}