gpui-form-component 0.10.0

GPUI component runtimes for gpui-form, including InfiniteSelect for nested enum support
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
use std::{ops::Deref as _, str::FromStr as _};

use gpui_es_fluent::localize_message;
use gpui_kit::component::{
    ActiveTheme as _, Disableable, Icon, IconName, Sizable, Size, StyleSized as _, StyledExt as _,
    ThemeStyled as _,
    button::{Button, ButtonVariants as _},
    h_flex,
};
use gpui_kit::{
    App, AppContext as _, ClickEvent, Context, ElementId, Empty, Entity, EventEmitter, FocusHandle,
    Focusable, InteractiveElement as _, IntoElement, MouseButton, ParentElement as _, Render,
    RenderOnce, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled,
    Subscription, Window, anchored, deferred, div, prelude::FluentBuilder as _, px,
};
use icu_calendar::{Date as IcuDate, Gregorian};
use icu_datetime::{FixedCalendarDateTimeFormatter, fieldsets};
use icu_locale_core::Locale;
use jiff::civil::Date as JiffDate;

use crate::calendar::{Calendar, CalendarEvent, CalendarState, Date as CalendarDate};
use crate::i18n::DatePickerText;
#[cfg(feature = "component-shape")]
use gpui_form_runtime::shape::ValueChange;

mod formatting;
mod state;

pub use formatting::parse_form_date;
use formatting::*;

/// Localized date display widths for the runtime date picker.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum DateDisplayStyle {
    Short,
    #[default]
    Medium,
    Long,
}

/// Events emitted by the runtime date picker.
#[derive(Clone)]
pub enum DatePickerEvent {
    Change(Option<JiffDate>),
}

/// Events emitted by the runtime date range picker.
#[derive(Clone)]
pub enum DateRangePickerEvent {
    Change(Option<JiffDate>, Option<JiffDate>),
}

/// Use to store the state of the date picker.
pub struct DatePickerState {
    focus_handle: FocusHandle,
    date: Option<JiffDate>,
    open: bool,
    calendar: Entity<CalendarState>,
    display_locale: Option<Locale>,
    display_style: DateDisplayStyle,
    _subscriptions: Vec<Subscription>,
}

#[cfg(feature = "component-shape")]
impl gpui_form_runtime::shape::GpuiComponentStateValueBinding<JiffDate> for DatePickerState {
    type Event = DatePickerEvent;

    fn seed_value_binding_state(
        state: &mut Self,
        value: Option<&JiffDate>,
        window: &mut Window,
        cx: &mut Context<'_, Self>,
    ) {
        state.set_date(value.copied(), window, cx);
    }

    fn value_change(_state: &Self, event: &Self::Event) -> ValueChange<JiffDate> {
        match event {
            DatePickerEvent::Change(Some(date)) => ValueChange::Set(*date),
            DatePickerEvent::Change(None) => ValueChange::Clear,
        }
    }
}

impl Focusable for DatePickerState {
    fn focus_handle(&self, _: &App) -> FocusHandle {
        self.focus_handle.clone()
    }
}

impl EventEmitter<DatePickerEvent> for DatePickerState {}

/// Use to store the state of the date range picker.
pub struct DateRangePickerState {
    focus_handle: FocusHandle,
    start_date: Option<JiffDate>,
    end_date: Option<JiffDate>,
    open: bool,
    calendar: Entity<CalendarState>,
    display_locale: Option<Locale>,
    display_style: DateDisplayStyle,
    _subscriptions: Vec<Subscription>,
}

#[cfg(feature = "component-shape")]
impl gpui_form_runtime::shape::GpuiComponentStateValueBinding<(JiffDate, JiffDate)>
    for DateRangePickerState
{
    type Event = DateRangePickerEvent;

    fn seed_value_binding_state(
        state: &mut Self,
        value: Option<&(JiffDate, JiffDate)>,
        window: &mut Window,
        cx: &mut Context<'_, Self>,
    ) {
        state.set_range(
            value.map(|(start, _)| *start),
            value.map(|(_, end)| *end),
            window,
            cx,
        );
    }

    fn value_change(_state: &Self, event: &Self::Event) -> ValueChange<(JiffDate, JiffDate)> {
        match event {
            DateRangePickerEvent::Change(Some(start), Some(end)) => {
                ValueChange::Set((*start, *end))
            },
            DateRangePickerEvent::Change(_, _) => ValueChange::Clear,
        }
    }
}

