tessera-components 0.0.0

Basic components for tessera-ui, using md3e design principles.
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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
//! Time picker components for selecting a clock time.
//!
//! ## Usage
//!
//! Use to let users choose a time for alarms, reminders, or schedules.
use std::{
    sync::Arc,
    time::{SystemTime, UNIX_EPOCH},
};

use derive_setters::Setters;
use tessera_ui::{
    DimensionValue, Dp, Modifier, State, provide_context, remember, tessera, use_context,
};

use crate::{
    alignment::{Alignment, CrossAxisAlignment, MainAxisAlignment},
    column::{ColumnArgs, column},
    modifier::ModifierExt as _,
    row::{RowArgs, row},
    shape_def::Shape,
    spacer::spacer,
    surface::{SurfaceArgs, SurfaceStyle, surface},
    text::{TextArgs, text},
    theme::{ContentColor, MaterialTheme},
};

const TIME_CELL_WIDTH: Dp = Dp(72.0);
const TIME_CELL_HEIGHT: Dp = Dp(56.0);
const TIME_CELL_RADIUS: Dp = Dp(12.0);
const TIME_STEP_BUTTON_SIZE: Dp = Dp(28.0);
const PERIOD_BUTTON_WIDTH: Dp = Dp(56.0);
const PERIOD_BUTTON_HEIGHT: Dp = Dp(32.0);
const TIME_ROW_GAP: Dp = Dp(12.0);

/// Display modes supported by [`time_picker`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TimePickerDisplayMode {
    /// Touch-friendly picker layout.
    #[default]
    Picker,
    /// Input-focused layout with labels.
    Input,
}

/// Indicates whether the selected time is in AM or PM.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DayPeriod {
    /// Ante meridiem (before noon).
    Am,
    /// Post meridiem (after noon).
    Pm,
}

/// Holds the current selection for a time picker.
pub struct TimePickerState {
    hour: u8,
    minute: u8,
    is_24_hour: bool,
    display_mode: TimePickerDisplayMode,
}

impl TimePickerState {
    /// Creates a time picker state with the provided initial values.
    pub fn new(
        initial_hour: u8,
        initial_minute: u8,
        is_24_hour: bool,
        display_mode: TimePickerDisplayMode,
    ) -> Self {
        Self {
            hour: clamp_hour(initial_hour),
            minute: clamp_minute(initial_minute),
            is_24_hour,
            display_mode,
        }
    }

    /// Returns the selected hour in 24-hour form (0-23).
    pub fn hour(&self) -> u8 {
        self.hour
    }

    /// Returns the selected minute (0-59).
    pub fn minute(&self) -> u8 {
        self.minute
    }

    /// Returns whether the picker uses 24-hour mode.
    pub fn is_24_hour(&self) -> bool {
        self.is_24_hour
    }

    /// Returns the display mode.
    pub fn display_mode(&self) -> TimePickerDisplayMode {
        self.display_mode
    }

    /// Returns the period for 12-hour mode.
    pub fn period(&self) -> DayPeriod {
        if self.hour >= 12 {
            DayPeriod::Pm
        } else {
            DayPeriod::Am
        }
    }

    /// Returns the hour to display in the UI.
    pub fn hour_for_display(&self) -> u8 {
        if self.is_24_hour {
            self.hour
        } else {
            let hour = self.hour % 12;
            if hour == 0 { 12 } else { hour }
        }
    }

    /// Sets the hour, clamped to 0-23.
    pub fn set_hour(&mut self, hour: u8) {
        self.hour = clamp_hour(hour);
    }

    /// Sets the minute, clamped to 0-59.
    pub fn set_minute(&mut self, minute: u8) {
        self.minute = clamp_minute(minute);
    }

    /// Sets 24-hour mode on or off.
    pub fn set_is_24_hour(&mut self, is_24_hour: bool) {
        self.is_24_hour = is_24_hour;
    }

    /// Sets the display mode.
    pub fn set_display_mode(&mut self, mode: TimePickerDisplayMode) {
        self.display_mode = mode;
    }

    /// Toggles between picker and input modes.
    pub fn toggle_display_mode(&mut self) {
        self.display_mode = match self.display_mode {
            TimePickerDisplayMode::Picker => TimePickerDisplayMode::Input,
            TimePickerDisplayMode::Input => TimePickerDisplayMode::Picker,
        };
    }

