Skip to main content

gpui_table_runtime/
cell.rs

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