tablo_core/column/
icon.rs1use std::sync::Arc;
4
5use derive_where::derive_where;
6use toasty::stmt::OrderByExpr;
7use topcoat::{context::Cx, icon::IconData, view::*};
8
9use super::{Column, ColumnBase, ColumnWidth, ReadFn, cell::icon_view, sort_order};
10use crate::{Lens, display::Color, values::FormScalar};
11
12#[derive_where(Clone, Debug)]
30pub struct IconColumn<M, T> {
31 lens: Lens<M, T>,
32 base: ColumnBase,
33 sortable: bool,
34 #[derive_where(skip(Debug))]
35 icon: ReadFn<T, Option<IconData>>,
36 #[derive_where(skip(Debug))]
37 color: ReadFn<T, Option<Color>>,
38}
39
40impl<M, T> IconColumn<M, T>
41where
42 M: toasty::schema::Model,
43 T: FormScalar + Send + Sync + 'static,
44{
45 pub fn new(lens: Lens<M, T>) -> Self {
47 Self {
48 base: ColumnBase::new(lens.path(), ColumnWidth::Auto),
49 lens,
50 sortable: false,
51 icon: Arc::new(|_, value: &T| T::icon(value)),
52 color: Arc::new(|_, value: &T| T::color(value)),
53 }
54 }
55
56 pub fn icon(
58 mut self,
59 icon: impl Fn(&Cx, &T) -> Option<IconData> + Send + Sync + 'static,
60 ) -> Self {
61 self.icon = Arc::new(icon);
62 self
63 }
64
65 pub fn color(
67 mut self,
68 color: impl Fn(&Cx, &T) -> Option<Color> + Send + Sync + 'static,
69 ) -> Self {
70 self.color = Arc::new(color);
71 self
72 }
73
74 base_builders!(sortable);
75}
76
77impl<M, T> Column<M> for IconColumn<M, T>
78where
79 M: toasty::schema::Model + Send + Sync + 'static,
80 T: FormScalar + Send + Sync + 'static,
81{
82 base_column_methods!();
83
84 fn text(&self, cx: &Cx, row: &M) -> String {
85 self.lens.read(row).to_label().localize(cx)
86 }
87
88 fn cell<'a>(&self, cx: &'a Cx, row: &M) -> BoxView<'a> {
89 let value = self.lens.read(row);
90 let label = value.to_label().localize(cx);
91 match (self.icon)(cx, value) {
92 Some(data) => icon_cell(cx, label, icon_view(cx, data, (self.color)(cx, value))),
93 None => crate::schema::value_cell(cx, &label),
94 }
95 }
96
97 fn order_by(&self, descending: bool) -> Option<OrderByExpr> {
98 self.sortable
99 .then(|| sort_order(self.lens.path(), descending))
100 }
101}
102
103impl<M, T> crate::column::ColumnInternals<M> for IconColumn<M, T>
104where
105 M: toasty::schema::Model + Send + Sync + 'static,
106 T: FormScalar + Send + Sync + 'static,
107{
108 base_internals!(binding);
109}
110
111fn icon_cell<'a>(cx: &'a Cx, label: String, glyph: BoxView<'a>) -> BoxView<'a> {
113 view! {
114 <span class="inline-flex items-center" title=(label.clone())>
115 (glyph)
116 <span class="sr-only">(label)</span>
117 </span>
118 }
119 .boxed()
120}