    /// Updates the period when in 12-hour mode.
    pub fn set_period(&mut self, period: DayPeriod) {
        if self.is_24_hour {
            return;
        }
        let is_pm = self.hour >= 12;
        match (period, is_pm) {
            (DayPeriod::Am, true) => self.hour = self.hour.saturating_sub(12),
            (DayPeriod::Pm, false) => self.hour = (self.hour + 12).min(23),
            _ => {}
        }
    }

    /// Increments the hour by the given step, wrapping around.
    pub fn increment_hour(&mut self, step: u8) {
        let step = normalize_step(step, 23);
        self.hour = ((self.hour as u16 + step as u16) % 24) as u8;
    }

    /// Decrements the hour by the given step, wrapping around.
    pub fn decrement_hour(&mut self, step: u8) {
        let step = normalize_step(step, 23) as i16;
        let value = (self.hour as i16 - step).rem_euclid(24);
        self.hour = value as u8;
    }

    /// Increments the minute by the given step, wrapping around.
    pub fn increment_minute(&mut self, step: u8) {
        let step = normalize_step(step, 59);
        self.minute = ((self.minute as u16 + step as u16) % 60) as u8;
    }

    /// Decrements the minute by the given step, wrapping around.
    pub fn decrement_minute(&mut self, step: u8) {
        let step = normalize_step(step, 59) as i16;
        let value = (self.minute as i16 - step).rem_euclid(60);
        self.minute = value as u8;
    }

    fn snapshot(&self) -> TimePickerSnapshot {
        TimePickerSnapshot {
            hour: self.hour,
            minute: self.minute,
            is_24_hour: self.is_24_hour,
            display_mode: self.display_mode,
        }
    }
}

impl Default for TimePickerState {
    fn default() -> Self {
        let (hour, minute) = current_time_utc();
        TimePickerState::new(hour, minute, false, TimePickerDisplayMode::Picker)
    }
}

#[derive(Clone)]
struct TimePickerSnapshot {
    hour: u8,
    minute: u8,
    is_24_hour: bool,
    display_mode: TimePickerDisplayMode,
}

/// Configuration options for [`time_picker`].
///
/// Initial-state fields are applied only when `time_picker` owns the state.
#[derive(Clone, Setters)]
pub struct TimePickerArgs {
    /// Optional modifier chain applied to the time picker.
    pub modifier: Modifier,
    /// Initial hour for the internal state.
    pub initial_hour: u8,
    /// Initial minute for the internal state.
    pub initial_minute: u8,
    /// Whether the internal state uses 24-hour mode.
    pub is_24_hour: bool,
    /// Initial display mode for the internal state.
    pub display_mode: TimePickerDisplayMode,
    /// Step size for hour changes.
    pub hour_step: u8,
    /// Step size for minute changes.
    pub minute_step: u8,
}

impl Default for TimePickerArgs {
    fn default() -> Self {
        let (hour, minute) = current_time_utc();
        Self {
            modifier: Modifier::new()
                .constrain(Some(DimensionValue::WRAP), Some(DimensionValue::WRAP)),
            initial_hour: hour,
            initial_minute: minute,
            is_24_hour: false,
            display_mode: TimePickerDisplayMode::Picker,
            hour_step: 1,
            minute_step: 1,
        }
    }
}

/// Configuration for [`time_picker_dialog`].
#[derive(Setters)]
pub struct TimePickerDialogArgs {
    /// State handle used by the embedded time picker.
    #[setters(skip)]
    pub state: State<TimePickerState>,
    /// Optional override for the dialog title.
    #[setters(strip_option, into)]
    pub title: Option<String>,
    /// Optional confirm button content.
    #[setters(skip)]
    pub confirm_button: Option<Arc<dyn Fn() + Send + Sync>>,
    /// Optional dismiss button content.
    #[setters(skip)]
    pub dismiss_button: Option<Arc<dyn Fn() + Send + Sync>>,
    /// Whether the display mode toggle is shown.
    pub show_mode_toggle: bool,
    /// Picker configuration forwarded to [`time_picker_with_state`].
    pub picker_args: TimePickerArgs,
}

