1use std::collections::{BTreeMap, BTreeSet};
22use std::fmt;
23use std::sync::Arc;
24
25use serde_json::Value;
26
27use crate::runtime_resource::Row;
28
29#[derive(Debug, Clone, PartialEq, Eq)]
32#[non_exhaustive]
33pub enum FilterCondition {
34 Eq(String, Value),
36 Ne(String, Value),
39 In(String, Vec<Value>),
41 Null(String),
43 NotNull(String),
45}
46
47#[derive(Debug, Clone, Default, PartialEq, Eq)]
55pub struct ListFilter {
56 conditions: Vec<FilterCondition>,
57}
58
59impl ListFilter {
60 pub fn new() -> Self {
62 ListFilter::default()
63 }
64
65 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 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 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 pub fn where_null(mut self, column: impl Into<String>) -> Self {
94 self.conditions.push(FilterCondition::Null(column.into()));
95 self
96 }
97
98 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 pub fn is_empty(&self) -> bool {
107 self.conditions.is_empty()
108 }
109
110 pub fn conditions(&self) -> &[FilterCondition] {
112 &self.conditions
113 }
114
115 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 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
155fn 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#[derive(Debug, Clone, PartialEq, Eq)]
175pub struct Tab {
176 pub key: String,
179 pub label: String,
181 pub filter: ListFilter,
184}
185
186impl Tab {
187 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 pub fn label(mut self, label: impl Into<String>) -> Self {
202 self.label = label.into();
203 self
204 }
205
206 pub fn filter(mut self, filter: ListFilter) -> Self {
208 self.filter = filter;
209 self
210 }
211
212 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 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 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 pub fn where_null(mut self, column: impl Into<String>) -> Self {
237 self.filter = self.filter.where_null(column);
238 self
239 }
240
241 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
248fn 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
259pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
277pub enum BadgeColor {
278 Gray,
280 Info,
282 Success,
284 Warning,
286 Danger,
288 Primary,
290}
291
292impl BadgeColor {
293 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
307type ColorRule = Arc<dyn Fn(&str) -> BadgeColor + Send + Sync>;
309
310#[derive(Clone, Default)]
312struct Badge {
313 color: Option<ColorRule>,
314 inside: Option<String>,
315 tabs: Option<Vec<String>>,
316}
317
318#[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 pub fn new() -> Self {
342 ColumnBadges::default()
343 }
344
345 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 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 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 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 pub fn is_empty(&self) -> bool {
391 self.columns.is_empty()
392 }
393
394 pub fn is_badge(&self, column: &str) -> bool {
396 self.columns.contains_key(column)
397 }
398
399 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 pub fn inside_of(&self, column: &str) -> Option<&str> {
412 self.columns.get(column)?.inside.as_deref()
413 }
414
415 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 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 let badges = ColumnBadges::new()
524 .badge_inside("status", "title")
525 .badge("status");
526 assert_eq!(badges.inside_of("status"), Some("title"));
527 }
528}