Skip to main content

gpui_material_extras/date_time/time/
panel.rs

1use std::{cell::Cell, f32::consts::TAU, rc::Rc};
2
3use chrono::Timelike;
4use gpui::{
5    AccessibleAction, AnyElement, App, Bounds, ElementId, Entity, Hsla, InteractiveElement as _,
6    IntoElement, MouseButton, ParentElement as _, PathBuilder, Pixels, Point, RenderOnce, Role,
7    SharedString, StatefulInteractiveElement as _, Styled as _, Window, canvas, div, point,
8    prelude::FluentBuilder as _, px,
9};
10use gpui_base::{Button as BaseButton, TestSupportExt as _};
11use gpui_material_components::{Text, TextField, TextFieldColors, TextFieldVariant};
12use gpui_material_foundation::{color, current_material_theme};
13use gpui_material_theme::{ColorRole, CornerRole, CornerShape, Direction, MaterialTheme, TypeRole};
14
15use super::{
16    TimeFormat, TimePickerLayout, TimePickerSegment, TimePickerState, TimePickerVariant,
17    dialog::{ModeSlot, TimePickerModeAction, mode_action},
18    display_hour, format_time,
19};
20use crate::date_time::{ScrollField, ScrollFieldColors, status};
21
22/// Container and content colors for selected and unselected controls.
23#[derive(Clone, Copy, Debug, Default)]
24pub struct TimePickerSelectionColors {
25    /// Background fill color when the control is selected.
26    pub selected_container: Option<Hsla>,
27    /// Background fill color when the control is unselected.
28    pub container: Option<Hsla>,
29    /// Foreground text color when the control is selected.
30    pub selected_content: Option<Hsla>,
31    /// Foreground text color when the control is unselected.
32    pub content: Option<Hsla>,
33}
34
35/// Instance appearance for the dial, input, and scroll panels.
36#[derive(Clone, Copy, Debug, Default)]
37pub struct TimePickerStyle {
38    /// Corner shape override for hour and minute selector boxes and inputs.
39    pub time_field_shape: Option<CornerShape>,
40    /// Corner shape override for the AM/PM period selector.
41    pub period_selector_shape: Option<CornerShape>,
42    /// Background fill color for the panel container.
43    pub container: Option<Hsla>,
44    /// Background fill color for the circular clock dial face.
45    pub clock_dial: Option<Hsla>,
46    /// Text color for unselected numbers on the clock dial.
47    pub clock_dial_content: Option<Hsla>,
48    /// Text color for the currently selected number on the clock dial.
49    pub clock_dial_selected_content: Option<Hsla>,
50    /// Accent color for the clock dial hand and selection handle.
51    pub selector: Option<Hsla>,
52    /// Colors for the hour and minute header selector tiles.
53    pub time_selector: TimePickerSelectionColors,
54    /// Colors for the AM/PM period selector buttons.
55    pub period_selector: TimePickerSelectionColors,
56    /// Outline border color around the AM/PM period selector.
57    pub period_selector_border: Option<Hsla>,
58    /// Color overrides applied to the text-input fields.
59    pub input: TextFieldColors,
60    /// Color overrides applied to the scroll-wheel fields.
61    pub scroll: ScrollFieldColors,
62}
63
64#[derive(Clone, Copy)]
65struct Presentation {
66    style: TimePickerStyle,
67    vibrant: bool,
68}
69
70impl Presentation {
71    fn selector_shape(self) -> CornerShape {
72        self.style.time_field_shape.unwrap_or_else(|| {
73            if self.vibrant {
74                CornerRole::Large
75            } else {
76                CornerRole::Small
77            }
78            .shape()
79        })
80    }
81
82    fn period_shape(self) -> CornerShape {
83        self.style.period_selector_shape.unwrap_or_else(|| {
84            if self.vibrant {
85                CornerRole::Full
86            } else {
87                CornerRole::Small
88            }
89            .shape()
90        })
91    }
92
93    fn input_colors(self, theme: &MaterialTheme) -> TextFieldColors {
94        let mut input = self.style.input;
95        if self.vibrant {
96            let tone = |role| color(theme.colors.color(role));
97            for state in [&mut input.unfocused, &mut input.focused] {
98                state
99                    .container
100                    .get_or_insert_with(|| tone(ColorRole::SurfaceContainerLowest));
101            }
102            input
103                .focused
104                .text
105                .get_or_insert_with(|| tone(ColorRole::Primary));
106            input
107                .invalid
108                .container
109                .get_or_insert_with(|| tone(ColorRole::ErrorContainer));
110            input
111                .invalid
112                .text
113                .get_or_insert_with(|| tone(ColorRole::OnErrorContainer));
114        }
115        input
116    }
117}
118
119/// An independently mountable Material time-editing panel.
120#[derive(IntoElement)]
121pub struct TimePickerPanel {
122    id: ElementId,
123    state: Entity<TimePickerState>,
124    variant: Option<TimePickerVariant>,
125    layout: TimePickerLayout,
126    presentation: Presentation,
127    toggle: Option<ModeSlot>,
128}
129
130impl TimePickerPanel {
131    /// Creates a panel that follows `state.mode()` dynamically.
132    pub fn new(id: impl Into<ElementId>, state: &Entity<TimePickerState>) -> Self {
133        Self {
134            id: id.into(),
135            state: state.clone(),
136            variant: None,
137            layout: TimePickerLayout::Auto,
138            presentation: Presentation {
139                style: TimePickerStyle::default(),
140                vibrant: false,
141            },
142            toggle: None,
143        }
144    }
145
146    /// Creates a panel pinned to [`TimePickerVariant::Dial`].
147    pub fn dial(id: impl Into<ElementId>, state: &Entity<TimePickerState>) -> Self {
148        Self::new(id, state).fixed(TimePickerVariant::Dial)
149    }
150
151    /// Creates a panel pinned to [`TimePickerVariant::Input`].
152    pub fn input(id: impl Into<ElementId>, state: &Entity<TimePickerState>) -> Self {
153        Self::new(id, state).fixed(TimePickerVariant::Input)
154    }
155
156    fn fixed(mut self, variant: TimePickerVariant) -> Self {
157        self.variant = Some(variant);
158        self
159    }
160
161    /// Sets the dial layout orientation. Defaults to [`TimePickerLayout::Auto`].
162    pub fn layout(mut self, layout: TimePickerLayout) -> Self {
163        self.layout = layout;
164        self
165    }
166
167    /// Overrides the panel's appearance and color tokens.
168    pub fn style(mut self, style: TimePickerStyle) -> Self {
169        self.presentation.style = style;
170        self
171    }
172
173    /// Enables or disables the expressive vibrant styling preset.
174    pub fn vibrant(mut self, vibrant: bool) -> Self {
175        self.presentation.vibrant = vibrant;
176        self
177    }
178
179    /// Renders a custom mode-toggle control inside the panel.
180    pub fn mode_toggle_content<E: IntoElement>(
181        mut self,
182        content: impl FnOnce(TimePickerModeAction) -> E + 'static,
183    ) -> Self {
184        self.toggle = Some(Box::new(move |action| content(action).into_any_element()));
185        self
186    }
187}
188
189impl RenderOnce for TimePickerPanel {
190    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
191        let model = self.state.read(cx);
192        let mode = self.variant.unwrap_or(model.mode);
193        let appearance = self.presentation;
194        let controls = match mode {
195            TimePickerVariant::Dial => time_selector(&self.id, &self.state, appearance, window, cx),
196            TimePickerVariant::Input => time_input(&self.id, &self.state, appearance, window, cx),
197            TimePickerVariant::Scroll => time_scroll(&self.id, model, appearance, window, cx),
198        };
199        let period = (model.format == TimeFormat::TwelveHour)
200            .then(|| period_selector(&self.id, &self.state, appearance, window, cx));
201        let horizontal = mode == TimePickerVariant::Dial
202            && window.viewport_size().width >= px(600.)
203            && match self.layout {
204                TimePickerLayout::Vertical => false,
205                TimePickerLayout::Horizontal => true,
206                TimePickerLayout::Auto => window.viewport_size().height < px(650.),
207            };
208        let rtl = current_material_theme(window, cx).layout.direction == Direction::Rtl;
209        let toggle = self
210            .toggle
211            .map(|content| content(mode_action(&self.state, model, mode, false)));
212        div()
213            .id((self.id.clone(), "panel"))
214            .track_focus(&model.panel)
215            .flex()
216            .gap(px(12.))
217            .items_center()
218            .when(!horizontal, gpui::Styled::flex_col)
219            .when(horizontal && rtl, gpui::Styled::flex_row_reverse)
220            .when_some(appearance.style.container, |body, container| {
221                body.bg(container)
222            })
223            .child(
224                div()
225                    .min_w_0()
226                    .w(px(216.))
227                    .max_w_full()
228                    .flex()
229                    .flex_col()
230                    .gap(px(8.))
231                    .child(controls)
232                    .children(period)
233                    .children(toggle),
234            )
235            .children(
236                (mode == TimePickerVariant::Dial)
237                    .then(|| dial(&self.id, &self.state, appearance, window, cx)),
238            )
239    }
240}
241
242/// An uncontained vibrant panel with separate, wrapping hour and minute wheels.
243#[derive(IntoElement)]
244pub struct TimeScroll(TimePickerPanel);
245
246impl TimeScroll {
247    /// Creates a vibrant scroll-wheel time panel bound to `state`.
248    pub fn new(id: impl Into<ElementId>, state: &Entity<TimePickerState>) -> Self {
249        Self(
250            TimePickerPanel::new(id, state)
251                .fixed(TimePickerVariant::Scroll)
252                .vibrant(true),
253        )
254    }
255
256    /// Overrides the panel's appearance and color tokens.
257    pub fn style(mut self, style: TimePickerStyle) -> Self {
258        self.0 = self.0.style(style);
259        self
260    }
261
262    /// Renders a custom mode-toggle control inside the scroll panel.
263    pub fn mode_toggle_content<E: IntoElement>(
264        mut self,
265        content: impl FnOnce(TimePickerModeAction) -> E + 'static,
266    ) -> Self {
267        self.0 = self.0.mode_toggle_content(content);
268        self
269    }
270}
271
272impl RenderOnce for TimeScroll {
273    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
274        self.0
275    }
276}
277
278fn time_input(
279    id: &ElementId,
280    state: &Entity<TimePickerState>,
281    appearance: Presentation,
282    window: &Window,
283    cx: &App,
284) -> AnyElement {
285    let model = state.read(cx);
286    let state = state.clone();
287    let theme = current_material_theme(window, cx);
288    let colors = appearance.input_colors(&theme);
289    let field = |segment, label: &SharedString, part| {
290        let editor = model.field(segment);
291        let invalid = model.input_attempted
292            && model
293                .parse_segment(segment, &editor.read(cx).value())
294                .is_none();
295        let control = TextField::new((id.clone(), part), label.clone(), editor)
296            .variant(TextFieldVariant::Outlined)
297            .colors(colors)
298            .invalid(invalid)
299            .when_some(
300                appearance
301                    .style
302                    .time_field_shape
303                    .or_else(|| appearance.vibrant.then(|| appearance.selector_shape())),
304                |field, shape| field.shape(shape),
305            );
306        div().flex_1().min_w_0().child(control)
307    };
308    div()
309        .capture_action(move |_: &gpui_base::input::Escape, window, cx| {
310            if state.update(cx, |state, cx| state.finish_composition(window, cx)) {
311                cx.stop_propagation();
312            }
313        })
314        .flex()
315        .flex_col()
316        .gap(px(8.))
317        .child(
318            div()
319                .flex()
320                .items_start()
321                .gap(px(12.))
322                .w_full()
323                .when(
324                    theme.layout.direction == Direction::Rtl,
325                    gpui::Styled::flex_row_reverse,
326                )
327                .child(field(TimePickerSegment::Hour, &model.locale.hour, "hour"))
328                .child(field(
329                    TimePickerSegment::Minute,
330                    &model.locale.minute,
331                    "minute",
332                )),
333        )
334        .when(
335            model.input_attempted && !model.is_input_valid(cx),
336            |column| column.child(status(model.locale.validation_message.clone(), true)),
337        )
338        .into_any_element()
339}
340
341fn time_scroll(
342    id: &ElementId,
343    model: &TimePickerState,
344    appearance: Presentation,
345    window: &Window,
346    cx: &App,
347) -> AnyElement {
348    let theme = current_material_theme(window, cx);
349    let wheel = |segment, name: &SharedString, part| {
350        let offset = usize::from(
351            segment == TimePickerSegment::Hour && model.format == TimeFormat::TwelveHour,
352        );
353        let describe = model.locale.number.clone();
354        let display = describe.clone();
355        let scroll = ScrollField::new((id.clone(), part), name.clone(), model.wheel(segment))
356            .colors(appearance.style.scroll)
357            .time_field(appearance.style.time_field_shape, offset)
358            .value_description(move |index| describe((index + offset) as u32))
359            .item_content(move |index, selected, _| {
360                Text::new(display((index + offset) as u32))
361                    .role(if selected {
362                        TypeRole::DisplayLarge
363                    } else {
364                        TypeRole::DisplayMedium
365                    })
366                    .emphasized(selected)
367            });
368        div().flex_1().min_w_0().child(scroll)
369    };
370    div()
371        .flex()
372        .w_full()
373        .gap(px(4.))
374        .when(
375            theme.layout.direction == Direction::Rtl,
376            gpui::Styled::flex_row_reverse,
377        )
378        .child(wheel(
379            TimePickerSegment::Hour,
380            &model.locale.hour,
381            "hour-scroll",
382        ))
383        .child(wheel(
384            TimePickerSegment::Minute,
385            &model.locale.minute,
386            "minute-scroll",
387        ))
388        .into_any_element()
389}
390
391fn time_selector(
392    id: &ElementId,
393    state: &Entity<TimePickerState>,
394    appearance: Presentation,
395    window: &Window,
396    cx: &App,
397) -> AnyElement {
398    let model = state.read(cx);
399    let (format, locale) = (model.format, &model.locale);
400    let theme = current_material_theme(window, cx);
401    let rtl = theme.layout.direction == Direction::Rtl;
402    let tone = |role| color(theme.colors.color(role));
403    let palette = appearance.style.time_selector;
404    let [tl, tr, br, bl] = appearance
405        .selector_shape()
406        .radii(96., 80., theme.layout.direction)
407        .map(px);
408    let segment = |part, label: &SharedString, value| {
409        let selected = part == model.segment;
410        let state = state.clone();
411        let text = (locale.number)(value);
412        let action = Rc::new(move |window: &mut Window, cx: &mut App| {
413            state.update(cx, |state, cx| {
414                state.set_segment(part, cx);
415                state.dial.focus(window, cx);
416            });
417        });
418        let click = action.clone();
419        BaseButton::new((
420            id.clone(),
421            if part == TimePickerSegment::Hour {
422                "select-hour"
423            } else {
424                "select-minute"
425            },
426        ))
427        .role(Role::RadioButton)
428        .aria_toggled(if selected {
429            gpui::Toggled::True
430        } else {
431            gpui::Toggled::False
432        })
433        .accessibility_label(format!("{label} {text}"))
434        .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
435            action(window, cx)
436        })
437        .on_click(move |_, window, cx| click(window, cx))
438        .w(px(96.))
439        .h(px(80.))
440        .max_w_full()
441        .min_w_0()
442        .flex_shrink(1.)
443        .rounded_tl(tl)
444        .rounded_tr(tr)
445        .rounded_br(br)
446        .rounded_bl(bl)
447        .bg(if appearance.vibrant {
448            (if selected {
449                palette.selected_container
450            } else {
451                palette.container
452            })
453            .unwrap_or_else(|| tone(ColorRole::SurfaceContainerLowest))
454        } else if selected {
455            palette
456                .selected_container
457                .unwrap_or_else(|| tone(ColorRole::PrimaryContainer))
458        } else {
459            palette
460                .container
461                .unwrap_or_else(|| tone(ColorRole::SurfaceContainerHighest))
462        })
463        .text_color(if selected {
464            palette.selected_content.unwrap_or_else(|| {
465                tone(if appearance.vibrant {
466                    ColorRole::Primary
467                } else {
468                    ColorRole::OnPrimaryContainer
469                })
470            })
471        } else {
472            palette
473                .content
474                .unwrap_or_else(|| tone(ColorRole::OnSurface))
475        })
476        .when(appearance.vibrant && selected, |button| {
477            button.border_2().border_color(tone(ColorRole::Primary))
478        })
479        .child(Text::new(text).role(TypeRole::DisplayMedium))
480    };
481    div()
482        .flex()
483        .items_center()
484        .justify_center()
485        .gap(px(4.))
486        .when(rtl, gpui::Styled::flex_row_reverse)
487        .child(segment(
488            TimePickerSegment::Hour,
489            &locale.hour,
490            display_hour(model.draft, format),
491        ))
492        .child(Text::new(locale.separator.clone()).role(TypeRole::DisplayMedium))
493        .child(segment(
494            TimePickerSegment::Minute,
495            &locale.minute,
496            model.draft.minute(),
497        ))
498        .into_any_element()
499}
500
501fn period_selector(
502    id: &ElementId,
503    state: &Entity<TimePickerState>,
504    appearance: Presentation,
505    window: &Window,
506    cx: &App,
507) -> AnyElement {
508    let model = state.read(cx);
509    let locale = &model.locale;
510    let theme = current_material_theme(window, cx);
511    let rtl = theme.layout.direction == Direction::Rtl;
512    let tone = |role| color(theme.colors.color(role));
513    let palette = appearance.style.period_selector;
514    let [tl, tr, br, bl] = appearance
515        .period_shape()
516        .radii(108., 38., theme.layout.direction)
517        .map(px);
518    let button = |pm, label: SharedString| {
519        let selected = (model.draft.hour() >= 12) == pm;
520        let state = state.clone();
521        let activate = Rc::new(move |_: &mut Window, cx: &mut App| {
522            state.update(cx, |state, cx| {
523                let next = state
524                    .draft
525                    .with_hour(state.draft.hour() % 12 + if pm { 12 } else { 0 })
526                    .unwrap();
527                if state.draft != next {
528                    state.draft = next;
529                    cx.notify();
530                }
531            });
532        });
533        let click = activate.clone();
534        BaseButton::new((id.clone(), if pm { "pm" } else { "am" }))
535            .role(Role::RadioButton)
536            .aria_toggled(if selected {
537                gpui::Toggled::True
538            } else {
539                gpui::Toggled::False
540            })
541            .accessibility_label(label.clone())
542            .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
543                activate(window, cx)
544            })
545            .on_click(move |_, window, cx| click(window, cx))
546            .flex_1()
547            .h(px(38.))
548            .rounded_tl(tl)
549            .rounded_tr(tr)
550            .rounded_br(br)
551            .rounded_bl(bl)
552            .when_some(
553                if selected {
554                    Some(palette.selected_container.unwrap_or_else(|| {
555                        tone(if appearance.vibrant {
556                            ColorRole::PrimaryContainer
557                        } else {
558                            ColorRole::TertiaryContainer
559                        })
560                    }))
561                } else {
562                    palette.container.or_else(|| {
563                        appearance
564                            .vibrant
565                            .then(|| tone(ColorRole::SurfaceContainerLowest))
566                    })
567                },
568                |button, container| button.bg(container),
569            )
570            .text_color(if selected {
571                palette.selected_content.unwrap_or_else(|| {
572                    tone(if appearance.vibrant {
573                        ColorRole::OnPrimaryContainer
574                    } else {
575                        ColorRole::OnTertiaryContainer
576                    })
577                })
578            } else {
579                palette
580                    .content
581                    .unwrap_or_else(|| tone(ColorRole::OnSurfaceVariant))
582            })
583            .child(Text::new(label).role(TypeRole::TitleMedium))
584    };
585    div()
586        .flex()
587        .w_full()
588        .rounded_tl(tl)
589        .rounded_tr(tr)
590        .rounded_br(br)
591        .rounded_bl(bl)
592        .border_1()
593        .border_color(
594            appearance
595                .style
596                .period_selector_border
597                .unwrap_or_else(|| tone(ColorRole::Outline)),
598        )
599        .when(rtl, gpui::Styled::flex_row_reverse)
600        .child(button(false, locale.am.clone()))
601        .child(button(true, locale.pm.clone()))
602        .into_any_element()
603}
604
605fn polar(step: u32, divisions: u32, radius: Pixels) -> Point<Pixels> {
606    let angle = step as f32 * TAU / divisions as f32;
607    point(radius * angle.sin(), -radius * angle.cos())
608}
609
610fn dial_position(
611    value: u32,
612    segment: TimePickerSegment,
613    format: TimeFormat,
614    diameter: Pixels,
615) -> Point<Pixels> {
616    if segment == TimePickerSegment::Minute {
617        return polar(value, 60, diameter * 0.365);
618    }
619    let inner = format == TimeFormat::TwentyFourHour && (value == 0 || value > 12);
620    polar(value % 12, 12, diameter * if inner { 0.205 } else { 0.365 })
621}
622
623fn dial_value(
624    offset: Point<Pixels>,
625    segment: TimePickerSegment,
626    format: TimeFormat,
627    diameter: Pixels,
628) -> u32 {
629    let (x, y) = (f32::from(offset.x), f32::from(offset.y));
630    let turn = x.atan2(-y).rem_euclid(TAU) / TAU;
631    if segment == TimePickerSegment::Minute {
632        return ((turn * 60.).round() as u32) % 60;
633    }
634    let hour = ((turn * 12.).round() as u32) % 12;
635    let inner = format == TimeFormat::TwentyFourHour && x.hypot(y) < f32::from(diameter * 0.285);
636    match (inner, hour) {
637        (true, 0) => 0,
638        (true, _) => hour + 12,
639        (_, 0) => 12,
640        _ => hour,
641    }
642}
643
644const MINUTE_MARKS: &[u32] = &[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55];
645const TWELVE_HOUR_MARKS: &[u32] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
646const TWENTY_FOUR_HOUR_MARKS: &[u32] = &[
647    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
648];
649const MARK_IDS: [&str; 60] = [
650    "mark-0", "mark-1", "mark-2", "mark-3", "mark-4", "mark-5", "mark-6", "mark-7", "mark-8",
651    "mark-9", "mark-10", "mark-11", "mark-12", "mark-13", "mark-14", "mark-15", "mark-16",
652    "mark-17", "mark-18", "mark-19", "mark-20", "mark-21", "mark-22", "mark-23", "mark-24",
653    "mark-25", "mark-26", "mark-27", "mark-28", "mark-29", "mark-30", "mark-31", "mark-32",
654    "mark-33", "mark-34", "mark-35", "mark-36", "mark-37", "mark-38", "mark-39", "mark-40",
655    "mark-41", "mark-42", "mark-43", "mark-44", "mark-45", "mark-46", "mark-47", "mark-48",
656    "mark-49", "mark-50", "mark-51", "mark-52", "mark-53", "mark-54", "mark-55", "mark-56",
657    "mark-57", "mark-58", "mark-59",
658];
659
660fn dial(
661    id: &ElementId,
662    state: &Entity<TimePickerState>,
663    appearance: Presentation,
664    window: &Window,
665    cx: &App,
666) -> AnyElement {
667    let model = state.read(cx);
668    let (format, locale) = (model.format, &model.locale);
669    let segment = model.segment;
670    let focus = model.dial.clone();
671    let selected = if segment == TimePickerSegment::Hour {
672        display_hour(model.draft, format)
673    } else {
674        model.draft.minute()
675    };
676    let label = if segment == TimePickerSegment::Hour {
677        &locale.hour
678    } else {
679        &locale.minute
680    };
681    let theme = current_material_theme(window, cx);
682    let tone = |role| color(theme.colors.color(role));
683    let diameter = (window.viewport_size().width - px(110.)).clamp(px(120.), px(256.));
684    let center = diameter / 2.;
685    let handle = diameter * (48. / 256.);
686    let selected_position = dial_position(selected, segment, format, diameter);
687    let bounds = Rc::new(Cell::new(Bounds::default()));
688    let measured = bounds.clone();
689    let accent = appearance
690        .style
691        .selector
692        .unwrap_or_else(|| tone(ColorRole::Primary));
693    let content = appearance
694        .style
695        .clock_dial_content
696        .unwrap_or_else(|| tone(ColorRole::OnSurface));
697    let selected_content = appearance
698        .style
699        .clock_dial_selected_content
700        .unwrap_or_else(|| tone(ColorRole::OnPrimary));
701    let track = canvas(
702        move |bounds, _, _| {
703            measured.set(bounds);
704        },
705        move |bounds, _, window, _| {
706            let start = bounds.center();
707            let mut line = PathBuilder::stroke(px(2.));
708            line.move_to(start);
709            line.line_to(start + selected_position);
710            if let Ok(path) = line.build() {
711                window.paint_path(path, accent);
712            }
713        },
714    )
715    .absolute()
716    .size_full();
717    let key_state = state.clone();
718    let click_state = state.clone();
719    let click_focus = focus.clone();
720    let keyboard_focus = focus.is_focused(window) && window.last_input_was_keyboard();
721    let marks: &[u32] = match (segment, format) {
722        (TimePickerSegment::Minute, _) => MINUTE_MARKS,
723        (_, TimeFormat::TwelveHour) => TWELVE_HOUR_MARKS,
724        (_, TimeFormat::TwentyFourHour) => TWENTY_FOUR_HOUR_MARKS,
725    };
726    div()
727        .id((id.clone(), "dial"))
728        .test_support()
729        .role(Role::Group)
730        .aria_label(format!(
731            "{label}, {}",
732            format_time(model.draft, format, locale)
733        ))
734        .track_focus(&focus)
735        .tab_stop(true)
736        .size(diameter)
737        .flex_none()
738        .relative()
739        .rounded_full()
740        .bg(appearance.style.clock_dial.unwrap_or_else(|| {
741            tone(if appearance.vibrant {
742                ColorRole::SurfaceContainerLowest
743            } else {
744                ColorRole::SurfaceContainerHighest
745            })
746        }))
747        .when(keyboard_focus, |dial| {
748            dial.border_2().border_color(tone(ColorRole::Secondary))
749        })
750        .child(track)
751        .child(
752            div()
753                .absolute()
754                .size(px(8.))
755                .left(center - px(4.))
756                .top(center - px(4.))
757                .rounded_full()
758                .bg(accent),
759        )
760        .child(
761            div()
762                .absolute()
763                .size(handle)
764                .left(center + selected_position.x - handle / 2.)
765                .top(center + selected_position.y - handle / 2.)
766                .rounded_full()
767                .bg(accent),
768        )
769        .on_mouse_down(MouseButton::Left, move |event, window, cx| {
770            let offset = event.position - bounds.get().center();
771            let distance = f32::from(offset.x).hypot(f32::from(offset.y));
772            if distance <= f32::from(diameter / 2.) {
773                click_focus.focus(window, cx);
774                let value = dial_value(offset, segment, format, diameter);
775                click_state.update(cx, |state, cx| state.select(value, true, window, cx));
776            }
777        })
778        .capture_key_down(move |event, window, cx| {
779            if !focus.is_focused(window) || event.keystroke.modifiers.modified() {
780                return;
781            }
782            let divisions = match (segment, format) {
783                (TimePickerSegment::Minute, _) => 60,
784                (_, TimeFormat::TwelveHour) => 12,
785                (_, TimeFormat::TwentyFourHour) => 24,
786            };
787            let value = match event.keystroke.key.as_str() {
788                "left" | "down" => Some((selected + divisions - 1) % divisions),
789                "up" | "right" => Some((selected + 1) % divisions),
790                "home" => Some(0),
791                "end" => Some(divisions - 1),
792                "space" if segment == TimePickerSegment::Hour => Some(selected),
793                _ => None,
794            };
795            if let Some(value) = value {
796                key_state.update(cx, |state, cx| {
797                    state.select(value, event.keystroke.key == "space", window, cx)
798                });
799                cx.stop_propagation();
800            }
801        })
802        .children(marks.iter().copied().map(|value| {
803            let position = dial_position(value, segment, format, diameter);
804            let active = value == selected;
805            let label = (locale.number)(value);
806            let state = state.clone();
807            let activate = Rc::new(move |window: &mut Window, cx: &mut App| {
808                state.update(cx, |state, cx| {
809                    state.dial.focus(window, cx);
810                    state.select(value, true, window, cx);
811                });
812            });
813            let click = activate.clone();
814            BaseButton::new((id.clone(), MARK_IDS[value as usize]))
815                .role(Role::ListBoxOption)
816                .aria_selected(active)
817                .accessibility_label(label.clone())
818                .tab_stop(false)
819                .absolute()
820                .size(handle)
821                .left(center + position.x - handle / 2.)
822                .top(center + position.y - handle / 2.)
823                .on_mouse_down(MouseButton::Left, move |_, _, cx| cx.stop_propagation())
824                .on_a11y_action(AccessibleAction::Click, move |_, window, cx| {
825                    activate(window, cx)
826                })
827                .on_click(move |_, window, cx| click(window, cx))
828                .text_color(if active { selected_content } else { content })
829                .child(Text::new(label).role(TypeRole::BodyLarge))
830        }))
831        .into_any_element()
832}
833
834#[cfg(test)]
835mod tests {
836    use super::*;
837
838    #[test]
839    fn dial_position_round_trips_both_hour_rings_and_every_minute() {
840        let size = px(256.);
841        for (segment, format, values) in [
842            (TimePickerSegment::Hour, TimeFormat::TwentyFourHour, 0..24),
843            (TimePickerSegment::Hour, TimeFormat::TwelveHour, 1..13),
844            (TimePickerSegment::Minute, TimeFormat::TwentyFourHour, 0..60),
845        ] {
846            for value in values {
847                let point = dial_position(value, segment, format, size);
848                assert_eq!(dial_value(point, segment, format, size), value);
849            }
850        }
851    }
852}