impl TimePickerDialogArgs {
    /// Creates dialog args with the required time picker state.
    pub fn new(state: State<TimePickerState>) -> Self {
        Self {
            state,
            title: None,
            confirm_button: None,
            dismiss_button: None,
            show_mode_toggle: false,
            picker_args: TimePickerArgs::default(),
        }
    }

    /// Sets the confirm button content.
    pub fn confirm_button<F>(mut self, f: F) -> Self
    where
        F: Fn() + Send + Sync + 'static,
    {
        self.confirm_button = Some(Arc::new(f));
        self
    }

    /// Sets the confirm button content using a shared callback.
    pub fn confirm_button_shared(mut self, f: Arc<dyn Fn() + Send + Sync>) -> Self {
        self.confirm_button = Some(f);
        self
    }

    /// Sets the dismiss button content.
    pub fn dismiss_button<F>(mut self, f: F) -> Self
    where
        F: Fn() + Send + Sync + 'static,
    {
        self.dismiss_button = Some(Arc::new(f));
        self
    }

    /// Sets the dismiss button content using a shared callback.
    pub fn dismiss_button_shared(mut self, f: Arc<dyn Fn() + Send + Sync>) -> Self {
        self.dismiss_button = Some(f);
        self
    }
}

/// # time_picker
///
/// Render a time picker for selecting an hour and minute value.
///
/// ## Usage
///
/// Use when users need to choose a time for reminders or scheduling.
///
/// ## Parameters
///
/// - `args` — configuration for the picker layout and internal state defaults;
///   see [`TimePickerArgs`].
///
/// ## Examples
///
/// ```
/// # use tessera_ui::tessera;
/// # #[tessera]
/// # fn component() {
/// use tessera_components::time_picker::{TimePickerArgs, TimePickerState, time_picker};
/// # use tessera_components::theme::{MaterialTheme, material_theme};
///
/// # material_theme(
/// #     || MaterialTheme::default(),
/// #     || {
/// time_picker(TimePickerArgs::default());
///
/// let state = TimePickerState::default();
/// assert!(state.hour() <= 23);
/// #     },
/// # );
/// # }
/// # component();
/// ```
#[tessera]
pub fn time_picker(args: impl Into<TimePickerArgs>) {
    let args: TimePickerArgs = args.into();
    let initial_hour = args.initial_hour;
    let initial_minute = args.initial_minute;
    let is_24_hour = args.is_24_hour;
    let display_mode = args.display_mode;

    let state =
        remember(|| TimePickerState::new(initial_hour, initial_minute, is_24_hour, display_mode));
    time_picker_with_state(args, state);
}

