use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::sync::Arc;
use serde_json::Value;
use crate::runtime_resource::Row;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum FilterCondition {
Eq(String, Value),
Ne(String, Value),
In(String, Vec<Value>),
Null(String),
NotNull(String),
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ListFilter {
conditions: Vec<FilterCondition>,
}
impl ListFilter {
pub fn new() -> Self {
ListFilter::default()
}
pub fn where_eq(mut self, column: impl Into<String>, value: impl Into<Value>) -> Self {
self.conditions
.push(FilterCondition::Eq(column.into(), value.into()));
self
}
pub fn where_ne(mut self, column: impl Into<String>, value: impl Into<Value>) -> Self {
self.conditions
.push(FilterCondition::Ne(column.into(), value.into()));
self
}
pub fn where_in<V: Into<Value>>(
mut self,
column: impl Into<String>,
values: impl IntoIterator<Item = V>,
) -> Self {
self.conditions.push(FilterCondition::In(
column.into(),
values.into_iter().map(Into::into).collect(),
));
self
}
pub fn where_null(mut self, column: impl Into<String>) -> Self {
self.conditions.push(FilterCondition::Null(column.into()));
self
}
pub fn where_not_null(mut self, column: impl Into<String>) -> Self {
self.conditions
.push(FilterCondition::NotNull(column.into()));
self
}
pub fn is_empty(&self) -> bool {
self.conditions.is_empty()
}
pub fn conditions(&self) -> &[FilterCondition] {
&self.conditions
}
pub fn apply<M: orbit_orm::Model>(&self, query: orbit_orm::Query<M>) -> orbit_orm::Query<M> {
self.conditions
.iter()
.fold(query, |query, condition| match condition {
FilterCondition::Eq(column, value) => query.where_eq(column, orbit_value(value)),
FilterCondition::Ne(column, Value::Null) => query.where_not_null(column),
FilterCondition::Ne(column, value) => {
query.where_op(column, orbit_orm::Operator::Ne, orbit_value(value))
}
FilterCondition::In(column, values) => {
query.where_in(column, values.iter().map(orbit_value))
}
FilterCondition::Null(column) => query.where_null(column),
FilterCondition::NotNull(column) => query.where_not_null(column),
})
}
pub fn matches(&self, row: &Row) -> bool {
self.conditions.iter().all(|condition| {
let get = |column: &str| row.get(column).filter(|v| !v.is_null());
match condition {
FilterCondition::Eq(column, Value::Null) | FilterCondition::Null(column) => {
get(column).is_none()
}
FilterCondition::Ne(column, Value::Null) | FilterCondition::NotNull(column) => {
get(column).is_some()
}
FilterCondition::Eq(column, value) => get(column) == Some(value),
FilterCondition::Ne(column, value) => get(column).is_some_and(|v| v != value),
FilterCondition::In(column, values) => {
get(column).is_some_and(|v| values.contains(v))
}
}
})
}
}
fn orbit_value(value: &Value) -> orbit_orm::Value {
match value {
Value::Null => orbit_orm::Value::Null,
Value::Bool(b) => orbit_orm::Value::Bool(*b),
Value::Number(n) => match (n.as_i64(), n.as_u64(), n.as_f64()) {
(Some(i), _, _) => orbit_orm::Value::Int(i),
(None, Some(u), _) => orbit_orm::Value::UInt(u),
(None, None, Some(f)) => orbit_orm::Value::Float(f),
_ => orbit_orm::Value::Text(n.to_string()),
},
Value::String(s) => orbit_orm::Value::Text(s.clone()),
other => orbit_orm::Value::Text(other.to_string()),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Tab {
pub key: String,
pub label: String,
pub filter: ListFilter,
}
impl Tab {
pub fn make(key: impl Into<String>) -> Self {
let key = key.into();
let label = generate_label(&key);
Tab {
key,
label,
filter: ListFilter::new(),
}
}
pub fn label(mut self, label: impl Into<String>) -> Self {
self.label = label.into();
self
}
pub fn filter(mut self, filter: ListFilter) -> Self {
self.filter = filter;
self
}
pub fn where_eq(mut self, column: impl Into<String>, value: impl Into<Value>) -> Self {
self.filter = self.filter.where_eq(column, value);
self
}
pub fn where_ne(mut self, column: impl Into<String>, value: impl Into<Value>) -> Self {
self.filter = self.filter.where_ne(column, value);
self
}
pub fn where_in<V: Into<Value>>(
mut self,
column: impl Into<String>,
values: impl IntoIterator<Item = V>,
) -> Self {
self.filter = self.filter.where_in(column, values);
self
}
pub fn where_null(mut self, column: impl Into<String>) -> Self {
self.filter = self.filter.where_null(column);
self
}
pub fn where_not_null(mut self, column: impl Into<String>) -> Self {
self.filter = self.filter.where_not_null(column);
self
}
}
fn generate_label(key: &str) -> String {
let spaced = key.replace(['_', '-'], " ");
let mut chars = spaced.chars();
match chars.next() {
Some(first) => first.to_uppercase().chain(chars).collect(),
None => String::new(),
}
}
pub fn active_tab<'a>(
tabs: &'a [Tab],
requested: Option<&str>,
default: Option<&str>,
) -> Option<&'a Tab> {
let find = |key: &str| tabs.iter().find(|tab| tab.key == key);
match requested.filter(|key| !key.is_empty()) {
Some(key) => find(key),
None => default.and_then(find).or_else(|| tabs.first()),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BadgeColor {
Gray,
Info,
Success,
Warning,
Danger,
Primary,
}
impl BadgeColor {
pub fn as_str(self) -> &'static str {
match self {
BadgeColor::Gray => "gray",
BadgeColor::Info => "info",
BadgeColor::Success => "success",
BadgeColor::Warning => "warning",
BadgeColor::Danger => "danger",
BadgeColor::Primary => "primary",
}
}
}
type ColorRule = Arc<dyn Fn(&str) -> BadgeColor + Send + Sync>;
#[derive(Clone, Default)]
struct Badge {
color: Option<ColorRule>,
inside: Option<String>,
tabs: Option<Vec<String>>,
}
#[derive(Clone, Default)]
pub struct ColumnBadges {
columns: BTreeMap<String, Badge>,
}
impl fmt::Debug for ColumnBadges {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ColumnBadges")
.field("columns", &self.columns.keys().collect::<BTreeSet<_>>())
.finish()
}
}
impl ColumnBadges {
pub fn new() -> Self {
ColumnBadges::default()
}
pub fn badge(mut self, column: impl Into<String>) -> Self {
self.columns.entry(column.into()).or_default().color = None;
self
}
pub fn badge_color(
mut self,
column: impl Into<String>,
color: impl Fn(&str) -> BadgeColor + Send + Sync + 'static,
) -> Self {
self.columns.entry(column.into()).or_default().color = Some(Arc::new(color));
self
}
pub fn badge_inside(mut self, column: impl Into<String>, target: impl Into<String>) -> Self {
self.columns.entry(column.into()).or_default().inside = Some(target.into());
self
}
pub fn badge_on_tabs<S: Into<String>>(
mut self,
column: impl Into<String>,
tabs: impl IntoIterator<Item = S>,
) -> Self {
self.columns.entry(column.into()).or_default().tabs =
Some(tabs.into_iter().map(Into::into).collect());
self
}
pub fn is_empty(&self) -> bool {
self.columns.is_empty()
}
pub fn is_badge(&self, column: &str) -> bool {
self.columns.contains_key(column)
}
pub fn color(&self, column: &str, state: &str) -> Option<BadgeColor> {
self.columns.get(column).map(|badge| {
badge
.color
.as_ref()
.map_or(BadgeColor::Primary, |rule| rule(state))
})
}
pub fn inside_of(&self, column: &str) -> Option<&str> {
self.columns.get(column)?.inside.as_deref()
}
pub fn inside(&self, target: &str) -> Vec<&str> {
self.columns
.iter()
.filter(|(_, badge)| badge.inside.as_deref() == Some(target))
.map(|(column, _)| column.as_str())
.collect()
}
pub fn shows_on(&self, column: &str, tab: Option<&str>) -> bool {
match self
.columns
.get(column)
.and_then(|badge| badge.tabs.as_ref())
{
None => true,
Some(tabs) => tab.is_some_and(|tab| tabs.iter().any(|key| key == tab)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn row(value: Value) -> Row {
value.as_object().cloned().unwrap()
}
#[test]
fn a_tab_label_is_generated_from_its_key_as_filament_does() {
assert_eq!(Tab::make("needs_review").label, "Needs review");
assert_eq!(Tab::make("all-posts").label, "All posts");
assert_eq!(Tab::make("drafts").label("My drafts").label, "My drafts");
}
#[test]
fn the_active_tab_is_the_requested_one_or_the_default_or_the_first() {
let tabs = [Tab::make("all"), Tab::make("drafts")];
assert_eq!(
active_tab(&tabs, Some("drafts"), None).unwrap().key,
"drafts"
);
assert_eq!(active_tab(&tabs, None, None).unwrap().key, "all");
assert_eq!(
active_tab(&tabs, Some(""), Some("drafts")).unwrap().key,
"drafts"
);
assert_eq!(active_tab(&tabs, None, Some("missing")).unwrap().key, "all");
assert!(active_tab(&tabs, Some("missing"), None).is_none());
assert!(active_tab(&[], None, None).is_none());
}
#[test]
fn a_filter_matches_rows_as_the_database_would() {
let draft = row(json!({"status": "draft", "author": null, "id": 3}));
let published = row(json!({"status": "publish", "author": 1, "id": 4}));
let drafts = ListFilter::new().where_eq("status", "draft");
assert!(drafts.matches(&draft));
assert!(!drafts.matches(&published));
assert!(ListFilter::new().where_null("author").matches(&draft));
assert!(ListFilter::new()
.where_not_null("author")
.matches(&published));
assert!(!ListFilter::new().where_ne("author", 2).matches(&draft));
assert!(ListFilter::new().where_ne("author", 2).matches(&published));
assert!(ListFilter::new().where_in("id", [3, 5]).matches(&draft));
assert!(!ListFilter::new()
.where_in("id", Vec::<i64>::new())
.matches(&draft));
assert!(ListFilter::new().matches(&published));
}
#[test]
fn a_badge_column_takes_its_colour_from_the_state() {
let badges = ColumnBadges::new()
.badge("kind")
.badge_color("status", |state| match state {
"draft" => BadgeColor::Gray,
_ => BadgeColor::Success,
});
assert_eq!(badges.color("status", "draft"), Some(BadgeColor::Gray));
assert_eq!(badges.color("status", "publish"), Some(BadgeColor::Success));
assert_eq!(badges.color("kind", "x"), Some(BadgeColor::Primary));
assert_eq!(badges.color("title", "x"), None);
assert_eq!(BadgeColor::Danger.as_str(), "danger");
}
#[test]
fn a_badge_shows_inside_another_cell_and_on_its_tabs() {
let badges = ColumnBadges::new()
.badge_color("status", |_| BadgeColor::Gray)
.badge_inside("status", "title")
.badge_on_tabs("status", ["all"])
.badge("kind");
assert_eq!(badges.inside_of("status"), Some("title"));
assert_eq!(badges.inside("title"), ["status"]);
assert_eq!(badges.inside_of("kind"), None);
assert_eq!(badges.color("status", "x"), Some(BadgeColor::Gray));
assert!(badges.shows_on("status", Some("all")));
assert!(!badges.shows_on("status", Some("drafts")));
assert!(!badges.shows_on("status", None));
assert!(badges.shows_on("kind", None) && badges.shows_on("title", Some("drafts")));
let badges = ColumnBadges::new()
.badge_inside("status", "title")
.badge("status");
assert_eq!(badges.inside_of("status"), Some("title"));
}
}