use gpui_kit::{AnyElement, App, IntoElement as _, Window};
use std::fmt::Display;
pub trait TableCell {
fn draw(&self, window: &mut Window, cx: &mut App) -> AnyElement;
}
pub struct DisplayCell<T>(pub T);
impl<T> DisplayCell<T> {
pub fn new(value: T) -> Self {
Self(value)
}
pub fn into_inner(self) -> T {
self.0
}
}
impl<T: Display> TableCell for DisplayCell<T> {
fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
self.0.to_string().into_any_element()
}
}
pub struct FormattedCell<T, F> {
value: T,
formatter: F,
}
impl<T, F> FormattedCell<T, F> {
pub fn new(value: T, formatter: F) -> Self {
Self { value, formatter }
}
pub fn value(&self) -> &T {
&self.value
}
pub fn into_inner(self) -> T {
self.value
}
}
impl<T, F, S> TableCell for FormattedCell<T, F>
where
F: Fn(&T) -> S,
S: Display,
{
fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
(self.formatter)(&self.value).to_string().into_any_element()
}
}
#[cfg(feature = "jiff")]
mod datetime_format {
use icu::{
calendar::{Date, Iso},
datetime::{
DateTimeFormatter, DateTimeFormatterPreferences, NoCalendarFormatter,
fieldsets::{self, Combo},
input::{DateTime as IcuDateTime, Time, UtcOffset, ZonedDateTime},
},
locale::Locale,
};
use jiff::{Timestamp, Zoned, civil, tz::TimeZone};
type DateFormatter = DateTimeFormatter<fieldsets::YMD>;
type DateTimeFormatterNoZone = DateTimeFormatter<fieldsets::YMDT>;
type DateTimeFormatterWithZone =
DateTimeFormatter<Combo<fieldsets::YMDT, fieldsets::zone::LocalizedOffsetLong>>;
type TimeFormatter = NoCalendarFormatter<fieldsets::T>;
fn formatter_preferences() -> DateTimeFormatterPreferences {
let raw = gpui_kit::component::locale();
let normalized = raw.replace('_', "-");
let locale = normalized.parse::<Locale>().unwrap_or_else(|error| {
panic!("gpui-kit locale `{normalized}` is not a valid ICU locale: {error}")
});
locale.into()
}
fn date_formatter() -> DateFormatter {
DateTimeFormatter::try_new(formatter_preferences(), fieldsets::YMD::medium())
.unwrap_or_else(|error| panic!("failed to create ICU date formatter: {error:?}"))
}
fn datetime_formatter() -> DateTimeFormatterNoZone {
let fieldset = fieldsets::YMD::medium().with_time_hms();
DateTimeFormatter::try_new(formatter_preferences(), fieldset)
.unwrap_or_else(|error| panic!("failed to create ICU datetime formatter: {error:?}"))
}
fn zoned_datetime_formatter() -> DateTimeFormatterWithZone {
let fieldset = fieldsets::YMD::medium()
.with_time_hms()
.with_zone(fieldsets::zone::LocalizedOffsetLong);
DateTimeFormatter::try_new(formatter_preferences(), fieldset).unwrap_or_else(|error| {
panic!("failed to create ICU zoned datetime formatter: {error:?}")
})
}
fn time_formatter() -> TimeFormatter {
NoCalendarFormatter::try_new(formatter_preferences(), fieldsets::T::medium())
.unwrap_or_else(|error| panic!("failed to create ICU time formatter: {error:?}"))
}
fn to_icu_date(value: civil::Date) -> Date<Iso> {
let month = u8::try_from(value.month()).expect("jiff months fit ICU month values");
let day = u8::try_from(value.day()).expect("jiff days fit ICU day values");
Date::try_new_iso(i32::from(value.year()), month, day).unwrap_or_else(|error| {
panic!("jiff date `{value}` is not a valid ICU date: {error:?}")
})
}
fn to_icu_time(value: civil::Time) -> Time {
let hour = u8::try_from(value.hour()).expect("jiff hours fit ICU hour values");
let minute = u8::try_from(value.minute()).expect("jiff minutes fit ICU minute values");
let second = u8::try_from(value.second()).expect("jiff seconds fit ICU second values");
let nanosecond =
u32::try_from(value.subsec_nanosecond()).expect("jiff nanoseconds fit ICU values");
Time::try_new(hour, minute, second, nanosecond).unwrap_or_else(|error| {
panic!("jiff time `{value}` is not a valid ICU time: {error:?}")
})
}
pub(super) fn format_zoned(value: &Zoned) -> String {
let utc_offset =
UtcOffset::try_from_seconds(value.offset().seconds()).unwrap_or_else(|error| {
panic!("zoned datetime `{value}` has an invalid ICU offset: {error:?}")
});
let zoned = ZonedDateTime::from_epoch_milliseconds_and_utc_offset(
value.timestamp().as_millisecond(),
utc_offset,
);
let formatter = zoned_datetime_formatter();
formatter.format(&zoned).to_string()
}
pub(super) fn format_timestamp_local(value: Timestamp) -> String {
let zoned = value.to_zoned(TimeZone::system());
format_zoned(&zoned)
}
pub(super) fn format_civil_datetime(value: civil::DateTime) -> String {
let date = to_icu_date(value.date());
let time = to_icu_time(value.time());
let datetime = IcuDateTime { date, time };
datetime_formatter().format(&datetime).to_string()
}
pub(super) fn format_civil_date(value: civil::Date) -> String {
let date = to_icu_date(value);
date_formatter().format(&date).to_string()
}
pub(super) fn format_civil_time(value: civil::Time) -> String {
let time = to_icu_time(value);
time_formatter().format(&time).to_string()
}
#[cfg(feature = "chrono")]
pub(super) fn chrono_datetime_to_system_zoned<Tz: chrono::TimeZone>(
value: &chrono::DateTime<Tz>,
) -> Option<Zoned> {
if value.timestamp_subsec_nanos() >= 1_000_000_000 {
return None;
}
let nanosecond = i32::try_from(value.timestamp_subsec_nanos()).ok()?;
let timestamp = Timestamp::new(value.timestamp(), nanosecond).ok()?;
Some(timestamp.to_zoned(TimeZone::system()))
}
#[cfg(feature = "chrono")]
pub(super) fn chrono_naive_datetime_to_jiff(
value: &chrono::NaiveDateTime,
) -> Option<civil::DateTime> {
Some(civil::DateTime::from_parts(
chrono_naive_date_to_jiff(&value.date())?,
chrono_naive_time_to_jiff(&value.time())?,
))
}
#[cfg(feature = "chrono")]
pub(super) fn chrono_naive_date_to_jiff(value: &chrono::NaiveDate) -> Option<civil::Date> {
use chrono::Datelike as _;
civil::Date::new(
i16::try_from(value.year()).ok()?,
i8::try_from(value.month()).ok()?,
i8::try_from(value.day()).ok()?,
)
.ok()
}
#[cfg(feature = "chrono")]
pub(super) fn chrono_naive_time_to_jiff(value: &chrono::NaiveTime) -> Option<civil::Time> {
use chrono::Timelike as _;
civil::Time::new(
i8::try_from(value.hour()).ok()?,
i8::try_from(value.minute()).ok()?,
i8::try_from(value.second()).ok()?,
i32::try_from(value.nanosecond()).ok()?,
)
.ok()
}
#[cfg(feature = "chrono")]
pub(super) fn format_chrono_datetime<Tz: chrono::TimeZone>(
value: &chrono::DateTime<Tz>,
) -> String
where
Tz::Offset: std::fmt::Display,
{
chrono_datetime_to_system_zoned(value)
.map(|zoned| format_zoned(&zoned))
.unwrap_or_else(|| value.to_string())
}
#[cfg(feature = "chrono")]
pub(super) fn format_chrono_naive_datetime(value: &chrono::NaiveDateTime) -> String {
chrono_naive_datetime_to_jiff(value)
.map(format_civil_datetime)
.unwrap_or_else(|| value.to_string())
}
#[cfg(feature = "chrono")]
pub(super) fn format_chrono_naive_date(value: &chrono::NaiveDate) -> String {
chrono_naive_date_to_jiff(value)
.map(format_civil_date)
.unwrap_or_else(|| value.to_string())
}
#[cfg(feature = "chrono")]
pub(super) fn format_chrono_naive_time(value: &chrono::NaiveTime) -> String {
chrono_naive_time_to_jiff(value)
.map(format_civil_time)
.unwrap_or_else(|| value.to_string())
}
}
macro_rules! impl_table_cell_display {
($($t:ty),* $(,)?) => {
$(
impl TableCell for $t {
fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
self.to_string().into_any_element()
}
}
)*
};
}
macro_rules! impl_table_cell_float {
($($t:ty),* $(,)?) => {
$(
impl TableCell for $t {
fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
format!("{:.2}", self).into_any_element()
}
}
)*
};
}
impl<T: TableCell> TableCell for Option<T> {
fn draw(&self, window: &mut Window, cx: &mut App) -> AnyElement {
match self {
Some(value) => value.draw(window, cx),
None => "".into_any_element(),
}
}
}
impl<T: TableCell> TableCell for Vec<T> {
fn draw(&self, window: &mut Window, cx: &mut App) -> AnyElement {
use gpui_kit::{ParentElement as _, Styled as _};
let mut children = Vec::with_capacity(self.len().saturating_mul(2));
for (index, value) in self.iter().enumerate() {
if index > 0 {
children.push(", ".into_any_element());
}
children.push(value.draw(window, cx));
}
gpui_kit::div()
.flex()
.items_center()
.gap_1()
.children(children)
.into_any_element()
}
}
impl_table_cell_display!(
String, &str, usize, isize, u8, u16, u32, u64, u128, i8, i16, i32, i64, i128
);
impl_table_cell_float!(f32, f64);
impl TableCell for bool {
fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
(if *self { "✓" } else { "✗" }).into_any_element()
}
}
#[cfg(feature = "spacetimedb")]
impl TableCell for spacetimedb_lib::Timestamp {
fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
self.to_string().into_any_element()
}
}
#[cfg(feature = "rust_decimal")]
impl TableCell for rust_decimal::Decimal {
fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
format!("{:.2}", self).into_any_element()
}
}
#[cfg(feature = "chrono")]
impl<Tz: chrono::TimeZone> TableCell for chrono::DateTime<Tz>
where
Tz::Offset: std::fmt::Display,
{
fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
datetime_format::format_chrono_datetime(self).into_any_element()
}
}
#[cfg(feature = "chrono")]
impl TableCell for chrono::NaiveDateTime {
fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
datetime_format::format_chrono_naive_datetime(self).into_any_element()
}
}
#[cfg(feature = "chrono")]
impl TableCell for chrono::NaiveDate {
fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
datetime_format::format_chrono_naive_date(self).into_any_element()
}
}
#[cfg(feature = "chrono")]
impl TableCell for chrono::NaiveTime {
fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
datetime_format::format_chrono_naive_time(self).into_any_element()
}
}
#[cfg(feature = "jiff")]
impl TableCell for jiff::Zoned {
fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
datetime_format::format_zoned(self).into_any_element()
}
}
#[cfg(feature = "jiff")]
impl TableCell for jiff::Timestamp {
fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
datetime_format::format_timestamp_local(*self).into_any_element()
}
}
#[cfg(feature = "jiff")]
impl TableCell for jiff::civil::DateTime {
fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
datetime_format::format_civil_datetime(*self).into_any_element()
}
}
#[cfg(feature = "jiff")]
impl TableCell for jiff::civil::Date {
fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
datetime_format::format_civil_date(*self).into_any_element()
}
}
#[cfg(feature = "jiff")]
impl TableCell for jiff::civil::Time {
fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
datetime_format::format_civil_time(*self).into_any_element()
}
}
#[cfg(test)]
mod tests {
use super::{DisplayCell, FormattedCell};
#[test]
fn cell_wrappers_preserve_values_and_formatters() {
let display = DisplayCell::new(42);
assert_eq!(display.into_inner(), 42);
let formatted = FormattedCell::new(42, |value: &i32| format!("{value} kg"));
assert_eq!(formatted.value(), &42);
assert_eq!((formatted.formatter)(formatted.value()), "42 kg");
assert_eq!(formatted.into_inner(), 42);
}
#[cfg(feature = "jiff")]
#[test]
fn jiff_values_format_through_icu() {
use super::datetime_format::{
format_civil_date, format_civil_datetime, format_civil_time, format_timestamp_local,
format_zoned,
};
use jiff::{Timestamp, Zoned, civil};
let date = civil::Date::new(2026, 7, 11).unwrap();
let time = civil::Time::new(12, 34, 56, 123_000_000).unwrap();
let datetime = civil::DateTime::from_parts(date, time);
let zoned: Zoned = "2026-07-11T12:34:56-04:00[America/New_York]"
.parse()
.unwrap();
let timestamp: Timestamp = "2026-07-11T16:34:56Z".parse().unwrap();
assert!(!format_civil_date(date).is_empty());
assert!(!format_civil_time(time).is_empty());
assert!(!format_civil_datetime(datetime).is_empty());
assert!(!format_zoned(&zoned).is_empty());
assert!(!format_timestamp_local(timestamp).is_empty());
}
#[cfg(all(feature = "jiff", feature = "chrono"))]
#[test]
fn chrono_values_convert_to_jiff_equivalents() {
use super::datetime_format::{
chrono_datetime_to_system_zoned, chrono_naive_date_to_jiff,
chrono_naive_datetime_to_jiff, chrono_naive_time_to_jiff,
};
use chrono::{DateTime, NaiveDate, Utc};
let date = NaiveDate::from_ymd_opt(2026, 7, 11).unwrap();
let time = date.and_hms_nano_opt(12, 34, 56, 123_000_000).unwrap();
let zoned = DateTime::<Utc>::from_naive_utc_and_offset(time, Utc);
assert_eq!(
chrono_naive_date_to_jiff(&date).unwrap().to_string(),
"2026-07-11"
);
assert_eq!(
chrono_naive_time_to_jiff(&time.time()).unwrap().to_string(),
"12:34:56.123"
);
assert_eq!(
chrono_naive_datetime_to_jiff(&time).unwrap().to_string(),
"2026-07-11T12:34:56.123"
);
assert_eq!(
chrono_datetime_to_system_zoned(&zoned).unwrap().timestamp(),
"2026-07-11T12:34:56.123Z".parse().unwrap()
);
}
#[cfg(feature = "chrono")]
#[test]
fn chrono_dates_outside_jiff_range_preserve_original_display() {
use super::datetime_format::{format_chrono_naive_date, format_chrono_naive_datetime};
use chrono::NaiveDate;
for date in [
NaiveDate::MIN,
NaiveDate::MAX,
NaiveDate::from_ymd_opt(-10_000, 1, 1).unwrap(),
NaiveDate::from_ymd_opt(10_000, 12, 31).unwrap(),
] {
assert_eq!(format_chrono_naive_date(&date), date.to_string());
let datetime = date.and_hms_nano_opt(12, 34, 56, 123_000_000).unwrap();
assert_eq!(
format_chrono_naive_datetime(&datetime),
datetime.to_string()
);
}
}
#[cfg(feature = "chrono")]
#[test]
fn chrono_timestamps_outside_jiff_range_preserve_original_offset() {
use super::datetime_format::format_chrono_datetime;
use chrono::{DateTime, FixedOffset, NaiveDate, TimeZone as _, Utc};
for datetime in [DateTime::<Utc>::MIN_UTC, DateTime::<Utc>::MAX_UTC] {
assert_eq!(format_chrono_datetime(&datetime), datetime.to_string());
}
let local = NaiveDate::from_ymd_opt(10_000, 1, 1)
.unwrap()
.and_hms_opt(12, 34, 56)
.unwrap();
let offset = FixedOffset::east_opt(3600).unwrap();
let datetime = offset.from_local_datetime(&local).single().unwrap();
assert_eq!(
format_chrono_datetime(&datetime),
"+10000-01-01 12:34:56 +01:00"
);
}
#[cfg(feature = "chrono")]
#[test]
fn chrono_leap_seconds_preserve_original_display() {
use super::datetime_format::{
format_chrono_datetime, format_chrono_naive_datetime, format_chrono_naive_time,
};
use chrono::{DateTime, NaiveDate, NaiveTime, Utc};
let time = NaiveTime::from_hms_nano_opt(23, 59, 59, 1_500_000_000).unwrap();
let datetime = NaiveDate::from_ymd_opt(2016, 12, 31)
.unwrap()
.and_time(time);
let zoned = DateTime::<Utc>::from_naive_utc_and_offset(datetime, Utc);
assert_eq!(format_chrono_naive_time(&time), "23:59:60.500");
assert_eq!(
format_chrono_naive_datetime(&datetime),
"2016-12-31 23:59:60.500"
);
assert_eq!(
format_chrono_datetime(&zoned),
"2016-12-31 23:59:60.500 UTC"
);
}
}