impl Focusable for DateRangePickerState {
    fn focus_handle(&self, _: &App) -> FocusHandle {
        self.focus_handle.clone()
    }
}

impl EventEmitter<DateRangePickerEvent> for DateRangePickerState {}

impl Render for DatePickerState {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        Empty
    }
}

impl Render for DateRangePickerState {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        Empty
    }
}

/// A localized date picker element.
#[cfg_attr(
    feature = "component-shape",
    derive(component_shape_gpui::GpuiComponentShape)
)]
#[cfg_attr(
    feature = "component-shape",
    gpui_component_shape(
        state = DatePickerState,
        value = jiff::civil::Date,
        field_suffix = "date_picker",
        value_binding
    )
)]
#[derive(IntoElement)]
pub struct DatePicker {
    id: ElementId,
    style: StyleRefinement,
    state: Entity<DatePickerState>,
    cleanable: bool,
    placeholder: Option<SharedString>,
    size: Size,
    number_of_months: usize,
    appearance: bool,
    disabled: bool,
}

#[cfg(feature = "component-shape")]
impl gpui_form_runtime::shape::GpuiFormComponentShapePolicy for DatePicker {
    type ValueStoragePolicy = gpui_form_runtime::shape::RequiredValueStorage;
}

/// A localized date range picker element.
#[cfg_attr(
    feature = "component-shape",
    derive(component_shape_gpui::GpuiComponentShape)
)]
#[cfg_attr(
    feature = "component-shape",
    gpui_component_shape(
        state = DateRangePickerState,
        value = (jiff::civil::Date, jiff::civil::Date),
        field_suffix = "date_range_picker",
        value_binding
    )
)]
#[derive(IntoElement)]
pub struct DateRangePicker {
    id: ElementId,
    style: StyleRefinement,
    state: Entity<DateRangePickerState>,
    cleanable: bool,
    placeholder: Option<SharedString>,
    size: Size,
    number_of_months: usize,
    appearance: bool,
    disabled: bool,
}

#[cfg(feature = "component-shape")]
impl gpui_form_runtime::shape::GpuiFormComponentShapePolicy for DateRangePicker {
    type ValueStoragePolicy = gpui_form_runtime::shape::RequiredValueStorage;
}

impl Sizable for DatePicker {
    fn with_size(mut self, size: impl Into<Size>) -> Self {
        self.size = size.into();
        self
    }
}

impl Sizable for DateRangePicker {
    fn with_size(mut self, size: impl Into<Size>) -> Self {
        self.size = size.into();
        self
    }
}

impl Focusable for DatePicker {
    fn focus_handle(&self, cx: &App) -> FocusHandle {
        self.state.focus_handle(cx)
    }
}

impl Focusable for DateRangePicker {
    fn focus_handle(&self, cx: &App) -> FocusHandle {
        self.state.focus_handle(cx)
    }
}

impl Styled for DatePicker {
    fn style(&mut self) -> &mut StyleRefinement {
        &mut self.style
    }
}

impl Styled for DateRangePicker {
    fn style(&mut self) -> &mut StyleRefinement {
        &mut self.style
    }
}

impl Disableable for DatePicker {
    fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }
}

impl Disableable for DateRangePicker {
    fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }
}

impl DatePicker {
    /// Create a new `DatePicker` with the given `DatePickerState`.
    pub fn new(state: &Entity<DatePickerState>) -> Self {
        Self {
            id: ("date-picker", state.entity_id()).into(),
            state: state.clone(),
            cleanable: false,
            placeholder: None,
            size: Size::default(),
            style: StyleRefinement::default(),
            number_of_months: 2,
            appearance: true,
            disabled: false,
        }
    }

    /// Set the placeholder text, default: `Select date`.
    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
        self.placeholder = Some(placeholder.into());
        self
    }

    /// Set whether to show the clear button when a date is selected.
    pub fn cleanable(mut self, cleanable: bool) -> Self {
        self.cleanable = cleanable;
        self
    }

    /// Set the number of months to show, default is `2`.
    pub fn number_of_months(mut self, number_of_months: usize) -> Self {
        self.number_of_months = number_of_months;
        self
    }

    /// Set whether to render the picker with the default bordered input style.
    pub fn appearance(mut self, appearance: bool) -> Self {
        self.appearance = appearance;
        self
    }
}

