gpui-table-runtime 0.8.1

GPUI runtime traits and helpers for gpui-table.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
use gpui_kit::{AnyElement, App, IntoElement as _, Window};
use std::fmt::Display;

/// A value that can be displayed in a table cell.
///
/// Built-in Chrono cells use localized formatting when Jiff can represent the
/// value. Dates outside Jiff's range and leap seconds use the original Chrono
/// [`Display`] representation, preserving the value and its original offset.
pub trait TableCell {
    fn draw(&self, window: &mut Window, cx: &mut App) -> AnyElement;
}

/// Table-cell wrapper for values that should render through [`Display`].
///
/// This is useful for value objects where a blanket `TableCell for T:
/// Display` implementation would conflict with downstream implementations.
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()
    }
}

/// Table-cell wrapper that renders a value with a caller-provided formatter.
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> {
        // Chrono encodes leap seconds with overflowing nanoseconds. Jiff cannot
        // represent them, so preserve the original value through the display fallback.
        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(feature = "spacetimedb")]
impl TableCell for spacetimedb_lib::TimeDuration {
    fn draw(&self, _: &mut Window, _: &mut App) -> AnyElement {
        self.to_string().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"
        );
    }
}