/// # time_picker_with_state
///
/// Render a time picker using an external state handle.
///
/// ## Usage
///
/// Use when you need to observe or control the selected time externally.
///
/// ## Parameters
///
/// - `args` — configuration for the picker layout; see [`TimePickerArgs`].
/// - `state` — a [`TimePickerState`] storing the selected time.
///
/// ## Examples
///
/// ```
/// # use tessera_ui::tessera;
/// # #[tessera]
/// # fn component() {
/// use tessera_ui::remember;
/// # use tessera_components::theme::{MaterialTheme, material_theme};
/// use tessera_components::time_picker::{
///     TimePickerArgs, TimePickerState, time_picker_with_state,
/// };
///
/// # material_theme(
/// #     || MaterialTheme::default(),
/// #     || {
/// let state = remember(TimePickerState::default);
/// time_picker_with_state(TimePickerArgs::default(), state);
///
/// state.with_mut(|s| {
///     s.set_hour(9);
///     s.set_minute(30);
///     assert_eq!(s.minute(), 30);
/// });
/// #     },
/// # );
/// # }
/// # component();
/// ```
#[tessera]
pub fn time_picker_with_state(args: impl Into<TimePickerArgs>, state: State<TimePickerState>) {
    let args: TimePickerArgs = args.into();
    let snapshot = state.with(|s| s.snapshot());
    let theme = use_context::<MaterialTheme>()
        .expect("MaterialTheme must be provided")
        .get();
    let scheme = theme.color_scheme;
    let typography = theme.typography;

    let modifier = args.modifier;
    let hour_step = normalize_step(args.hour_step, 23);
    let minute_step = normalize_step(args.minute_step, 59);

    let hour_display = format_two_digit(hour_for_display(snapshot.hour, snapshot.is_24_hour));
    let minute_display = format_two_digit(snapshot.minute);
    let show_labels = snapshot.display_mode == TimePickerDisplayMode::Input;

    column(ColumnArgs::default().modifier(modifier), move |scope| {
        scope.child(move || {
            let hour_display = hour_display.clone();
            let minute_display = minute_display.clone();
            row(
                RowArgs::default()
                    .main_axis_alignment(MainAxisAlignment::Center)
                    .cross_axis_alignment(CrossAxisAlignment::Center),
                move |row_scope| {
                    let hour_display = hour_display.clone();
                    row_scope.child(move || {
                        time_stepper_column(
                            "Hour",
                            hour_display,
                            show_labels,
                            move || {
                                state.with_mut(|s| s.increment_hour(hour_step));
                            },
                            move || {
                                state.with_mut(|s| s.decrement_hour(hour_step));
                            },
                        );
                    });

                    row_scope.child(|| spacer(Modifier::new().width(Dp(6.0))));
                    row_scope.child(move || {
                        text(
                            TextArgs::default()
                                .text(":")
                                .size(typography.headline_small.font_size)
                                .color(scheme.on_surface_variant),
                        );
                    });
                    row_scope.child(|| spacer(Modifier::new().width(Dp(6.0))));

                    row_scope.child(move || {
                        let minute_display = minute_display.clone();
                        time_stepper_column(
                            "Minute",
                            minute_display,
                            show_labels,
                            move || {
                                state.with_mut(|s| s.increment_minute(minute_step));
                            },
                            move || {
                                state.with_mut(|s| s.decrement_minute(minute_step));
                            },
                        );
                    });
                },
            );
        });

        if !snapshot.is_24_hour {
            scope.child(|| spacer(Modifier::new().height(TIME_ROW_GAP)));
            let is_pm = snapshot.hour >= 12;
            scope.child(move || {
                period_toggle(is_pm, state);
            });
        }
    });
}

/// # time_picker_dialog
///
/// Render a time picker dialog body with optional action buttons.
///
/// ## Usage
///
/// Use inside `dialog_provider` when presenting a modal time selection flow.
///
/// ## Parameters
///
/// - `args` — dialog layout and action configuration; see
///   [`TimePickerDialogArgs`].
///
/// ## Examples
///
/// ```
/// # use tessera_ui::tessera;
/// # #[tessera]
/// # fn component() {
/// use tessera_ui::remember;
/// # use tessera_components::theme::{MaterialTheme, material_theme};
/// use tessera_components::time_picker::{
///     TimePickerDialogArgs, TimePickerState, time_picker_dialog,
/// };
///
/// # material_theme(
/// #     || MaterialTheme::default(),
/// #     || {
/// let state = remember(TimePickerState::default);
/// time_picker_dialog(TimePickerDialogArgs::new(state));
/// #     },
/// # );
/// # }
/// # component();
/// ```
#[tessera]
pub fn time_picker_dialog(args: impl Into<TimePickerDialogArgs>) {
    let args: TimePickerDialogArgs = args.into();
    let scheme = use_context::<MaterialTheme>()
        .expect("MaterialTheme must be provided")
        .get()
        .color_scheme;
    let title = args.title;
    let picker_args = args.picker_args;
    let state = args.state;
    let confirm_button = args.confirm_button;
    let dismiss_button = args.dismiss_button;
    let show_mode_toggle = args.show_mode_toggle;
    let has_confirm = confirm_button.is_some();
    let has_dismiss = dismiss_button.is_some();

    column(
        ColumnArgs::default().modifier(Modifier::new().constrain(
            Some(DimensionValue::Wrap {
                min: Some(Dp(280.0).into()),
                max: Some(Dp(520.0).into()),
            }),
            Some(DimensionValue::WRAP),
        )),
        move |scope| {
            scope.child(move || {
                row(
                    RowArgs::default()
                        .modifier(Modifier::new().fill_max_width())
                        .main_axis_alignment(MainAxisAlignment::SpaceBetween)
                        .cross_axis_alignment(CrossAxisAlignment::Center),
                    move |row_scope| {
                        row_scope.child(move || {
                            let title_text = title.as_deref().unwrap_or("Select time");
                            text(
                                TextArgs::default()
                                    .text(title_text)
                                    .size(
                                        use_context::<MaterialTheme>()
                                            .expect("MaterialTheme must be provided")
                                            .get()
                                            .typography
                                            .title_medium
                                            .font_size,
                                    )
                                    .color(scheme.on_surface),
                            );
                        });
                        if show_mode_toggle {
                            row_scope.child(move || {
                                time_display_mode_toggle(state);
                            });
                        }
                    },
                );
            });

            scope.child(|| spacer(Modifier::new().height(Dp(12.0))));

            scope.child(move || {
                time_picker_with_state(picker_args, state);
            });

            if has_confirm || has_dismiss {
                scope.child(|| spacer(Modifier::new().height(Dp(16.0))));
                let action_color = scheme.primary;
                scope.child(move || {
                    provide_context(
                        || ContentColor {
                            current: action_color,
                        },
                        || {
                            row(
                                RowArgs::default()
                                    .modifier(Modifier::new().fill_max_width())
                                    .main_axis_alignment(MainAxisAlignment::End)
                                    .cross_axis_alignment(CrossAxisAlignment::Center),
                                move |row_scope| {
                                    if let Some(dismiss) = dismiss_button {
                                        row_scope.child(move || dismiss());
                                    }
                                    if has_confirm && has_dismiss {
                                        row_scope.child(|| spacer(Modifier::new().width(Dp(8.0))));
                                    }
                                    if let Some(confirm) = confirm_button {
                                        row_scope.child(move || confirm());
                                    }
                                },
                            );
                        },
                    );
                });
            }
        },
    );
}

