1use std::collections::BTreeMap;
4use std::sync::Arc;
5
6use laravel::db::{Builder, col};
7use laravel::model::Model;
8use laravel::time::civil::Date;
9
10use crate::protocol::{
11 BadgeColor, ColumnAlign, ColumnKind, ColumnSchemaDto, DefaultSortDto, FilterKindDto, FilterSchemaDto,
12 SelectOptionDto, SortDirection, TableTabSchemaDto,
13};
14use crate::schema::action::{BulkAction, RowAction};
15use crate::schema::form::SelectOption;
16use crate::schema::humanize;
17
18#[derive(Debug, Clone)]
20pub struct Column {
21 pub(crate) name: String,
22 pub(crate) label: String,
23 pub(crate) kind: ColumnKind,
24 pub(crate) align: ColumnAlign,
25 pub(crate) sortable: bool,
26 pub(crate) searchable: bool,
27 pub(crate) toggleable: bool,
28 pub(crate) hidden_by_default: bool,
29 pub(crate) copyable: bool,
30 pub(crate) mono: bool,
31 pub(crate) prefix: Option<String>,
32 pub(crate) suffix: Option<String>,
33 pub(crate) currency: Option<String>,
34 pub(crate) description_column: Option<String>,
35 pub(crate) limit: Option<usize>,
36 pub(crate) badge_colors: BTreeMap<String, BadgeColor>,
37 pub(crate) badge_dot: bool,
38}
39
40impl Column {
41 fn new(name: impl Into<String>, kind: ColumnKind) -> Self {
42 let name = name.into();
43 let label = humanize(&name);
44 let align = match kind {
45 ColumnKind::Number | ColumnKind::Currency => ColumnAlign::Right,
46 ColumnKind::Boolean => ColumnAlign::Center,
47 _ => ColumnAlign::Left,
48 };
49 Self {
50 name,
51 label,
52 kind,
53 align,
54 sortable: false,
55 searchable: false,
56 toggleable: true,
57 hidden_by_default: false,
58 copyable: false,
59 mono: false,
60 prefix: None,
61 suffix: None,
62 currency: None,
63 description_column: None,
64 limit: None,
65 badge_colors: BTreeMap::new(),
66 badge_dot: false,
67 }
68 }
69
70 #[must_use]
77 pub fn text(name: impl Into<String>) -> Self {
78 Self::new(name, ColumnKind::Text)
79 }
80
81 #[must_use]
84 pub fn badge(name: impl Into<String>) -> Self {
85 let mut col = Self::new(name, ColumnKind::Badge);
86 col.badge_dot = true;
87 col
88 }
89
90 #[must_use]
92 pub fn boolean(name: impl Into<String>) -> Self {
93 Self::new(name, ColumnKind::Boolean)
94 }
95
96 #[must_use]
98 pub fn number(name: impl Into<String>) -> Self {
99 Self::new(name, ColumnKind::Number)
100 }
101
102 #[must_use]
105 pub fn currency(name: impl Into<String>, currency_code: impl Into<String>) -> Self {
106 let mut col = Self::new(name, ColumnKind::Currency);
107 col.currency = Some(currency_code.into());
108 col
109 }
110
111 #[must_use]
113 pub fn datetime(name: impl Into<String>) -> Self {
114 Self::new(name, ColumnKind::Datetime)
115 }
116
117 #[must_use]
119 pub fn date(name: impl Into<String>) -> Self {
120 Self::new(name, ColumnKind::Date)
121 }
122
123 #[must_use]
126 pub fn relative_time(name: impl Into<String>) -> Self {
127 Self::new(name, ColumnKind::RelativeTime)
128 }
129
130 #[must_use]
133 pub fn avatar(name: impl Into<String>) -> Self {
134 Self::new(name, ColumnKind::Avatar)
135 }
136
137 #[must_use]
139 pub fn tags(name: impl Into<String>) -> Self {
140 Self::new(name, ColumnKind::Tags)
141 }
142
143 #[must_use]
145 pub fn json(name: impl Into<String>) -> Self {
146 Self::new(name, ColumnKind::Json)
147 }
148
149 #[must_use]
151 pub fn label(mut self, label: impl Into<String>) -> Self {
152 self.label = label.into();
153 self
154 }
155
156 #[must_use]
158 pub fn align(mut self, align: ColumnAlign) -> Self {
159 self.align = align;
160 self
161 }
162
163 #[must_use]
165 pub fn sortable(mut self) -> Self {
166 self.sortable = true;
167 self
168 }
169
170 #[must_use]
173 pub fn searchable(mut self) -> Self {
174 self.searchable = true;
175 self
176 }
177
178 #[must_use]
181 pub fn toggleable(mut self, toggleable: bool) -> Self {
182 self.toggleable = toggleable;
183 self
184 }
185
186 #[must_use]
188 pub fn hidden_by_default(mut self) -> Self {
189 self.hidden_by_default = true;
190 self
191 }
192
193 #[must_use]
195 pub fn copyable(mut self) -> Self {
196 self.copyable = true;
197 self
198 }
199
200 #[must_use]
203 pub fn mono(mut self) -> Self {
204 self.mono = true;
205 self
206 }
207
208 #[must_use]
210 pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
211 self.prefix = Some(prefix.into());
212 self
213 }
214
215 #[must_use]
217 pub fn suffix(mut self, suffix: impl Into<String>) -> Self {
218 self.suffix = Some(suffix.into());
219 self
220 }
221
222 #[must_use]
225 pub fn description_column(mut self, column: impl Into<String>) -> Self {
226 self.description_column = Some(column.into());
227 self
228 }
229
230 #[must_use]
232 pub fn limit(mut self, chars: usize) -> Self {
233 self.limit = Some(chars);
234 self
235 }
236
237 #[must_use]
240 pub fn color(mut self, value: impl Into<String>, color: BadgeColor) -> Self {
241 self.badge_colors.insert(value.into(), color);
242 self
243 }
244
245 #[must_use]
247 pub fn dot(mut self, show_dot: bool) -> Self {
248 self.badge_dot = show_dot;
249 self
250 }
251
252 pub(crate) fn to_dto(&self) -> ColumnSchemaDto {
253 ColumnSchemaDto {
254 name: self.name.clone(),
255 label: self.label.clone(),
256 kind: self.kind,
257 align: self.align,
258 sortable: self.sortable,
259 searchable: self.searchable,
260 toggleable: self.toggleable,
261 hidden_by_default: self.hidden_by_default,
262 copyable: self.copyable,
263 mono: self.mono,
264 prefix: self.prefix.clone(),
265 suffix: self.suffix.clone(),
266 currency: self.currency.clone(),
267 description_column: self.description_column.clone(),
268 limit: self.limit,
269 badge_colors: self.badge_colors.clone(),
270 badge_dot: self.badge_dot,
271 }
272 }
273}
274
275type QueryModifier<M> = Arc<dyn Fn(Builder<M>, &str) -> Builder<M> + Send + Sync>;
276type TabModifier<M> = Arc<dyn Fn(Builder<M>) -> Builder<M> + Send + Sync>;
277
278pub struct Filter<M: Model> {
280 pub(crate) name: String,
281 pub(crate) label: String,
282 pub(crate) control: FilterKindDto,
283 pub(crate) apply: QueryModifier<M>,
284}
285
286impl<M: Model> Filter<M> {
287 #[must_use]
294 pub fn select(name: impl Into<String>) -> SelectFilterBuilder<M> {
295 let name = name.into();
296 let label = humanize(&name);
297 SelectFilterBuilder {
298 column: name.clone(),
299 name,
300 label,
301 options: Vec::new(),
302 custom: None,
303 _marker: std::marker::PhantomData,
304 }
305 }
306
307 #[must_use]
309 pub fn boolean(name: impl Into<String>) -> Self {
310 let name = name.into();
311 let label = humanize(&name);
312 let apply_col = name.clone();
313 Self {
314 name,
315 label,
316 control: FilterKindDto::Boolean {
317 true_label: "Yes".to_owned(),
318 false_label: "No".to_owned(),
319 },
320 apply: Arc::new(move |query, value| match value {
321 "true" | "1" | "yes" => query.filter(col(apply_col.as_str()).eq(true)),
322 "false" | "0" | "no" => query.filter(col(apply_col.as_str()).eq(false)),
323 _ => query,
324 }),
325 }
326 }
327
328 #[must_use]
331 pub fn date_range(name: impl Into<String>) -> Self {
332 let name = name.into();
333 let label = humanize(&name);
334 let apply_col = name.clone();
335 Self {
336 name,
337 label,
338 control: FilterKindDto::DateRange,
339 apply: Arc::new(move |mut query, value| {
340 let Some((from, to)) = value.split_once("..") else {
343 return query;
344 };
345 if let Ok(from) = from.parse::<Date>() {
346 query = query.filter(col(apply_col.as_str()).date().ge(from));
347 }
348 if let Ok(to) = to.parse::<Date>() {
349 query = query.filter(col(apply_col.as_str()).date().le(to));
350 }
351 query
352 }),
353 }
354 }
355
356 #[must_use]
358 pub fn text(name: impl Into<String>) -> Self {
359 let name = name.into();
360 let label = humanize(&name);
361 let apply_col = name.clone();
362 Self {
363 name,
364 label,
365 control: FilterKindDto::Text { placeholder: None },
366 apply: Arc::new(move |query, value| {
367 if value.trim().is_empty() {
368 query
369 } else {
370 query.filter(col(apply_col.as_str()).contains(value.trim()))
371 }
372 }),
373 }
374 }
375
376 #[must_use]
378 pub fn label(mut self, label: impl Into<String>) -> Self {
379 self.label = label.into();
380 self
381 }
382
383 #[must_use]
386 pub fn boolean_labels(mut self, true_label: impl Into<String>, false_label: impl Into<String>) -> Self {
387 if let FilterKindDto::Boolean {
388 true_label: t,
389 false_label: f,
390 } = &mut self.control
391 {
392 *t = true_label.into();
393 *f = false_label.into();
394 }
395 self
396 }
397
398 #[must_use]
401 pub fn query<F>(mut self, modifier: F) -> Self
402 where
403 F: Fn(Builder<M>, &str) -> Builder<M> + Send + Sync + 'static,
404 {
405 self.apply = Arc::new(modifier);
406 self
407 }
408
409 pub(crate) fn to_dto(&self) -> FilterSchemaDto {
410 FilterSchemaDto {
411 name: self.name.clone(),
412 label: self.label.clone(),
413 control: self.control.clone(),
414 }
415 }
416}
417
418pub struct SelectFilterBuilder<M: Model> {
420 name: String,
421 label: String,
422 column: String,
423 options: Vec<SelectOptionDto>,
424 custom: Option<QueryModifier<M>>,
425 _marker: std::marker::PhantomData<fn() -> M>,
426}
427
428impl<M: Model> SelectFilterBuilder<M> {
429 #[must_use]
431 pub fn label(mut self, label: impl Into<String>) -> Self {
432 self.label = label.into();
433 self
434 }
435
436 #[must_use]
438 pub fn column(mut self, column: impl Into<String>) -> Self {
439 self.column = column.into();
440 self
441 }
442
443 #[must_use]
445 pub fn options<I, O>(mut self, options: I) -> Self
446 where
447 I: IntoIterator<Item = O>,
448 O: Into<SelectOption>,
449 {
450 self.options = options.into_iter().map(|opt| opt.into().to_dto()).collect();
451 self
452 }
453
454 #[must_use]
457 pub fn query<F>(mut self, modifier: F) -> Self
458 where
459 F: Fn(Builder<M>, &str) -> Builder<M> + Send + Sync + 'static,
460 {
461 self.custom = Some(Arc::new(modifier));
462 self
463 }
464
465 #[must_use]
467 pub fn build(self) -> Filter<M> {
468 let apply_col = self.column.clone();
469 let apply = self.custom.unwrap_or_else(|| {
470 Arc::new(move |query: Builder<M>, value: &str| {
471 if value.is_empty() {
472 query
473 } else {
474 query.filter(col(apply_col.as_str()).eq(value.to_owned()))
475 }
476 })
477 });
478 Filter {
479 name: self.name,
480 label: self.label,
481 control: FilterKindDto::Select { options: self.options },
482 apply,
483 }
484 }
485}
486
487impl<M: Model> From<SelectFilterBuilder<M>> for Filter<M> {
488 fn from(builder: SelectFilterBuilder<M>) -> Self {
489 builder.build()
490 }
491}
492
493pub struct TableTab<M: Model> {
496 pub(crate) key: String,
497 pub(crate) label: String,
498 pub(crate) badge_color: Option<BadgeColor>,
499 pub(crate) apply: TabModifier<M>,
500}
501
502impl<M: Model> TableTab<M> {
503 #[must_use]
506 pub fn new<F>(key: impl Into<String>, label: impl Into<String>, modifier: F) -> Self
507 where
508 F: Fn(Builder<M>) -> Builder<M> + Send + Sync + 'static,
509 {
510 Self {
511 key: key.into(),
512 label: label.into(),
513 badge_color: None,
514 apply: Arc::new(modifier),
515 }
516 }
517
518 #[must_use]
520 pub fn all(label: impl Into<String>) -> Self {
521 Self::new("all", label, |q| q)
522 }
523
524 #[must_use]
526 pub fn color(mut self, color: BadgeColor) -> Self {
527 self.badge_color = Some(color);
528 self
529 }
530
531 pub(crate) fn to_dto(&self) -> TableTabSchemaDto {
532 TableTabSchemaDto {
533 key: self.key.clone(),
534 label: self.label.clone(),
535 badge_color: self.badge_color,
536 }
537 }
538}
539
540pub struct TableBuilder<M: Model> {
543 pub(crate) columns: Vec<Column>,
544 pub(crate) filters: Vec<Filter<M>>,
545 pub(crate) tabs: Vec<TableTab<M>>,
546 pub(crate) row_actions: Vec<RowAction<M>>,
547 pub(crate) bulk_actions: Vec<BulkAction<M>>,
548 pub(crate) default_sort: Option<DefaultSortDto>,
549 pub(crate) exportable: bool,
550 pub(crate) search_by: Vec<String>,
552}
553
554impl<M: Model> Default for TableBuilder<M> {
555 fn default() -> Self {
556 Self {
557 columns: Vec::new(),
558 filters: Vec::new(),
559 tabs: Vec::new(),
560 row_actions: Vec::new(),
561 bulk_actions: Vec::new(),
562 default_sort: None,
563 exportable: true,
564 search_by: Vec::new(),
565 }
566 }
567}
568
569impl<M: Model> TableBuilder<M> {
570 #[must_use]
572 pub fn column(mut self, column: Column) -> Self {
573 self.columns.push(column);
574 self
575 }
576
577 #[must_use]
579 pub fn columns(mut self, columns: impl IntoIterator<Item = Column>) -> Self {
580 self.columns.extend(columns);
581 self
582 }
583
584 #[must_use]
586 pub fn filter(mut self, filter: impl Into<Filter<M>>) -> Self {
587 self.filters.push(filter.into());
588 self
589 }
590
591 #[must_use]
593 pub fn tab(mut self, tab: TableTab<M>) -> Self {
594 self.tabs.push(tab);
595 self
596 }
597
598 #[must_use]
600 pub fn action(mut self, action: RowAction<M>) -> Self {
601 self.row_actions.push(action);
602 self
603 }
604
605 #[must_use]
607 pub fn bulk_action(mut self, action: BulkAction<M>) -> Self {
608 self.bulk_actions.push(action);
609 self
610 }
611
612 #[must_use]
614 pub fn default_sort(mut self, column: impl Into<String>, direction: SortDirection) -> Self {
615 self.default_sort = Some(DefaultSortDto {
616 column: column.into(),
617 direction,
618 });
619 self
620 }
621
622 pub(crate) fn search_columns(&self) -> Vec<&str> {
625 let mut columns: Vec<&str> = self
626 .columns
627 .iter()
628 .filter(|column| column.searchable)
629 .map(|column| column.name.as_str())
630 .collect();
631 for column in &self.search_by {
632 if !columns.contains(&column.as_str()) {
633 columns.push(column);
634 }
635 }
636 columns
637 }
638
639 #[must_use]
650 pub fn search_by(mut self, columns: impl IntoIterator<Item = impl Into<String>>) -> Self {
651 self.search_by.extend(columns.into_iter().map(Into::into));
652 self
653 }
654
655 #[must_use]
660 pub fn exportable(mut self, exportable: bool) -> Self {
661 self.exportable = exportable;
662 self
663 }
664}