1use gpui_kit::{AnyElement, App, IntoElement as _, Window};
2use std::fmt::Display;
3
4pub trait TableCell {
10 fn draw(&self, window: &mut Window, cx: &mut App) -> AnyElement;
11}
12
13pub struct DisplayCell<T>(pub T);
18
19impl<T> DisplayCell<T> {
20 pub fn new(value: T) -> Self {
21 Self(value)
22 }
23
24 pub fn into_inner(self) -> T {
25 self.0
26 }
27}
28
29impl<T: Display> TableCell for DisplayCell<T> {
30 fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
31 self.0.to_string().into_any_element()
32 }
33}
34
35pub struct FormattedCell<T, F> {
37 value: T,
38 formatter: F,
39}
40
41impl<T, F> FormattedCell<T, F> {
42 pub fn new(value: T, formatter: F) -> Self {
43 Self { value, formatter }
44 }
45
46 pub fn value(&self) -> &T {
47 &self.value
48 }
49
50 pub fn into_inner(self) -> T {
51 self.value
52 }
53}
54
55impl<T, F, S> TableCell for FormattedCell<T, F>
56where
57 F: Fn(&T) -> S,
58 S: Display,
59{
60 fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
61 (self.formatter)(&self.value).to_string().into_any_element()
62 }
63}
64
65#[cfg(feature = "jiff")]
66mod datetime_format {
67 use icu::{
68 calendar::{Date, Iso},
69 datetime::{
70 DateTimeFormatter, DateTimeFormatterPreferences, NoCalendarFormatter,
71 fieldsets::{self, Combo},
72 input::{DateTime as IcuDateTime, Time, UtcOffset, ZonedDateTime},
73 },
74 locale::Locale,
75 };
76 use jiff::{Timestamp, Zoned, civil, tz::TimeZone};
77
78 type DateFormatter = DateTimeFormatter<fieldsets::YMD>;
79 type DateTimeFormatterNoZone = DateTimeFormatter<fieldsets::YMDT>;
80 type DateTimeFormatterWithZone =
81 DateTimeFormatter<Combo<fieldsets::YMDT, fieldsets::zone::LocalizedOffsetLong>>;
82 type TimeFormatter = NoCalendarFormatter<fieldsets::T>;
83
84 fn formatter_preferences() -> DateTimeFormatterPreferences {
85 let raw = gpui_kit::component::locale();
86 let normalized = raw.replace('_', "-");
87 let locale = normalized.parse::<Locale>().unwrap_or_else(|error| {
88 panic!("gpui-kit locale `{normalized}` is not a valid ICU locale: {error}")
89 });
90 locale.into()
91 }
92
93 fn date_formatter() -> DateFormatter {
94 DateTimeFormatter::try_new(formatter_preferences(), fieldsets::YMD::medium())
95 .unwrap_or_else(|error| panic!("failed to create ICU date formatter: {error:?}"))
96 }
97
98 fn datetime_formatter() -> DateTimeFormatterNoZone {
99 let fieldset = fieldsets::YMD::medium().with_time_hms();
100 DateTimeFormatter::try_new(formatter_preferences(), fieldset)
101 .unwrap_or_else(|error| panic!("failed to create ICU datetime formatter: {error:?}"))
102 }
103
104 fn zoned_datetime_formatter() -> DateTimeFormatterWithZone {
105 let fieldset = fieldsets::YMD::medium()
106 .with_time_hms()
107 .with_zone(fieldsets::zone::LocalizedOffsetLong);
108 DateTimeFormatter::try_new(formatter_preferences(), fieldset).unwrap_or_else(|error| {
109 panic!("failed to create ICU zoned datetime formatter: {error:?}")
110 })
111 }
112
113 fn time_formatter() -> TimeFormatter {
114 NoCalendarFormatter::try_new(formatter_preferences(), fieldsets::T::medium())
115 .unwrap_or_else(|error| panic!("failed to create ICU time formatter: {error:?}"))
116 }
117
118 fn to_icu_date(value: civil::Date) -> Date<Iso> {
119 let month = u8::try_from(value.month()).expect("jiff months fit ICU month values");
120 let day = u8::try_from(value.day()).expect("jiff days fit ICU day values");
121 Date::try_new_iso(i32::from(value.year()), month, day).unwrap_or_else(|error| {
122 panic!("jiff date `{value}` is not a valid ICU date: {error:?}")
123 })
124 }
125
126 fn to_icu_time(value: civil::Time) -> Time {
127 let hour = u8::try_from(value.hour()).expect("jiff hours fit ICU hour values");
128 let minute = u8::try_from(value.minute()).expect("jiff minutes fit ICU minute values");
129 let second = u8::try_from(value.second()).expect("jiff seconds fit ICU second values");
130 let nanosecond =
131 u32::try_from(value.subsec_nanosecond()).expect("jiff nanoseconds fit ICU values");
132 Time::try_new(hour, minute, second, nanosecond).unwrap_or_else(|error| {
133 panic!("jiff time `{value}` is not a valid ICU time: {error:?}")
134 })
135 }
136
137 pub(super) fn format_zoned(value: &Zoned) -> String {
138 let utc_offset =
139 UtcOffset::try_from_seconds(value.offset().seconds()).unwrap_or_else(|error| {
140 panic!("zoned datetime `{value}` has an invalid ICU offset: {error:?}")
141 });
142 let zoned = ZonedDateTime::from_epoch_milliseconds_and_utc_offset(
143 value.timestamp().as_millisecond(),
144 utc_offset,
145 );
146 let formatter = zoned_datetime_formatter();
147 formatter.format(&zoned).to_string()
148 }
149
150 pub(super) fn format_timestamp_local(value: Timestamp) -> String {
151 let zoned = value.to_zoned(TimeZone::system());
152 format_zoned(&zoned)
153 }
154
155 pub(super) fn format_civil_datetime(value: civil::DateTime) -> String {
156 let date = to_icu_date(value.date());
157 let time = to_icu_time(value.time());
158 let datetime = IcuDateTime { date, time };
159 datetime_formatter().format(&datetime).to_string()
160 }
161
162 pub(super) fn format_civil_date(value: civil::Date) -> String {
163 let date = to_icu_date(value);
164 date_formatter().format(&date).to_string()
165 }
166
167 pub(super) fn format_civil_time(value: civil::Time) -> String {
168 let time = to_icu_time(value);
169 time_formatter().format(&time).to_string()
170 }
171
172 #[cfg(feature = "chrono")]
173 pub(super) fn chrono_datetime_to_system_zoned<Tz: chrono::TimeZone>(
174 value: &chrono::DateTime<Tz>,
175 ) -> Option<Zoned> {
176 if value.timestamp_subsec_nanos() >= 1_000_000_000 {
179 return None;
180 }
181 let nanosecond = i32::try_from(value.timestamp_subsec_nanos()).ok()?;
182 let timestamp = Timestamp::new(value.timestamp(), nanosecond).ok()?;
183 Some(timestamp.to_zoned(TimeZone::system()))
184 }
185
186 #[cfg(feature = "chrono")]
187 pub(super) fn chrono_naive_datetime_to_jiff(
188 value: &chrono::NaiveDateTime,
189 ) -> Option<civil::DateTime> {
190 Some(civil::DateTime::from_parts(
191 chrono_naive_date_to_jiff(&value.date())?,
192 chrono_naive_time_to_jiff(&value.time())?,
193 ))
194 }
195
196 #[cfg(feature = "chrono")]
197 pub(super) fn chrono_naive_date_to_jiff(value: &chrono::NaiveDate) -> Option<civil::Date> {
198 use chrono::Datelike as _;
199
200 civil::Date::new(
201 i16::try_from(value.year()).ok()?,
202 i8::try_from(value.month()).ok()?,
203 i8::try_from(value.day()).ok()?,
204 )
205 .ok()
206 }
207
208 #[cfg(feature = "chrono")]
209 pub(super) fn chrono_naive_time_to_jiff(value: &chrono::NaiveTime) -> Option<civil::Time> {
210 use chrono::Timelike as _;
211
212 civil::Time::new(
213 i8::try_from(value.hour()).ok()?,
214 i8::try_from(value.minute()).ok()?,
215 i8::try_from(value.second()).ok()?,
216 i32::try_from(value.nanosecond()).ok()?,
217 )
218 .ok()
219 }
220
221 #[cfg(feature = "chrono")]
222 pub(super) fn format_chrono_datetime<Tz: chrono::TimeZone>(
223 value: &chrono::DateTime<Tz>,
224 ) -> String
225 where
226 Tz::Offset: std::fmt::Display,
227 {
228 chrono_datetime_to_system_zoned(value)
229 .map(|zoned| format_zoned(&zoned))
230 .unwrap_or_else(|| value.to_string())
231 }
232
233 #[cfg(feature = "chrono")]
234 pub(super) fn format_chrono_naive_datetime(value: &chrono::NaiveDateTime) -> String {
235 chrono_naive_datetime_to_jiff(value)
236 .map(format_civil_datetime)
237 .unwrap_or_else(|| value.to_string())
238 }
239
240 #[cfg(feature = "chrono")]
241 pub(super) fn format_chrono_naive_date(value: &chrono::NaiveDate) -> String {
242 chrono_naive_date_to_jiff(value)
243 .map(format_civil_date)
244 .unwrap_or_else(|| value.to_string())
245 }
246
247 #[cfg(feature = "chrono")]
248 pub(super) fn format_chrono_naive_time(value: &chrono::NaiveTime) -> String {
249 chrono_naive_time_to_jiff(value)
250 .map(format_civil_time)
251 .unwrap_or_else(|| value.to_string())
252 }
253}
254
255macro_rules! impl_table_cell_display {
256 ($($t:ty),* $(,)?) => {
257 $(
258 impl TableCell for $t {
259 fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
260 self.to_string().into_any_element()
261 }
262 }
263 )*
264 };
265}
266
267macro_rules! impl_table_cell_float {
268 ($($t:ty),* $(,)?) => {
269 $(
270 impl TableCell for $t {
271 fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
272 format!("{:.2}", self).into_any_element()
273 }
274 }
275 )*
276 };
277}
278
279impl<T: TableCell> TableCell for Option<T> {
280 fn draw(&self, window: &mut Window, cx: &mut App) -> AnyElement {
281 match self {
282 Some(value) => value.draw(window, cx),
283 None => "".into_any_element(),
284 }
285 }
286}
287
288impl<T: TableCell> TableCell for Vec<T> {
289 fn draw(&self, window: &mut Window, cx: &mut App) -> AnyElement {
290 use gpui_kit::{ParentElement as _, Styled as _};
291
292 let mut children = Vec::with_capacity(self.len().saturating_mul(2));
293 for (index, value) in self.iter().enumerate() {
294 if index > 0 {
295 children.push(", ".into_any_element());
296 }
297 children.push(value.draw(window, cx));
298 }
299
300 gpui_kit::div()
301 .flex()
302 .items_center()
303 .gap_1()
304 .children(children)
305 .into_any_element()
306 }
307}
308
309impl_table_cell_display!(
310 String, &str, usize, isize, u8, u16, u32, u64, u128, i8, i16, i32, i64, i128
311);
312impl_table_cell_float!(f32, f64);
313
314impl TableCell for bool {
315 fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
316 (if *self { "✓" } else { "✗" }).into_any_element()
317 }
318}
319
320#[cfg(feature = "spacetimedb")]
321impl TableCell for spacetimedb_lib::Timestamp {
322 fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
323 self.to_string().into_any_element()
324 }
325}
326
327#[cfg(feature = "rust_decimal")]
328impl TableCell for rust_decimal::Decimal {
329 fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
330 format!("{:.2}", self).into_any_element()
331 }
332}
333
334#[cfg(feature = "chrono")]
335impl<Tz: chrono::TimeZone> TableCell for chrono::DateTime<Tz>
336where
337 Tz::Offset: std::fmt::Display,
338{
339 fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
340 datetime_format::format_chrono_datetime(self).into_any_element()
341 }
342}
343
344#[cfg(feature = "chrono")]
345impl TableCell for chrono::NaiveDateTime {
346 fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
347 datetime_format::format_chrono_naive_datetime(self).into_any_element()
348 }
349}
350
351#[cfg(feature = "chrono")]
352impl TableCell for chrono::NaiveDate {
353 fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
354 datetime_format::format_chrono_naive_date(self).into_any_element()
355 }
356}
357
358#[cfg(feature = "chrono")]
359impl TableCell for chrono::NaiveTime {
360 fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
361 datetime_format::format_chrono_naive_time(self).into_any_element()
362 }
363}
364
365#[cfg(feature = "jiff")]
366impl TableCell for jiff::Zoned {
367 fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
368 datetime_format::format_zoned(self).into_any_element()
369 }
370}
371
372#[cfg(feature = "jiff")]
373impl TableCell for jiff::Timestamp {
374 fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
375 datetime_format::format_timestamp_local(*self).into_any_element()
376 }
377}
378
379#[cfg(feature = "jiff")]
380impl TableCell for jiff::civil::DateTime {
381 fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
382 datetime_format::format_civil_datetime(*self).into_any_element()
383 }
384}
385
386#[cfg(feature = "jiff")]
387impl TableCell for jiff::civil::Date {
388 fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
389 datetime_format::format_civil_date(*self).into_any_element()
390 }
391}
392
393#[cfg(feature = "jiff")]
394impl TableCell for jiff::civil::Time {
395 fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
396 datetime_format::format_civil_time(*self).into_any_element()
397 }
398}
399
400#[cfg(feature = "spacetimedb")]
401impl TableCell for spacetimedb_lib::TimeDuration {
402 fn draw(&self, _: &mut Window, _: &mut App) -> AnyElement {
403 self.to_string().into_any_element()
404 }
405}
406
407#[cfg(test)]
408mod tests {
409 use super::{DisplayCell, FormattedCell};
410
411 #[test]
412 fn cell_wrappers_preserve_values_and_formatters() {
413 let display = DisplayCell::new(42);
414 assert_eq!(display.into_inner(), 42);
415
416 let formatted = FormattedCell::new(42, |value: &i32| format!("{value} kg"));
417 assert_eq!(formatted.value(), &42);
418 assert_eq!((formatted.formatter)(formatted.value()), "42 kg");
419 assert_eq!(formatted.into_inner(), 42);
420 }
421
422 #[cfg(feature = "jiff")]
423 #[test]
424 fn jiff_values_format_through_icu() {
425 use super::datetime_format::{
426 format_civil_date, format_civil_datetime, format_civil_time, format_timestamp_local,
427 format_zoned,
428 };
429 use jiff::{Timestamp, Zoned, civil};
430
431 let date = civil::Date::new(2026, 7, 11).unwrap();
432 let time = civil::Time::new(12, 34, 56, 123_000_000).unwrap();
433 let datetime = civil::DateTime::from_parts(date, time);
434 let zoned: Zoned = "2026-07-11T12:34:56-04:00[America/New_York]"
435 .parse()
436 .unwrap();
437 let timestamp: Timestamp = "2026-07-11T16:34:56Z".parse().unwrap();
438
439 assert!(!format_civil_date(date).is_empty());
440 assert!(!format_civil_time(time).is_empty());
441 assert!(!format_civil_datetime(datetime).is_empty());
442 assert!(!format_zoned(&zoned).is_empty());
443 assert!(!format_timestamp_local(timestamp).is_empty());
444 }
445
446 #[cfg(all(feature = "jiff", feature = "chrono"))]
447 #[test]
448 fn chrono_values_convert_to_jiff_equivalents() {
449 use super::datetime_format::{
450 chrono_datetime_to_system_zoned, chrono_naive_date_to_jiff,
451 chrono_naive_datetime_to_jiff, chrono_naive_time_to_jiff,
452 };
453 use chrono::{DateTime, NaiveDate, Utc};
454
455 let date = NaiveDate::from_ymd_opt(2026, 7, 11).unwrap();
456 let time = date.and_hms_nano_opt(12, 34, 56, 123_000_000).unwrap();
457 let zoned = DateTime::<Utc>::from_naive_utc_and_offset(time, Utc);
458
459 assert_eq!(
460 chrono_naive_date_to_jiff(&date).unwrap().to_string(),
461 "2026-07-11"
462 );
463 assert_eq!(
464 chrono_naive_time_to_jiff(&time.time()).unwrap().to_string(),
465 "12:34:56.123"
466 );
467 assert_eq!(
468 chrono_naive_datetime_to_jiff(&time).unwrap().to_string(),
469 "2026-07-11T12:34:56.123"
470 );
471 assert_eq!(
472 chrono_datetime_to_system_zoned(&zoned).unwrap().timestamp(),
473 "2026-07-11T12:34:56.123Z".parse().unwrap()
474 );
475 }
476
477 #[cfg(feature = "chrono")]
478 #[test]
479 fn chrono_dates_outside_jiff_range_preserve_original_display() {
480 use super::datetime_format::{format_chrono_naive_date, format_chrono_naive_datetime};
481 use chrono::NaiveDate;
482
483 for date in [
484 NaiveDate::MIN,
485 NaiveDate::MAX,
486 NaiveDate::from_ymd_opt(-10_000, 1, 1).unwrap(),
487 NaiveDate::from_ymd_opt(10_000, 12, 31).unwrap(),
488 ] {
489 assert_eq!(format_chrono_naive_date(&date), date.to_string());
490 let datetime = date.and_hms_nano_opt(12, 34, 56, 123_000_000).unwrap();
491 assert_eq!(
492 format_chrono_naive_datetime(&datetime),
493 datetime.to_string()
494 );
495 }
496 }
497
498 #[cfg(feature = "chrono")]
499 #[test]
500 fn chrono_timestamps_outside_jiff_range_preserve_original_offset() {
501 use super::datetime_format::format_chrono_datetime;
502 use chrono::{DateTime, FixedOffset, NaiveDate, TimeZone as _, Utc};
503
504 for datetime in [DateTime::<Utc>::MIN_UTC, DateTime::<Utc>::MAX_UTC] {
505 assert_eq!(format_chrono_datetime(&datetime), datetime.to_string());
506 }
507 let local = NaiveDate::from_ymd_opt(10_000, 1, 1)
508 .unwrap()
509 .and_hms_opt(12, 34, 56)
510 .unwrap();
511 let offset = FixedOffset::east_opt(3600).unwrap();
512 let datetime = offset.from_local_datetime(&local).single().unwrap();
513 assert_eq!(
514 format_chrono_datetime(&datetime),
515 "+10000-01-01 12:34:56 +01:00"
516 );
517 }
518
519 #[cfg(feature = "chrono")]
520 #[test]
521 fn chrono_leap_seconds_preserve_original_display() {
522 use super::datetime_format::{
523 format_chrono_datetime, format_chrono_naive_datetime, format_chrono_naive_time,
524 };
525 use chrono::{DateTime, NaiveDate, NaiveTime, Utc};
526
527 let time = NaiveTime::from_hms_nano_opt(23, 59, 59, 1_500_000_000).unwrap();
528 let datetime = NaiveDate::from_ymd_opt(2016, 12, 31)
529 .unwrap()
530 .and_time(time);
531 let zoned = DateTime::<Utc>::from_naive_utc_and_offset(datetime, Utc);
532 assert_eq!(format_chrono_naive_time(&time), "23:59:60.500");
533 assert_eq!(
534 format_chrono_naive_datetime(&datetime),
535 "2016-12-31 23:59:60.500"
536 );
537 assert_eq!(
538 format_chrono_datetime(&zoned),
539 "2016-12-31 23:59:60.500 UTC"
540 );
541 }
542}