fn time_stepper_column(
    label: &'static str,
    value: String,
    show_label: bool,
    on_increment: impl Fn() + Send + Sync + 'static,
    on_decrement: impl Fn() + Send + Sync + 'static,
) {
    let theme = use_context::<MaterialTheme>()
        .expect("MaterialTheme must be provided")
        .get();
    let scheme = theme.color_scheme;
    let typography = theme.typography;

    column(
        ColumnArgs::default().cross_axis_alignment(CrossAxisAlignment::Center),
        move |scope| {
            scope.child(move || {
                step_button("+", on_increment);
            });
            scope.child(|| spacer(Modifier::new().height(Dp(6.0))));
            scope.child(move || {
                time_value_cell(value);
            });
            scope.child(|| spacer(Modifier::new().height(Dp(6.0))));
            scope.child(move || {
                step_button("-", on_decrement);
            });
            if show_label {
                scope.child(|| spacer(Modifier::new().height(Dp(6.0))));
                scope.child(move || {
                    text(
                        TextArgs::default()
                            .text(label)
                            .size(typography.label_small.font_size)
                            .color(scheme.on_surface_variant),
                    );
                });
            }
        },
    );
}

fn time_value_cell(value: String) {
    let scheme = use_context::<MaterialTheme>()
        .expect("MaterialTheme must be provided")
        .get()
        .color_scheme;
    surface(
        SurfaceArgs::default()
            .modifier(
                Modifier::new()
                    .width(TIME_CELL_WIDTH)
                    .height(TIME_CELL_HEIGHT),
            )
            .style(SurfaceStyle::Filled {
                color: scheme.surface_container_high,
            })
            .shape(Shape::rounded_rectangle(TIME_CELL_RADIUS))
            .content_alignment(Alignment::Center),
        move || {
            text(
                TextArgs::default()
                    .text(value)
                    .size(
                        use_context::<MaterialTheme>()
                            .expect("MaterialTheme must be provided")
                            .get()
                            .typography
                            .headline_small
                            .font_size,
                    )
                    .color(scheme.on_surface),
            );
        },
    );
}