impl DateRangePicker {
    /// Create a new `DateRangePicker` with the given `DateRangePickerState`.
    pub fn new(state: &Entity<DateRangePickerState>) -> Self {
        Self {
            id: ("date-range-picker", state.entity_id()).into(),
            state: state.clone(),
            cleanable: false,
            placeholder: None,
            size: Size::default(),
            style: StyleRefinement::default(),
            number_of_months: 2,
            appearance: true,
            disabled: false,
        }
    }

    /// Set the placeholder text, default: `Select date`.
    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
        self.placeholder = Some(placeholder.into());
        self
    }

    /// Set whether to show the clear button when a range is selected.
    pub fn cleanable(mut self, cleanable: bool) -> Self {
        self.cleanable = cleanable;
        self
    }

    /// Set the number of months to show, default is `2`.
    pub fn number_of_months(mut self, number_of_months: usize) -> Self {
        self.number_of_months = number_of_months;
        self
    }

    /// Set whether to render the picker with the default bordered input style.
    pub fn appearance(mut self, appearance: bool) -> Self {
        self.appearance = appearance;
        self
    }
}

impl RenderOnce for DatePicker {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let is_focused = self.focus_handle(cx).contains_focused(window, cx);
        let state = self.state.read(cx);
        let show_clean = self.cleanable && state.date.is_some();
        let placeholder = self
            .placeholder
            .clone()
            .unwrap_or_else(|| localize_message(cx, &DatePickerText::SelectDate).into());
        let locale = state.display_locale.clone().unwrap_or_else(active_locale);
        let display_title = state
            .date
            .and_then(|date| format_display_date(date, &locale, state.display_style))
            .unwrap_or_else(|| placeholder.clone());

        div()
            .id(self.id.clone())
            .track_focus(&self.focus_handle(cx).tab_stop(true))
            .flex_none()
            .w_full()
            .relative()
            .input_text_size(self.size)
            .refine_style(&self.style)
            .child(
                div()
                    .id("date-picker-input")
                    .relative()
                    .flex()
                    .items_center()
                    .justify_between()
                    .when(self.appearance, |this| {
                        this.bg(cx.theme().background)
                            .text_color(cx.theme().foreground)
                            .when(self.disabled, |this| this.opacity(0.5))
                            .border_1()
                            .border_color(cx.theme().input)
                            .rounded(cx.theme().radius)
                            .when(cx.theme().shadow, |this| this.shadow_xs())
                            .when(is_focused, |this| this.border_color(cx.theme().ring))
                    })
                    .when(is_focused && self.appearance && !self.disabled, |this| {
                        this.focus_ring_style(window, cx)
                    })
                    .overflow_hidden()
                    .input_text_size(self.size)
                    .input_size(self.size)
                    .when(!self.disabled, |this| {
                        this.on_click(
                            window.listener_for(&self.state, DatePickerState::toggle_calendar),
                        )
                    })
                    .child(
                        h_flex()
                            .w_full()
                            .items_center()
                            .justify_between()
                            .gap_1()
                            .child(
                                div()
                                    .w_full()
                                    .overflow_hidden()
                                    .when(state.date.is_none(), |this| {
                                        this.text_color(cx.theme().muted_foreground)
                                    })
                                    .child(display_title),
                            )
                            .when(!self.disabled, |this| {
                                this.when(show_clean, |this| {
                                    this.child(
                                        Button::new(("clear-date", self.state.entity_id()))
                                            .small()
                                            .ghost()
                                            .icon(IconName::Close)
                                            .on_click(
                                                window.listener_for(
                                                    &self.state,
                                                    DatePickerState::clean,
                                                ),
                                            ),
                                    )
                                })
                                .when(!show_clean, |this| {
                                    this.child(
                                        Icon::new(IconName::Calendar)
                                            .xsmall()
                                            .text_color(cx.theme().muted_foreground),
                                    )
                                })
                            }),
                    ),
            )
            .when(state.open, |this| {
                this.child(
                    deferred(
                        anchored().snap_to_window_with_margin(px(8.)).child(
                            div()
                                .occlude()
                                .mt_1p5()
                                .p_3()
                                .border_1()
                                .border_color(cx.theme().border)
                                .shadow_lg()
                                .rounded((cx.theme().radius * 2.).min(px(8.)))
                                .bg(cx.theme().popover)
                                .text_color(cx.theme().popover_foreground)
                                .on_mouse_up_out(
                                    MouseButton::Left,
                                    window.listener_for(&self.state, |state, _, window, cx| {
                                        state.close_calendar(window, cx);
                                    }),
                                )
                                .child(
                                    Calendar::new(&state.calendar)
                                        .display_locale(locale.clone())
                                        .number_of_months(self.number_of_months)
                                        .border_0()
                                        .rounded_none()
                                        .p_0()
                                        .with_size(self.size),
                                ),
                        ),
                    )
                    .with_priority(2),
                )
            })
    }
}

