Skip to main content

gpui_table_runtime/
cell.rs

1use crate::text_cell;
2use gpui_kit::{AnyElement, App, IntoElement as _, Window};
3use std::fmt::Display;
4
5/// A value that can be displayed in a table cell.
6///
7/// Built-in Jiff date and time cells use localized formatting.
8pub trait TableCell {
9    fn draw(&self, window: &mut Window, cx: &mut App) -> AnyElement;
10}
11
12/// Table-cell wrapper for values that should render through [`Display`].
13///
14/// This is useful for value objects where a blanket `TableCell for T:
15/// Display` implementation would conflict with downstream implementations.
16pub struct DisplayCell<T>(pub T);
17
18impl<T> DisplayCell<T> {
19    pub fn new(value: T) -> Self {
20        Self(value)
21    }
22
23    pub fn into_inner(self) -> T {
24        self.0
25    }
26}
27
28impl<T: Display> TableCell for DisplayCell<T> {
29    fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
30        text_cell(self.0.to_string())
31    }
32}
33
34/// Table-cell wrapper that renders a value with a caller-provided formatter.
35pub struct FormattedCell<T, F> {
36    value: T,
37    formatter: F,
38}
39
40impl<T, F> FormattedCell<T, F> {
41    pub fn new(value: T, formatter: F) -> Self {
42        Self { value, formatter }
43    }
44
45    pub fn value(&self) -> &T {
46        &self.value
47    }
48
49    pub fn into_inner(self) -> T {
50        self.value
51    }
52}
53
54impl<T, F, S> TableCell for FormattedCell<T, F>
55where
56    F: Fn(&T) -> S,
57    S: Display,
58{
59    fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
60        text_cell((self.formatter)(&self.value).to_string())
61    }
62}
63
64#[cfg(feature = "jiff")]
65mod datetime_format {
66    use icu::{
67        calendar::{Date, Iso},
68        datetime::{
69            DateTimeFormatter, DateTimeFormatterPreferences, NoCalendarFormatter,
70            fieldsets::{self, Combo},
71            input::{DateTime as IcuDateTime, Time, UtcOffset, ZonedDateTime as IcuZonedDateTime},
72        },
73        locale::Locale,
74    };
75    use jiff::{Timestamp, ZonedDateTime, civil, tz::TimeZone};
76
77    type DateFormatter = DateTimeFormatter<fieldsets::YMD>;
78    type DateTimeFormatterNoZone = DateTimeFormatter<fieldsets::YMDT>;
79    type DateTimeFormatterWithZone =
80        DateTimeFormatter<Combo<fieldsets::YMDT, fieldsets::zone::LocalizedOffsetLong>>;
81    type TimeFormatter = NoCalendarFormatter<fieldsets::T>;
82
83    fn formatter_preferences() -> DateTimeFormatterPreferences {
84        let raw = gpui_kit::component::locale();
85        let normalized = raw.replace('_', "-");
86        let locale = normalized.parse::<Locale>().unwrap_or_else(|error| {
87            panic!("gpui-kit locale `{normalized}` is not a valid ICU locale: {error}")
88        });
89        locale.into()
90    }
91
92    fn date_formatter() -> DateFormatter {
93        DateTimeFormatter::try_new(formatter_preferences(), fieldsets::YMD::medium())
94            .unwrap_or_else(|error| panic!("failed to create ICU date formatter: {error:?}"))
95    }
96
97    fn datetime_formatter() -> DateTimeFormatterNoZone {
98        let fieldset = fieldsets::YMD::medium().with_time_hms();
99        DateTimeFormatter::try_new(formatter_preferences(), fieldset)
100            .unwrap_or_else(|error| panic!("failed to create ICU datetime formatter: {error:?}"))
101    }
102
103    fn zoned_datetime_formatter() -> DateTimeFormatterWithZone {
104        let fieldset = fieldsets::YMD::medium()
105            .with_time_hms()
106            .with_zone(fieldsets::zone::LocalizedOffsetLong);
107        DateTimeFormatter::try_new(formatter_preferences(), fieldset).unwrap_or_else(|error| {
108            panic!("failed to create ICU zoned datetime formatter: {error:?}")
109        })
110    }
111
112    fn time_formatter() -> TimeFormatter {
113        NoCalendarFormatter::try_new(formatter_preferences(), fieldsets::T::medium())
114            .unwrap_or_else(|error| panic!("failed to create ICU time formatter: {error:?}"))
115    }
116
117    fn to_icu_date(value: civil::Date) -> Date<Iso> {
118        let month = u8::try_from(value.month()).expect("jiff months fit ICU month values");
119        let day = u8::try_from(value.day()).expect("jiff days fit ICU day values");
120        Date::try_new_iso(i32::from(value.year()), month, day).unwrap_or_else(|error| {
121            panic!("jiff date `{value}` is not a valid ICU date: {error:?}")
122        })
123    }
124
125    fn to_icu_time(value: civil::Time) -> Time {
126        let hour = u8::try_from(value.hour()).expect("jiff hours fit ICU hour values");
127        let minute = u8::try_from(value.minute()).expect("jiff minutes fit ICU minute values");
128        let second = u8::try_from(value.second()).expect("jiff seconds fit ICU second values");
129        let nanosecond =
130            u32::try_from(value.subsec_nanosecond()).expect("jiff nanoseconds fit ICU values");
131        Time::try_new(hour, minute, second, nanosecond).unwrap_or_else(|error| {
132            panic!("jiff time `{value}` is not a valid ICU time: {error:?}")
133        })
134    }
135
136    pub(super) fn format_zoned(value: &ZonedDateTime) -> String {
137        let Ok(utc_offset) = UtcOffset::try_from_seconds(value.offset().seconds()) else {
138            // A valid Jiff fixed offset can exceed ICU's 18-hour range.
139            return value.to_string();
140        };
141        let zoned = IcuZonedDateTime::from_epoch_milliseconds_and_utc_offset(
142            i64::try_from(value.timestamp().as_nanosecond().div_euclid(1_000_000))
143                .expect("Jiff epoch milliseconds fit i64"),
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_datetime(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
173macro_rules! impl_table_cell_display {
174    ($($t:ty),* $(,)?) => {
175        $(
176            impl TableCell for $t {
177                fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
178                    text_cell(self.to_string())
179                }
180            }
181        )*
182    };
183}
184
185macro_rules! impl_table_cell_float {
186    ($($t:ty),* $(,)?) => {
187        $(
188            impl TableCell for $t {
189                fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
190                    text_cell(format!("{:.2}", self))
191                }
192            }
193        )*
194    };
195}
196
197impl<T: TableCell> TableCell for Option<T> {
198    fn draw(&self, window: &mut Window, cx: &mut App) -> AnyElement {
199        match self {
200            Some(value) => value.draw(window, cx),
201            None => text_cell(""),
202        }
203    }
204}
205
206impl<T: TableCell> TableCell for Vec<T> {
207    fn draw(&self, window: &mut Window, cx: &mut App) -> AnyElement {
208        use gpui_kit::{InteractiveElement as _, ParentElement as _, Styled as _};
209
210        let mut children = Vec::with_capacity(self.len().saturating_mul(2));
211        for (index, value) in self.iter().enumerate() {
212            if index > 0 {
213                children.push(", ".into_any_element());
214            }
215            children.push(
216                gpui_kit::div()
217                    .id(("cell-value", index))
218                    .child(value.draw(window, cx))
219                    .into_any_element(),
220            );
221        }
222
223        gpui_kit::div()
224            .flex()
225            .items_center()
226            .gap_1()
227            .children(children)
228            .into_any_element()
229    }
230}
231
232impl_table_cell_display!(
233    String, &str, usize, isize, u8, u16, u32, u64, u128, i8, i16, i32, i64, i128
234);
235impl_table_cell_float!(f32, f64);
236
237impl TableCell for bool {
238    fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
239        text_cell(if *self { "✓" } else { "✗" })
240    }
241}
242
243#[cfg(feature = "spacetimedb")]
244impl TableCell for spacetimedb_lib::Timestamp {
245    fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
246        text_cell(self.to_string())
247    }
248}
249
250#[cfg(feature = "rust_decimal")]
251impl TableCell for rust_decimal::Decimal {
252    fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
253        text_cell(format!("{:.2}", self))
254    }
255}
256
257#[cfg(feature = "jiff")]
258impl TableCell for jiff::ZonedDateTime {
259    fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
260        text_cell(datetime_format::format_zoned(self))
261    }
262}
263
264#[cfg(feature = "jiff")]
265impl TableCell for jiff::Timestamp {
266    fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
267        text_cell(datetime_format::format_timestamp_local(*self))
268    }
269}
270
271#[cfg(feature = "jiff")]
272impl TableCell for jiff::civil::DateTime {
273    fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
274        text_cell(datetime_format::format_civil_datetime(*self))
275    }
276}
277
278#[cfg(feature = "jiff")]
279impl TableCell for jiff::civil::Date {
280    fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
281        text_cell(datetime_format::format_civil_date(*self))
282    }
283}
284
285#[cfg(feature = "jiff")]
286impl TableCell for jiff::civil::Time {
287    fn draw(&self, _window: &mut Window, _cx: &mut App) -> AnyElement {
288        text_cell(datetime_format::format_civil_time(*self))
289    }
290}
291
292#[cfg(feature = "spacetimedb")]
293impl TableCell for spacetimedb_lib::TimeDuration {
294    fn draw(&self, _: &mut Window, _: &mut App) -> AnyElement {
295        text_cell(self.to_string())
296    }
297}
298
299#[cfg(test)]
300mod tests {
301    use super::{DisplayCell, FormattedCell};
302
303    #[test]
304    fn cell_wrappers_preserve_values_and_formatters() {
305        let display = DisplayCell::new(42);
306        assert_eq!(display.into_inner(), 42);
307
308        let formatted = FormattedCell::new(42, |value: &i32| format!("{value} kg"));
309        assert_eq!(formatted.value(), &42);
310        assert_eq!((formatted.formatter)(formatted.value()), "42 kg");
311        assert_eq!(formatted.into_inner(), 42);
312    }
313
314    #[cfg(feature = "jiff")]
315    #[test]
316    fn jiff_values_format_through_icu() {
317        use super::datetime_format::{
318            format_civil_date, format_civil_datetime, format_civil_time, format_timestamp_local,
319            format_zoned,
320        };
321        use jiff::{Timestamp, ZonedDateTime, civil};
322
323        let date = civil::Date::new(2026, 7, 11).unwrap();
324        let time = civil::Time::new(12, 34, 56, 123_000_000).unwrap();
325        let datetime = civil::DateTime::from_parts(date, time);
326        let zoned: ZonedDateTime = "2026-07-11T12:34:56-04:00[America/New_York]"
327            .parse()
328            .unwrap();
329        let timestamp: Timestamp = "2026-07-11T16:34:56Z".parse().unwrap();
330
331        assert!(!format_civil_date(date).is_empty());
332        assert!(!format_civil_time(time).is_empty());
333        assert!(!format_civil_datetime(datetime).is_empty());
334        assert!(!format_zoned(&zoned).is_empty());
335        assert!(!format_timestamp_local(timestamp).is_empty());
336    }
337
338    #[cfg(feature = "jiff")]
339    #[test]
340    fn pre_epoch_cell_does_not_round_across_midnight() {
341        use super::datetime_format::format_zoned;
342        use jiff::{Timestamp, tz::TimeZone};
343
344        let formatted = |nanos| {
345            format_zoned(
346                &Timestamp::from_nanosecond(nanos)
347                    .unwrap()
348                    .to_zoned_datetime(TimeZone::UTC),
349            )
350        };
351        assert_eq!(formatted(-1), formatted(-1_000_000));
352        assert_ne!(formatted(-1), formatted(0));
353    }
354
355    #[cfg(feature = "jiff")]
356    #[test]
357    fn valid_offsets_outside_icu_range_keep_the_original_value() {
358        use super::datetime_format::format_zoned;
359        use jiff::{
360            Timestamp,
361            tz::{Offset, TimeZone},
362        };
363
364        let timestamp: Timestamp = "2026-01-01T00:00:00Z".parse().unwrap();
365        let offset = Offset::from_seconds(19 * 3600).unwrap();
366        let zoned = timestamp.to_zoned_datetime(TimeZone::fixed(offset));
367        assert_eq!(format_zoned(&zoned), zoned.to_string());
368    }
369}