fn step_button(label: &'static str, on_click: impl Fn() + Send + Sync + 'static) {
    let scheme = use_context::<MaterialTheme>()
        .expect("MaterialTheme must be provided")
        .get()
        .color_scheme;
    surface(
        SurfaceArgs::default()
            .modifier(Modifier::new().size(TIME_STEP_BUTTON_SIZE, TIME_STEP_BUTTON_SIZE))
            .style(SurfaceStyle::Filled {
                color: scheme.surface_container_low,
            })
            .shape(Shape::capsule())
            .content_alignment(Alignment::Center)
            .on_click(on_click),
        move || {
            text(
                TextArgs::default()
                    .text(label)
                    .size(
                        use_context::<MaterialTheme>()
                            .expect("MaterialTheme must be provided")
                            .get()
                            .typography
                            .body_medium
                            .font_size,
                    )
                    .color(scheme.on_surface),
            );
        },
    );
}

fn period_toggle(is_pm: bool, state: State<TimePickerState>) {
    row(
        RowArgs::default()
            .main_axis_alignment(MainAxisAlignment::Center)
            .cross_axis_alignment(CrossAxisAlignment::Center),
        move |scope| {
            scope.child(move || {
                period_button("AM", !is_pm, DayPeriod::Am, state);
            });
            scope.child(|| spacer(Modifier::new().width(Dp(8.0))));
            scope.child(move || {
                period_button("PM", is_pm, DayPeriod::Pm, state);
            });
        },
    );
}

fn period_button(
    label: &'static str,
    selected: bool,
    period: DayPeriod,
    state: State<TimePickerState>,
) {
    let scheme = use_context::<MaterialTheme>()
        .expect("MaterialTheme must be provided")
        .get()
        .color_scheme;
    let text_color = if selected {
        scheme.on_primary
    } else {
        scheme.on_surface
    };
    let style = if selected {
        SurfaceStyle::Filled {
            color: scheme.primary,
        }
    } else {
        SurfaceStyle::Filled {
            color: scheme.surface_container_low,
        }
    };
    surface(
        SurfaceArgs::default()
            .modifier(
                Modifier::new()
                    .width(PERIOD_BUTTON_WIDTH)
                    .height(PERIOD_BUTTON_HEIGHT),
            )
            .style(style)
            .shape(Shape::capsule())
            .content_alignment(Alignment::Center)
            .on_click(move || {
                state.with_mut(|s| s.set_period(period));
            }),
        move || {
            text(
                TextArgs::default()
                    .text(label)
                    .size(
                        use_context::<MaterialTheme>()
                            .expect("MaterialTheme must be provided")
                            .get()
                            .typography
                            .label_medium
                            .font_size,
                    )
                    .color(text_color),
            );
        },
    );
}

fn time_display_mode_toggle(state: State<TimePickerState>) {
    let scheme = use_context::<MaterialTheme>()
        .expect("MaterialTheme must be provided")
        .get()
        .color_scheme;
    let label = state.with(|s| match s.display_mode() {
        TimePickerDisplayMode::Picker => "Input",
        TimePickerDisplayMode::Input => "Picker",
    });
    surface(
        SurfaceArgs::default()
            .modifier(Modifier::new().padding_all(Dp(4.0)))
            .style(SurfaceStyle::Filled {
                color: scheme.surface_container_high,
            })
            .shape(Shape::capsule())
            .content_alignment(Alignment::Center)
            .on_click(move || {
                state.with_mut(|s| s.toggle_display_mode());
            }),
        move || {
            text(
                TextArgs::default()
                    .text(label)
                    .size(
                        use_context::<MaterialTheme>()
                            .expect("MaterialTheme must be provided")
                            .get()
                            .typography
                            .label_small
                            .font_size,
                    )
                    .color(scheme.primary),
            );
        },
    );
}

fn format_two_digit(value: u8) -> String {
    format!("{value:02}")
}

fn hour_for_display(hour: u8, is_24_hour: bool) -> u8 {
    if is_24_hour {
        hour
    } else {
        let hour = hour % 12;
        if hour == 0 { 12 } else { hour }
    }
}

fn normalize_step(step: u8, max: u8) -> u8 {
    if step == 0 { 1 } else { step.min(max) }
}

fn clamp_hour(hour: u8) -> u8 {
    hour.min(23)
}

fn clamp_minute(minute: u8) -> u8 {
    minute.min(59)
}

fn current_time_utc() -> (u8, u8) {
    let duration = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default();
    let secs = duration.as_secs();
    let hour = ((secs / 3_600) % 24) as u8;
    let minute = ((secs / 60) % 60) as u8;
    (hour, minute)
}