gpui-table-runtime 0.7.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
use gpui_kit::{AnyElement, App, IntoElement as _, Window};
use std::fmt::Display;

/// A value that can be displayed in a table cell.
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>,
    ) -> Zoned {
        let nanosecond = i32::try_from(value.timestamp_subsec_nanos())
            .expect("chrono nanoseconds fit jiff values");
        let timestamp = Timestamp::new(value.timestamp(), nanosecond).unwrap_or_else(|error| {
            panic!(
                "chrono timestamp `{}.{nanosecond:09}` is outside jiff's range: {error}",
                value.timestamp()
            )
        });
        timestamp.to_zoned(TimeZone::system())
    }

    #[cfg(feature = "chrono")]
    pub(super) fn chrono_naive_datetime_to_jiff(value: &chrono::NaiveDateTime) -> civil::DateTime {
        use chrono::{Datelike as _, Timelike as _};

        let month = i8::try_from(value.month()).expect("chrono months fit jiff values");
        let day = i8::try_from(value.day()).expect("chrono days fit jiff values");
        let hour = i8::try_from(value.hour()).expect("chrono hours fit jiff values");
        let minute = i8::try_from(value.minute()).expect("chrono minutes fit jiff values");
        let second = i8::try_from(value.second()).expect("chrono seconds fit jiff values");
        let nanosecond =
            i32::try_from(value.nanosecond()).expect("chrono nanoseconds fit jiff values");
        let year = i16::try_from(value.year()).unwrap_or_else(|error| {
            panic!("chrono datetime `{value}` is outside jiff's year range: {error}")
        });
        civil::DateTime::new(year, month, day, hour, minute, second, nanosecond)
            .expect("valid chrono datetime should remain valid in jiff")
    }

    #[cfg(feature = "chrono")]
    pub(super) fn chrono_naive_date_to_jiff(value: &chrono::NaiveDate) -> civil::Date {
        use chrono::Datelike as _;

        let month = i8::try_from(value.month()).expect("chrono months fit jiff values");
        let day = i8::try_from(value.day()).expect("chrono days fit jiff values");
        let year = i16::try_from(value.year()).unwrap_or_else(|error| {
            panic!("chrono date `{value}` is outside jiff's year range: {error}")
        });
        civil::Date::new(year, month, day).expect("valid chrono date should remain valid in jiff")
    }

    #[cfg(feature = "chrono")]
    pub(super) fn chrono_naive_time_to_jiff(value: &chrono::NaiveTime) -> civil::Time {
        use chrono::Timelike as _;

        let hour = i8::try_from(value.hour()).expect("chrono hours fit jiff values");
        let minute = i8::try_from(value.minute()).expect("chrono minutes fit jiff values");
        let second = i8::try_from(value.second()).expect("chrono seconds fit jiff values");
        let nanosecond =
            i32::try_from(value.nanosecond()).expect("chrono nanoseconds fit jiff values");
        civil::Time::new(hour, minute, second, nanosecond)
            .expect("valid chrono time should remain valid in jiff")
    }
}

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_zoned(&datetime_format::chrono_datetime_to_system_zoned(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_civil_datetime(datetime_format::chrono_naive_datetime_to_jiff(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_civil_date(datetime_format::chrono_naive_date_to_jiff(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_civil_time(datetime_format::chrono_naive_time_to_jiff(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).to_string(), "2026-07-11");
        assert_eq!(
            chrono_naive_time_to_jiff(&time.time()).to_string(),
            "12:34:56.123"
        );
        assert_eq!(
            chrono_naive_datetime_to_jiff(&time).to_string(),
            "2026-07-11T12:34:56.123"
        );
        assert_eq!(
            chrono_datetime_to_system_zoned(&zoned).timestamp(),
            "2026-07-11T12:34:56.123Z".parse().unwrap()
        );
    }
}