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/// The list columns that show their value as a coloured badge, by column key, as Filament's
311/// `TextColumn::make($key)->badge()->color(fn (string $state) => ...)`. A column that is not
312/// listed shows its value as plain text.
313#[derive(Clone, Default)]
314pub struct ColumnBadges {
315    columns: BTreeMap<String, Option<ColorRule>>,
316}
317
318impl fmt::Debug for ColumnBadges {
319    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
320        f.debug_struct("ColumnBadges")
321            .field("columns", &self.columns.keys().collect::<BTreeSet<_>>())
322            .finish()
323    }
324}
325
326impl ColumnBadges {
327    /// No badge columns.
328    pub fn new() -> Self {
329        ColumnBadges::default()
330    }
331
332    /// Shows the column `column` as a badge in the primary colour, as Filament's `->badge()`
333    /// with no `color()`.
334    pub fn badge(mut self, column: impl Into<String>) -> Self {
335        self.columns.insert(column.into(), None);
336        self
337    }
338
339    /// Shows the column `column` as a badge whose colour `color` picks from the cell's state,
340    /// as Filament's `->badge()->color(fn (string $state): string => match ($state) { ... })`.
341    /// The state is the stored value as text, such as `"draft"`, before a select's or a
342    /// lookup's label replaces it for display.
343    pub fn badge_color(
344        mut self,
345        column: impl Into<String>,
346        color: impl Fn(&str) -> BadgeColor + Send + Sync + 'static,
347    ) -> Self {
348        self.columns.insert(column.into(), Some(Arc::new(color)));
349        self
350    }
351
352    /// Whether no column is a badge.
353    pub fn is_empty(&self) -> bool {
354        self.columns.is_empty()
355    }
356
357    /// Whether the column `column` is a badge.
358    pub fn is_badge(&self, column: &str) -> bool {
359        self.columns.contains_key(column)
360    }
361
362    /// The colour of the badge of the column `column` for `state`, or `None` when the column
363    /// is not a badge.
364    pub fn color(&self, column: &str, state: &str) -> Option<BadgeColor> {
365        self.columns.get(column).map(|rule| {
366            rule.as_ref()
367                .map_or(BadgeColor::Primary, |rule| rule(state))
368        })
369    }
370}
371
372#[cfg(test)]
373mod tests {
374    use super::*;
375    use serde_json::json;
376
377    fn row(value: Value) -> Row {
378        value.as_object().cloned().unwrap()
379    }
380
381    #[test]
382    fn a_tab_label_is_generated_from_its_key_as_filament_does() {
383        assert_eq!(Tab::make("needs_review").label, "Needs review");
384        assert_eq!(Tab::make("all-posts").label, "All posts");
385        assert_eq!(Tab::make("drafts").label("My drafts").label, "My drafts");
386    }
387
388    #[test]
389    fn the_active_tab_is_the_requested_one_or_the_default_or_the_first() {
390        let tabs = [Tab::make("all"), Tab::make("drafts")];
391        assert_eq!(
392            active_tab(&tabs, Some("drafts"), None).unwrap().key,
393            "drafts"
394        );
395        assert_eq!(active_tab(&tabs, None, None).unwrap().key, "all");
396        assert_eq!(
397            active_tab(&tabs, Some(""), Some("drafts")).unwrap().key,
398            "drafts"
399        );
400        assert_eq!(active_tab(&tabs, None, Some("missing")).unwrap().key, "all");
401        assert!(active_tab(&tabs, Some("missing"), None).is_none());
402        assert!(active_tab(&[], None, None).is_none());
403    }
404
405    #[test]
406    fn a_filter_matches_rows_as_the_database_would() {
407        let draft = row(json!({"status": "draft", "author": null, "id": 3}));
408        let published = row(json!({"status": "publish", "author": 1, "id": 4}));
409        let drafts = ListFilter::new().where_eq("status", "draft");
410        assert!(drafts.matches(&draft));
411        assert!(!drafts.matches(&published));
412        assert!(ListFilter::new().where_null("author").matches(&draft));
413        assert!(ListFilter::new()
414            .where_not_null("author")
415            .matches(&published));
416        assert!(!ListFilter::new().where_ne("author", 2).matches(&draft));
417        assert!(ListFilter::new().where_ne("author", 2).matches(&published));
418        assert!(ListFilter::new().where_in("id", [3, 5]).matches(&draft));
419        assert!(!ListFilter::new()
420            .where_in("id", Vec::<i64>::new())
421            .matches(&draft));
422        assert!(ListFilter::new().matches(&published));
423    }
424
425    #[test]
426    fn a_badge_column_takes_its_colour_from_the_state() {
427        let badges = ColumnBadges::new()
428            .badge("kind")
429            .badge_color("status", |state| match state {
430                "draft" => BadgeColor::Gray,
431                _ => BadgeColor::Success,
432            });
433        assert_eq!(badges.color("status", "draft"), Some(BadgeColor::Gray));
434        assert_eq!(badges.color("status", "publish"), Some(BadgeColor::Success));
435        assert_eq!(badges.color("kind", "x"), Some(BadgeColor::Primary));
436        assert_eq!(badges.color("title", "x"), None);
437        assert_eq!(BadgeColor::Danger.as_str(), "danger");
438    }
439}