Skip to main content

tablo_core/
display.rs

1//! How a cell presents its value: its [`Color`], its [`Alignment`], and the number and money
2//! spellings of a [`Numeric`] value, and the badge every colored value shares.
3
4use topcoat::{
5    context::Cx,
6    icon::{IconData, icon},
7    view::{BoxView, ViewExt, attributes, view},
8};
9
10/// A semantic color for a badge, a status dot or a cell's text.
11///
12/// Each maps to a theme token (`--success`, `--warning`, `--info`, `--destructive`,
13/// `--primary`, `--muted-foreground`), so a theme that redeclares the token recolors every cell
14/// that uses it.
15///
16/// ```rust
17/// #[derive(tablo_core::Options)]
18/// enum Status {
19///     #[option(color = "warning")]
20///     Pending,
21///     #[option(color = "success")]
22///     Paid,
23///     #[option(color = "danger")]
24///     Refunded,
25/// }
26/// ```
27#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
28#[non_exhaustive]
29pub enum Color {
30    /// A neutral, muted status.
31    #[default]
32    Gray,
33    /// The theme's primary color.
34    Primary,
35    /// Done, paid, active.
36    Success,
37    /// Pending, expiring, low.
38    Warning,
39    /// Failed, refunded, overdue.
40    Danger,
41    /// Informational, in progress.
42    Info,
43}
44
45impl Color {
46    /// The color a `#[option(color = "…")]` attribute names.
47    #[doc(hidden)]
48    pub const fn from_name(name: &str) -> Option<Self> {
49        Some(match name.as_bytes() {
50            b"gray" => Self::Gray,
51            b"primary" => Self::Primary,
52            b"success" => Self::Success,
53            b"warning" => Self::Warning,
54            b"danger" => Self::Danger,
55            b"info" => Self::Info,
56            _ => return None,
57        })
58    }
59
60    /// The name a `#[option(color = "…")]` attribute gives this color.
61    pub(crate) const fn name(self) -> &'static str {
62        match self {
63            Self::Gray => "gray",
64            Self::Primary => "primary",
65            Self::Success => "success",
66            Self::Warning => "warning",
67            Self::Danger => "danger",
68            Self::Info => "info",
69        }
70    }
71
72    /// The class of a badge's status dot in this color.
73    pub(crate) const fn dot_class(self) -> &'static str {
74        match self {
75            Self::Gray => "size-1.5 shrink-0 rounded-full bg-muted-foreground/60",
76            Self::Primary => "size-1.5 shrink-0 rounded-full bg-primary",
77            Self::Success => "size-1.5 shrink-0 rounded-full bg-success",
78            Self::Warning => "size-1.5 shrink-0 rounded-full bg-warning",
79            Self::Danger => "size-1.5 shrink-0 rounded-full bg-destructive",
80            Self::Info => "size-1.5 shrink-0 rounded-full bg-info",
81        }
82    }
83
84    /// The classes of a badge in this color: a tint of it behind its text, ringed by a stronger
85    /// one.
86    pub(crate) const fn badge_class(self) -> &'static str {
87        match self {
88            Self::Gray => "bg-muted text-muted-foreground ring-foreground/10",
89            Self::Primary => "bg-primary/10 text-primary ring-primary/25",
90            Self::Success => "bg-success/10 text-success ring-success/25",
91            Self::Warning => "bg-warning/10 text-warning ring-warning/30",
92            Self::Danger => "bg-destructive/10 text-destructive ring-destructive/25",
93            Self::Info => "bg-info/10 text-info ring-info/25",
94        }
95    }
96
97    /// The classes of a choice's button in this color: its icon in the color, and the button
98    /// tinted in it while its option is chosen.
99    pub(crate) const fn toggle_class(self) -> &'static str {
100        match self {
101            Self::Gray => {
102                "[&>svg]:text-muted-foreground has-[:checked]:border-foreground/25 \
103                 has-[:checked]:bg-muted has-[:checked]:text-foreground"
104            }
105            Self::Primary => {
106                "[&>svg]:text-primary has-[:checked]:border-primary has-[:checked]:bg-primary/10 \
107                 has-[:checked]:text-primary"
108            }
109            Self::Success => {
110                "[&>svg]:text-success has-[:checked]:border-success has-[:checked]:bg-success/10 \
111                 has-[:checked]:text-success"
112            }
113            Self::Warning => {
114                "[&>svg]:text-warning has-[:checked]:border-warning has-[:checked]:bg-warning/10 \
115                 has-[:checked]:text-warning"
116            }
117            Self::Danger => {
118                "[&>svg]:text-destructive has-[:checked]:border-destructive \
119                 has-[:checked]:bg-destructive/10 has-[:checked]:text-destructive"
120            }
121            Self::Info => {
122                "[&>svg]:text-info has-[:checked]:border-info has-[:checked]:bg-info/10 \
123                 has-[:checked]:text-info"
124            }
125        }
126    }
127
128    /// The class of a surface filled with this color, such as an environment's stripe.
129    pub(crate) const fn fill_class(self) -> &'static str {
130        match self {
131            Self::Gray => "bg-muted-foreground",
132            Self::Primary => "bg-primary",
133            Self::Success => "bg-success",
134            Self::Warning => "bg-warning",
135            Self::Danger => "bg-destructive",
136            Self::Info => "bg-info",
137        }
138    }
139
140    /// The class of a table row tinted in this color.
141    pub(crate) const fn row_class(self) -> &'static str {
142        match self {
143            Self::Gray => "bg-muted/50",
144            Self::Primary => "bg-primary/5",
145            Self::Success => "bg-success/10",
146            Self::Warning => "bg-warning/10",
147            Self::Danger => "bg-destructive/10",
148            Self::Info => "bg-info/10",
149        }
150    }
151
152    /// The classes that tint a button in this color, `None` for the neutral button. They are
153    /// marked important to win over the outline button's own colors.
154    pub(crate) const fn button_tone(self) -> Option<&'static str> {
155        match self {
156            Self::Gray => None,
157            Self::Primary => Some("text-primary! hover:bg-primary/5! active:bg-primary/10!"),
158            Self::Success => Some("text-success! hover:bg-success/5! active:bg-success/10!"),
159            Self::Warning => Some("text-warning! hover:bg-warning/5! active:bg-warning/10!"),
160            Self::Danger => {
161                Some("text-destructive! hover:bg-destructive/5! active:bg-destructive/10!")
162            }
163            Self::Info => Some("text-info! hover:bg-info/5! active:bg-info/10!"),
164        }
165    }
166
167    /// The class of a cell's text in this color.
168    pub(crate) const fn text_class(self) -> &'static str {
169        match self {
170            Self::Gray => "text-muted-foreground",
171            Self::Primary => "text-primary",
172            Self::Success => "text-success",
173            Self::Warning => "text-warning",
174            Self::Danger => "text-destructive",
175            Self::Info => "text-info",
176        }
177    }
178}
179
180/// How heavy a column's text renders.
181#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
182pub enum FontWeight {
183    /// Lighter than the body text.
184    Light,
185    /// The body text's weight, the default.
186    #[default]
187    Normal,
188    /// Between normal and semibold.
189    Medium,
190    /// Between medium and bold.
191    Semibold,
192    /// The heaviest.
193    Bold,
194}
195
196impl FontWeight {
197    /// The font-weight class of this weight, empty at the body text's.
198    pub(crate) const fn class(self) -> &'static str {
199        match self {
200            Self::Light => "font-light",
201            Self::Normal => "",
202            Self::Medium => "font-medium",
203            Self::Semibold => "font-semibold",
204            Self::Bold => "font-bold",
205        }
206    }
207}
208
209/// Where a column's header and cells align their content.
210#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
211pub enum Alignment {
212    /// The reading direction's start, the default.
213    #[default]
214    Start,
215    /// The middle of the column.
216    Center,
217    /// The reading direction's end: numbers and money, so their digits line up.
218    End,
219}
220
221impl Alignment {
222    /// The text-alignment class of this alignment, empty at the start.
223    pub(crate) const fn class(self) -> &'static str {
224        match self {
225            Self::Start => "",
226            Self::Center => "text-center",
227            Self::End => "text-end",
228        }
229    }
230}
231
232/// A number as a cell reads it: an integer and a decimal stay exact, a float is rounded when
233/// spelled.
234///
235/// Equality compares the representation, not the amount: `Decimal { mantissa: 1250, scale: 2 }`
236/// differs from `Decimal { mantissa: 125, scale: 1 }`, and `Int(12)` from
237/// `Decimal { mantissa: 12, scale: 0 }`.
238#[derive(Clone, Copy, Debug, PartialEq)]
239#[non_exhaustive]
240pub enum Number {
241    /// Any integer type, widened.
242    Int(i128),
243    /// `f32` or `f64`.
244    Float(f64),
245    /// `mantissa / 10^scale`, exactly: a decimal type's value. Spelled with fewer digits than
246    /// `scale`, it rounds half to even, as a float's spelling does.
247    Decimal {
248        /// The digits, with the sign.
249        mantissa: i128,
250        /// How many of the digits follow the point.
251        scale: u32,
252    },
253}
254
255/// A field a [`TextColumn`](crate::TextColumn) can spell as a number or an amount of money:
256/// every integer and float type, `rust_decimal::Decimal` and `bigdecimal::BigDecimal` with the
257/// features of those names, and an `Option` of one, which reads as the table's dash when `None`.
258pub trait Numeric {
259    /// The value, `None` when it holds none.
260    fn number(&self) -> Option<Number>;
261}
262
263impl<T: Numeric + ?Sized> Numeric for &T {
264    fn number(&self) -> Option<Number> {
265        (**self).number()
266    }
267}
268
269macro_rules! numeric_ints {
270    ($($ty:ty),+) => {
271        $(
272            impl Numeric for $ty {
273                fn number(&self) -> Option<Number> {
274                    Some(Number::Int(i128::from(*self)))
275                }
276            }
277        )+
278    };
279}
280
281numeric_ints!(i8, i16, i32, i64, u8, u16, u32, u64);
282
283impl Numeric for f32 {
284    fn number(&self) -> Option<Number> {
285        Some(Number::Float(f64::from(*self)))
286    }
287}
288
289impl Numeric for f64 {
290    fn number(&self) -> Option<Number> {
291        Some(Number::Float(*self))
292    }
293}
294
295#[cfg(feature = "rust_decimal")]
296impl Numeric for rust_decimal::Decimal {
297    fn number(&self) -> Option<Number> {
298        Some(Number::Decimal {
299            mantissa: self.mantissa(),
300            scale: self.scale(),
301        })
302    }
303}
304
305/// A value of more than 38 significant digits, which no `i128` mantissa holds, is rounded to 38,
306/// half to even; one whose integer part alone outgrows them reads as a float.
307#[cfg(feature = "bigdecimal")]
308impl Numeric for bigdecimal::BigDecimal {
309    fn number(&self) -> Option<Number> {
310        use bigdecimal::{RoundingMode, ToPrimitive};
311
312        const DIGITS: u64 = 38;
313        let exact = || {
314            let (mantissa, scale) = match self.digits().checked_sub(DIGITS) {
315                Some(excess @ 1..) => {
316                    let (_, scale) = self.as_bigint_and_scale();
317                    let scale = scale.checked_sub(i64::try_from(excess).ok()?)?;
318                    self.with_scale_round(scale, RoundingMode::HalfEven)
319                        .into_bigint_and_scale()
320                }
321                _ => self.clone().into_bigint_and_scale(),
322            };
323            let mantissa = mantissa.to_i128()?;
324            match u32::try_from(scale) {
325                Ok(scale) => Some(Number::Decimal { mantissa, scale }),
326                Err(_) if scale < 0 => {
327                    let shift = 10i128.checked_pow(u32::try_from(scale.unsigned_abs()).ok()?)?;
328                    Some(Number::Decimal {
329                        mantissa: mantissa.checked_mul(shift)?,
330                        scale: 0,
331                    })
332                }
333                Err(_) => None,
334            }
335        };
336        exact().or_else(|| {
337            self.to_f64()
338                .filter(|float| float.is_finite())
339                .map(Number::Float)
340        })
341    }
342}
343
344impl<T: Numeric> Numeric for Option<T> {
345    fn number(&self) -> Option<Number> {
346        self.as_ref().and_then(Numeric::number)
347    }
348}
349
350mod number;
351
352pub use number::Currency;
353pub(crate) use number::NumberFormat;
354#[cfg(test)]
355use number::format_number;
356
357#[cfg(test)]
358mod tests;
359
360/// The classes every badge shares, before its color's.
361const BADGE: &str = "inline-flex w-fit shrink-0 items-center gap-1 rounded-md px-1.5 py-0.5 text-xs \
362     font-medium whitespace-nowrap ring-1 ring-inset [&>svg]:size-3.5 [&>svg]:shrink-0";
363
364/// `text` as a badge tinted in `color`, gray without one, led by `icon` when it has one: a
365/// cell's, a tab's or a sidebar entry's.
366pub(crate) fn badge<'a>(
367    cx: &'a Cx,
368    text: String,
369    color: Option<Color>,
370    icon_data: Option<IconData>,
371) -> BoxView<'a> {
372    let class = format!("{BADGE} {}", color.unwrap_or_default().badge_class());
373    view! {
374        <span class=(class) data-slot="badge">
375            if let Some(data) = icon_data {
376                icon(data: data, attrs: attributes! { aria-hidden="true" })
377            }
378            (text)
379        </span>
380    }
381    .boxed()
382}