impl RenderOnce for DateRangePicker {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let is_focused = self.focus_handle(cx).contains_focused(window, cx);
        let state = self.state.read(cx);
        let show_clean = self.cleanable && (state.start_date.is_some() || state.end_date.is_some());
        let placeholder = self
            .placeholder
            .clone()
            .unwrap_or_else(|| localize_message(cx, &DatePickerText::SelectDate).into());
        let locale = state.display_locale.clone().unwrap_or_else(active_locale);
        let display_title = format_display_range(
            state.start_date,
            state.end_date,
            &locale,
            state.display_style,
        )
        .unwrap_or_else(|| placeholder.clone());

        div()
            .id(self.id.clone())
            .track_focus(&self.focus_handle(cx).tab_stop(true))
            .flex_none()
            .w_full()
            .relative()
            .input_text_size(self.size)
            .refine_style(&self.style)
            .child(
                div()
                    .id("date-range-picker-input")
                    .relative()
                    .flex()
                    .items_center()
                    .justify_between()
                    .when(self.appearance, |this| {
                        this.bg(cx.theme().background)
                            .text_color(cx.theme().foreground)
                            .when(self.disabled, |this| this.opacity(0.5))
                            .border_1()
                            .border_color(cx.theme().input)
                            .rounded(cx.theme().radius)
                            .when(cx.theme().shadow, |this| this.shadow_xs())
                            .when(is_focused, |this| this.border_color(cx.theme().ring))
                    })
                    .when(is_focused && self.appearance && !self.disabled, |this| {
                        this.focus_ring_style(window, cx)
                    })
                    .overflow_hidden()
                    .input_text_size(self.size)
                    .input_size(self.size)
                    .when(!self.disabled, |this| {
                        this.on_click(
                            window.listener_for(&self.state, DateRangePickerState::toggle_calendar),
                        )
                    })
                    .child(
                        h_flex()
                            .w_full()
                            .items_center()
                            .justify_between()
                            .gap_1()
                            .child(
                                div()
                                    .w_full()
                                    .overflow_hidden()
                                    .when(
                                        state.start_date.is_none() && state.end_date.is_none(),
                                        |this| this.text_color(cx.theme().muted_foreground),
                                    )
                                    .child(display_title),
                            )
                            .when(!self.disabled, |this| {
                                this.when(show_clean, |this| {
                                    this.child(
                                        Button::new(("clear-date-range", self.state.entity_id()))
                                            .small()
                                            .ghost()
                                            .icon(IconName::Close)
                                            .on_click(window.listener_for(
                                                &self.state,
                                                DateRangePickerState::clean,
                                            )),
                                    )
                                })
                                .when(!show_clean, |this| {
                                    this.child(
                                        Icon::new(IconName::Calendar)
                                            .xsmall()
                                            .text_color(cx.theme().muted_foreground),
                                    )
                                })
                            }),
                    ),
            )
            .when(state.open, |this| {
                this.child(
                    deferred(
                        anchored().snap_to_window_with_margin(px(8.)).child(
                            div()
                                .occlude()
                                .mt_1p5()
                                .p_3()
                                .border_1()
                                .border_color(cx.theme().border)
                                .shadow_lg()
                                .rounded((cx.theme().radius * 2.).min(px(8.)))
                                .bg(cx.theme().popover)
                                .text_color(cx.theme().popover_foreground)
                                .on_mouse_up_out(
                                    MouseButton::Left,
                                    window.listener_for(&self.state, |state, _, window, cx| {
                                        state.close_calendar(window, cx);
                                    }),
                                )
                                .child(
                                    Calendar::new(&state.calendar)
                                        .display_locale(locale.clone())
                                        .number_of_months(self.number_of_months)
                                        .border_0()
                                        .rounded_none()
                                        .p_0()
                                        .with_size(self.size),
                                ),
                        ),
                    )
                    .with_priority(2),
                )
            })
    }
}

#[cfg(test)]
mod tests;