Skip to main content

fc_ui/capabilities/controls/
time_picker.rs

1use crate::capabilities::foundation::theme::use_theme;
2use crate::capabilities::primitives::button::{Button, ButtonSize, ButtonVariant};
3use gpui::{prelude::FluentBuilder as _, *};
4use std::rc::Rc;
5
6#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7pub enum TimeFormat {
8    Hour12,
9    Hour24,
10}
11
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub enum TimePeriod {
14    AM,
15    PM,
16}
17
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19pub struct TimeValue {
20    pub hour: u8,
21    pub minute: u8,
22    pub second: Option<u8>,
23    pub period: Option<TimePeriod>,
24}
25
26impl TimeValue {
27    pub fn new(hour: u8, minute: u8) -> Self {
28        Self {
29            hour: hour.min(23),
30            minute: minute.min(59),
31            second: None,
32            period: None,
33        }
34    }
35
36    pub fn with_seconds(mut self, second: u8) -> Self {
37        self.second = Some(second.min(59));
38        self
39    }
40
41    pub fn with_period(mut self, period: TimePeriod) -> Self {
42        self.period = Some(period);
43        self
44    }
45
46    pub fn to_24h(&self) -> (u8, u8, Option<u8>) {
47        let hour = match self.period {
48            Some(TimePeriod::AM) => {
49                if self.hour == 12 {
50                    0
51                } else {
52                    self.hour
53                }
54            }
55            Some(TimePeriod::PM) => {
56                if self.hour == 12 {
57                    12
58                } else {
59                    self.hour + 12
60                }
61            }
62            None => self.hour,
63        };
64        (hour, self.minute, self.second)
65    }
66
67    pub fn from_24h(hour: u8, minute: u8, second: Option<u8>, format: TimeFormat) -> Self {
68        match format {
69            TimeFormat::Hour24 => Self {
70                hour: hour.min(23),
71                minute: minute.min(59),
72                second,
73                period: None,
74            },
75            TimeFormat::Hour12 => {
76                let (h12, period) = if hour == 0 {
77                    (12, TimePeriod::AM)
78                } else if hour < 12 {
79                    (hour, TimePeriod::AM)
80                } else if hour == 12 {
81                    (12, TimePeriod::PM)
82                } else {
83                    (hour - 12, TimePeriod::PM)
84                };
85                Self {
86                    hour: h12,
87                    minute: minute.min(59),
88                    second,
89                    period: Some(period),
90                }
91            }
92        }
93    }
94
95    pub fn format_string(&self, format: TimeFormat) -> String {
96        let hour_str = format!("{:02}", self.hour);
97        let minute_str = format!("{:02}", self.minute);
98
99        let base = if let Some(sec) = self.second {
100            format!("{}:{}:{:02}", hour_str, minute_str, sec)
101        } else {
102            format!("{}:{}", hour_str, minute_str)
103        };
104
105        match (format, self.period) {
106            (TimeFormat::Hour12, Some(TimePeriod::AM)) => format!("{} AM", base),
107            (TimeFormat::Hour12, Some(TimePeriod::PM)) => format!("{} PM", base),
108            _ => base,
109        }
110    }
111}
112
113impl Default for TimeValue {
114    fn default() -> Self {
115        Self::new(12, 0)
116    }
117}
118
119pub struct TimePickerState {
120    value: TimeValue,
121    has_value: bool,
122    format: TimeFormat,
123    show_seconds: bool,
124    open: bool,
125    focus_handle: FocusHandle,
126}
127
128impl TimePickerState {
129    pub fn new(cx: &mut Context<Self>) -> Self {
130        Self {
131            value: TimeValue::default(),
132            has_value: false,
133            format: TimeFormat::Hour24,
134            show_seconds: false,
135            open: false,
136            focus_handle: cx.focus_handle(),
137        }
138    }
139
140    pub fn value(&self) -> TimeValue {
141        self.value
142    }
143
144    pub fn has_value(&self) -> bool {
145        self.has_value
146    }
147
148    pub fn set_value(&mut self, value: TimeValue, cx: &mut Context<Self>) {
149        self.value = value;
150        self.has_value = true;
151        cx.notify();
152    }
153
154    pub fn set_hour(&mut self, hour: u8, cx: &mut Context<Self>) {
155        let max_hour = match self.format {
156            TimeFormat::Hour12 => 12,
157            TimeFormat::Hour24 => 23,
158        };
159        self.value.hour = hour.min(max_hour);
160        if self.format == TimeFormat::Hour12 && self.value.hour == 0 {
161            self.value.hour = 12;
162        }
163        self.has_value = true;
164        cx.notify();
165    }
166
167    pub fn set_minute(&mut self, minute: u8, cx: &mut Context<Self>) {
168        self.value.minute = minute.min(59);
169        self.has_value = true;
170        cx.notify();
171    }
172
173    pub fn set_second(&mut self, second: u8, cx: &mut Context<Self>) {
174        self.value.second = Some(second.min(59));
175        self.has_value = true;
176        cx.notify();
177    }
178
179    pub fn set_period(&mut self, period: TimePeriod, cx: &mut Context<Self>) {
180        self.value.period = Some(period);
181        self.has_value = true;
182        cx.notify();
183    }
184
185    pub fn increment_hour(&mut self, cx: &mut Context<Self>) {
186        let max = match self.format {
187            TimeFormat::Hour12 => 12,
188            TimeFormat::Hour24 => 23,
189        };
190        let min = match self.format {
191            TimeFormat::Hour12 => 1,
192            TimeFormat::Hour24 => 0,
193        };
194        self.value.hour = if self.value.hour >= max {
195            min
196        } else {
197            self.value.hour + 1
198        };
199        self.has_value = true;
200        cx.notify();
201    }
202
203    pub fn decrement_hour(&mut self, cx: &mut Context<Self>) {
204        let max = match self.format {
205            TimeFormat::Hour12 => 12,
206            TimeFormat::Hour24 => 23,
207        };
208        let min = match self.format {
209            TimeFormat::Hour12 => 1,
210            TimeFormat::Hour24 => 0,
211        };
212        self.value.hour = if self.value.hour <= min {
213            max
214        } else {
215            self.value.hour - 1
216        };
217        self.has_value = true;
218        cx.notify();
219    }
220
221    pub fn increment_minute(&mut self, cx: &mut Context<Self>) {
222        self.value.minute = if self.value.minute >= 59 {
223            0
224        } else {
225            self.value.minute + 1
226        };
227        self.has_value = true;
228        cx.notify();
229    }
230
231    pub fn decrement_minute(&mut self, cx: &mut Context<Self>) {
232        self.value.minute = if self.value.minute == 0 {
233            59
234        } else {
235            self.value.minute - 1
236        };
237        self.has_value = true;
238        cx.notify();
239    }
240
241    pub fn increment_second(&mut self, cx: &mut Context<Self>) {
242        if let Some(sec) = self.value.second {
243            self.value.second = Some(if sec >= 59 { 0 } else { sec + 1 });
244            self.has_value = true;
245            cx.notify();
246        }
247    }
248
249    pub fn decrement_second(&mut self, cx: &mut Context<Self>) {
250        if let Some(sec) = self.value.second {
251            self.value.second = Some(if sec == 0 { 59 } else { sec - 1 });
252            self.has_value = true;
253            cx.notify();
254        }
255    }
256
257    pub fn is_open(&self) -> bool {
258        self.open
259    }
260
261    pub fn toggle(&mut self, cx: &mut Context<Self>) {
262        self.open = !self.open;
263        cx.notify();
264    }
265
266    pub fn close(&mut self, cx: &mut Context<Self>) {
267        self.open = false;
268        cx.notify();
269    }
270
271    pub fn format(&self) -> TimeFormat {
272        self.format
273    }
274
275    pub fn set_format(&mut self, format: TimeFormat, cx: &mut Context<Self>) {
276        if self.format != format {
277            let (h24, m, s) = self.value.to_24h();
278            self.value = TimeValue::from_24h(h24, m, s, format);
279            self.format = format;
280            cx.notify();
281        }
282    }
283
284    pub fn show_seconds(&self) -> bool {
285        self.show_seconds
286    }
287
288    pub fn set_show_seconds(&mut self, show: bool, cx: &mut Context<Self>) {
289        self.show_seconds = show;
290        if show && self.value.second.is_none() {
291            self.value.second = Some(0);
292        } else if !show {
293            self.value.second = None;
294        }
295        cx.notify();
296    }
297}
298
299impl Focusable for TimePickerState {
300    fn focus_handle(&self, _: &App) -> FocusHandle {
301        self.focus_handle.clone()
302    }
303}
304
305impl Render for TimePickerState {
306    fn render(&mut self, _: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
307        div()
308    }
309}
310
311#[derive(IntoElement)]
312pub struct TimePicker {
313    state: Entity<TimePickerState>,
314    placeholder: SharedString,
315    disabled: bool,
316    on_change: Option<Rc<dyn Fn(&TimeValue, &mut Window, &mut App)>>,
317    style: StyleRefinement,
318}
319
320impl TimePicker {
321    pub fn new(state: Entity<TimePickerState>) -> Self {
322        Self {
323            state,
324            placeholder: "Select time".into(),
325            disabled: false,
326            on_change: None,
327            style: StyleRefinement::default(),
328        }
329    }
330
331    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
332        self.placeholder = placeholder.into();
333        self
334    }
335
336    pub fn disabled(mut self, disabled: bool) -> Self {
337        self.disabled = disabled;
338        self
339    }
340
341    pub fn on_change(
342        mut self,
343        handler: impl Fn(&TimeValue, &mut Window, &mut App) + 'static,
344    ) -> Self {
345        self.on_change = Some(Rc::new(handler));
346        self
347    }
348}
349
350impl Styled for TimePicker {
351    fn style(&mut self) -> &mut StyleRefinement {
352        &mut self.style
353    }
354}
355
356impl RenderOnce for TimePicker {
357    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
358        let theme = use_theme(cx);
359        let user_style = self.style;
360        let state_data = self.state.read(cx);
361        let is_open = state_data.open;
362        let has_value = state_data.has_value;
363        let value = state_data.value;
364        let format = state_data.format;
365        let show_seconds = state_data.show_seconds;
366        let state = self.state.clone();
367
368        let display_text: SharedString = if has_value {
369            value.format_string(format).into()
370        } else {
371            self.placeholder.clone()
372        };
373
374        div()
375            .relative()
376            .map(|this| {
377                let mut div = this;
378                div.style().refine(&user_style);
379                div
380            })
381            .child(
382                div()
383                    .id("time-picker-trigger")
384                    .flex()
385                    .items_center()
386                    .gap(px(8.0))
387                    .px(px(12.0))
388                    .py(px(8.0))
389                    .min_w(px(140.0))
390                    .bg(theme.tokens.background)
391                    .border_1()
392                    .border_color(if is_open {
393                        theme.tokens.ring
394                    } else {
395                        theme.tokens.input
396                    })
397                    .rounded(theme.tokens.radius_md)
398                    .text_size(px(14.0))
399                    .text_color(if has_value {
400                        theme.tokens.foreground
401                    } else {
402                        theme.tokens.muted_foreground
403                    })
404                    .font_family(theme.tokens.font_family.clone())
405                    .when(!self.disabled, |d| d.cursor_pointer())
406                    .when(self.disabled, |d| d.opacity(0.5))
407                    .when(!self.disabled, {
408                        let state = state.clone();
409                        move |d| {
410                            d.on_click(move |_, _, cx| {
411                                state.update(cx, |s, cx| s.toggle(cx));
412                            })
413                        }
414                    })
415                    .child(div().flex_1().child(display_text))
416                    .child(div().text_color(theme.tokens.muted_foreground).child("🕐")),
417            )
418            .when(is_open && !self.disabled, |this| {
419                this.child(
420                    div()
421                        .absolute()
422                        .top_full()
423                        .left_0()
424                        .mt(px(4.0))
425                        .bg(theme.tokens.popover)
426                        .border_1()
427                        .border_color(theme.tokens.border)
428                        .rounded(theme.tokens.radius_md)
429                        .shadow(smallvec::smallvec![BoxShadow {
430                            color: hsla(0.0, 0.0, 0.0, 0.15),
431                            offset: point(px(0.0), px(4.0)),
432                            blur_radius: px(12.0),
433                            spread_radius: px(0.0),
434                            inset: false,
435                        }])
436                        .p(px(16.0))
437                        .child({
438                            let on_change = self.on_change.clone();
439                            let state_for_seconds = state.clone();
440                            let state_for_period = state.clone();
441                            div()
442                                .flex()
443                                .items_center()
444                                .gap(px(8.0))
445                                .child(Self::render_spinner(
446                                    "hour",
447                                    value.hour,
448                                    state.clone(),
449                                    "hour",
450                                    &theme,
451                                    on_change.clone(),
452                                ))
453                                .child(
454                                    div()
455                                        .text_size(px(20.0))
456                                        .font_weight(FontWeight::BOLD)
457                                        .text_color(theme.tokens.foreground)
458                                        .child(":"),
459                                )
460                                .child(Self::render_spinner(
461                                    "minute",
462                                    value.minute,
463                                    state.clone(),
464                                    "minute",
465                                    &theme,
466                                    on_change.clone(),
467                                ))
468                                .when(show_seconds, {
469                                    let on_change = on_change.clone();
470                                    move |this| {
471                                        this.child(
472                                            div()
473                                                .text_size(px(20.0))
474                                                .font_weight(FontWeight::BOLD)
475                                                .text_color(theme.tokens.foreground)
476                                                .child(":"),
477                                        )
478                                        .child(
479                                            Self::render_spinner(
480                                                "second",
481                                                value.second.unwrap_or(0),
482                                                state_for_seconds.clone(),
483                                                "second",
484                                                &theme,
485                                                on_change,
486                                            ),
487                                        )
488                                    }
489                                })
490                                .when(format == TimeFormat::Hour12, {
491                                    let is_am = value.period == Some(TimePeriod::AM);
492                                    let on_change = on_change.clone();
493                                    move |this| {
494                                        this.child(
495                                            div()
496                                                .ml(px(8.0))
497                                                .flex()
498                                                .flex_col()
499                                                .gap(px(4.0))
500                                                .child(
501                                                    Button::new("am", "AM")
502                                                        .size(ButtonSize::Sm)
503                                                        .variant(if is_am {
504                                                            ButtonVariant::Default
505                                                        } else {
506                                                            ButtonVariant::Ghost
507                                                        })
508                                                        .on_click({
509                                                            let state = state_for_period.clone();
510                                                            let on_change = on_change.clone();
511                                                            move |_, window, cx| {
512                                                                state.update(cx, |s, cx| {
513                                                                    s.set_period(
514                                                                        TimePeriod::AM,
515                                                                        cx,
516                                                                    );
517                                                                    if let Some(ref handler) =
518                                                                        on_change
519                                                                    {
520                                                                        handler(
521                                                                            &s.value, window, cx,
522                                                                        );
523                                                                    }
524                                                                });
525                                                            }
526                                                        }),
527                                                )
528                                                .child(
529                                                    Button::new("pm", "PM")
530                                                        .size(ButtonSize::Sm)
531                                                        .variant(if !is_am {
532                                                            ButtonVariant::Default
533                                                        } else {
534                                                            ButtonVariant::Ghost
535                                                        })
536                                                        .on_click({
537                                                            let state = state_for_period.clone();
538                                                            let on_change = on_change.clone();
539                                                            move |_, window, cx| {
540                                                                state.update(cx, |s, cx| {
541                                                                    s.set_period(
542                                                                        TimePeriod::PM,
543                                                                        cx,
544                                                                    );
545                                                                    if let Some(ref handler) =
546                                                                        on_change
547                                                                    {
548                                                                        handler(
549                                                                            &s.value, window, cx,
550                                                                        );
551                                                                    }
552                                                                });
553                                                            }
554                                                        }),
555                                                ),
556                                        )
557                                    }
558                                })
559                        }),
560                )
561            })
562    }
563}
564
565impl TimePicker {
566    fn render_spinner(
567        id: &str,
568        value: u8,
569        state: Entity<TimePickerState>,
570        field: &str,
571        theme: &crate::capabilities::foundation::theme::Theme,
572        on_change: Option<Rc<dyn Fn(&TimeValue, &mut Window, &mut App)>>,
573    ) -> impl IntoElement {
574        let field_up = field.to_string();
575        let field_down = field.to_string();
576        let state_up = state.clone();
577        let state_down = state.clone();
578        let on_change_up = on_change.clone();
579        let on_change_down = on_change;
580
581        div()
582            .flex()
583            .flex_col()
584            .items_center()
585            .gap(px(4.0))
586            .child(
587                div()
588                    .id(SharedString::from(format!("{}-up", id)))
589                    .w(px(40.0))
590                    .h(px(28.0))
591                    .flex()
592                    .items_center()
593                    .justify_center()
594                    .rounded(px(4.0))
595                    .cursor_pointer()
596                    .hover(|s| s.bg(theme.tokens.accent))
597                    .text_color(theme.tokens.muted_foreground)
598                    .on_click(move |_, window, cx| {
599                        state_up.update(cx, |s, cx| {
600                            match field_up.as_str() {
601                                "hour" => s.increment_hour(cx),
602                                "minute" => s.increment_minute(cx),
603                                "second" => s.increment_second(cx),
604                                _ => {}
605                            }
606                            if let Some(ref handler) = on_change_up {
607                                handler(&s.value, window, cx);
608                            }
609                        });
610                    })
611                    .child("▲"),
612            )
613            .child(
614                div()
615                    .w(px(48.0))
616                    .h(px(40.0))
617                    .flex()
618                    .items_center()
619                    .justify_center()
620                    .bg(theme.tokens.muted)
621                    .rounded(px(6.0))
622                    .text_size(px(20.0))
623                    .font_weight(FontWeight::SEMIBOLD)
624                    .text_color(theme.tokens.foreground)
625                    .font_family(theme.tokens.font_family.clone())
626                    .child(format!("{:02}", value)),
627            )
628            .child(
629                div()
630                    .id(SharedString::from(format!("{}-down", id)))
631                    .w(px(40.0))
632                    .h(px(28.0))
633                    .flex()
634                    .items_center()
635                    .justify_center()
636                    .rounded(px(4.0))
637                    .cursor_pointer()
638                    .hover(|s| s.bg(theme.tokens.accent))
639                    .text_color(theme.tokens.muted_foreground)
640                    .on_click(move |_, window, cx| {
641                        state_down.update(cx, |s, cx| {
642                            match field_down.as_str() {
643                                "hour" => s.decrement_hour(cx),
644                                "minute" => s.decrement_minute(cx),
645                                "second" => s.decrement_second(cx),
646                                _ => {}
647                            }
648                            if let Some(ref handler) = on_change_down {
649                                handler(&s.value, window, cx);
650                            }
651                        });
652                    })
653                    .child("▼"),
654            )
655    }
656}