use std::collections::BTreeMap;
use std::sync::Arc;
use laravel::db::{Builder, col};
use laravel::model::Model;
use laravel::time::civil::Date;
use crate::protocol::{
BadgeColor, ColumnAlign, ColumnKind, ColumnSchemaDto, DefaultSortDto, FilterKindDto, FilterSchemaDto,
SelectOptionDto, SortDirection, TableTabSchemaDto,
};
use crate::schema::action::{BulkAction, RowAction};
use crate::schema::form::SelectOption;
use crate::schema::humanize;
#[derive(Debug, Clone)]
pub struct Column {
pub(crate) name: String,
pub(crate) label: String,
pub(crate) kind: ColumnKind,
pub(crate) align: ColumnAlign,
pub(crate) sortable: bool,
pub(crate) searchable: bool,
pub(crate) toggleable: bool,
pub(crate) hidden_by_default: bool,
pub(crate) copyable: bool,
pub(crate) mono: bool,
pub(crate) prefix: Option<String>,
pub(crate) suffix: Option<String>,
pub(crate) currency: Option<String>,
pub(crate) description_column: Option<String>,
pub(crate) limit: Option<usize>,
pub(crate) badge_colors: BTreeMap<String, BadgeColor>,
pub(crate) badge_dot: bool,
}
impl Column {
fn new(name: impl Into<String>, kind: ColumnKind) -> Self {
let name = name.into();
let label = humanize(&name);
let align = match kind {
ColumnKind::Number | ColumnKind::Currency => ColumnAlign::Right,
ColumnKind::Boolean => ColumnAlign::Center,
_ => ColumnAlign::Left,
};
Self {
name,
label,
kind,
align,
sortable: false,
searchable: false,
toggleable: true,
hidden_by_default: false,
copyable: false,
mono: false,
prefix: None,
suffix: None,
currency: None,
description_column: None,
limit: None,
badge_colors: BTreeMap::new(),
badge_dot: false,
}
}
#[must_use]
pub fn text(name: impl Into<String>) -> Self {
Self::new(name, ColumnKind::Text)
}
#[must_use]
pub fn badge(name: impl Into<String>) -> Self {
let mut col = Self::new(name, ColumnKind::Badge);
col.badge_dot = true;
col
}
#[must_use]
pub fn boolean(name: impl Into<String>) -> Self {
Self::new(name, ColumnKind::Boolean)
}
#[must_use]
pub fn number(name: impl Into<String>) -> Self {
Self::new(name, ColumnKind::Number)
}
#[must_use]
pub fn currency(name: impl Into<String>, currency_code: impl Into<String>) -> Self {
let mut col = Self::new(name, ColumnKind::Currency);
col.currency = Some(currency_code.into());
col
}
#[must_use]
pub fn datetime(name: impl Into<String>) -> Self {
Self::new(name, ColumnKind::Datetime)
}
#[must_use]
pub fn date(name: impl Into<String>) -> Self {
Self::new(name, ColumnKind::Date)
}
#[must_use]
pub fn relative_time(name: impl Into<String>) -> Self {
Self::new(name, ColumnKind::RelativeTime)
}
#[must_use]
pub fn avatar(name: impl Into<String>) -> Self {
Self::new(name, ColumnKind::Avatar)
}
#[must_use]
pub fn tags(name: impl Into<String>) -> Self {
Self::new(name, ColumnKind::Tags)
}
#[must_use]
pub fn json(name: impl Into<String>) -> Self {
Self::new(name, ColumnKind::Json)
}
#[must_use]
pub fn label(mut self, label: impl Into<String>) -> Self {
self.label = label.into();
self
}
#[must_use]
pub fn align(mut self, align: ColumnAlign) -> Self {
self.align = align;
self
}
#[must_use]
pub fn sortable(mut self) -> Self {
self.sortable = true;
self
}
#[must_use]
pub fn searchable(mut self) -> Self {
self.searchable = true;
self
}
#[must_use]
pub fn toggleable(mut self, toggleable: bool) -> Self {
self.toggleable = toggleable;
self
}
#[must_use]
pub fn hidden_by_default(mut self) -> Self {
self.hidden_by_default = true;
self
}
#[must_use]
pub fn copyable(mut self) -> Self {
self.copyable = true;
self
}
#[must_use]
pub fn mono(mut self) -> Self {
self.mono = true;
self
}
#[must_use]
pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
self.prefix = Some(prefix.into());
self
}
#[must_use]
pub fn suffix(mut self, suffix: impl Into<String>) -> Self {
self.suffix = Some(suffix.into());
self
}
#[must_use]
pub fn description_column(mut self, column: impl Into<String>) -> Self {
self.description_column = Some(column.into());
self
}
#[must_use]
pub fn limit(mut self, chars: usize) -> Self {
self.limit = Some(chars);
self
}
#[must_use]
pub fn color(mut self, value: impl Into<String>, color: BadgeColor) -> Self {
self.badge_colors.insert(value.into(), color);
self
}
#[must_use]
pub fn dot(mut self, show_dot: bool) -> Self {
self.badge_dot = show_dot;
self
}
pub(crate) fn to_dto(&self) -> ColumnSchemaDto {
ColumnSchemaDto {
name: self.name.clone(),
label: self.label.clone(),
kind: self.kind,
align: self.align,
sortable: self.sortable,
searchable: self.searchable,
toggleable: self.toggleable,
hidden_by_default: self.hidden_by_default,
copyable: self.copyable,
mono: self.mono,
prefix: self.prefix.clone(),
suffix: self.suffix.clone(),
currency: self.currency.clone(),
description_column: self.description_column.clone(),
limit: self.limit,
badge_colors: self.badge_colors.clone(),
badge_dot: self.badge_dot,
}
}
}
type QueryModifier<M> = Arc<dyn Fn(Builder<M>, &str) -> Builder<M> + Send + Sync>;
type TabModifier<M> = Arc<dyn Fn(Builder<M>) -> Builder<M> + Send + Sync>;
pub struct Filter<M: Model> {
pub(crate) name: String,
pub(crate) label: String,
pub(crate) control: FilterKindDto,
pub(crate) apply: QueryModifier<M>,
}
impl<M: Model> Filter<M> {
#[must_use]
pub fn select(name: impl Into<String>) -> SelectFilterBuilder<M> {
let name = name.into();
let label = humanize(&name);
SelectFilterBuilder {
column: name.clone(),
name,
label,
options: Vec::new(),
custom: None,
_marker: std::marker::PhantomData,
}
}
#[must_use]
pub fn boolean(name: impl Into<String>) -> Self {
let name = name.into();
let label = humanize(&name);
let apply_col = name.clone();
Self {
name,
label,
control: FilterKindDto::Boolean {
true_label: "Yes".to_owned(),
false_label: "No".to_owned(),
},
apply: Arc::new(move |query, value| match value {
"true" | "1" | "yes" => query.filter(col(apply_col.as_str()).eq(true)),
"false" | "0" | "no" => query.filter(col(apply_col.as_str()).eq(false)),
_ => query,
}),
}
}
#[must_use]
pub fn date_range(name: impl Into<String>) -> Self {
let name = name.into();
let label = humanize(&name);
let apply_col = name.clone();
Self {
name,
label,
control: FilterKindDto::DateRange,
apply: Arc::new(move |mut query, value| {
let Some((from, to)) = value.split_once("..") else {
return query;
};
if let Ok(from) = from.parse::<Date>() {
query = query.filter(col(apply_col.as_str()).date().ge(from));
}
if let Ok(to) = to.parse::<Date>() {
query = query.filter(col(apply_col.as_str()).date().le(to));
}
query
}),
}
}
#[must_use]
pub fn text(name: impl Into<String>) -> Self {
let name = name.into();
let label = humanize(&name);
let apply_col = name.clone();
Self {
name,
label,
control: FilterKindDto::Text { placeholder: None },
apply: Arc::new(move |query, value| {
if value.trim().is_empty() {
query
} else {
query.filter(col(apply_col.as_str()).contains(value.trim()))
}
}),
}
}
#[must_use]
pub fn label(mut self, label: impl Into<String>) -> Self {
self.label = label.into();
self
}
#[must_use]
pub fn boolean_labels(mut self, true_label: impl Into<String>, false_label: impl Into<String>) -> Self {
if let FilterKindDto::Boolean {
true_label: t,
false_label: f,
} = &mut self.control
{
*t = true_label.into();
*f = false_label.into();
}
self
}
#[must_use]
pub fn query<F>(mut self, modifier: F) -> Self
where
F: Fn(Builder<M>, &str) -> Builder<M> + Send + Sync + 'static,
{
self.apply = Arc::new(modifier);
self
}
pub(crate) fn to_dto(&self) -> FilterSchemaDto {
FilterSchemaDto {
name: self.name.clone(),
label: self.label.clone(),
control: self.control.clone(),
}
}
}
pub struct SelectFilterBuilder<M: Model> {
name: String,
label: String,
column: String,
options: Vec<SelectOptionDto>,
custom: Option<QueryModifier<M>>,
_marker: std::marker::PhantomData<fn() -> M>,
}
impl<M: Model> SelectFilterBuilder<M> {
#[must_use]
pub fn label(mut self, label: impl Into<String>) -> Self {
self.label = label.into();
self
}
#[must_use]
pub fn column(mut self, column: impl Into<String>) -> Self {
self.column = column.into();
self
}
#[must_use]
pub fn options<I, O>(mut self, options: I) -> Self
where
I: IntoIterator<Item = O>,
O: Into<SelectOption>,
{
self.options = options.into_iter().map(|opt| opt.into().to_dto()).collect();
self
}
#[must_use]
pub fn query<F>(mut self, modifier: F) -> Self
where
F: Fn(Builder<M>, &str) -> Builder<M> + Send + Sync + 'static,
{
self.custom = Some(Arc::new(modifier));
self
}
#[must_use]
pub fn build(self) -> Filter<M> {
let apply_col = self.column.clone();
let apply = self.custom.unwrap_or_else(|| {
Arc::new(move |query: Builder<M>, value: &str| {
if value.is_empty() {
query
} else {
query.filter(col(apply_col.as_str()).eq(value.to_owned()))
}
})
});
Filter {
name: self.name,
label: self.label,
control: FilterKindDto::Select { options: self.options },
apply,
}
}
}
impl<M: Model> From<SelectFilterBuilder<M>> for Filter<M> {
fn from(builder: SelectFilterBuilder<M>) -> Self {
builder.build()
}
}
pub struct TableTab<M: Model> {
pub(crate) key: String,
pub(crate) label: String,
pub(crate) badge_color: Option<BadgeColor>,
pub(crate) apply: TabModifier<M>,
}
impl<M: Model> TableTab<M> {
#[must_use]
pub fn new<F>(key: impl Into<String>, label: impl Into<String>, modifier: F) -> Self
where
F: Fn(Builder<M>) -> Builder<M> + Send + Sync + 'static,
{
Self {
key: key.into(),
label: label.into(),
badge_color: None,
apply: Arc::new(modifier),
}
}
#[must_use]
pub fn all(label: impl Into<String>) -> Self {
Self::new("all", label, |q| q)
}
#[must_use]
pub fn color(mut self, color: BadgeColor) -> Self {
self.badge_color = Some(color);
self
}
pub(crate) fn to_dto(&self) -> TableTabSchemaDto {
TableTabSchemaDto {
key: self.key.clone(),
label: self.label.clone(),
badge_color: self.badge_color,
}
}
}
pub struct TableBuilder<M: Model> {
pub(crate) columns: Vec<Column>,
pub(crate) filters: Vec<Filter<M>>,
pub(crate) tabs: Vec<TableTab<M>>,
pub(crate) row_actions: Vec<RowAction<M>>,
pub(crate) bulk_actions: Vec<BulkAction<M>>,
pub(crate) default_sort: Option<DefaultSortDto>,
pub(crate) exportable: bool,
pub(crate) search_by: Vec<String>,
}
impl<M: Model> Default for TableBuilder<M> {
fn default() -> Self {
Self {
columns: Vec::new(),
filters: Vec::new(),
tabs: Vec::new(),
row_actions: Vec::new(),
bulk_actions: Vec::new(),
default_sort: None,
exportable: true,
search_by: Vec::new(),
}
}
}
impl<M: Model> TableBuilder<M> {
#[must_use]
pub fn column(mut self, column: Column) -> Self {
self.columns.push(column);
self
}
#[must_use]
pub fn columns(mut self, columns: impl IntoIterator<Item = Column>) -> Self {
self.columns.extend(columns);
self
}
#[must_use]
pub fn filter(mut self, filter: impl Into<Filter<M>>) -> Self {
self.filters.push(filter.into());
self
}
#[must_use]
pub fn tab(mut self, tab: TableTab<M>) -> Self {
self.tabs.push(tab);
self
}
#[must_use]
pub fn action(mut self, action: RowAction<M>) -> Self {
self.row_actions.push(action);
self
}
#[must_use]
pub fn bulk_action(mut self, action: BulkAction<M>) -> Self {
self.bulk_actions.push(action);
self
}
#[must_use]
pub fn default_sort(mut self, column: impl Into<String>, direction: SortDirection) -> Self {
self.default_sort = Some(DefaultSortDto {
column: column.into(),
direction,
});
self
}
pub(crate) fn search_columns(&self) -> Vec<&str> {
let mut columns: Vec<&str> = self
.columns
.iter()
.filter(|column| column.searchable)
.map(|column| column.name.as_str())
.collect();
for column in &self.search_by {
if !columns.contains(&column.as_str()) {
columns.push(column);
}
}
columns
}
#[must_use]
pub fn search_by(mut self, columns: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.search_by.extend(columns.into_iter().map(Into::into));
self
}
#[must_use]
pub fn exportable(mut self, exportable: bool) -> Self {
self.exportable = exportable;
self
}
}