Skip to main content

waft_material/
time_picker.rs

1//! Flutter counterpart: material_ui's `time_picker.dart`. Its part
2//! `generated/time_picker_defaults_m3.g.dart` is `generated/time_picker_defaults_m3.rs`.
3
4use std::any::Any;
5use std::cell::RefCell;
6use std::collections::{HashMap, HashSet};
7use std::f64::consts::PI;
8use std::fmt;
9use std::rc::Rc;
10
11use waft_animation::{
12    AnimationBehavior, AnimationController, AnimationRef, CurveTween, Drive, Tween,
13};
14use waft_embedder::{
15    Brightness, Canvas, Clip, ClipOp, Color, Locale, Offset, Paint, Path, PathBuilder, Size,
16    TargetPlatform, TextBaseline, TextEditingValue,
17};
18use waft_foundation::{App, Handle, ListenableObject, Listener, Ref, Timer, VoidCallback};
19use waft_painting::{
20    Alignment, AlignmentDirectional, AlignmentGeometry, AnyColor, AnyTextStyle, Axis, BorderRadius,
21    BorderRadiusGeometry, BorderSide, EdgeInsets, EdgeInsetsDirectional, EdgeInsetsGeometry,
22    OutlinedBorderRef, PaintingBinding, RoundedRectangleBorder, ShapeBorderRef, TextAlign,
23    TextDirection, TextOverflow, TextPainter, TextScaler, TextSpan, TextStyle, VerticalDirection,
24    draw_line, force_to_point,
25};
26use waft_rendering::{
27    AnyRenderBox, AnyRenderObject, BoxConstraints, BoxHitTestResult, BoxParentData,
28    ChildLayoutHelper, ChildLayouter, CrossAxisAlignment, CustomPainter, MainAxisAlignment,
29    MainAxisSize, PaintingContext, RenderBox, RenderBoxBase, RenderBoxData, RenderHandle,
30    RenderObject, RenderObjectData, RenderObjectWithChildData, RenderObjectWithChildMixin,
31    RenderShiftedBox,
32};
33use waft_services::{
34    HapticFeedback, LengthLimitingTextInputFormatter, TextInputAction, TextInputFormatterRef,
35    TextInputType,
36};
37use waft_widgets::{
38    Align, AspectRatio, AutovalidateMode, BuildContext, Builder, Center, Column, ConstrainedBox,
39    CustomPaint, Directionality, ExcludeSemantics, Expanded, Flexible, FocusNode, FocusNodeLeaf,
40    FocusScope, Form, FormState, GestureDetector, GlobalKey, Icon, InheritedModel,
41    InheritedModelKind, InheritedWidget, IntoWidget, LayoutBuilder, Localizations, MediaQuery,
42    Navigator, Orientation, OverflowBar, OverflowBarAlignment, Padding, RenderObjectWidget,
43    RestorableBool, RestorableBoolN, RestorableEnum, RestorableEnumN, RestorableListenable,
44    RestorableProperty, RestorableTextEditingController, RestorableValue, RestorationMixin,
45    RestorationMixinData, Row, Semantics, SingleChildRenderObjectWidget, SingleChildScrollView,
46    SingleTickerProviderStateMixin, SingleTickerProviderStateMixinData, SizedBox, Stack, State,
47    StateData, StatefulWidget, StatelessWidget, Text, TextEditingControllerLeaf,
48    UnfocusDisposition, UnmanagedRestorationScope, WidgetRef, WidgetState, WidgetStateColor,
49    WidgetStateProperty, WidgetStatePropertyRef, WidgetStates,
50};
51
52use crate::button_style::ButtonStyle;
53use crate::colors::Colors;
54use crate::constants::K_MIN_INTERACTIVE_DIMENSION;
55#[allow(deprecated)]
56use crate::curves::standard_easing;
57use crate::dialog::{Dialog, ShowDialog};
58use crate::generated::time_picker_defaults_m3::TimePickerDefaultsM3;
59use crate::icon_button::IconButton;
60use crate::icons::Icons;
61use crate::ink_well::InkWell;
62use crate::input_border::OutlineInputBorder;
63use crate::input_decorator::{InputDecoration, InputDecorationThemeData};
64use crate::material::Material;
65use crate::material_localizations::MaterialLocalizations;
66use crate::text_button::TextButton;
67use crate::text_form_field::TextFormField;
68use crate::theme::Theme;
69use crate::theme_data::{MaterialTapTargetSize, ThemeData};
70use crate::theme_data_getters::DefaultsContext;
71use crate::time::{
72    DayPeriod, HourFormat, RestorableTimeOfDay, TimeOfDay, TimeOfDayFormat, hour_format,
73};
74use crate::time_picker_theme::{TimePickerTheme, TimePickerThemeData};
75
76const K_DIALOG_SIZE_ANIMATION_DURATION: std::time::Duration = std::time::Duration::from_millis(200);
77const K_DIAL_ANIMATE_DURATION: std::time::Duration = std::time::Duration::from_millis(200);
78const K_TWO_PI: f64 = 2.0 * std::f64::consts::PI;
79const K_VIBRATE_COMMIT_DELAY: std::time::Duration = std::time::Duration::from_millis(100);
80
81const K_TIME_PICKER_HEADER_LANDSCAPE_WIDTH: f64 = 216.0;
82const K_TIME_PICKER_INNER_DIAL_OFFSET: f64 = 28.0;
83const K_TIME_PICKER_DIAL_MIN_RADIUS: f64 = 50.0;
84const K_TIME_PICKER_DIAL_PADDING: f64 = 28.0;
85
86/// Dart's `TimePickerEntryMode`: the ways a time picker dialog can be shown.
87#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
88pub enum TimePickerEntryMode {
89    /// User picks time from a clock dial. Can switch to [`Input`](Self::Input) by pressing a
90    /// button in the dialog.
91    Dial,
92
93    /// User can input the time by typing it into text fields. Can switch to
94    /// [`Dial`](Self::Dial) by pressing a button in the dialog.
95    Input,
96
97    /// User can only pick time from a clock dial. Not user-switchable.
98    DialOnly,
99
100    /// User can only input the time by typing it into text fields. Not user-switchable.
101    InputOnly,
102}
103
104/// Whether the dial-mode time picker is currently selecting the hour or the minute.
105#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
106enum HourMinuteMode {
107    Hour,
108    Minute,
109}
110
111/// Dart's `_HourDialType`.
112#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
113enum HourDialType {
114    TwentyFourHour,
115    TwentyFourHourDoubleRing,
116    TwelveHour,
117}
118
119/// Aspects of [`TimePickerModel`] that can be depended upon.
120#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
121enum TimePickerAspect {
122    Use24HourFormat,
123    UseMaterial3,
124    EntryMode,
125    HourMinuteMode,
126    OnHourMinuteModeChanged,
127    OnHourDoubleTapped,
128    OnMinuteDoubleTapped,
129    HourDialType,
130    SelectedTime,
131    OnSelectedTimeChanged,
132    Orientation,
133    Theme,
134    DefaultTheme,
135}
136
137type HourMinuteModeChanged = Rc<dyn Fn(&mut App, HourMinuteMode)>;
138type SelectedTimeChanged = Rc<dyn Fn(&mut App, TimeOfDay)>;
139type StringChanged = Rc<dyn Fn(&mut App, &str)>;
140
141/// Dart's `_TimePickerModel`.
142struct TimePickerModel {
143    entry_mode: TimePickerEntryMode,
144    hour_minute_mode: HourMinuteMode,
145    on_hour_minute_mode_changed: HourMinuteModeChanged,
146    on_hour_double_tapped: Listener,
147    on_minute_double_tapped: Listener,
148    selected_time: TimeOfDay,
149    on_selected_time_changed: SelectedTimeChanged,
150    use_24_hour_format: bool,
151    use_material3: bool,
152    hour_dial_type: HourDialType,
153    orientation: Orientation,
154    theme: TimePickerThemeData,
155    default_theme: Rc<dyn TimePickerDefaults>,
156    child: WidgetRef,
157}
158
159impl fmt::Debug for TimePickerModel {
160    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161        f.debug_struct("TimePickerModel")
162            .field("entry_mode", &self.entry_mode)
163            .field("hour_minute_mode", &self.hour_minute_mode)
164            .field("selected_time", &self.selected_time)
165            .finish_non_exhaustive()
166    }
167}
168
169impl TimePickerModel {
170    /// The erased widget: an [`InheritedModel`] has two `IntoWidget` impls, so the kind is
171    /// named here.
172    fn into_widget(self) -> WidgetRef {
173        IntoWidget::<InheritedModelKind>::into_widget(self)
174    }
175
176    fn of<R>(
177        app: &mut App,
178        context: BuildContext,
179        aspect: TimePickerAspect,
180        read: impl FnOnce(&TimePickerModel) -> R,
181    ) -> R {
182        read(
183            TimePickerModel::inherit_from(app, context, Some(aspect))
184                .expect("a time picker model above"),
185        )
186    }
187
188    fn entry_mode_of(app: &mut App, context: BuildContext) -> TimePickerEntryMode {
189        Self::of(app, context, TimePickerAspect::EntryMode, |model| {
190            model.entry_mode
191        })
192    }
193
194    fn hour_minute_mode_of(app: &mut App, context: BuildContext) -> HourMinuteMode {
195        Self::of(app, context, TimePickerAspect::HourMinuteMode, |model| {
196            model.hour_minute_mode
197        })
198    }
199
200    fn selected_time_of(app: &mut App, context: BuildContext) -> TimeOfDay {
201        Self::of(app, context, TimePickerAspect::SelectedTime, |model| {
202            model.selected_time
203        })
204    }
205
206    fn use_24_hour_format_of(app: &mut App, context: BuildContext) -> bool {
207        Self::of(app, context, TimePickerAspect::Use24HourFormat, |model| {
208            model.use_24_hour_format
209        })
210    }
211
212    fn use_material3_of(app: &mut App, context: BuildContext) -> bool {
213        Self::of(app, context, TimePickerAspect::UseMaterial3, |model| {
214            model.use_material3
215        })
216    }
217
218    fn hour_dial_type_of(app: &mut App, context: BuildContext) -> HourDialType {
219        Self::of(app, context, TimePickerAspect::HourDialType, |model| {
220            model.hour_dial_type
221        })
222    }
223
224    fn orientation_of(app: &mut App, context: BuildContext) -> Orientation {
225        Self::of(app, context, TimePickerAspect::Orientation, |model| {
226            model.orientation
227        })
228    }
229
230    fn theme_of(app: &mut App, context: BuildContext) -> TimePickerThemeData {
231        Self::of(app, context, TimePickerAspect::Theme, |model| {
232            model.theme.clone()
233        })
234    }
235
236    fn default_theme_of(app: &mut App, context: BuildContext) -> Rc<dyn TimePickerDefaults> {
237        Self::of(app, context, TimePickerAspect::DefaultTheme, |model| {
238            Rc::clone(&model.default_theme)
239        })
240    }
241
242    fn on_hour_double_tapped_of(app: &mut App, context: BuildContext) -> Listener {
243        Self::of(
244            app,
245            context,
246            TimePickerAspect::OnHourDoubleTapped,
247            |model| model.on_hour_double_tapped.clone(),
248        )
249    }
250
251    fn on_minute_double_tapped_of(app: &mut App, context: BuildContext) -> Listener {
252        Self::of(
253            app,
254            context,
255            TimePickerAspect::OnMinuteDoubleTapped,
256            |model| model.on_minute_double_tapped.clone(),
257        )
258    }
259
260    fn set_selected_time(app: &mut App, context: BuildContext, value: TimeOfDay) {
261        let callback = Self::of(
262            app,
263            context,
264            TimePickerAspect::OnSelectedTimeChanged,
265            |model| Rc::clone(&model.on_selected_time_changed),
266        );
267        callback(app, value);
268    }
269
270    fn set_hour_minute_mode(app: &mut App, context: BuildContext, value: HourMinuteMode) {
271        let callback = Self::of(
272            app,
273            context,
274            TimePickerAspect::OnHourMinuteModeChanged,
275            |model| Rc::clone(&model.on_hour_minute_mode_changed),
276        );
277        callback(app, value);
278    }
279}
280
281impl InheritedWidget for TimePickerModel {
282    fn child(&self) -> &WidgetRef {
283        &self.child
284    }
285
286    fn update_should_notify(&self, old_widget: &TimePickerModel) -> bool {
287        self.use_24_hour_format != old_widget.use_24_hour_format
288            || self.use_material3 != old_widget.use_material3
289            || self.entry_mode != old_widget.entry_mode
290            || self.hour_minute_mode != old_widget.hour_minute_mode
291            || !Rc::ptr_eq(
292                &self.on_hour_minute_mode_changed,
293                &old_widget.on_hour_minute_mode_changed,
294            )
295            || self.on_hour_double_tapped != old_widget.on_hour_double_tapped
296            || self.on_minute_double_tapped != old_widget.on_minute_double_tapped
297            || self.hour_dial_type != old_widget.hour_dial_type
298            || self.selected_time != old_widget.selected_time
299            || !Rc::ptr_eq(
300                &self.on_selected_time_changed,
301                &old_widget.on_selected_time_changed,
302            )
303            || self.orientation != old_widget.orientation
304            || self.theme != old_widget.theme
305            || !Rc::ptr_eq(&self.default_theme, &old_widget.default_theme)
306    }
307}
308
309impl InheritedModel for TimePickerModel {
310    type Aspect = TimePickerAspect;
311
312    fn update_should_notify_dependent(
313        &self,
314        old_widget: &TimePickerModel,
315        dependencies: &HashSet<TimePickerAspect>,
316    ) -> bool {
317        let changed =
318            |aspect: TimePickerAspect, changed: bool| changed && dependencies.contains(&aspect);
319        changed(
320            TimePickerAspect::Use24HourFormat,
321            self.use_24_hour_format != old_widget.use_24_hour_format,
322        ) || changed(
323            TimePickerAspect::UseMaterial3,
324            self.use_material3 != old_widget.use_material3,
325        ) || changed(
326            TimePickerAspect::EntryMode,
327            self.entry_mode != old_widget.entry_mode,
328        ) || changed(
329            TimePickerAspect::HourMinuteMode,
330            self.hour_minute_mode != old_widget.hour_minute_mode,
331        ) || changed(
332            TimePickerAspect::OnHourMinuteModeChanged,
333            !Rc::ptr_eq(
334                &self.on_hour_minute_mode_changed,
335                &old_widget.on_hour_minute_mode_changed,
336            ),
337        )
338            // Dart compares `onHourMinuteModeChanged` against the old double-tap callbacks for
339            // the next two aspects, a typo that makes them notify whenever it differs from them.
340            || changed(TimePickerAspect::OnHourDoubleTapped, true)
341            || changed(TimePickerAspect::OnMinuteDoubleTapped, true)
342            || changed(
343                TimePickerAspect::HourDialType,
344                self.hour_dial_type != old_widget.hour_dial_type,
345            )
346            || changed(
347                TimePickerAspect::SelectedTime,
348                self.selected_time != old_widget.selected_time,
349            )
350            || changed(
351                TimePickerAspect::OnSelectedTimeChanged,
352                !Rc::ptr_eq(
353                    &self.on_selected_time_changed,
354                    &old_widget.on_selected_time_changed,
355                ),
356            )
357            || changed(
358                TimePickerAspect::Orientation,
359                self.orientation != old_widget.orientation,
360            )
361            || changed(TimePickerAspect::Theme, self.theme != old_widget.theme)
362            || changed(
363                TimePickerAspect::DefaultTheme,
364                !Rc::ptr_eq(&self.default_theme, &old_widget.default_theme),
365            )
366    }
367}
368
369/// Dart's `_debugDialTimePickerEntryMode`.
370fn debug_dial_time_picker_entry_mode(app: &mut App, context: BuildContext) -> bool {
371    let entry_mode = TimePickerModel::entry_mode_of(app, context);
372    entry_mode == TimePickerEntryMode::Dial || entry_mode == TimePickerEntryMode::DialOnly
373}
374
375/// A style as a plain [`TextStyle`]: what Dart's `Text(style:)` merges when the style is a
376/// `WidgetStateTextStyle`.
377fn plain(style: &waft_painting::AnyTextStyle) -> TextStyle {
378    style.value().clone()
379}
380
381/// Dart's `_DialTimePickerHeader`.
382#[derive(Debug)]
383struct DialTimePickerHeader {
384    help_text: String,
385}
386
387impl StatelessWidget for DialTimePickerHeader {
388    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
389        debug_assert!(debug_dial_time_picker_entry_mode(app, context));
390        let localizations = <dyn MaterialLocalizations>::of(app, context);
391        let use_24_hour_format = TimePickerModel::use_24_hour_format_of(app, context);
392        let time_of_day_format = localizations.time_of_day_format(use_24_hour_format);
393
394        let default_theme = TimePickerModel::default_theme_of(app, context);
395        let orientation = TimePickerModel::orientation_of(app, context);
396        let day_period_height = if orientation == Orientation::Portrait {
397            default_theme.day_period_portrait_size(app).height()
398        } else {
399            default_theme.day_period_landscape_size(app).height()
400        };
401        let min_interactive_vertical_padding = if orientation == Orientation::Portrait {
402            (2.0 * K_MIN_INTERACTIVE_DIMENSION - day_period_height).max(0.0)
403        } else {
404            (K_MIN_INTERACTIVE_DIMENSION - day_period_height).max(0.0)
405        };
406
407        let hour_dial_type = TimePickerModel::hour_dial_type_of(app, context);
408        let theme = TimePickerModel::theme_of(app, context);
409        let help_text_style = plain(
410            &theme
411                .help_text_style
412                .clone()
413                .unwrap_or_else(|| default_theme.help_text_style(app)),
414        );
415        let hour_minute_row = || {
416            Row::new()
417                // Hour/minutes should not change positions in RTL locales.
418                .text_direction(TextDirection::Ltr)
419                .children([
420                    Expanded::new(DialHourControl).into_widget(),
421                    TimeSelectorSeparator { time_of_day_format }.into_widget(),
422                    Expanded::new(DialMinuteControl).into_widget(),
423                ])
424        };
425        let orientation_specific_header = match orientation {
426            Orientation::Portrait => Column::new()
427                .cross_axis_alignment(CrossAxisAlignment::Start)
428                .children([
429                    Padding::new(EdgeInsetsDirectional::only(
430                        0.0,
431                        0.0,
432                        0.0,
433                        (if TimePickerModel::use_material3_of(app, context) {
434                            20.0
435                        } else {
436                            24.0
437                        }) - min_interactive_vertical_padding / 2.0,
438                    ))
439                    .child(Text::new(self.help_text.clone()).style(help_text_style))
440                    .into_widget(),
441                    Row::new()
442                        .text_direction(
443                            if time_of_day_format == TimeOfDayFormat::a_space_h_colon_mm {
444                                TextDirection::Rtl
445                            } else {
446                                TextDirection::Ltr
447                            },
448                        )
449                        .spacing(12.0)
450                        .children(
451                            [Expanded::new(hour_minute_row()).into_widget()]
452                                .into_iter()
453                                .chain(
454                                    (hour_dial_type == HourDialType::TwelveHour)
455                                        .then(|| DayPeriodControl::default().into_widget()),
456                                ),
457                        )
458                        .into_widget(),
459                ])
460                .into_widget(),
461            Orientation::Landscape => SizedBox::new()
462                .width(K_TIME_PICKER_HEADER_LANDSCAPE_WIDTH)
463                .child(
464                    Stack::new().children([
465                        Text::new(self.help_text.clone())
466                            .style(help_text_style)
467                            .into_widget(),
468                        Column::new()
469                            .vertical_direction(
470                                if time_of_day_format == TimeOfDayFormat::a_space_h_colon_mm {
471                                    VerticalDirection::Up
472                                } else {
473                                    VerticalDirection::Down
474                                },
475                            )
476                            .main_axis_alignment(MainAxisAlignment::Center)
477                            .cross_axis_alignment(CrossAxisAlignment::Start)
478                            .spacing((16.0 - min_interactive_vertical_padding / 2.0).max(0.0))
479                            .children(
480                                [hour_minute_row().into_widget()].into_iter().chain(
481                                    (hour_dial_type == HourDialType::TwelveHour)
482                                        .then(|| DayPeriodControl::default().into_widget()),
483                                ),
484                            )
485                            .into_widget(),
486                    ]),
487                )
488                .into_widget(),
489        };
490
491        Semantics::new()
492            .label(localizations.format_time_of_day(
493                &TimePickerModel::selected_time_of(app, context),
494                MediaQuery::always_use_24_hour_format_of(app, context),
495            ))
496            .child(orientation_specific_header)
497            .into_widget()
498    }
499}
500
501/// Dart's `_DialTimeSelectorControl`.
502#[derive(Debug)]
503struct DialTimeSelectorControl {
504    text: String,
505    on_tap: Listener,
506    on_double_tap: Listener,
507    is_selected: bool,
508}
509
510impl StatelessWidget for DialTimeSelectorControl {
511    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
512        debug_assert!(debug_dial_time_picker_entry_mode(app, context));
513        let time_picker_theme = TimePickerModel::theme_of(app, context);
514        let default_theme = TimePickerModel::default_theme_of(app, context);
515        let background_color = time_picker_theme
516            .hour_minute_color
517            .clone()
518            .unwrap_or_else(|| default_theme.hour_minute_color(app));
519        let shape = time_picker_theme
520            .hour_minute_shape
521            .clone()
522            .unwrap_or_else(|| default_theme.hour_minute_shape(app));
523
524        let mut states = WidgetStates::new();
525        if self.is_selected {
526            states.insert(WidgetState::Selected);
527        }
528        let effective_text_color = <dyn WidgetStateProperty<Color>>::resolve_as(
529            &time_picker_theme
530                .hour_minute_text_color
531                .clone()
532                .unwrap_or_else(|| default_theme.hour_minute_text_color(app)),
533            &states,
534        );
535        let hour_minute_text_style = time_picker_theme
536            .hour_minute_text_style
537            .clone()
538            .unwrap_or_else(|| default_theme.hour_minute_text_style(app));
539        let effective_style =
540            <dyn WidgetStateProperty<TextStyle>>::resolve_as(&hour_minute_text_style, &states)
541                .value()
542                .copy_with()
543                .color(effective_text_color.color());
544
545        let mut ink_well = InkWell::new().on_tap(self.on_tap.clone());
546        if self.is_selected {
547            ink_well = ink_well.on_double_tap(self.on_double_tap.clone());
548        }
549        let background_color =
550            <dyn WidgetStateProperty<Color>>::resolve_as(&background_color, &states);
551        SizedBox::new()
552            .height(default_theme.hour_minute_size(app).height())
553            .child(
554                Material::new()
555                    .color(background_color.color())
556                    .clip_behavior(Clip::AntiAlias)
557                    .shape(shape)
558                    .child(
559                        ink_well.child(
560                            Center::new().child(
561                                Text::new(self.text.clone())
562                                    .style(effective_style)
563                                    .text_scaler(TextScaler::NO_SCALING),
564                            ),
565                        ),
566                    ),
567            )
568            .into_widget()
569    }
570}
571
572/// Dart's `_DialHourControl`.
573#[derive(Debug)]
574struct DialHourControl;
575
576impl StatelessWidget for DialHourControl {
577    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
578        debug_assert!(debug_dial_time_picker_entry_mode(app, context));
579        waft_widgets::debug_check_has_media_query(app, context);
580        let always_use_24_hour_format = MediaQuery::always_use_24_hour_format_of(app, context);
581        let selected_time = TimePickerModel::selected_time_of(app, context);
582        let localizations = <dyn MaterialLocalizations>::of(app, context);
583        let formatted_hour = localizations.format_hour(
584            &selected_time,
585            TimePickerModel::use_24_hour_format_of(app, context),
586        );
587
588        let hour_dial_type = TimePickerModel::hour_dial_type_of(app, context);
589        let hours_from_selected = |hours_to_add: i32| -> TimeOfDay {
590            match hour_dial_type {
591                HourDialType::TwentyFourHour | HourDialType::TwentyFourHourDoubleRing => {
592                    let selected_hour = selected_time.hour;
593                    selected_time.replacing(
594                        Some((selected_hour + hours_to_add).rem_euclid(TimeOfDay::HOURS_PER_DAY)),
595                        None,
596                    )
597                }
598                HourDialType::TwelveHour => {
599                    // Cycle 1 through 12 without changing day period.
600                    let period_offset = selected_time.period_offset();
601                    let hours = selected_time.hour_of_period();
602                    selected_time.replacing(
603                        Some(
604                            period_offset
605                                + (hours + hours_to_add).rem_euclid(TimeOfDay::HOURS_PER_PERIOD),
606                        ),
607                        None,
608                    )
609                }
610            }
611        };
612
613        let next_hour = hours_from_selected(1);
614        let formatted_next_hour = localizations.format_hour(&next_hour, always_use_24_hour_format);
615        let previous_hour = hours_from_selected(-1);
616        let formatted_previous_hour =
617            localizations.format_hour(&previous_hour, always_use_24_hour_format);
618
619        Semantics::new()
620            .value(format!(
621                "{} {}",
622                localizations.time_picker_hour_mode_announcement(),
623                formatted_hour
624            ))
625            .exclude_semantics(true)
626            .increased_value(formatted_next_hour)
627            .on_increase(std::rc::Rc::new(move |app: &mut App| {
628                TimePickerModel::set_selected_time(app, context, next_hour);
629            }))
630            .decreased_value(formatted_previous_hour)
631            .on_decrease(std::rc::Rc::new(move |app: &mut App| {
632                TimePickerModel::set_selected_time(app, context, previous_hour);
633            }))
634            .child(DialTimeSelectorControl {
635                is_selected: TimePickerModel::hour_minute_mode_of(app, context)
636                    == HourMinuteMode::Hour,
637                text: formatted_hour,
638                on_tap: Listener::new(move |app| {
639                    TimePickerModel::set_hour_minute_mode(app, context, HourMinuteMode::Hour);
640                }),
641                on_double_tap: TimePickerModel::on_hour_double_tapped_of(app, context),
642            })
643            .into_widget()
644    }
645}
646
647/// Dart's `_TimeSelectorSeparator`.
648#[derive(Debug)]
649struct TimeSelectorSeparator {
650    time_of_day_format: TimeOfDayFormat,
651}
652
653impl TimeSelectorSeparator {
654    fn time_selector_separator_value(time_of_day_format: TimeOfDayFormat) -> &'static str {
655        match time_of_day_format {
656            TimeOfDayFormat::h_colon_mm_space_a
657            | TimeOfDayFormat::a_space_h_colon_mm
658            | TimeOfDayFormat::H_colon_mm
659            | TimeOfDayFormat::HH_colon_mm => ":",
660            TimeOfDayFormat::HH_dot_mm => ".",
661            TimeOfDayFormat::FrenchCanadian => "h",
662        }
663    }
664}
665
666impl StatelessWidget for TimeSelectorSeparator {
667    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
668        let theme = Theme::of(app, context);
669        let time_picker_theme = TimePickerTheme::of(app, context);
670        let default_theme: std::rc::Rc<dyn TimePickerDefaults> = if theme.use_material3 {
671            std::rc::Rc::new(TimePickerDefaultsM3::new(
672                context,
673                TimePickerEntryMode::Dial,
674            ))
675        } else {
676            std::rc::Rc::new(TimePickerDefaultsM2::new(context))
677        };
678        let states = WidgetStates::new();
679
680        let effective_text_color = <dyn WidgetStateProperty<Color>>::resolve_as(
681            &time_picker_theme
682                .time_selector_separator_color
683                .as_ref()
684                .and_then(|color| color.resolve(&states))
685                .map(AnyColor::from)
686                .or_else(|| time_picker_theme.hour_minute_text_color.clone())
687                .or_else(|| {
688                    default_theme
689                        .time_selector_separator_color(app)
690                        .and_then(|color| color.resolve(&states))
691                        .map(AnyColor::from)
692                })
693                .unwrap_or_else(|| default_theme.hour_minute_text_color(app)),
694            &states,
695        );
696        let separator_text_style = time_picker_theme
697            .time_selector_separator_text_style
698            .as_ref()
699            .and_then(|style| style.resolve(&states))
700            .map(waft_painting::AnyTextStyle::from)
701            .or_else(|| time_picker_theme.hour_minute_text_style.clone())
702            .or_else(|| {
703                default_theme
704                    .time_selector_separator_text_style(app)
705                    .and_then(|style| style.resolve(&states))
706                    .map(waft_painting::AnyTextStyle::from)
707            })
708            .unwrap_or_else(|| default_theme.hour_minute_text_style(app));
709        let effective_style =
710            <dyn WidgetStateProperty<TextStyle>>::resolve_as(&separator_text_style, &states)
711                .value()
712                .copy_with()
713                .color(effective_text_color.color())
714                .height(1.0);
715
716        let height = match TimePickerModel::entry_mode_of(app, context) {
717            TimePickerEntryMode::Dial | TimePickerEntryMode::DialOnly => {
718                default_theme.hour_minute_size(app).height()
719            }
720            TimePickerEntryMode::Input | TimePickerEntryMode::InputOnly => {
721                default_theme.hour_minute_input_size(app).height()
722            }
723        };
724
725        ExcludeSemantics::new()
726            .child(
727                SizedBox::new()
728                    .width(
729                        if self.time_of_day_format == TimeOfDayFormat::FrenchCanadian {
730                            36.0
731                        } else {
732                            24.0
733                        },
734                    )
735                    .height(height)
736                    .child(
737                        Center::new().child(
738                            Text::new(Self::time_selector_separator_value(self.time_of_day_format))
739                                .style(effective_style)
740                                .text_scaler(TextScaler::NO_SCALING),
741                        ),
742                    ),
743            )
744            .into_widget()
745    }
746}
747
748/// Dart's `_DialMinuteControl`.
749#[derive(Debug)]
750struct DialMinuteControl;
751
752impl StatelessWidget for DialMinuteControl {
753    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
754        debug_assert!(debug_dial_time_picker_entry_mode(app, context));
755        let localizations = <dyn MaterialLocalizations>::of(app, context);
756        let selected_time = TimePickerModel::selected_time_of(app, context);
757        let formatted_minute = localizations.format_minute(&selected_time);
758        let next_minute = selected_time.replacing(
759            None,
760            Some((selected_time.minute + 1).rem_euclid(TimeOfDay::MINUTES_PER_HOUR)),
761        );
762        let formatted_next_minute = localizations.format_minute(&next_minute);
763        let previous_minute = selected_time.replacing(
764            None,
765            Some((selected_time.minute - 1).rem_euclid(TimeOfDay::MINUTES_PER_HOUR)),
766        );
767        let formatted_previous_minute = localizations.format_minute(&previous_minute);
768
769        Semantics::new()
770            .exclude_semantics(true)
771            .value(format!(
772                "{} {}",
773                localizations.time_picker_minute_mode_announcement(),
774                formatted_minute
775            ))
776            .increased_value(formatted_next_minute)
777            .on_increase(std::rc::Rc::new(move |app: &mut App| {
778                TimePickerModel::set_selected_time(app, context, next_minute);
779            }))
780            .decreased_value(formatted_previous_minute)
781            .on_decrease(std::rc::Rc::new(move |app: &mut App| {
782                TimePickerModel::set_selected_time(app, context, previous_minute);
783            }))
784            .child(DialTimeSelectorControl {
785                is_selected: TimePickerModel::hour_minute_mode_of(app, context)
786                    == HourMinuteMode::Minute,
787                text: formatted_minute,
788                on_tap: Listener::new(move |app| {
789                    TimePickerModel::set_hour_minute_mode(app, context, HourMinuteMode::Minute);
790                }),
791                on_double_tap: TimePickerModel::on_minute_double_tapped_of(app, context),
792            })
793            .into_widget()
794    }
795}
796
797/// Dart's `_DayPeriodControl`.
798#[derive(Default)]
799struct DayPeriodControl {
800    /// Dart's `onPeriodChanged`.
801    on_period_changed: Option<SelectedTimeChanged>,
802}
803
804impl std::fmt::Debug for DayPeriodControl {
805    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
806        f.debug_struct("DayPeriodControl").finish_non_exhaustive()
807    }
808}
809
810impl DayPeriodControl {
811    fn toggle_period(
812        on_period_changed: Option<&SelectedTimeChanged>,
813        app: &mut App,
814        context: BuildContext,
815    ) {
816        let selected_time = TimePickerModel::selected_time_of(app, context);
817        let new_hour =
818            (selected_time.hour + TimeOfDay::HOURS_PER_PERIOD).rem_euclid(TimeOfDay::HOURS_PER_DAY);
819        let new_time = selected_time.replacing(Some(new_hour), None);
820        if let Some(on_period_changed) = on_period_changed {
821            on_period_changed(app, new_time);
822        } else {
823            TimePickerModel::set_selected_time(app, context, new_time);
824        }
825    }
826
827    fn set_am(
828        on_period_changed: Option<&SelectedTimeChanged>,
829        app: &mut App,
830        context: BuildContext,
831    ) {
832        let selected_time = TimePickerModel::selected_time_of(app, context);
833        if selected_time.period() == DayPeriod::Am {
834            return;
835        }
836        Self::toggle_period(on_period_changed, app, context);
837    }
838
839    fn set_pm(
840        on_period_changed: Option<&SelectedTimeChanged>,
841        app: &mut App,
842        context: BuildContext,
843    ) {
844        let selected_time = TimePickerModel::selected_time_of(app, context);
845        if selected_time.period() == DayPeriod::Pm {
846            return;
847        }
848        Self::toggle_period(on_period_changed, app, context);
849    }
850}
851
852impl StatelessWidget for DayPeriodControl {
853    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
854        let material_localizations = <dyn MaterialLocalizations>::of(app, context);
855        let time_picker_theme = TimePickerModel::theme_of(app, context);
856        let default_theme = TimePickerModel::default_theme_of(app, context);
857        let selected_time = TimePickerModel::selected_time_of(app, context);
858        let am_selected = selected_time.period() == DayPeriod::Am;
859        let pm_selected = !am_selected;
860        let resolved_side = time_picker_theme
861            .day_period_border_side
862            .unwrap_or_else(|| default_theme.day_period_border_side(app));
863        let resolved_shape: OutlinedBorderRef = time_picker_theme
864            .day_period_shape
865            .clone()
866            .unwrap_or_else(|| default_theme.day_period_shape(app))
867            .copy_with(Some(resolved_side));
868
869        let (day_period_size, orientation) = match TimePickerModel::entry_mode_of(app, context) {
870            TimePickerEntryMode::Dial | TimePickerEntryMode::DialOnly => {
871                let orientation = TimePickerModel::orientation_of(app, context);
872                (
873                    match orientation {
874                        Orientation::Portrait => default_theme.day_period_portrait_size(app),
875                        Orientation::Landscape => default_theme.day_period_landscape_size(app),
876                    },
877                    orientation,
878                )
879            }
880            TimePickerEntryMode::Input | TimePickerEntryMode::InputOnly => (
881                default_theme.day_period_input_size(app),
882                Orientation::Portrait,
883            ),
884        };
885
886        let mut am_shape = resolved_shape.clone();
887        let mut pm_shape = resolved_shape.clone();
888        let rounded_border: Option<(RoundedRectangleBorder, BorderRadius)> = resolved_shape
889            .as_any()
890            .downcast_ref::<RoundedRectangleBorder>()
891            .and_then(|border| match &border.border_radius {
892                BorderRadiusGeometry::BorderRadius(radius) => Some((*border, *radius)),
893                _ => None,
894            });
895        let with_radius = |border: &RoundedRectangleBorder, radius: BorderRadius| {
896            OutlinedBorderRef::new(
897                border.copy_with(None, Some(BorderRadiusGeometry::BorderRadius(radius))),
898            )
899        };
900
901        // In order to respect Material touch target guidelines, the Semantics for
902        // AM and PM buttons needs to expand out of the bounds of the buttons
903        // (Similarly to Google Agenda).
904        // To achieve this, instead of using a parent Material which clips
905        // the Semantics, each button should manage its own shape.
906        // The logic below "cuts" the given period selector shape in two parts,
907        // one for the AM button, the other for the PM button. Each sub-shape
908        // is obtained by removing some rounded corners from the original shape.
909        let on_period_changed = self.on_period_changed.clone();
910        let on_am = {
911            let on_period_changed = on_period_changed.clone();
912            Listener::new(move |app| Self::set_am(on_period_changed.as_ref(), app, context))
913        };
914        let on_pm =
915            Listener::new(move |app| Self::set_pm(on_period_changed.as_ref(), app, context));
916
917        match orientation {
918            Orientation::Portrait => {
919                if let Some((border, border_radius)) = rounded_border {
920                    am_shape = with_radius(
921                        &border,
922                        BorderRadius::only(
923                            border_radius.top_left,
924                            border_radius.top_right,
925                            waft_embedder::Radius::ZERO,
926                            waft_embedder::Radius::ZERO,
927                        ),
928                    );
929                    pm_shape = with_radius(
930                        &border,
931                        BorderRadius::only(
932                            waft_embedder::Radius::ZERO,
933                            waft_embedder::Radius::ZERO,
934                            border_radius.bottom_left,
935                            border_radius.bottom_right,
936                        ),
937                    );
938                }
939
940                let min_interactive_size = Size::new(
941                    day_period_size.width(),
942                    day_period_size
943                        .height()
944                        .max(2.0 * K_MIN_INTERACTIVE_DIMENSION),
945                );
946
947                let am_button = AmPmButton {
948                    selected: am_selected,
949                    on_pressed: on_am,
950                    label: material_localizations.ante_meridiem_abbreviation(),
951                    padding: EdgeInsets::only(
952                        0.0,
953                        (min_interactive_size.height() - day_period_size.height()) / 2.0,
954                        0.0,
955                        0.0,
956                    ),
957                    shape: am_shape,
958                };
959                let pm_button = AmPmButton {
960                    selected: pm_selected,
961                    on_pressed: on_pm,
962                    label: material_localizations.post_meridiem_abbreviation(),
963                    padding: EdgeInsets::only(
964                        0.0,
965                        0.0,
966                        0.0,
967                        (min_interactive_size.height() - day_period_size.height()) / 2.0,
968                    ),
969                    shape: pm_shape,
970                };
971
972                DayPeriodInputPadding {
973                    min_size: min_interactive_size,
974                    orientation,
975                    child: Some(
976                        SizedBox::new()
977                            .width(min_interactive_size.width())
978                            .height(min_interactive_size.height())
979                            .child(Column::new().children([
980                                Expanded::new(am_button).into_widget(),
981                                Expanded::new(pm_button).into_widget(),
982                            ]))
983                            .into_widget(),
984                    ),
985                }
986                .into_widget()
987            }
988            Orientation::Landscape => {
989                if let Some((border, border_radius)) = rounded_border {
990                    am_shape = with_radius(
991                        &border,
992                        BorderRadius::only(
993                            border_radius.top_left,
994                            waft_embedder::Radius::ZERO,
995                            border_radius.bottom_left,
996                            waft_embedder::Radius::ZERO,
997                        ),
998                    );
999                    pm_shape = with_radius(
1000                        &border,
1001                        BorderRadius::only(
1002                            waft_embedder::Radius::ZERO,
1003                            border_radius.top_right,
1004                            waft_embedder::Radius::ZERO,
1005                            border_radius.bottom_right,
1006                        ),
1007                    );
1008                }
1009
1010                let min_interactive_size = Size::new(
1011                    day_period_size.width(),
1012                    day_period_size.height().max(K_MIN_INTERACTIVE_DIMENSION),
1013                );
1014                let vertical = (min_interactive_size.height() - day_period_size.height()) / 2.0;
1015
1016                let am_button = AmPmButton {
1017                    selected: am_selected,
1018                    on_pressed: on_am,
1019                    label: material_localizations.ante_meridiem_abbreviation(),
1020                    padding: EdgeInsets::symmetric(vertical, 0.0),
1021                    shape: am_shape,
1022                };
1023                let pm_button = AmPmButton {
1024                    selected: pm_selected,
1025                    on_pressed: on_pm,
1026                    label: material_localizations.post_meridiem_abbreviation(),
1027                    padding: EdgeInsets::symmetric(vertical, 0.0),
1028                    shape: pm_shape,
1029                };
1030
1031                DayPeriodInputPadding {
1032                    min_size: min_interactive_size,
1033                    orientation,
1034                    child: Some(
1035                        SizedBox::new()
1036                            .height(min_interactive_size.height())
1037                            .child(Row::new().children([
1038                                Expanded::new(am_button).into_widget(),
1039                                Expanded::new(pm_button).into_widget(),
1040                            ]))
1041                            .into_widget(),
1042                    ),
1043                }
1044                .into_widget()
1045            }
1046        }
1047    }
1048}
1049
1050/// Dart's `_AmPmButton`.
1051#[derive(Debug)]
1052struct AmPmButton {
1053    selected: bool,
1054    on_pressed: Listener,
1055    label: String,
1056    padding: EdgeInsets,
1057    shape: OutlinedBorderRef,
1058}
1059
1060impl StatelessWidget for AmPmButton {
1061    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
1062        let mut states = WidgetStates::new();
1063        if self.selected {
1064            states.insert(WidgetState::Selected);
1065        }
1066        let time_picker_theme = TimePickerModel::theme_of(app, context);
1067        let default_theme = TimePickerModel::default_theme_of(app, context);
1068        let resolved_background_color = <dyn WidgetStateProperty<Color>>::resolve_as(
1069            &time_picker_theme
1070                .day_period_color_getter()
1071                .unwrap_or_else(|| default_theme.day_period_color(app)),
1072            &states,
1073        );
1074        let resolved_text_color = <dyn WidgetStateProperty<Color>>::resolve_as(
1075            &time_picker_theme
1076                .day_period_text_color
1077                .clone()
1078                .unwrap_or_else(|| default_theme.day_period_text_color(app)),
1079            &states,
1080        );
1081        let resolved_text_style = <dyn WidgetStateProperty<TextStyle>>::resolve_as(
1082            &time_picker_theme
1083                .day_period_text_style
1084                .clone()
1085                .unwrap_or_else(|| default_theme.day_period_text_style(app)),
1086            &states,
1087        )
1088        .value()
1089        .copy_with()
1090        .color(resolved_text_color.color());
1091        let button_text_scaler = MediaQuery::text_scaler_of(app, context).clamp(0.0, 2.0);
1092
1093        let is_ios = app.platform().target_platform() == TargetPlatform::IOS;
1094        let mut semantics = Semantics::new()
1095            // Platform-specific semantics vary slightly here on iOS.
1096            .in_mutually_exclusive_group(true)
1097            .button(true);
1098        semantics = if is_ios {
1099            semantics.selected(self.selected)
1100        } else {
1101            semantics.checked(self.selected)
1102        };
1103        semantics
1104            .child(
1105                Padding::new(self.padding).child(
1106                    Material::new()
1107                        .clip_behavior(Clip::AntiAlias)
1108                        .color(resolved_background_color.color())
1109                        .shape(ShapeBorderRef::from(self.shape.clone()))
1110                        .child(
1111                            InkWell::new().on_tap(self.on_pressed.clone()).child(
1112                                Center::new().child(
1113                                    Text::new(self.label.clone())
1114                                        .style(resolved_text_style)
1115                                        .text_scaler(button_text_scaler),
1116                                ),
1117                            ),
1118                        ),
1119                ),
1120            )
1121            .into_widget()
1122    }
1123}
1124
1125/// Dart's `_DayPeriodInputPadding`.
1126#[derive(Debug)]
1127struct DayPeriodInputPadding {
1128    child: Option<WidgetRef>,
1129    min_size: Size,
1130    orientation: Orientation,
1131}
1132
1133impl RenderObjectWidget for DayPeriodInputPadding {
1134    type RenderObject = RenderInputPadding;
1135
1136    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
1137        RenderInputPadding::new(app, self.min_size, self.orientation, None).as_object()
1138    }
1139
1140    fn update_render_object(
1141        &self,
1142        app: &mut App,
1143        _context: BuildContext,
1144        render_object: RenderHandle<RenderInputPadding>,
1145    ) {
1146        render_object.set_min_size(app, self.min_size);
1147        render_object.set_orientation(app, self.orientation);
1148    }
1149}
1150
1151impl SingleChildRenderObjectWidget for DayPeriodInputPadding {
1152    fn child(&self) -> Option<&WidgetRef> {
1153        self.child.as_ref()
1154    }
1155}
1156
1157/// Dart's `_RenderInputPadding`.
1158struct RenderInputPadding {
1159    render_object: RenderObjectData,
1160    render_box: RenderBoxData,
1161    child: RenderObjectWithChildData<AnyRenderBox>,
1162    min_size: Size,
1163    orientation: Orientation,
1164}
1165
1166impl RenderInputPadding {
1167    fn new(
1168        app: &mut App,
1169        min_size: Size,
1170        orientation: Orientation,
1171        child: Option<AnyRenderBox>,
1172    ) -> RenderHandle<RenderInputPadding> {
1173        let this = RenderHandle::new_box(
1174            app,
1175            RenderInputPadding {
1176                render_object: RenderObjectData::new(),
1177                render_box: RenderBoxData::new(),
1178                child: RenderObjectWithChildData::new(),
1179                min_size,
1180                orientation,
1181            },
1182        );
1183        this.set_child(app, child);
1184        this
1185    }
1186
1187    fn min_size(self: RenderHandle<Self>, app: &App) -> Size {
1188        self.get(app).min_size
1189    }
1190
1191    fn set_min_size(self: RenderHandle<Self>, app: &mut App, value: Size) {
1192        if self.get(app).min_size == value {
1193            return;
1194        }
1195        self.get_mut(app).min_size = value;
1196        RenderBox::mark_needs_layout(self, app);
1197    }
1198
1199    fn orientation(self: RenderHandle<Self>, app: &App) -> Orientation {
1200        self.get(app).orientation
1201    }
1202
1203    fn set_orientation(self: RenderHandle<Self>, app: &mut App, value: Orientation) {
1204        if self.get(app).orientation == value {
1205            return;
1206        }
1207        self.get_mut(app).orientation = value;
1208        RenderBox::mark_needs_layout(self, app);
1209    }
1210
1211    fn compute_size(
1212        self: RenderHandle<Self>,
1213        app: &mut App,
1214        constraints: BoxConstraints,
1215        layout_child: ChildLayouter,
1216    ) -> Size {
1217        if let Some(child) = self.child(app) {
1218            let child_size = layout_child(app, child, constraints);
1219            let min_size = self.min_size(app);
1220            let width = child_size.width().max(min_size.width());
1221            let height = child_size.height().max(min_size.height());
1222            return constraints.constrain(Size::new(width, height));
1223        }
1224        Size::ZERO
1225    }
1226}
1227
1228impl RenderObjectWithChildMixin for RenderInputPadding {
1229    type ChildType = AnyRenderBox;
1230
1231    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
1232        &self.get(app).child
1233    }
1234
1235    fn child_data_mut(
1236        self: RenderHandle<Self>,
1237        app: &mut App,
1238    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
1239        &mut self.get_mut(app).child
1240    }
1241}
1242
1243impl RenderShiftedBox for RenderInputPadding {}
1244
1245impl RenderObject for RenderInputPadding {
1246    waft_rendering::render_object_accessors!();
1247
1248    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
1249        let constraints = self.constraints(app);
1250        let size = self.compute_size(app, constraints, ChildLayoutHelper::layout_child);
1251        self.set_size(app, size);
1252        if let Some(child) = self.child(app) {
1253            let child_size = child.size(app);
1254            child.parent_data_of_mut::<BoxParentData>(app).offset =
1255                Alignment::CENTER.along_offset(size - child_size);
1256        }
1257    }
1258
1259    fn paint(
1260        self: RenderHandle<Self>,
1261        app: &mut App,
1262        context: &mut PaintingContext,
1263        offset: Offset,
1264    ) {
1265        RenderShiftedBox::paint(self, app, context, offset);
1266    }
1267
1268    fn visit_children(
1269        self: RenderHandle<Self>,
1270        app: &App,
1271        visitor: &mut dyn FnMut(AnyRenderObject),
1272    ) {
1273        if let Some(child) = self.child(app) {
1274            visitor(child.as_object());
1275        }
1276    }
1277}
1278
1279impl RenderBox for RenderInputPadding {
1280    waft_rendering::render_box_accessors!();
1281
1282    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1283        if let Some(child) = self.child(app) {
1284            return child
1285                .get_min_intrinsic_width(app, height)
1286                .max(self.min_size(app).width());
1287        }
1288        0.0
1289    }
1290
1291    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1292        if let Some(child) = self.child(app) {
1293            return child
1294                .get_min_intrinsic_height(app, width)
1295                .max(self.min_size(app).height());
1296        }
1297        0.0
1298    }
1299
1300    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1301        if let Some(child) = self.child(app) {
1302            return child
1303                .get_max_intrinsic_width(app, height)
1304                .max(self.min_size(app).width());
1305        }
1306        0.0
1307    }
1308
1309    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1310        if let Some(child) = self.child(app) {
1311            return child
1312                .get_max_intrinsic_height(app, width)
1313                .max(self.min_size(app).height());
1314        }
1315        0.0
1316    }
1317
1318    fn compute_dry_layout(
1319        self: RenderHandle<Self>,
1320        app: &mut App,
1321        constraints: BoxConstraints,
1322    ) -> Size {
1323        self.compute_size(app, constraints, ChildLayoutHelper::dry_layout_child)
1324    }
1325
1326    fn compute_dry_baseline(
1327        self: RenderHandle<Self>,
1328        app: &mut App,
1329        constraints: BoxConstraints,
1330        baseline: TextBaseline,
1331    ) -> Option<f64> {
1332        let child = self.child(app)?;
1333        let result = child.get_dry_baseline(app, constraints, baseline)?;
1334        let child_size = child.get_dry_layout(app, constraints);
1335        let size = self.as_box().get_dry_layout(app, constraints);
1336        Some(result + Alignment::CENTER.along_offset(size - child_size).dy())
1337    }
1338
1339    fn compute_distance_to_actual_baseline(
1340        self: RenderHandle<Self>,
1341        app: &mut App,
1342        baseline: TextBaseline,
1343    ) -> Option<f64> {
1344        RenderShiftedBox::compute_distance_to_actual_baseline(self, app, baseline)
1345    }
1346
1347    fn hit_test_children(
1348        self: RenderHandle<Self>,
1349        app: &mut App,
1350        result: &mut BoxHitTestResult<'_>,
1351        position: Offset,
1352    ) -> bool {
1353        RenderShiftedBox::hit_test_children(self, app, result, position)
1354    }
1355
1356    fn hit_test(
1357        self: RenderHandle<Self>,
1358        app: &mut App,
1359        result: &mut BoxHitTestResult<'_>,
1360        position: Offset,
1361    ) -> bool {
1362        if RenderBoxBase::hit_test(self, app, result, position) {
1363            return true;
1364        }
1365
1366        let child = self.child(app).expect("an input padding has a child");
1367        let child_size = child.size(app);
1368        let min_size = self.min_size(app);
1369        if position.dx() < 0.0
1370            || position.dx() > child_size.width().max(min_size.width())
1371            || position.dy() < 0.0
1372            || position.dy() > child_size.height().max(min_size.height())
1373        {
1374            return false;
1375        }
1376
1377        let mut new_position = child_size.center(Offset::ZERO);
1378        new_position = new_position
1379            + match self.orientation(app) {
1380                Orientation::Portrait if position.dy() > new_position.dy() => Offset::new(0.0, 1.0),
1381                Orientation::Landscape if position.dx() > new_position.dx() => {
1382                    Offset::new(1.0, 0.0)
1383                }
1384                Orientation::Portrait => Offset::new(0.0, -1.0),
1385                Orientation::Landscape => Offset::new(-1.0, 0.0),
1386            };
1387
1388        result.add_with_raw_transform(
1389            Some(force_to_point(new_position)),
1390            new_position,
1391            |result, position| {
1392                debug_assert!(
1393                    (position.dx() - new_position.dx()).abs()
1394                        <= new_position.dx().abs() * f32::EPSILON as f64
1395                        && (position.dy() - new_position.dy()).abs()
1396                            <= new_position.dy().abs() * f32::EPSILON as f64,
1397                    "the forced transform maps every hit to the new position"
1398                );
1399                child.hit_test(app, result, new_position)
1400            },
1401        )
1402    }
1403}
1404
1405/// Dart's `_TappableLabel`.
1406struct TappableLabel {
1407    #[expect(dead_code, reason = "Dart's field, which only its constructor reads")]
1408    value: i32,
1409
1410    /// Whether this is the inner ring of a double-ring dial.
1411    inner: bool,
1412
1413    /// The text painter, laid out at its natural size.
1414    painter: RefCell<TextPainter>,
1415
1416    #[expect(dead_code, reason = "Dart's field, which only its constructor reads")]
1417    on_tap: Listener,
1418}
1419
1420/// Dart's `_DialPainter`.
1421struct DialPainter {
1422    primary_labels: Vec<TappableLabel>,
1423    selected_labels: Vec<TappableLabel>,
1424    background_color: Color,
1425    hand_color: Color,
1426    hand_width: f64,
1427    dot_color: Color,
1428    dot_radius: f64,
1429    center_radius: f64,
1430    theta: f64,
1431    radius: f64,
1432    #[expect(dead_code, reason = "Dart's field, which only its constructor reads")]
1433    text_direction: TextDirection,
1434    #[expect(dead_code, reason = "Dart's field, which only its constructor reads")]
1435    selected_value: i32,
1436    repaint: Rc<dyn waft_foundation::Listenable>,
1437}
1438
1439impl DialPainter {
1440    #[allow(clippy::too_many_arguments)]
1441    fn new(
1442        app: &mut App,
1443        primary_labels: Vec<TappableLabel>,
1444        selected_labels: Vec<TappableLabel>,
1445        background_color: Color,
1446        hand_color: Color,
1447        hand_width: f64,
1448        dot_color: Color,
1449        dot_radius: f64,
1450        center_radius: f64,
1451        theta: f64,
1452        radius: f64,
1453        text_direction: TextDirection,
1454        selected_value: i32,
1455    ) -> DialPainter {
1456        let repaint: Rc<dyn waft_foundation::Listenable> =
1457            Rc::new(PaintingBinding::instance(app).system_fonts(app).keep(app));
1458        DialPainter {
1459            primary_labels,
1460            selected_labels,
1461            background_color,
1462            hand_color,
1463            hand_width,
1464            dot_color,
1465            dot_radius,
1466            center_radius,
1467            theta,
1468            radius,
1469            text_direction,
1470            selected_value,
1471            repaint,
1472        }
1473    }
1474
1475    /// Dart's `dispose`.
1476    fn dispose(&mut self) {
1477        for label in self.primary_labels.drain(..) {
1478            label.painter.borrow_mut().dispose();
1479        }
1480        for label in self.selected_labels.drain(..) {
1481            label.painter.borrow_mut().dispose();
1482        }
1483    }
1484
1485    fn get_offset_for_theta(center: Offset, theta: f64, radius: f64) -> Offset {
1486        center + Offset::new(radius * theta.cos(), -radius * theta.sin())
1487    }
1488
1489    fn paint_labels(
1490        app: &mut App,
1491        canvas: &mut Canvas,
1492        center: Offset,
1493        labels: &[&TappableLabel],
1494        radius: f64,
1495    ) {
1496        if labels.is_empty() {
1497            return;
1498        }
1499        let label_theta_increment = -K_TWO_PI / labels.len() as f64;
1500        let mut label_theta = PI / 2.0;
1501
1502        let fonts = PaintingBinding::instance(app).fonts(app);
1503        for label in labels {
1504            let mut label_painter = label.painter.borrow_mut();
1505            let label_offset =
1506                Offset::new(-label_painter.width() / 2.0, -label_painter.height() / 2.0);
1507            label_painter.paint(
1508                app.get_mut(fonts),
1509                canvas,
1510                Self::get_offset_for_theta(center, label_theta, radius) + label_offset,
1511            );
1512            label_theta += label_theta_increment;
1513        }
1514    }
1515
1516    fn paint_inner_outer_labels(
1517        app: &mut App,
1518        canvas: &mut Canvas,
1519        center: Offset,
1520        labels: &[TappableLabel],
1521        label_radius: f64,
1522        inner_label_radius: f64,
1523    ) {
1524        let outer: Vec<&TappableLabel> = labels.iter().filter(|label| !label.inner).collect();
1525        let inner: Vec<&TappableLabel> = labels.iter().filter(|label| label.inner).collect();
1526        Self::paint_labels(app, canvas, center, &outer, label_radius);
1527        Self::paint_labels(app, canvas, center, &inner, inner_label_radius);
1528    }
1529}
1530
1531impl CustomPainter for DialPainter {
1532    fn repaint(&self) -> Option<&Rc<dyn waft_foundation::Listenable>> {
1533        Some(&self.repaint)
1534    }
1535
1536    fn paint(&self, app: &mut App, canvas: &mut Canvas, size: Size) {
1537        let dial_radius =
1538            (size.shortest_side() / 2.0).max(K_TIME_PICKER_DIAL_MIN_RADIUS + self.dot_radius);
1539        let label_radius =
1540            (dial_radius - K_TIME_PICKER_DIAL_PADDING).max(K_TIME_PICKER_DIAL_MIN_RADIUS);
1541        let inner_label_radius = (label_radius - K_TIME_PICKER_INNER_DIAL_OFFSET).max(0.0);
1542        let handle_radius = (label_radius
1543            - (if self.radius < 0.5 { 1.0 } else { 0.0 }) * (label_radius - inner_label_radius))
1544            .max(K_TIME_PICKER_DIAL_MIN_RADIUS);
1545        let center = Offset::new(size.width() / 2.0, size.height() / 2.0);
1546        let center_point = center;
1547        canvas.draw_circle(
1548            center_point,
1549            dial_radius as f32,
1550            &Paint::from_color(self.background_color.into()),
1551        );
1552
1553        Self::paint_inner_outer_labels(
1554            app,
1555            canvas,
1556            center,
1557            &self.primary_labels,
1558            label_radius,
1559            inner_label_radius,
1560        );
1561
1562        let selector_paint = Paint::from_color(self.hand_color.into());
1563        let focused_point = Self::get_offset_for_theta(center, self.theta, handle_radius);
1564        canvas.draw_circle(center_point, self.center_radius as f32, &selector_paint);
1565        canvas.draw_circle(focused_point, self.dot_radius as f32, &selector_paint);
1566        let mut line_paint = Paint::from_color(self.hand_color.into());
1567        line_paint.style =
1568            waft_embedder::PaintStyle::Stroke(waft_embedder::Stroke::new(self.hand_width as f32));
1569        draw_line(canvas, center_point, focused_point, &line_paint);
1570
1571        // Add a dot inside the selector but only when it isn't over the labels.
1572        // This checks that the selector's theta is between two labels. A remainder
1573        // between 0.1 and 0.45 indicates that the selector is roughly not above any
1574        // labels. The values were derived by manually testing the dial.
1575        let label_theta_increment = -K_TWO_PI / self.primary_labels.len() as f64;
1576        let remainder = dart_remainder(self.theta, label_theta_increment);
1577        if remainder > 0.1 && remainder < 0.45 {
1578            let mut dot_paint = Paint::from_color(self.dot_color.into());
1579            dot_paint.style = waft_embedder::PaintStyle::Stroke(waft_embedder::Stroke::new(
1580                self.hand_width as f32,
1581            ));
1582            canvas.draw_circle(focused_point, 2.0, &dot_paint);
1583        }
1584
1585        let mut oval = PathBuilder::new();
1586        oval.arc(
1587            focused_point,
1588            self.dot_radius as f32,
1589            0.0,
1590            std::f32::consts::TAU,
1591        );
1592        let focused_path = Path::new(oval.build());
1593        canvas.save();
1594        canvas.clip_path(
1595            focused_path.as_valo(),
1596            focused_path.fill_type,
1597            ClipOp::Intersect,
1598            true,
1599        );
1600        Self::paint_inner_outer_labels(
1601            app,
1602            canvas,
1603            center,
1604            &self.selected_labels,
1605            label_radius,
1606            inner_label_radius,
1607        );
1608        canvas.restore();
1609    }
1610
1611    fn should_repaint(&self, _app: &App, _old_painter: &dyn CustomPainter) -> bool {
1612        // Dart compares the label lists by identity, and every build makes new ones.
1613        true
1614    }
1615
1616    fn as_any(&self) -> &dyn Any {
1617        self
1618    }
1619}
1620
1621#[cfg(test)]
1622impl DialPainter {
1623    /// The text of the primary labels, which the tests read through `painter.text.text`.
1624    fn primary_label_texts(&self) -> Vec<String> {
1625        Self::label_texts(&self.primary_labels)
1626    }
1627
1628    /// The text of the selected labels.
1629    fn selected_label_texts(&self) -> Vec<String> {
1630        Self::label_texts(&self.selected_labels)
1631    }
1632
1633    /// Whether each primary label is on the inner ring.
1634    fn primary_label_inner(&self) -> Vec<bool> {
1635        self.primary_labels
1636            .iter()
1637            .map(|label| label.inner)
1638            .collect()
1639    }
1640
1641    /// Whether each selected label is on the inner ring.
1642    fn selected_label_inner(&self) -> Vec<bool> {
1643        self.selected_labels
1644            .iter()
1645            .map(|label| label.inner)
1646            .collect()
1647    }
1648
1649    /// The style of the first primary label's text, which the tests read through
1650    /// `primaryLabels.first.painter.text.style`.
1651    fn first_primary_label_style(&self) -> Option<waft_painting::TextStyle> {
1652        Self::first_label_style(&self.primary_labels)
1653    }
1654
1655    /// The style of the first selected label's text.
1656    fn first_selected_label_style(&self) -> Option<waft_painting::TextStyle> {
1657        Self::first_label_style(&self.selected_labels)
1658    }
1659
1660    fn first_label_style(labels: &[TappableLabel]) -> Option<waft_painting::TextStyle> {
1661        labels[0]
1662            .painter
1663            .borrow()
1664            .text()
1665            .and_then(|span| span.style().cloned())
1666    }
1667
1668    fn label_texts(labels: &[TappableLabel]) -> Vec<String> {
1669        labels
1670            .iter()
1671            .map(|label| label.painter.borrow_mut().plain_text().to_string())
1672            .collect()
1673    }
1674}
1675
1676/// Dart's `%` on doubles: the result has the sign of the divisor's magnitude, never negative.
1677fn dart_remainder(a: f64, b: f64) -> f64 {
1678    a.rem_euclid(b.abs())
1679}
1680
1681/// Dart's `_Dial`.
1682struct Dial {
1683    selected_time: TimeOfDay,
1684    hour_minute_mode: HourMinuteMode,
1685    hour_dial_type: HourDialType,
1686    on_changed: Option<SelectedTimeChanged>,
1687    on_hour_selected: Option<VoidCallback>,
1688}
1689
1690impl std::fmt::Debug for Dial {
1691    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1692        f.debug_struct("Dial")
1693            .field("selected_time", &self.selected_time)
1694            .finish_non_exhaustive()
1695    }
1696}
1697
1698impl StatefulWidget for Dial {
1699    type State = DialState;
1700
1701    fn create_state(&self) -> DialState {
1702        DialState {
1703            state: StateData::new(),
1704            single_ticker_provider: SingleTickerProviderStateMixinData::default(),
1705            theme_data: None,
1706            localizations: None,
1707            painter: None,
1708            animation_controller: None,
1709            theta_tween: None,
1710            theta: None,
1711            radius_tween: None,
1712            radius: None,
1713            dragging: false,
1714            position: None,
1715            center: None,
1716            dial_size: None,
1717        }
1718    }
1719}
1720
1721/// Dart's `_DialState`.
1722struct DialState {
1723    state: StateData<Dial>,
1724    single_ticker_provider: SingleTickerProviderStateMixinData,
1725    theme_data: Option<Rc<ThemeData>>,
1726    localizations: Option<Rc<dyn MaterialLocalizations>>,
1727    painter: Option<Rc<RefCell<DialPainter>>>,
1728    animation_controller: Option<Ref<AnimationController>>,
1729    theta_tween: Option<Ref<Tween<f64>>>,
1730    theta: Option<AnimationRef<f64>>,
1731    radius_tween: Option<Ref<Tween<f64>>>,
1732    radius: Option<AnimationRef<f64>>,
1733    dragging: bool,
1734    position: Option<Offset>,
1735    center: Option<Offset>,
1736    dial_size: Option<Size>,
1737}
1738
1739impl SingleTickerProviderStateMixin for DialState {
1740    fn single_ticker_provider_data(
1741        self: Handle<Self>,
1742        app: &App,
1743    ) -> &SingleTickerProviderStateMixinData {
1744        &app.get(self).single_ticker_provider
1745    }
1746
1747    fn single_ticker_provider_data_mut(
1748        self: Handle<Self>,
1749        app: &mut App,
1750    ) -> &mut SingleTickerProviderStateMixinData {
1751        &mut app.get_mut(self).single_ticker_provider
1752    }
1753}
1754
1755impl waft_scheduler::TickerProviderObject for DialState {
1756    fn create_ticker(
1757        self: Handle<Self>,
1758        app: &mut App,
1759        on_tick: waft_scheduler::TickerCallback,
1760    ) -> Ref<waft_scheduler::Ticker> {
1761        SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
1762    }
1763}
1764
1765impl DialState {
1766    fn animation_controller(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
1767        app.get(self)
1768            .animation_controller
1769            .as_ref()
1770            .expect("init_state ran")
1771            .handle()
1772    }
1773
1774    fn theta_tween(self: Handle<Self>, app: &App) -> Handle<Tween<f64>> {
1775        app.get(self)
1776            .theta_tween
1777            .as_ref()
1778            .expect("init_state ran")
1779            .handle()
1780    }
1781
1782    fn radius_tween(self: Handle<Self>, app: &App) -> Handle<Tween<f64>> {
1783        app.get(self)
1784            .radius_tween
1785            .as_ref()
1786            .expect("init_state ran")
1787            .handle()
1788    }
1789
1790    fn theta_value(self: Handle<Self>, app: &App) -> f64 {
1791        app.get(self)
1792            .theta
1793            .as_ref()
1794            .expect("init_state ran")
1795            .value(app)
1796    }
1797
1798    fn radius_value(self: Handle<Self>, app: &App) -> f64 {
1799        app.get(self)
1800            .radius
1801            .as_ref()
1802            .expect("init_state ran")
1803            .value(app)
1804    }
1805
1806    fn handle_animation_value_changed(self: Handle<Self>, app: &mut App) {
1807        // _theta.value or _radius.value has changed
1808        self.set_state(app, |_state| {});
1809    }
1810
1811    fn nearest(target: f64, a: f64, b: f64) -> f64 {
1812        if (target - a).abs() < (target - b).abs() {
1813            a
1814        } else {
1815            b
1816        }
1817    }
1818
1819    fn animate_to(self: Handle<Self>, app: &mut App, target_theta: f64, target_radius: f64) {
1820        #[allow(clippy::too_many_arguments)]
1821        fn animate_to_value(
1822            app: &mut App,
1823            target: f64,
1824            animation_value: f64,
1825            tween: Handle<Tween<f64>>,
1826            controller: Handle<AnimationController>,
1827            min: f64,
1828            max: f64,
1829        ) {
1830            let mut begin_value = DialState::nearest(target, animation_value, max);
1831            begin_value = DialState::nearest(target, begin_value, min);
1832            tween.set_begin(app, Some(begin_value));
1833            tween.set_end(app, Some(target));
1834            controller.set_value(app, 0.0);
1835            controller.forward(app, None);
1836        }
1837
1838        let theta_value = self.theta_value(app);
1839        animate_to_value(
1840            app,
1841            target_theta,
1842            theta_value,
1843            self.theta_tween(app),
1844            self.animation_controller(app),
1845            theta_value - K_TWO_PI,
1846            theta_value + K_TWO_PI,
1847        );
1848        let radius_value = self.radius_value(app);
1849        animate_to_value(
1850            app,
1851            target_radius,
1852            radius_value,
1853            self.radius_tween(app),
1854            self.animation_controller(app),
1855            0.0,
1856            1.0,
1857        );
1858    }
1859
1860    fn get_radius_for_time(self: Handle<Self>, app: &App, time: TimeOfDay) -> f64 {
1861        let widget = self.widget(app);
1862        match widget.hour_minute_mode {
1863            HourMinuteMode::Hour => match widget.hour_dial_type {
1864                HourDialType::TwentyFourHourDoubleRing => {
1865                    if time.hour >= 12 {
1866                        0.0
1867                    } else {
1868                        1.0
1869                    }
1870                }
1871                HourDialType::TwentyFourHour | HourDialType::TwelveHour => 1.0,
1872            },
1873            HourMinuteMode::Minute => 1.0,
1874        }
1875    }
1876
1877    fn get_theta_for_time(self: Handle<Self>, app: &App, time: TimeOfDay) -> f64 {
1878        let widget = self.widget(app);
1879        let hours_factor = match widget.hour_dial_type {
1880            HourDialType::TwentyFourHour => TimeOfDay::HOURS_PER_DAY,
1881            HourDialType::TwentyFourHourDoubleRing => TimeOfDay::HOURS_PER_PERIOD,
1882            HourDialType::TwelveHour => TimeOfDay::HOURS_PER_PERIOD,
1883        };
1884        let fraction = match widget.hour_minute_mode {
1885            HourMinuteMode::Hour => {
1886                (f64::from(time.hour) / f64::from(hours_factor)).rem_euclid(f64::from(hours_factor))
1887            }
1888            HourMinuteMode::Minute => (f64::from(time.minute)
1889                / f64::from(TimeOfDay::MINUTES_PER_HOUR))
1890            .rem_euclid(f64::from(TimeOfDay::MINUTES_PER_HOUR)),
1891        };
1892        (PI / 2.0 - fraction * K_TWO_PI).rem_euclid(K_TWO_PI)
1893    }
1894
1895    fn get_time_for_theta(
1896        self: Handle<Self>,
1897        app: &App,
1898        theta: f64,
1899        round_minutes: bool,
1900        radius: f64,
1901    ) -> TimeOfDay {
1902        let widget = self.widget(app);
1903        let fraction = (0.25 - theta.rem_euclid(K_TWO_PI) / K_TWO_PI).rem_euclid(1.0);
1904        match widget.hour_minute_mode {
1905            HourMinuteMode::Hour => {
1906                let new_hour = match widget.hour_dial_type {
1907                    HourDialType::TwentyFourHour => {
1908                        dart_round(fraction * f64::from(TimeOfDay::HOURS_PER_DAY))
1909                            .rem_euclid(TimeOfDay::HOURS_PER_DAY)
1910                    }
1911                    HourDialType::TwentyFourHourDoubleRing => {
1912                        let mut new_hour =
1913                            dart_round(fraction * f64::from(TimeOfDay::HOURS_PER_PERIOD))
1914                                .rem_euclid(TimeOfDay::HOURS_PER_PERIOD);
1915                        if radius < 0.5 {
1916                            new_hour += TimeOfDay::HOURS_PER_PERIOD;
1917                        }
1918                        new_hour
1919                    }
1920                    HourDialType::TwelveHour => {
1921                        let new_hour =
1922                            dart_round(fraction * f64::from(TimeOfDay::HOURS_PER_PERIOD))
1923                                .rem_euclid(TimeOfDay::HOURS_PER_PERIOD);
1924                        new_hour + widget.selected_time.period_offset()
1925                    }
1926                };
1927                widget.selected_time.replacing(Some(new_hour), None)
1928            }
1929            HourMinuteMode::Minute => {
1930                let mut minute = dart_round(fraction * f64::from(TimeOfDay::MINUTES_PER_HOUR))
1931                    .rem_euclid(TimeOfDay::MINUTES_PER_HOUR);
1932                if round_minutes {
1933                    // Round the minutes to nearest 5 minute interval.
1934                    minute = ((minute + 2) / 5 * 5).rem_euclid(TimeOfDay::MINUTES_PER_HOUR);
1935                }
1936                widget.selected_time.replacing(None, Some(minute))
1937            }
1938        }
1939    }
1940
1941    fn notify_on_changed_if_needed(
1942        self: Handle<Self>,
1943        app: &mut App,
1944        round_minutes: bool,
1945    ) -> TimeOfDay {
1946        let current = self.get_time_for_theta(
1947            app,
1948            self.theta_value(app),
1949            round_minutes,
1950            self.radius_value(app),
1951        );
1952        let widget = self.widget(app);
1953        let Some(on_changed) = widget.on_changed.clone() else {
1954            return current;
1955        };
1956        let selected_time = widget.selected_time;
1957        if current != selected_time {
1958            on_changed(app, current);
1959        }
1960        current
1961    }
1962
1963    fn update_theta_for_pan(self: Handle<Self>, app: &mut App, round_minutes: bool) {
1964        self.set_state(app, |_state| {});
1965        let state = app.get(self);
1966        let offset = state.position.expect("a pan has a position")
1967            - state.center.expect("a pan has a center");
1968        let label_radius = state
1969            .dial_size
1970            .expect("a pan has a dial size")
1971            .shortest_side()
1972            / 2.0
1973            - K_TIME_PICKER_DIAL_PADDING;
1974        let inner_radius = label_radius - K_TIME_PICKER_INNER_DIAL_OFFSET;
1975        let mut angle = (offset.dx().atan2(offset.dy()) - PI / 2.0).rem_euclid(K_TWO_PI);
1976        let radius =
1977            ((offset.distance() - inner_radius) / K_TIME_PICKER_INNER_DIAL_OFFSET).clamp(0.0, 1.0);
1978        if round_minutes {
1979            let time = self.get_time_for_theta(app, angle, round_minutes, radius);
1980            angle = self.get_theta_for_time(app, time);
1981        }
1982        // The controller doesn't animate during the pan gesture.
1983        self.theta_tween(app).set_begin(app, Some(angle));
1984        self.theta_tween(app).set_end(app, Some(angle));
1985        self.radius_tween(app).set_begin(app, Some(radius));
1986        self.radius_tween(app).set_end(app, Some(radius));
1987    }
1988
1989    fn handle_pan_start(
1990        self: Handle<Self>,
1991        app: &mut App,
1992        details: &waft_gestures::DragStartDetails,
1993    ) {
1994        debug_assert!(!app.get(self).dragging);
1995        app.get_mut(self).dragging = true;
1996        let context = self.context(app);
1997        let render_box = context
1998            .find_render_object(app)
1999            .expect("the dial has a render object")
2000            .as_box()
2001            .expect("the dial is a box");
2002        let position = render_box.global_to_local(app, details.global_position, None);
2003        let size = render_box.size(app);
2004        {
2005            let state = app.get_mut(self);
2006            state.position = Some(position);
2007            state.dial_size = Some(size);
2008            state.center = Some(size.center(Offset::ZERO));
2009        }
2010        self.update_theta_for_pan(app, false);
2011        self.notify_on_changed_if_needed(app, false);
2012    }
2013
2014    fn handle_pan_update(
2015        self: Handle<Self>,
2016        app: &mut App,
2017        details: &waft_gestures::DragUpdateDetails,
2018    ) {
2019        let state = app.get_mut(self);
2020        state.position = Some(state.position.expect("a pan has a position") + details.delta);
2021        self.update_theta_for_pan(app, false);
2022        self.notify_on_changed_if_needed(app, false);
2023    }
2024
2025    fn handle_pan_end(self: Handle<Self>, app: &mut App, _details: &waft_gestures::DragEndDetails) {
2026        debug_assert!(app.get(self).dragging);
2027        {
2028            let state = app.get_mut(self);
2029            state.dragging = false;
2030            state.position = None;
2031            state.center = None;
2032            state.dial_size = None;
2033        }
2034        let selected_time = self.widget(app).selected_time;
2035        self.animate_to(
2036            app,
2037            self.get_theta_for_time(app, selected_time),
2038            self.get_radius_for_time(app, selected_time),
2039        );
2040        let widget = self.widget(app);
2041        if widget.hour_minute_mode == HourMinuteMode::Hour
2042            && let Some(on_hour_selected) = widget.on_hour_selected.clone()
2043        {
2044            on_hour_selected(app);
2045        }
2046    }
2047
2048    fn handle_tap_up(self: Handle<Self>, app: &mut App, details: &waft_gestures::TapUpDetails) {
2049        let context = self.context(app);
2050        let render_box = context
2051            .find_render_object(app)
2052            .expect("the dial has a render object")
2053            .as_box()
2054            .expect("the dial is a box");
2055        let position = render_box.global_to_local(app, details.global_position, None);
2056        let size = render_box.size(app);
2057        {
2058            let state = app.get_mut(self);
2059            state.position = Some(position);
2060            state.center = Some(size.center(Offset::ZERO));
2061            state.dial_size = Some(size);
2062        }
2063        self.update_theta_for_pan(app, true);
2064        self.notify_on_changed_if_needed(app, true);
2065        let widget = self.widget(app);
2066        if widget.hour_minute_mode == HourMinuteMode::Hour
2067            && let Some(on_hour_selected) = widget.on_hour_selected.clone()
2068        {
2069            on_hour_selected(app);
2070        }
2071        let time =
2072            self.get_time_for_theta(app, self.theta_value(app), true, self.radius_value(app));
2073        self.animate_to(
2074            app,
2075            self.get_theta_for_time(app, time),
2076            self.get_radius_for_time(app, time),
2077        );
2078        let state = app.get_mut(self);
2079        state.dragging = false;
2080        state.position = None;
2081        state.center = None;
2082        state.dial_size = None;
2083    }
2084
2085    fn select_hour(self: Handle<Self>, app: &mut App, hour: i32) {
2086        let widget = self.widget(app);
2087        let selected_time = widget.selected_time;
2088        let get_am_pm_time = || match selected_time.period() {
2089            DayPeriod::Am => TimeOfDay::new(hour, selected_time.minute),
2090            DayPeriod::Pm => {
2091                TimeOfDay::new(hour + TimeOfDay::HOURS_PER_PERIOD, selected_time.minute)
2092            }
2093        };
2094        let time = match widget.hour_minute_mode {
2095            HourMinuteMode::Hour => match widget.hour_dial_type {
2096                HourDialType::TwentyFourHour | HourDialType::TwentyFourHourDoubleRing => {
2097                    TimeOfDay::new(hour, selected_time.minute)
2098                }
2099                HourDialType::TwelveHour => get_am_pm_time(),
2100            },
2101            HourMinuteMode::Minute => get_am_pm_time(),
2102        };
2103        let angle = self.get_theta_for_time(app, time);
2104        self.theta_tween(app).set_begin(app, Some(angle));
2105        self.theta_tween(app).set_end(app, Some(angle));
2106        self.notify_on_changed_if_needed(app, false);
2107    }
2108
2109    fn select_minute(self: Handle<Self>, app: &mut App, minute: i32) {
2110        let time = TimeOfDay::new(self.widget(app).selected_time.hour, minute);
2111        let angle = self.get_theta_for_time(app, time);
2112        self.theta_tween(app).set_begin(app, Some(angle));
2113        self.theta_tween(app).set_end(app, Some(angle));
2114        self.notify_on_changed_if_needed(app, false);
2115    }
2116
2117    #[allow(clippy::too_many_arguments)]
2118    fn build_tappable_label(
2119        self: Handle<Self>,
2120        app: &mut App,
2121        context: BuildContext,
2122        text_style: &TextStyle,
2123        value: i32,
2124        inner: bool,
2125        label: String,
2126        on_tap: Listener,
2127    ) -> TappableLabel {
2128        let mut painter = TextPainter::new();
2129        painter.set_text(Some(Rc::new(
2130            TextSpan::new().style(text_style.clone()).text(label),
2131        )));
2132        painter.set_text_direction(Some(TextDirection::Ltr));
2133        painter.set_text_scaler(MediaQuery::text_scaler_of(app, context).clamp(0.0, 2.0));
2134        let fonts = PaintingBinding::instance(app).fonts(app);
2135        painter.layout(app.get_mut(fonts), 0.0, f64::INFINITY);
2136        TappableLabel {
2137            value,
2138            inner,
2139            painter: RefCell::new(painter),
2140            on_tap,
2141        }
2142    }
2143
2144    fn select_hour_listener(self: Handle<Self>, hour: i32) -> Listener {
2145        Listener::new(move |app| self.select_hour(app, hour))
2146    }
2147
2148    fn select_minute_listener(self: Handle<Self>, minute: i32) -> Listener {
2149        Listener::new(move |app| self.select_minute(app, minute))
2150    }
2151
2152    fn build_24_hour_ring(
2153        self: Handle<Self>,
2154        app: &mut App,
2155        context: BuildContext,
2156        text_style: &TextStyle,
2157    ) -> Vec<TappableLabel> {
2158        let theme_data = Rc::clone(app.get(self).theme_data.as_ref().expect("dependencies ran"));
2159        let localizations = Rc::clone(
2160            app.get(self)
2161                .localizations
2162                .as_ref()
2163                .expect("dependencies ran"),
2164        );
2165        let mut labels = Vec::new();
2166        if theme_data.use_material3 {
2167            for hour in 0..24 {
2168                let time_of_day = TimeOfDay::new(hour, 0);
2169                let label =
2170                    // The M3 specs for 24-hour ring show 0 hour as 00, but for 1-9,
2171                    // the specs show single digit.
2172                    if time_of_day.hour != 0 {
2173                        localizations.format_decimal(i64::from(time_of_day.hour))
2174                    } else {
2175                        localizations.format_hour(&time_of_day, true)
2176                    };
2177                labels.push(self.build_tappable_label(
2178                    app,
2179                    context,
2180                    text_style,
2181                    time_of_day.hour,
2182                    time_of_day.hour >= 12,
2183                    label,
2184                    self.select_hour_listener(time_of_day.hour),
2185                ));
2186            }
2187        } else {
2188            // On M2, there's no inner ring of numbers.
2189            for hour in (0..24).step_by(2) {
2190                let time_of_day = TimeOfDay::new(hour, 0);
2191                labels.push(self.build_tappable_label(
2192                    app,
2193                    context,
2194                    text_style,
2195                    time_of_day.hour,
2196                    false,
2197                    localizations.format_hour(&time_of_day, true),
2198                    self.select_hour_listener(time_of_day.hour),
2199                ));
2200            }
2201        }
2202        labels
2203    }
2204
2205    fn build_12_hour_ring(
2206        self: Handle<Self>,
2207        app: &mut App,
2208        context: BuildContext,
2209        text_style: &TextStyle,
2210    ) -> Vec<TappableLabel> {
2211        let localizations = Rc::clone(
2212            app.get(self)
2213                .localizations
2214                .as_ref()
2215                .expect("dependencies ran"),
2216        );
2217        let always_use_24_hour_format = MediaQuery::always_use_24_hour_format_of(app, context);
2218        // 12, then 1 through 11.
2219        (0..12)
2220            .map(|index| {
2221                let time_of_day = TimeOfDay::new(if index == 0 { 12 } else { index }, 0);
2222                self.build_tappable_label(
2223                    app,
2224                    context,
2225                    text_style,
2226                    time_of_day.hour,
2227                    false,
2228                    localizations.format_hour(&time_of_day, always_use_24_hour_format),
2229                    self.select_hour_listener(time_of_day.hour),
2230                )
2231            })
2232            .collect()
2233    }
2234
2235    fn build_minutes(
2236        self: Handle<Self>,
2237        app: &mut App,
2238        context: BuildContext,
2239        text_style: &TextStyle,
2240    ) -> Vec<TappableLabel> {
2241        let localizations = Rc::clone(
2242            app.get(self)
2243                .localizations
2244                .as_ref()
2245                .expect("dependencies ran"),
2246        );
2247        (0..12)
2248            .map(|index| {
2249                let time_of_day = TimeOfDay::new(0, index * 5);
2250                self.build_tappable_label(
2251                    app,
2252                    context,
2253                    text_style,
2254                    time_of_day.minute,
2255                    false,
2256                    localizations.format_minute(&time_of_day),
2257                    self.select_minute_listener(time_of_day.minute),
2258                )
2259            })
2260            .collect()
2261    }
2262}
2263
2264/// Dart's `double.round()`: half away from zero.
2265fn dart_round(value: f64) -> i32 {
2266    value.round() as i32
2267}
2268
2269impl State for DialState {
2270    type Widget = Dial;
2271    waft_widgets::state_accessors!();
2272
2273    #[allow(deprecated)]
2274    fn init_state(self: Handle<Self>, app: &mut App) {
2275        let animation_controller = AnimationController::new(
2276            app,
2277            None,
2278            Some(K_DIAL_ANIMATE_DURATION),
2279            None,
2280            0.0,
2281            1.0,
2282            AnimationBehavior::Normal,
2283            self,
2284        );
2285        let selected_time = self.widget(app).selected_time;
2286        let theta_tween = Tween::new(app, Some(self.get_theta_for_time(app, selected_time)), None);
2287        let radius_tween = Tween::new(
2288            app,
2289            Some(self.get_radius_for_time(app, selected_time)),
2290            None,
2291        );
2292        let eased = CurveTween::new(app, standard_easing());
2293        let eased = animation_controller.drive(app, eased);
2294        let theta = eased.drive(app, theta_tween.clone());
2295        theta.add_listener(
2296            app,
2297            Listener::handle_method(self, Self::handle_animation_value_changed),
2298        );
2299        let eased = CurveTween::new(app, standard_easing());
2300        let eased = animation_controller.drive(app, eased);
2301        let radius = eased.drive(app, radius_tween.clone());
2302        radius.add_listener(
2303            app,
2304            Listener::handle_method(self, Self::handle_animation_value_changed),
2305        );
2306        let state = app.get_mut(self);
2307        state.animation_controller = Some(animation_controller);
2308        state.theta_tween = Some(theta_tween);
2309        state.theta = Some(theta);
2310        state.radius_tween = Some(radius_tween);
2311        state.radius = Some(radius);
2312    }
2313
2314    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
2315        let context = self.context(app);
2316        waft_widgets::debug_check_has_media_query(app, context);
2317        let theme_data = Theme::of(app, context);
2318        let localizations = <dyn MaterialLocalizations>::of(app, context);
2319        let state = app.get_mut(self);
2320        state.theme_data = Some(theme_data);
2321        state.localizations = Some(localizations);
2322    }
2323
2324    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &Dial) {
2325        let widget = self.widget(app);
2326        if widget.hour_minute_mode != old_widget.hour_minute_mode
2327            || widget.selected_time != old_widget.selected_time
2328        {
2329            let selected_time = widget.selected_time;
2330            if !app.get(self).dragging {
2331                self.animate_to(
2332                    app,
2333                    self.get_theta_for_time(app, selected_time),
2334                    self.get_radius_for_time(app, selected_time),
2335                );
2336            }
2337        }
2338    }
2339
2340    fn dispose(self: Handle<Self>, app: &mut App) {
2341        self.animation_controller(app).dispose(app);
2342        if let Some(painter) = app.get_mut(self).painter.take() {
2343            painter.borrow_mut().dispose();
2344        }
2345        SingleTickerProviderStateMixin::dispose(self, app);
2346    }
2347
2348    fn activate(self: Handle<Self>, app: &mut App) {
2349        SingleTickerProviderStateMixin::activate(self, app);
2350    }
2351
2352    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
2353        debug_assert!(debug_dial_time_picker_entry_mode(app, context));
2354        let theme = Theme::of(app, context);
2355        let time_picker_theme = TimePickerTheme::of(app, context);
2356        let default_theme: Rc<dyn TimePickerDefaults> = if theme.use_material3 {
2357            Rc::new(TimePickerDefaultsM3::new(
2358                context,
2359                TimePickerEntryMode::Dial,
2360            ))
2361        } else {
2362            Rc::new(TimePickerDefaultsM2::new(context))
2363        };
2364        let background_color = time_picker_theme
2365            .dial_background_color
2366            .clone()
2367            .unwrap_or_else(|| default_theme.dial_background_color(app))
2368            .color();
2369        let dial_hand_color = time_picker_theme
2370            .dial_hand_color
2371            .clone()
2372            .unwrap_or_else(|| default_theme.dial_hand_color(app))
2373            .color();
2374        let label_style = time_picker_theme
2375            .dial_text_style
2376            .clone()
2377            .unwrap_or_else(|| default_theme.dial_text_style(app))
2378            .value()
2379            .clone();
2380        let dial_text_color = time_picker_theme
2381            .dial_text_color
2382            .clone()
2383            .unwrap_or_else(|| default_theme.dial_text_color(app));
2384        let dial_text_unselected_color =
2385            <dyn WidgetStateProperty<Color>>::resolve_as(&dial_text_color, &WidgetStates::new())
2386                .color();
2387        let mut selected_states = WidgetStates::new();
2388        selected_states.insert(WidgetState::Selected);
2389        let dial_text_selected_color =
2390            <dyn WidgetStateProperty<Color>>::resolve_as(&dial_text_color, &selected_states)
2391                .color();
2392        let resolved_unselected_label_style =
2393            label_style.copy_with().color(dial_text_unselected_color);
2394        let resolved_selected_label_style = label_style.copy_with().color(dial_text_selected_color);
2395        let dot_color = dial_text_selected_color;
2396
2397        let widget = self.widget(app);
2398        let (hour_minute_mode, hour_dial_type, selected_time) = (
2399            widget.hour_minute_mode,
2400            widget.hour_dial_type,
2401            widget.selected_time,
2402        );
2403        let (primary_labels, selected_labels, selected_dial_value, radius_value) =
2404            match hour_minute_mode {
2405                HourMinuteMode::Hour => match hour_dial_type {
2406                    HourDialType::TwentyFourHour | HourDialType::TwentyFourHourDoubleRing => (
2407                        self.build_24_hour_ring(app, context, &resolved_unselected_label_style),
2408                        self.build_24_hour_ring(app, context, &resolved_selected_label_style),
2409                        selected_time.hour,
2410                        if theme.use_material3 {
2411                            self.radius_value(app)
2412                        } else {
2413                            1.0
2414                        },
2415                    ),
2416                    HourDialType::TwelveHour => (
2417                        self.build_12_hour_ring(app, context, &resolved_unselected_label_style),
2418                        self.build_12_hour_ring(app, context, &resolved_selected_label_style),
2419                        selected_time.hour_of_period(),
2420                        1.0,
2421                    ),
2422                },
2423                HourMinuteMode::Minute => (
2424                    self.build_minutes(app, context, &resolved_unselected_label_style),
2425                    self.build_minutes(app, context, &resolved_selected_label_style),
2426                    selected_time.minute,
2427                    1.0,
2428                ),
2429            };
2430        if let Some(painter) = app.get_mut(self).painter.take() {
2431            painter.borrow_mut().dispose();
2432        }
2433        let (hand_width, dot_radius, center_radius) = (
2434            default_theme.hand_width(app),
2435            default_theme.dot_radius(app),
2436            default_theme.center_radius(app),
2437        );
2438        let theta = self.theta_value(app);
2439        let text_direction = Directionality::of(app, context);
2440        let painter = Rc::new(RefCell::new(DialPainter::new(
2441            app,
2442            primary_labels,
2443            selected_labels,
2444            background_color,
2445            dial_hand_color,
2446            hand_width,
2447            dot_color,
2448            dot_radius,
2449            center_radius,
2450            theta,
2451            radius_value,
2452            text_direction,
2453            selected_dial_value,
2454        )));
2455        app.get_mut(self).painter = Some(Rc::clone(&painter));
2456
2457        GestureDetector::new()
2458            .on_pan_start(Rc::new(move |app, details| {
2459                self.handle_pan_start(app, &details)
2460            }))
2461            .on_pan_update(Rc::new(move |app, details| {
2462                self.handle_pan_update(app, &details)
2463            }))
2464            .on_pan_end(Rc::new(move |app, details| {
2465                self.handle_pan_end(app, &details)
2466            }))
2467            .on_tap_up(Rc::new(move |app, details| {
2468                self.handle_tap_up(app, &details)
2469            }))
2470            .child(CustomPaint::new().painter(SharedDialPainter(painter)))
2471            .into_widget()
2472    }
2473}
2474
2475/// The painter object the `CustomPaint` holds, which `_DialState` also keeps to dispose.
2476struct SharedDialPainter(Rc<RefCell<DialPainter>>);
2477
2478impl CustomPainter for SharedDialPainter {
2479    fn repaint(&self) -> Option<&Rc<dyn waft_foundation::Listenable>> {
2480        None
2481    }
2482
2483    fn paint(&self, app: &mut App, canvas: &mut Canvas, size: Size) {
2484        self.0.borrow().paint(app, canvas, size);
2485    }
2486
2487    fn should_repaint(&self, app: &App, old_painter: &dyn CustomPainter) -> bool {
2488        let old_painter = old_painter
2489            .as_any()
2490            .downcast_ref::<SharedDialPainter>()
2491            .expect("Dart's covariant parameter");
2492        let old_painter = old_painter.0.borrow();
2493        self.0.borrow().should_repaint(app, &*old_painter)
2494    }
2495
2496    fn as_any(&self) -> &dyn Any {
2497        self
2498    }
2499}
2500
2501/// Dart's `_TimePickerInput`.
2502#[derive(Clone, Debug)]
2503struct TimePickerInput {
2504    initial_selected_time: TimeOfDay,
2505    error_invalid_text: Option<String>,
2506    hour_label_text: Option<String>,
2507    minute_label_text: Option<String>,
2508    help_text: String,
2509    autofocus_hour: Option<bool>,
2510    autofocus_minute: Option<bool>,
2511    restoration_id: Option<String>,
2512    empty_initial_time: bool,
2513}
2514
2515impl StatefulWidget for TimePickerInput {
2516    type State = TimePickerInputState;
2517
2518    fn create_state(&self) -> TimePickerInputState {
2519        TimePickerInputState {
2520            state: StateData::new(),
2521            restoration: RestorationMixinData::new(),
2522            selected_time: None,
2523            hour_has_error: None,
2524            minute_has_error: None,
2525            cached_numbers: None,
2526            cached_locale: None,
2527        }
2528    }
2529}
2530
2531/// Dart's `_TimePickerInputState`.
2532struct TimePickerInputState {
2533    state: StateData<TimePickerInput>,
2534    restoration: RestorationMixinData,
2535    selected_time: Option<Ref<RestorableTimeOfDay>>,
2536    hour_has_error: Option<Ref<RestorableBool>>,
2537    minute_has_error: Option<Ref<RestorableBool>>,
2538    cached_numbers: Option<HashMap<String, i32>>,
2539    cached_locale: Option<Locale>,
2540}
2541
2542impl TimePickerInputState {
2543    fn selected_time(self: Handle<Self>, app: &App) -> Handle<RestorableTimeOfDay> {
2544        app.get(self)
2545            .selected_time
2546            .as_ref()
2547            .expect("init_state ran")
2548            .handle()
2549    }
2550
2551    fn hour_has_error(self: Handle<Self>, app: &App) -> Handle<RestorableBool> {
2552        app.get(self)
2553            .hour_has_error
2554            .as_ref()
2555            .expect("init_state ran")
2556            .handle()
2557    }
2558
2559    fn minute_has_error(self: Handle<Self>, app: &App) -> Handle<RestorableBool> {
2560        app.get(self)
2561            .minute_has_error
2562            .as_ref()
2563            .expect("init_state ran")
2564            .handle()
2565    }
2566
2567    fn selected_time_value(self: Handle<Self>, app: &App) -> TimeOfDay {
2568        *self.selected_time(app).value(app)
2569    }
2570
2571    fn parse_hour(self: Handle<Self>, app: &mut App, value: Option<&str>) -> Option<i32> {
2572        let value = value?;
2573        let mut new_hour = self.try_parse_localized_number(app, value)?;
2574
2575        let context = self.context(app);
2576        if TimePickerModel::hour_dial_type_of(app, context) != HourDialType::TwelveHour {
2577            if (0..24).contains(&new_hour) {
2578                return Some(new_hour);
2579            }
2580        } else if new_hour > 0 && new_hour < 13 {
2581            let period = self.selected_time_value(app).period();
2582            if (period == DayPeriod::Pm && new_hour != 12)
2583                || (period == DayPeriod::Am && new_hour == 12)
2584            {
2585                new_hour =
2586                    (new_hour + TimeOfDay::HOURS_PER_PERIOD).rem_euclid(TimeOfDay::HOURS_PER_DAY);
2587            }
2588            return Some(new_hour);
2589        }
2590        None
2591    }
2592
2593    fn parse_minute(self: Handle<Self>, app: &mut App, value: Option<&str>) -> Option<i32> {
2594        let value = value?;
2595        let new_minute = self.try_parse_localized_number(app, value)?;
2596
2597        if (0..60).contains(&new_minute) {
2598            return Some(new_minute);
2599        }
2600        None
2601    }
2602
2603    fn try_parse_localized_number(self: Handle<Self>, app: &mut App, number: &str) -> Option<i32> {
2604        if let Ok(parsed_number) = number.parse::<i32>() {
2605            return Some(parsed_number);
2606        }
2607
2608        if app.get(self).cached_numbers.is_none() {
2609            let numbers = self.generate_localized_numbers(app);
2610            app.get_mut(self).cached_numbers = Some(numbers);
2611        }
2612
2613        let trimmed_number = self.remove_leading_zeros(app, number);
2614
2615        app.get(self)
2616            .cached_numbers
2617            .as_ref()
2618            .and_then(|numbers| numbers.get(&trimmed_number).copied())
2619    }
2620
2621    fn generate_localized_numbers(self: Handle<Self>, app: &mut App) -> HashMap<String, i32> {
2622        let context = self.context(app);
2623        let localizations = <dyn MaterialLocalizations>::of(app, context);
2624
2625        // Supports 0 - 59.
2626        (0..60)
2627            .map(|i| (localizations.format_decimal(i64::from(i)), i))
2628            .collect()
2629    }
2630
2631    fn remove_leading_zeros(self: Handle<Self>, app: &mut App, value: &str) -> String {
2632        let context = self.context(app);
2633        let localized_zero = <dyn MaterialLocalizations>::of(app, context).format_decimal(0);
2634        let mut value = value;
2635        while value.starts_with(&localized_zero) && value.len() > localized_zero.len() {
2636            value = &value[localized_zero.len()..];
2637        }
2638        value.to_string()
2639    }
2640
2641    fn handle_hour_saved_submitted(self: Handle<Self>, app: &mut App, value: Option<&str>) {
2642        let new_hour = self.parse_hour(app, value);
2643        if let Some(new_hour) = new_hour {
2644            let minute = self.selected_time_value(app).minute;
2645            self.selected_time(app)
2646                .set_value(app, TimeOfDay::new(new_hour, minute));
2647            let context = self.context(app);
2648            let selected_time = self.selected_time_value(app);
2649            TimePickerModel::set_selected_time(app, context, selected_time);
2650            FocusScope::of(app, context, false).request_focus(app, None);
2651        }
2652    }
2653
2654    fn handle_hour_changed(self: Handle<Self>, app: &mut App, value: &str) {
2655        let new_hour = self.parse_hour(app, Some(value));
2656        if new_hour.is_some() && value.chars().count() == 2 {
2657            // If a valid hour is typed, move focus to the minute TextField.
2658            let context = self.context(app);
2659            FocusScope::of(app, context, false)
2660                .as_node()
2661                .next_focus(app);
2662        }
2663    }
2664
2665    fn handle_minute_saved_submitted(self: Handle<Self>, app: &mut App, value: Option<&str>) {
2666        let new_minute = self.parse_minute(app, value);
2667        if let Some(new_minute) = new_minute {
2668            let hour = self.selected_time_value(app).hour;
2669            self.selected_time(app)
2670                .set_value(app, TimeOfDay::new(hour, new_minute));
2671            let context = self.context(app);
2672            let selected_time = self.selected_time_value(app);
2673            TimePickerModel::set_selected_time(app, context, selected_time);
2674            FocusScope::of(app, context, false).unfocus(app, UnfocusDisposition::Scope);
2675        }
2676    }
2677
2678    fn handle_day_period_changed(self: Handle<Self>, app: &mut App, value: TimeOfDay) {
2679        self.selected_time(app).set_value(app, value);
2680        let context = self.context(app);
2681        TimePickerModel::set_selected_time(app, context, value);
2682    }
2683
2684    fn validate_hour(self: Handle<Self>, app: &mut App, value: Option<&str>) -> Option<String> {
2685        let new_hour = self.parse_hour(app, value);
2686        self.set_state(app, |_state| {});
2687        self.hour_has_error(app).set_value(app, new_hour.is_none());
2688        // This is used as the validator for the [TextFormField].
2689        // Returning an empty string allows the field to go into an error state.
2690        // Returning null means no error in the validation of the entered text.
2691        new_hour.is_none().then(String::new)
2692    }
2693
2694    fn validate_minute(self: Handle<Self>, app: &mut App, value: Option<&str>) -> Option<String> {
2695        let new_minute = self.parse_minute(app, value);
2696        self.set_state(app, |_state| {});
2697        self.minute_has_error(app)
2698            .set_value(app, new_minute.is_none());
2699        // This is used as the validator for the [TextFormField].
2700        // Returning an empty string allows the field to go into an error state.
2701        // Returning null means no error in the validation of the entered text.
2702        new_minute.is_none().then(String::new)
2703    }
2704}
2705
2706impl RestorationMixin for TimePickerInputState {
2707    waft_widgets::restoration_mixin_accessors!();
2708
2709    fn restoration_id(self: Handle<Self>, app: &App) -> Option<&str> {
2710        self.widget(app).restoration_id.as_deref()
2711    }
2712
2713    fn restore_state(
2714        self: Handle<Self>,
2715        app: &mut App,
2716        _old_bucket: Option<Handle<waft_widgets::RestorationBucket>>,
2717        _initial_restore: bool,
2718    ) {
2719        let selected_time = self.selected_time(app);
2720        let hour_has_error = self.hour_has_error(app);
2721        let minute_has_error = self.minute_has_error(app);
2722        self.register_for_restoration(app, selected_time.as_property(), "selected_time");
2723        self.register_for_restoration(app, hour_has_error.as_property(), "hour_has_error");
2724        self.register_for_restoration(app, minute_has_error.as_property(), "minute_has_error");
2725    }
2726}
2727
2728impl State for TimePickerInputState {
2729    type Widget = TimePickerInput;
2730    waft_widgets::state_accessors!();
2731
2732    fn init_state(self: Handle<Self>, app: &mut App) {
2733        let initial_selected_time = self.widget(app).initial_selected_time;
2734        let selected_time = RestorableTimeOfDay::new(app, initial_selected_time);
2735        let hour_has_error = RestorableBool::new(app, false);
2736        let minute_has_error = RestorableBool::new(app, false);
2737        let state = app.get_mut(self);
2738        state.selected_time = Some(selected_time);
2739        state.hour_has_error = Some(hour_has_error);
2740        state.minute_has_error = Some(minute_has_error);
2741    }
2742
2743    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
2744        self.did_change_dependencies_restoration(app);
2745        let context = self.context(app);
2746        let locale = Localizations::locale_of(app, context);
2747        if app.get(self).cached_locale.as_ref() != Some(&locale) {
2748            let state = app.get_mut(self);
2749            state.cached_numbers = None;
2750            state.cached_locale = Some(locale);
2751        }
2752    }
2753
2754    fn did_update_widget(self: Handle<Self>, app: &mut App, _old_widget: &TimePickerInput) {
2755        self.did_update_restoration_id(app);
2756    }
2757
2758    fn dispose(self: Handle<Self>, app: &mut App) {
2759        self.selected_time(app).dispose(app);
2760        self.hour_has_error(app).dispose(app);
2761        self.minute_has_error(app).dispose(app);
2762        self.dispose_restoration(app);
2763    }
2764
2765    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
2766        waft_widgets::debug_check_has_media_query(app, context);
2767        let localizations = <dyn MaterialLocalizations>::of(app, context);
2768        let time_of_day_format =
2769            localizations.time_of_day_format(TimePickerModel::use_24_hour_format_of(app, context));
2770        let use_24_hour_dials = hour_format(time_of_day_format) != HourFormat::h;
2771        let theme = Theme::of(app, context);
2772        let time_picker_theme = TimePickerModel::theme_of(app, context);
2773        let default_theme = TimePickerModel::default_theme_of(app, context);
2774        let hour_minute_style = time_picker_theme
2775            .hour_minute_text_style
2776            .clone()
2777            .unwrap_or_else(|| default_theme.hour_minute_text_style(app));
2778
2779        let min_interactive_vertical_padding = (2.0 * K_MIN_INTERACTIVE_DIMENSION
2780            - default_theme.day_period_input_size(app).height())
2781        .max(0.0);
2782
2783        let widget = self.widget(app).clone();
2784        let use_material3 = TimePickerModel::use_material3_of(app, context);
2785        let help_text_style = time_picker_theme
2786            .help_text_style
2787            .clone()
2788            .unwrap_or_else(|| default_theme.help_text_style(app))
2789            .value()
2790            .clone();
2791        let hour_has_error = *self.hour_has_error(app).value(app);
2792        let minute_has_error = *self.minute_has_error(app).value(app);
2793        let selected_time = self.selected_time_value(app);
2794        let day_period_control = move || {
2795            DayPeriodControl {
2796                on_period_changed: Some(Rc::new(move |app: &mut App, value: TimeOfDay| {
2797                    self.handle_day_period_changed(app, value);
2798                })),
2799            }
2800            .into_widget()
2801        };
2802
2803        let mut top_row_children: Vec<WidgetRef> = Vec::new();
2804        if !use_24_hour_dials && time_of_day_format == TimeOfDayFormat::a_space_h_colon_mm {
2805            top_row_children.push(
2806                Padding::new(EdgeInsetsDirectional::only(0.0, 0.0, 12.0, 0.0))
2807                    .child(day_period_control())
2808                    .into_widget(),
2809            );
2810        }
2811        let error_free = !hour_has_error && !minute_has_error;
2812        let label_text_style = theme.text_theme.body_small.clone();
2813        let hour_column = Column::new()
2814            .cross_axis_alignment(CrossAxisAlignment::Stretch)
2815            .children(
2816                [Padding::new(EdgeInsets::only(0.0, 0.0, 0.0, 10.0))
2817                    .child(HourTextField {
2818                        restoration_id: Some("hour_text_field".to_string()),
2819                        selected_time,
2820                        style: hour_minute_style.clone(),
2821                        autofocus: widget.autofocus_hour,
2822                        input_action: TextInputAction::Next,
2823                        validator: Rc::new(move |app, value| self.validate_hour(app, value)),
2824                        on_saved_submitted: Rc::new(move |app, value| {
2825                            self.handle_hour_saved_submitted(app, value);
2826                        }),
2827                        on_changed: Rc::new(move |app, value| self.handle_hour_changed(app, value)),
2828                        hour_label_text: widget.hour_label_text.clone(),
2829                        empty_initial_time: widget.empty_initial_time,
2830                    })
2831                    .into_widget()]
2832                .into_iter()
2833                .chain(error_free.then(|| {
2834                    let mut text = Text::new(
2835                        widget
2836                            .hour_label_text
2837                            .clone()
2838                            .unwrap_or_else(|| localizations.time_picker_hour_label()),
2839                    )
2840                    .max_lines(1)
2841                    .overflow(TextOverflow::Ellipsis);
2842                    if let Some(style) = label_text_style.clone() {
2843                        text = text.style(style);
2844                    }
2845                    ExcludeSemantics::new().child(text).into_widget()
2846                })),
2847            );
2848        let minute_column = Column::new()
2849            .cross_axis_alignment(CrossAxisAlignment::Stretch)
2850            .children(
2851                [Padding::new(EdgeInsets::only(0.0, 0.0, 0.0, 10.0))
2852                    .child(MinuteTextField {
2853                        restoration_id: Some("minute_text_field".to_string()),
2854                        selected_time,
2855                        style: hour_minute_style,
2856                        autofocus: widget.autofocus_minute,
2857                        input_action: TextInputAction::Done,
2858                        validator: Rc::new(move |app, value| self.validate_minute(app, value)),
2859                        on_saved_submitted: Rc::new(move |app, value| {
2860                            self.handle_minute_saved_submitted(app, value);
2861                        }),
2862                        minute_label_text: widget.minute_label_text.clone(),
2863                        empty_initial_time: widget.empty_initial_time,
2864                    })
2865                    .into_widget()]
2866                .into_iter()
2867                .chain(error_free.then(|| {
2868                    let mut text = Text::new(
2869                        widget
2870                            .minute_label_text
2871                            .clone()
2872                            .unwrap_or_else(|| localizations.time_picker_minute_label()),
2873                    )
2874                    .max_lines(1)
2875                    .overflow(TextOverflow::Ellipsis);
2876                    if let Some(style) = label_text_style.clone() {
2877                        text = text.style(style);
2878                    }
2879                    ExcludeSemantics::new().child(text).into_widget()
2880                })),
2881            );
2882        top_row_children.push(
2883            Expanded::new(
2884                Padding::new(EdgeInsetsDirectional::only(
2885                    0.0,
2886                    min_interactive_vertical_padding / 2.0,
2887                    0.0,
2888                    0.0,
2889                ))
2890                .child(
2891                    Row::new()
2892                        .cross_axis_alignment(CrossAxisAlignment::Start)
2893                        // Hour/minutes should not change positions in RTL locales.
2894                        .text_direction(waft_painting::TextDirection::Ltr)
2895                        .children([
2896                            Expanded::new(hour_column).into_widget(),
2897                            TimeSelectorSeparator { time_of_day_format }.into_widget(),
2898                            Expanded::new(minute_column).into_widget(),
2899                        ]),
2900                ),
2901            )
2902            .into_widget(),
2903        );
2904        if !use_24_hour_dials && time_of_day_format != TimeOfDayFormat::a_space_h_colon_mm {
2905            top_row_children.push(
2906                Padding::new(EdgeInsetsDirectional::only(12.0, 0.0, 0.0, 0.0))
2907                    .child(day_period_control())
2908                    .into_widget(),
2909            );
2910        }
2911
2912        Padding::new(if use_material3 {
2913            EdgeInsetsGeometry::from(EdgeInsets::ZERO)
2914        } else {
2915            EdgeInsets::symmetric(0.0, 16.0).into()
2916        })
2917        .child(
2918            Column::new()
2919                .cross_axis_alignment(CrossAxisAlignment::Start)
2920                .children([
2921                    Padding::new(EdgeInsetsDirectional::only(
2922                        0.0,
2923                        0.0,
2924                        0.0,
2925                        (if use_material3 { 20.0 } else { 24.0 })
2926                            - min_interactive_vertical_padding / 2.0,
2927                    ))
2928                    .child(Text::new(widget.help_text.clone()).style(help_text_style))
2929                    .into_widget(),
2930                    Row::new()
2931                        .cross_axis_alignment(CrossAxisAlignment::Start)
2932                        .children(top_row_children)
2933                        .into_widget(),
2934                    if hour_has_error || minute_has_error {
2935                        let mut error_style: TextStyle = theme
2936                            .text_theme
2937                            .body_medium
2938                            .clone()
2939                            .expect("the text theme has bodyMedium");
2940                        error_style = error_style.copy_with().color(theme.color_scheme.error());
2941                        Text::new(
2942                            widget
2943                                .error_invalid_text
2944                                .clone()
2945                                .unwrap_or_else(|| localizations.invalid_time_label()),
2946                        )
2947                        .style(error_style)
2948                        .into_widget()
2949                    } else {
2950                        SizedBox::new().height(2.0).into_widget()
2951                    },
2952                ]),
2953        )
2954        .into_widget()
2955    }
2956}
2957
2958type FormFieldValidator = Rc<dyn Fn(&mut App, Option<&str>) -> Option<String>>;
2959type SavedSubmitted = Rc<dyn Fn(&mut App, Option<&str>)>;
2960
2961/// Dart's `_HourTextField`.
2962struct HourTextField {
2963    selected_time: TimeOfDay,
2964    style: waft_painting::AnyTextStyle,
2965    autofocus: Option<bool>,
2966    input_action: TextInputAction,
2967    validator: FormFieldValidator,
2968    on_saved_submitted: SavedSubmitted,
2969    on_changed: StringChanged,
2970    hour_label_text: Option<String>,
2971    restoration_id: Option<String>,
2972    empty_initial_time: bool,
2973}
2974
2975impl std::fmt::Debug for HourTextField {
2976    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2977        f.debug_struct("HourTextField").finish_non_exhaustive()
2978    }
2979}
2980
2981impl StatelessWidget for HourTextField {
2982    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
2983        HourMinuteTextField {
2984            restoration_id: self.restoration_id.clone(),
2985            selected_time: self.selected_time,
2986            is_hour: true,
2987            autofocus: self.autofocus,
2988            input_action: self.input_action,
2989            style: self.style.clone(),
2990            semantic_hint_text: self.hour_label_text.clone().unwrap_or_else(|| {
2991                <dyn MaterialLocalizations>::of(app, context).time_picker_hour_label()
2992            }),
2993            validator: Rc::clone(&self.validator),
2994            on_saved_submitted: Rc::clone(&self.on_saved_submitted),
2995            empty_initial_time: self.empty_initial_time,
2996            on_changed: Some(Rc::clone(&self.on_changed)),
2997        }
2998        .into_widget()
2999    }
3000}
3001
3002/// Dart's `_MinuteTextField`.
3003struct MinuteTextField {
3004    selected_time: TimeOfDay,
3005    style: waft_painting::AnyTextStyle,
3006    autofocus: Option<bool>,
3007    input_action: TextInputAction,
3008    validator: FormFieldValidator,
3009    on_saved_submitted: SavedSubmitted,
3010    minute_label_text: Option<String>,
3011    restoration_id: Option<String>,
3012    empty_initial_time: bool,
3013}
3014
3015impl std::fmt::Debug for MinuteTextField {
3016    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3017        f.debug_struct("MinuteTextField").finish_non_exhaustive()
3018    }
3019}
3020
3021impl StatelessWidget for MinuteTextField {
3022    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
3023        HourMinuteTextField {
3024            restoration_id: self.restoration_id.clone(),
3025            selected_time: self.selected_time,
3026            is_hour: false,
3027            autofocus: self.autofocus,
3028            input_action: self.input_action,
3029            style: self.style.clone(),
3030            semantic_hint_text: self.minute_label_text.clone().unwrap_or_else(|| {
3031                <dyn MaterialLocalizations>::of(app, context).time_picker_minute_label()
3032            }),
3033            validator: Rc::clone(&self.validator),
3034            empty_initial_time: self.empty_initial_time,
3035            on_saved_submitted: Rc::clone(&self.on_saved_submitted),
3036            on_changed: None,
3037        }
3038        .into_widget()
3039    }
3040}
3041
3042/// Dart's `_HourMinuteTextField`.
3043#[derive(Clone)]
3044struct HourMinuteTextField {
3045    selected_time: TimeOfDay,
3046    is_hour: bool,
3047    autofocus: Option<bool>,
3048    input_action: TextInputAction,
3049    style: waft_painting::AnyTextStyle,
3050    semantic_hint_text: String,
3051    validator: FormFieldValidator,
3052    on_saved_submitted: SavedSubmitted,
3053    on_changed: Option<StringChanged>,
3054    restoration_id: Option<String>,
3055    empty_initial_time: bool,
3056}
3057
3058impl std::fmt::Debug for HourMinuteTextField {
3059    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3060        f.debug_struct("HourMinuteTextField")
3061            .finish_non_exhaustive()
3062    }
3063}
3064
3065impl StatefulWidget for HourMinuteTextField {
3066    type State = HourMinuteTextFieldState;
3067
3068    fn create_state(&self) -> HourMinuteTextFieldState {
3069        HourMinuteTextFieldState {
3070            state: StateData::new(),
3071            restoration: RestorationMixinData::new(),
3072            controller: None,
3073            controller_has_been_set: None,
3074            focus_node: None,
3075        }
3076    }
3077}
3078
3079/// Dart's `_HourMinuteTextFieldState`.
3080struct HourMinuteTextFieldState {
3081    state: StateData<HourMinuteTextField>,
3082    restoration: RestorationMixinData,
3083    controller: Option<Ref<RestorableTextEditingController>>,
3084    controller_has_been_set: Option<Ref<RestorableBool>>,
3085    focus_node: Option<Ref<FocusNode>>,
3086}
3087
3088impl HourMinuteTextFieldState {
3089    fn controller(self: Handle<Self>, app: &App) -> Handle<RestorableTextEditingController> {
3090        app.get(self)
3091            .controller
3092            .as_ref()
3093            .expect("init_state ran")
3094            .handle()
3095    }
3096
3097    fn controller_has_been_set(self: Handle<Self>, app: &App) -> Handle<RestorableBool> {
3098        app.get(self)
3099            .controller_has_been_set
3100            .as_ref()
3101            .expect("init_state ran")
3102            .handle()
3103    }
3104
3105    fn focus_node(self: Handle<Self>, app: &App) -> Handle<FocusNode> {
3106        app.get(self)
3107            .focus_node
3108            .as_ref()
3109            .expect("init_state ran")
3110            .handle()
3111    }
3112
3113    fn handle_focus_changed(self: Handle<Self>, app: &mut App) {
3114        // Rebuild when focus changes.
3115        self.set_state(app, |_state| {});
3116        if waft_foundation::K_IS_WEB && self.focus_node(app).has_focus(app) {
3117            let primary_focus_context = waft_widgets::primary_focus(app)
3118                .and_then(|primary_focus| primary_focus.context(app));
3119            if let Some(context) = primary_focus_context {
3120                waft_widgets::Actions::maybe_invoke(
3121                    app,
3122                    context,
3123                    &waft_widgets::SelectAllTextIntent::new(
3124                        waft_services::SelectionChangedCause::Keyboard,
3125                    ),
3126                );
3127            }
3128        }
3129    }
3130
3131    fn formatted_value(self: Handle<Self>, app: &mut App) -> String {
3132        let context = self.context(app);
3133        let always_use_24_hour_format = MediaQuery::always_use_24_hour_format_of(app, context);
3134        let localizations = <dyn MaterialLocalizations>::of(app, context);
3135        let widget = self.widget(app);
3136        if !widget.is_hour {
3137            localizations.format_minute(&widget.selected_time)
3138        } else {
3139            localizations.format_hour(&widget.selected_time, always_use_24_hour_format)
3140        }
3141    }
3142}
3143
3144impl RestorationMixin for HourMinuteTextFieldState {
3145    waft_widgets::restoration_mixin_accessors!();
3146
3147    fn restoration_id(self: Handle<Self>, app: &App) -> Option<&str> {
3148        self.widget(app).restoration_id.as_deref()
3149    }
3150
3151    fn restore_state(
3152        self: Handle<Self>,
3153        app: &mut App,
3154        _old_bucket: Option<Handle<waft_widgets::RestorationBucket>>,
3155        _initial_restore: bool,
3156    ) {
3157        let controller = self.controller(app);
3158        let controller_has_been_set = self.controller_has_been_set(app);
3159        self.register_for_restoration(app, controller.as_property(), "text_editing_controller");
3160        self.register_for_restoration(
3161            app,
3162            controller_has_been_set.as_property(),
3163            "has_controller_been_set",
3164        );
3165    }
3166}
3167
3168impl State for HourMinuteTextFieldState {
3169    type Widget = HourMinuteTextField;
3170    waft_widgets::state_accessors!();
3171
3172    fn init_state(self: Handle<Self>, app: &mut App) {
3173        let controller = RestorableTextEditingController::new(app);
3174        let controller_has_been_set = RestorableBool::new(app, false);
3175        let focus_node = FocusNode::new(app);
3176        focus_node.add_listener(
3177            app,
3178            Listener::handle_method(self, Self::handle_focus_changed),
3179        );
3180        let state = app.get_mut(self);
3181        state.controller = Some(controller);
3182        state.controller_has_been_set = Some(controller_has_been_set);
3183        state.focus_node = Some(focus_node);
3184    }
3185
3186    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
3187        self.did_change_dependencies_restoration(app);
3188        // Only set the text value if it has not been populated with a localized
3189        // version yet.
3190        // If emptyInitialTime is true, set it to an empty string to indicate no
3191        // initial time.
3192        if !*self.controller_has_been_set(app).value(app) {
3193            self.controller_has_been_set(app).set_value(app, true);
3194            let initial_text_value = if self.widget(app).empty_initial_time {
3195                String::new()
3196            } else {
3197                self.formatted_value(app)
3198            };
3199            let controller = self.controller(app).value(app).handle();
3200            controller.set_value(
3201                app,
3202                TextEditingValue {
3203                    text: initial_text_value,
3204                    ..TextEditingValue::default()
3205                },
3206            );
3207        }
3208    }
3209
3210    fn did_update_widget(self: Handle<Self>, app: &mut App, _old_widget: &HourMinuteTextField) {
3211        self.did_update_restoration_id(app);
3212    }
3213
3214    fn dispose(self: Handle<Self>, app: &mut App) {
3215        RestorableProperty::dispose(self.controller(app), app);
3216        self.controller_has_been_set(app).dispose(app);
3217        self.focus_node(app).dispose(app);
3218        self.dispose_restoration(app);
3219    }
3220
3221    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
3222        let theme = Theme::of(app, context);
3223        let time_picker_theme = TimePickerTheme::of(app, context);
3224        let default_theme: Rc<dyn TimePickerDefaults> = if theme.use_material3 {
3225            Rc::new(TimePickerDefaultsM3::new(
3226                context,
3227                crate::time_picker::TimePickerEntryMode::Dial,
3228            ))
3229        } else {
3230            Rc::new(TimePickerDefaultsM2::new(context))
3231        };
3232        let always_use_24_hour_format = MediaQuery::always_use_24_hour_format_of(app, context);
3233
3234        let input_decoration_theme = time_picker_theme
3235            .input_decoration_theme
3236            .clone()
3237            .unwrap_or_else(|| default_theme.input_decoration_theme(app));
3238        let mut decoration = InputDecoration::new();
3239        // Prevent the error text from appearing when
3240        // timePickerTheme.inputDecorationTheme is used.
3241        if let Some(error_style) = default_theme.input_decoration_theme(app).error_style {
3242            decoration = decoration.error_style(error_style);
3243        }
3244        let mut input_decoration = decoration.apply_defaults(input_decoration_theme);
3245        // Remove the hint text when focused because the centered cursor
3246        // appears odd above the hint text.
3247        // Clear the hint text when emptyInitialTime is true.
3248        let has_focus = self.focus_node(app).has_focus(app);
3249        let empty_initial_time = self.widget(app).empty_initial_time;
3250        let hint_text = if has_focus || empty_initial_time {
3251            None
3252        } else {
3253            Some(self.formatted_value(app))
3254        };
3255
3256        // Because the fill color is specified in both the inputDecorationTheme and
3257        // the TimePickerTheme, if there's one in the user's input decoration theme,
3258        // use that. If not, but there's one in the user's
3259        // timePickerTheme.hourMinuteColor, use that, and otherwise use the default.
3260        // We ignore the value in the fillColor of the input decoration in the
3261        // default theme here, but it's the same as the hourMinuteColor.
3262        let starting_fill_color = time_picker_theme
3263            .input_decoration_theme
3264            .as_ref()
3265            .and_then(|theme| theme.fill_color.clone())
3266            .or_else(|| time_picker_theme.hour_minute_color.clone())
3267            .unwrap_or_else(|| default_theme.hour_minute_color(app));
3268        let fill_color: AnyColor = if theme.use_material3 {
3269            let mut states = WidgetStates::new();
3270            if has_focus {
3271                states.insert(WidgetState::Focused);
3272                states.insert(WidgetState::Selected);
3273            }
3274            <dyn WidgetStateProperty<Color>>::resolve_as(&starting_fill_color, &states)
3275        } else if has_focus {
3276            Colors::TRANSPARENT.into()
3277        } else {
3278            starting_fill_color
3279        };
3280
3281        if let Some(hint_text) = hint_text {
3282            input_decoration = input_decoration.hint_text(hint_text);
3283        }
3284        input_decoration = input_decoration.fill_color(fill_color);
3285
3286        let mut states = WidgetStates::new();
3287        if has_focus {
3288            states.insert(WidgetState::Focused);
3289            states.insert(WidgetState::Selected);
3290        }
3291        let effective_text_color = <dyn WidgetStateProperty<Color>>::resolve_as(
3292            &time_picker_theme
3293                .hour_minute_text_color
3294                .clone()
3295                .unwrap_or_else(|| default_theme.hour_minute_text_color(app)),
3296            &states,
3297        );
3298        let widget = self.widget(app).clone();
3299        let effective_style =
3300            <dyn WidgetStateProperty<TextStyle>>::resolve_as(&widget.style, &states)
3301                .value()
3302                .copy_with()
3303                .color(effective_text_color.color());
3304
3305        let size = if always_use_24_hour_format {
3306            default_theme.hour_minute_input_size_24_hour(app)
3307        } else {
3308            default_theme.hour_minute_input_size(app)
3309        };
3310        let controller = self.controller(app).value(app).clone();
3311        let controller_ref = controller.erase();
3312        let on_saved_submitted = Rc::clone(&widget.on_saved_submitted);
3313        let on_editing_complete: Rc<dyn Fn(&mut App)> = {
3314            let on_saved_submitted = Rc::clone(&on_saved_submitted);
3315            Rc::new(move |app: &mut App| {
3316                let text = controller.value(app).text.clone();
3317                on_saved_submitted(app, Some(&text));
3318            })
3319        };
3320        let mut field = TextFormField::new()
3321            .restoration_id("hour_minute_text_form_field")
3322            .autofocus(widget.autofocus.unwrap_or(false))
3323            .expands(true)
3324            .max_lines(None)
3325            .input_formatters(vec![TextInputFormatterRef(Rc::new(
3326                LengthLimitingTextInputFormatter::new(Some(2)),
3327            ))])
3328            .focus_node(
3329                app.get(self)
3330                    .focus_node
3331                    .as_ref()
3332                    .expect("init_state ran")
3333                    .erase(),
3334            )
3335            .text_align(TextAlign::Center)
3336            .text_input_action(widget.input_action)
3337            .keyboard_type(TextInputType::NUMBER)
3338            .style(effective_style)
3339            .controller(controller_ref)
3340            .decoration(Some(input_decoration))
3341            .validator({
3342                let validator = Rc::clone(&widget.validator);
3343                move |app, value| validator(app, value.map(String::as_str))
3344            })
3345            .on_editing_complete(move |app| on_editing_complete(app))
3346            .on_saved({
3347                let on_saved_submitted = Rc::clone(&on_saved_submitted);
3348                move |app, value| on_saved_submitted(app, value.as_deref())
3349            })
3350            .on_field_submitted({
3351                let on_saved_submitted = Rc::clone(&on_saved_submitted);
3352                move |app, value| on_saved_submitted(app, Some(&value))
3353            });
3354        if let Some(on_changed) = widget.on_changed.clone() {
3355            field = field.on_changed(move |app, value| on_changed(app, &value));
3356        }
3357
3358        let restoration_bucket = self.bucket(app).and_then(|bucket| bucket.upgrade(app));
3359        SizedBox::new()
3360            .width(size.width())
3361            .height(size.height())
3362            .child(MediaQuery::with_no_text_scaling(
3363                None,
3364                UnmanagedRestorationScope::new(
3365                    Semantics::new()
3366                        .label(widget.semantic_hint_text.clone())
3367                        .child(field),
3368                )
3369                .bucket(restoration_bucket),
3370            ))
3371            .into_widget()
3372    }
3373}
3374
3375/// Dart's `EntryModeChangeCallback`: called when the user switches the entry mode of a time
3376/// picker.
3377pub type EntryModeChangeCallback =
3378    std::rc::Rc<dyn Fn(&mut waft_foundation::App, TimePickerEntryMode)>;
3379
3380const TIME_PICKER_ENTRY_MODES: [TimePickerEntryMode; 4] = [
3381    TimePickerEntryMode::Dial,
3382    TimePickerEntryMode::Input,
3383    TimePickerEntryMode::DialOnly,
3384    TimePickerEntryMode::InputOnly,
3385];
3386const AUTOVALIDATE_MODES: [AutovalidateMode; 4] = [
3387    AutovalidateMode::Disabled,
3388    AutovalidateMode::Always,
3389    AutovalidateMode::OnUserInteraction,
3390    AutovalidateMode::OnUnfocus,
3391];
3392const ORIENTATIONS: [Orientation; 2] = [Orientation::Portrait, Orientation::Landscape];
3393const HOUR_MINUTE_MODES: [HourMinuteMode; 2] = [HourMinuteMode::Hour, HourMinuteMode::Minute];
3394
3395/// A Material Design time picker designed to appear inside a popup dialog.
3396///
3397/// Pass this widget to [`ShowDialog`]. The value returned by
3398/// [`ShowDialog`] is the selected [`TimeOfDay`] if the user taps the "OK"
3399/// button, or null if the user taps the "CANCEL" button. The selected time is reported by
3400/// popping the navigator with the selected time.
3401///
3402/// Use [`ShowTimePicker`] to show the dialog.
3403#[derive(Clone)]
3404pub struct TimePickerDialog {
3405    pub key: Option<waft_widgets::KeyRef>,
3406
3407    /// The time initially selected when the dialog is shown.
3408    pub initial_time: TimeOfDay,
3409
3410    /// Optionally provide your own text for the cancel button.
3411    ///
3412    /// If null, the button uses [`MaterialLocalizations::cancel_button_label`].
3413    pub cancel_text: Option<String>,
3414
3415    /// Optionally provide your own text for the confirm button.
3416    ///
3417    /// If null, the button uses [`MaterialLocalizations::ok_button_label`].
3418    pub confirm_text: Option<String>,
3419
3420    /// Optionally provide your own help text to the header of the time picker.
3421    pub help_text: Option<String>,
3422
3423    /// Optionally provide your own validation error text.
3424    pub error_invalid_text: Option<String>,
3425
3426    /// Optionally provide your own hour label text.
3427    pub hour_label_text: Option<String>,
3428
3429    /// Optionally provide your own minute label text.
3430    pub minute_label_text: Option<String>,
3431
3432    /// Restoration ID to save and restore the state of the [`TimePickerDialog`].
3433    ///
3434    /// If it is non-null, the time picker will persist and restore the selected time and
3435    /// whether the dialog was in the dial or input entry mode.
3436    ///
3437    /// The state of this widget is persisted in a [`RestorationBucket`] claimed from
3438    /// the surrounding [`RestorationScope`] using the provided restoration ID.
3439    pub restoration_id: Option<String>,
3440
3441    /// The entry mode for the picker. Whether it's text input or a dial.
3442    pub initial_entry_mode: TimePickerEntryMode,
3443
3444    /// The optional [`orientation`](Self::orientation) parameter sets the
3445    /// [`Orientation`] to use when displaying the dialog.
3446    ///
3447    /// By default, the orientation is derived from the [`MediaQueryData::size`] of the ambient
3448    /// [`MediaQuery`]. If the aspect of the size is tall, then [`Orientation::Portrait`] is
3449    /// used, if the size is wide, then [`Orientation::Landscape`] is used.
3450    ///
3451    /// Use this parameter to override the default and force the dialog to appear in either
3452    /// portrait or landscape mode regardless of the aspect of the [`MediaQueryData::size`].
3453    pub orientation: Option<Orientation>,
3454
3455    /// Callback called when the selected entry mode is changed.
3456    pub on_entry_mode_changed: Option<EntryModeChangeCallback>,
3457
3458    /// Optionally provide your own icon for the icon button used to switch the mode to input.
3459    pub switch_to_input_entry_mode_icon: Option<WidgetRef>,
3460
3461    /// Optionally provide your own icon for the icon button used to switch the mode to dial.
3462    pub switch_to_timer_entry_mode_icon: Option<WidgetRef>,
3463
3464    /// Whether the input mode should start empty.
3465    ///
3466    /// If true, the hour and minute fields start empty and display hints for the expected
3467    /// values.
3468    pub empty_initial_input: bool,
3469}
3470
3471impl std::fmt::Debug for TimePickerDialog {
3472    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3473        f.debug_struct("TimePickerDialog")
3474            .field("initial_time", &self.initial_time)
3475            .field("initial_entry_mode", &self.initial_entry_mode)
3476            .finish_non_exhaustive()
3477    }
3478}
3479
3480impl TimePickerDialog {
3481    /// Creates a Material Design time picker.
3482    ///
3483    /// Dart's named arguments are the setters.
3484    pub fn new(initial_time: TimeOfDay) -> TimePickerDialog {
3485        TimePickerDialog {
3486            key: None,
3487            initial_time,
3488            cancel_text: None,
3489            confirm_text: None,
3490            help_text: None,
3491            error_invalid_text: None,
3492            hour_label_text: None,
3493            minute_label_text: None,
3494            restoration_id: None,
3495            initial_entry_mode: TimePickerEntryMode::Dial,
3496            orientation: None,
3497            on_entry_mode_changed: None,
3498            switch_to_input_entry_mode_icon: None,
3499            switch_to_timer_entry_mode_icon: None,
3500            empty_initial_input: false,
3501        }
3502    }
3503
3504    /// Dart `TimePickerDialog(key:)`.
3505    pub fn key(mut self, key: waft_widgets::KeyRef) -> TimePickerDialog {
3506        self.key = Some(key);
3507        self
3508    }
3509
3510    /// Dart `TimePickerDialog(cancelText:)`.
3511    pub fn cancel_text(mut self, cancel_text: impl Into<String>) -> TimePickerDialog {
3512        self.cancel_text = Some(cancel_text.into());
3513        self
3514    }
3515
3516    /// Dart `TimePickerDialog(confirmText:)`.
3517    pub fn confirm_text(mut self, confirm_text: impl Into<String>) -> TimePickerDialog {
3518        self.confirm_text = Some(confirm_text.into());
3519        self
3520    }
3521
3522    /// Dart `TimePickerDialog(helpText:)`.
3523    pub fn help_text(mut self, help_text: impl Into<String>) -> TimePickerDialog {
3524        self.help_text = Some(help_text.into());
3525        self
3526    }
3527
3528    /// Dart `TimePickerDialog(errorInvalidText:)`.
3529    pub fn error_invalid_text(mut self, error_invalid_text: impl Into<String>) -> TimePickerDialog {
3530        self.error_invalid_text = Some(error_invalid_text.into());
3531        self
3532    }
3533
3534    /// Dart `TimePickerDialog(hourLabelText:)`.
3535    pub fn hour_label_text(mut self, hour_label_text: impl Into<String>) -> TimePickerDialog {
3536        self.hour_label_text = Some(hour_label_text.into());
3537        self
3538    }
3539
3540    /// Dart `TimePickerDialog(minuteLabelText:)`.
3541    pub fn minute_label_text(mut self, minute_label_text: impl Into<String>) -> TimePickerDialog {
3542        self.minute_label_text = Some(minute_label_text.into());
3543        self
3544    }
3545
3546    /// Dart `TimePickerDialog(restorationId:)`.
3547    pub fn restoration_id(mut self, restoration_id: impl Into<String>) -> TimePickerDialog {
3548        self.restoration_id = Some(restoration_id.into());
3549        self
3550    }
3551
3552    /// Dart `TimePickerDialog(initialEntryMode:)`.
3553    pub fn initial_entry_mode(
3554        mut self,
3555        initial_entry_mode: TimePickerEntryMode,
3556    ) -> TimePickerDialog {
3557        self.initial_entry_mode = initial_entry_mode;
3558        self
3559    }
3560
3561    /// Dart `TimePickerDialog(orientation:)`.
3562    pub fn orientation(mut self, orientation: Orientation) -> TimePickerDialog {
3563        self.orientation = Some(orientation);
3564        self
3565    }
3566
3567    /// Dart `TimePickerDialog(onEntryModeChanged:)`.
3568    pub fn on_entry_mode_changed(
3569        mut self,
3570        on_entry_mode_changed: EntryModeChangeCallback,
3571    ) -> TimePickerDialog {
3572        self.on_entry_mode_changed = Some(on_entry_mode_changed);
3573        self
3574    }
3575
3576    /// Dart `TimePickerDialog(switchToInputEntryModeIcon:)`.
3577    #[cfg_attr(debug_assertions, track_caller)]
3578    pub fn switch_to_input_entry_mode_icon(mut self, icon: Icon) -> TimePickerDialog {
3579        self.switch_to_input_entry_mode_icon = Some(icon.into_widget());
3580        self
3581    }
3582
3583    /// Dart `TimePickerDialog(switchToTimerEntryModeIcon:)`.
3584    #[cfg_attr(debug_assertions, track_caller)]
3585    pub fn switch_to_timer_entry_mode_icon(mut self, icon: Icon) -> TimePickerDialog {
3586        self.switch_to_timer_entry_mode_icon = Some(icon.into_widget());
3587        self
3588    }
3589
3590    /// Dart `TimePickerDialog(emptyInitialInput:)`.
3591    pub fn empty_initial_input(mut self, empty_initial_input: bool) -> TimePickerDialog {
3592        self.empty_initial_input = empty_initial_input;
3593        self
3594    }
3595}
3596
3597impl StatefulWidget for TimePickerDialog {
3598    type State = TimePickerDialogState;
3599
3600    fn key(&self) -> Option<&waft_widgets::KeyRef> {
3601        self.key.as_ref()
3602    }
3603
3604    fn create_state(&self) -> TimePickerDialogState {
3605        TimePickerDialogState {
3606            state: StateData::new(),
3607            restoration: RestorationMixinData::new(),
3608            entry_mode: None,
3609            selected_time: None,
3610            form_key: GlobalKey::new(),
3611            autovalidate_mode: None,
3612            orientation: None,
3613        }
3614    }
3615}
3616
3617/// Dart's `_TimePickerDialogState`.
3618pub struct TimePickerDialogState {
3619    state: StateData<TimePickerDialog>,
3620    restoration: RestorationMixinData,
3621    entry_mode: Option<Ref<RestorableEnum<TimePickerEntryMode>>>,
3622    selected_time: Option<Ref<RestorableTimeOfDay>>,
3623    form_key: GlobalKey,
3624    autovalidate_mode: Option<Ref<RestorableEnum<AutovalidateMode>>>,
3625    orientation: Option<Ref<RestorableEnumN<Orientation>>>,
3626}
3627
3628impl TimePickerDialogState {
3629    // Base sizes
3630    const K_TIME_PICKER_PORTRAIT_SIZE: Size = Size::new(310.0, 468.0);
3631    const K_TIME_PICKER_LANDSCAPE_SIZE: Size = Size::new(524.0, 342.0);
3632    const K_TIME_PICKER_LANDSCAPE_SIZE_M2: Size = Size::new(508.0, 300.0);
3633    const K_TIME_PICKER_INPUT_SIZE: Size = Size::new(312.0, 252.0);
3634    const K_TIME_PICKER_INPUT_MINIMUM_HEIGHT: f64 = 216.0;
3635
3636    // Absolute minimum dialog sizes, which is the point at which it begins
3637    // scrolling to fit everything in.
3638    const K_TIME_PICKER_MIN_PORTRAIT_SIZE: Size = Size::new(238.0, 326.0);
3639    const K_TIME_PICKER_MIN_LANDSCAPE_SIZE: Size = Size::new(416.0, 248.0);
3640    const K_TIME_PICKER_MIN_INPUT_SIZE: Size = Size::new(312.0, 196.0);
3641
3642    fn entry_mode(self: Handle<Self>, app: &App) -> Handle<RestorableEnum<TimePickerEntryMode>> {
3643        app.get(self)
3644            .entry_mode
3645            .as_ref()
3646            .expect("init_state ran")
3647            .handle()
3648    }
3649
3650    fn selected_time(self: Handle<Self>, app: &App) -> Handle<RestorableTimeOfDay> {
3651        app.get(self)
3652            .selected_time
3653            .as_ref()
3654            .expect("init_state ran")
3655            .handle()
3656    }
3657
3658    fn autovalidate_mode(
3659        self: Handle<Self>,
3660        app: &App,
3661    ) -> Handle<RestorableEnum<AutovalidateMode>> {
3662        app.get(self)
3663            .autovalidate_mode
3664            .as_ref()
3665            .expect("init_state ran")
3666            .handle()
3667    }
3668
3669    fn orientation(self: Handle<Self>, app: &App) -> Handle<RestorableEnumN<Orientation>> {
3670        app.get(self)
3671            .orientation
3672            .as_ref()
3673            .expect("init_state ran")
3674            .handle()
3675    }
3676
3677    fn handle_time_changed(self: Handle<Self>, app: &mut App, value: TimeOfDay) {
3678        if value != *self.selected_time(app).value(app) {
3679            self.set_state(app, |_state| {});
3680            self.selected_time(app).set_value(app, value);
3681        }
3682    }
3683
3684    fn handle_entry_mode_changed(self: Handle<Self>, app: &mut App, value: TimePickerEntryMode) {
3685        if value != *self.entry_mode(app).value(app) {
3686            self.set_state(app, |_state| {});
3687            match *self.entry_mode(app).value(app) {
3688                TimePickerEntryMode::Dial => {
3689                    self.autovalidate_mode(app)
3690                        .set_value(app, AutovalidateMode::Disabled);
3691                }
3692                TimePickerEntryMode::Input => {
3693                    let form_key = app.get(self).form_key.clone();
3694                    form_key
3695                        .current_state::<FormState>(app)
3696                        .expect("the form is mounted")
3697                        .save(app);
3698                }
3699                TimePickerEntryMode::DialOnly | TimePickerEntryMode::InputOnly => {}
3700            }
3701            self.entry_mode(app).set_value(app, value);
3702            if let Some(on_entry_mode_changed) = self.widget(app).on_entry_mode_changed.clone() {
3703                on_entry_mode_changed(app, value);
3704            }
3705        }
3706    }
3707
3708    fn toggle_entry_mode(self: Handle<Self>, app: &mut App) {
3709        match *self.entry_mode(app).value(app) {
3710            TimePickerEntryMode::Dial => {
3711                self.handle_entry_mode_changed(app, TimePickerEntryMode::Input);
3712            }
3713            TimePickerEntryMode::Input => {
3714                self.handle_entry_mode_changed(app, TimePickerEntryMode::Dial);
3715            }
3716            TimePickerEntryMode::DialOnly | TimePickerEntryMode::InputOnly => {
3717                // Dart builds a `FlutterError` here and drops it without throwing.
3718            }
3719        }
3720    }
3721
3722    fn handle_cancel(self: Handle<Self>, app: &mut App) {
3723        let context = self.context(app);
3724        Navigator::pop(app, context, None);
3725    }
3726
3727    fn handle_ok(self: Handle<Self>, app: &mut App) {
3728        let entry_mode = *self.entry_mode(app).value(app);
3729        if entry_mode == TimePickerEntryMode::Input || entry_mode == TimePickerEntryMode::InputOnly
3730        {
3731            let form_key = app.get(self).form_key.clone();
3732            let form = form_key
3733                .current_state::<FormState>(app)
3734                .expect("the form is mounted");
3735            if !form.validate(app) {
3736                self.set_state(app, |_state| {});
3737                self.autovalidate_mode(app)
3738                    .set_value(app, AutovalidateMode::Always);
3739                return;
3740            }
3741            form.save(app);
3742        }
3743        let context = self.context(app);
3744        let selected_time = *self.selected_time(app).value(app);
3745        Navigator::pop(app, context, Some(Rc::new(selected_time)));
3746    }
3747
3748    fn effective_orientation(
3749        self: Handle<Self>,
3750        app: &mut App,
3751        context: BuildContext,
3752    ) -> Orientation {
3753        self.orientation(app)
3754            .value(app)
3755            .unwrap_or_else(|| MediaQuery::orientation_of(app, context))
3756    }
3757
3758    fn min_dialog_size(
3759        self: Handle<Self>,
3760        app: &mut App,
3761        context: BuildContext,
3762        use_material3: bool,
3763    ) -> Size {
3764        let orientation = self.effective_orientation(app, context);
3765
3766        match *self.entry_mode(app).value(app) {
3767            TimePickerEntryMode::Dial | TimePickerEntryMode::DialOnly => match orientation {
3768                Orientation::Portrait => Self::K_TIME_PICKER_MIN_PORTRAIT_SIZE,
3769                Orientation::Landscape => Self::K_TIME_PICKER_MIN_LANDSCAPE_SIZE,
3770            },
3771            TimePickerEntryMode::Input | TimePickerEntryMode::InputOnly => {
3772                let localizations = <dyn MaterialLocalizations>::of(app, context);
3773                let time_of_day_format = localizations
3774                    .time_of_day_format(MediaQuery::always_use_24_hour_format_of(app, context));
3775                let time_picker_width = match time_of_day_format {
3776                    TimeOfDayFormat::HH_colon_mm
3777                    | TimeOfDayFormat::HH_dot_mm
3778                    | TimeOfDayFormat::FrenchCanadian
3779                    | TimeOfDayFormat::H_colon_mm => {
3780                        let default_theme: Rc<dyn TimePickerDefaults> = if use_material3 {
3781                            Rc::new(TimePickerDefaultsM3::new(
3782                                context,
3783                                TimePickerEntryMode::Dial,
3784                            ))
3785                        } else {
3786                            Rc::new(TimePickerDefaultsM2::new(context))
3787                        };
3788                        Self::K_TIME_PICKER_MIN_INPUT_SIZE.width()
3789                            - default_theme.day_period_portrait_size(app).width()
3790                            - 12.0
3791                    }
3792                    TimeOfDayFormat::a_space_h_colon_mm | TimeOfDayFormat::h_colon_mm_space_a => {
3793                        Self::K_TIME_PICKER_MIN_INPUT_SIZE.width()
3794                            - if use_material3 { 32.0 } else { 0.0 }
3795                    }
3796                };
3797                Size::new(
3798                    time_picker_width,
3799                    Self::K_TIME_PICKER_MIN_INPUT_SIZE.height(),
3800                )
3801            }
3802        }
3803    }
3804
3805    fn dialog_size(
3806        self: Handle<Self>,
3807        app: &mut App,
3808        context: BuildContext,
3809        use_material3: bool,
3810    ) -> Size {
3811        let orientation = self.effective_orientation(app, context);
3812        // Constrain the textScaleFactor to prevent layout issues. Since only some
3813        // parts of the time picker scale up with textScaleFactor, we cap the factor
3814        // to 1.1 as that provides enough space to reasonably fit all the content.
3815        //
3816        // 14 is a common font size used to compute the effective text scale.
3817        const FONT_SIZE_TO_SCALE: f64 = 14.0;
3818        let text_scale_factor = MediaQuery::text_scaler_of(app, context)
3819            .clamp(0.0, 1.1)
3820            .scale(FONT_SIZE_TO_SCALE)
3821            / FONT_SIZE_TO_SCALE;
3822
3823        let time_picker_size = match *self.entry_mode(app).value(app) {
3824            TimePickerEntryMode::Dial | TimePickerEntryMode::DialOnly => match orientation {
3825                Orientation::Portrait => Self::K_TIME_PICKER_PORTRAIT_SIZE,
3826                Orientation::Landscape => Size::new(
3827                    Self::K_TIME_PICKER_LANDSCAPE_SIZE.width() * text_scale_factor,
3828                    if use_material3 {
3829                        Self::K_TIME_PICKER_LANDSCAPE_SIZE.height()
3830                    } else {
3831                        Self::K_TIME_PICKER_LANDSCAPE_SIZE_M2.height()
3832                    },
3833                ),
3834            },
3835            TimePickerEntryMode::Input | TimePickerEntryMode::InputOnly => {
3836                let localizations = <dyn MaterialLocalizations>::of(app, context);
3837                let time_of_day_format = localizations
3838                    .time_of_day_format(MediaQuery::always_use_24_hour_format_of(app, context));
3839                let time_picker_width = match time_of_day_format {
3840                    TimeOfDayFormat::HH_colon_mm
3841                    | TimeOfDayFormat::HH_dot_mm
3842                    | TimeOfDayFormat::FrenchCanadian
3843                    | TimeOfDayFormat::H_colon_mm => {
3844                        let default_theme: Rc<dyn TimePickerDefaults> = if use_material3 {
3845                            Rc::new(TimePickerDefaultsM3::new(
3846                                context,
3847                                TimePickerEntryMode::Dial,
3848                            ))
3849                        } else {
3850                            Rc::new(TimePickerDefaultsM2::new(context))
3851                        };
3852                        Self::K_TIME_PICKER_INPUT_SIZE.width()
3853                            - default_theme.day_period_portrait_size(app).width()
3854                            - 12.0
3855                    }
3856                    TimeOfDayFormat::a_space_h_colon_mm | TimeOfDayFormat::h_colon_mm_space_a => {
3857                        Self::K_TIME_PICKER_INPUT_SIZE.width()
3858                            - if use_material3 { 32.0 } else { 0.0 }
3859                    }
3860                };
3861                Size::new(time_picker_width, Self::K_TIME_PICKER_INPUT_SIZE.height())
3862            }
3863        };
3864        Size::new(
3865            time_picker_size.width(),
3866            time_picker_size.height() * text_scale_factor,
3867        )
3868    }
3869}
3870
3871impl RestorationMixin for TimePickerDialogState {
3872    waft_widgets::restoration_mixin_accessors!();
3873
3874    fn restoration_id(self: Handle<Self>, app: &App) -> Option<&str> {
3875        self.widget(app).restoration_id.as_deref()
3876    }
3877
3878    fn restore_state(
3879        self: Handle<Self>,
3880        app: &mut App,
3881        _old_bucket: Option<Handle<waft_widgets::RestorationBucket>>,
3882        _initial_restore: bool,
3883    ) {
3884        let (selected_time, entry_mode, autovalidate_mode, orientation) = (
3885            self.selected_time(app),
3886            self.entry_mode(app),
3887            self.autovalidate_mode(app),
3888            self.orientation(app),
3889        );
3890        self.register_for_restoration(app, selected_time.as_property(), "selected_time");
3891        self.register_for_restoration(app, entry_mode.as_property(), "entry_mode");
3892        self.register_for_restoration(app, autovalidate_mode.as_property(), "autovalidate_mode");
3893        self.register_for_restoration(app, orientation.as_property(), "orientation");
3894    }
3895}
3896
3897impl State for TimePickerDialogState {
3898    type Widget = TimePickerDialog;
3899    waft_widgets::state_accessors!();
3900
3901    fn init_state(self: Handle<Self>, app: &mut App) {
3902        let widget = self.widget(app).clone();
3903        let entry_mode =
3904            RestorableEnum::new(app, widget.initial_entry_mode, TIME_PICKER_ENTRY_MODES);
3905        let selected_time = RestorableTimeOfDay::new(app, widget.initial_time);
3906        let autovalidate_mode =
3907            RestorableEnum::new(app, AutovalidateMode::Disabled, AUTOVALIDATE_MODES);
3908        let orientation = RestorableEnumN::new(app, widget.orientation, ORIENTATIONS);
3909        let state = app.get_mut(self);
3910        state.entry_mode = Some(entry_mode);
3911        state.selected_time = Some(selected_time);
3912        state.autovalidate_mode = Some(autovalidate_mode);
3913        state.orientation = Some(orientation);
3914    }
3915
3916    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
3917        self.did_change_dependencies_restoration(app);
3918    }
3919
3920    fn did_update_widget(self: Handle<Self>, app: &mut App, _old_widget: &TimePickerDialog) {
3921        self.did_update_restoration_id(app);
3922    }
3923
3924    fn dispose(self: Handle<Self>, app: &mut App) {
3925        self.selected_time(app).dispose(app);
3926        self.entry_mode(app).dispose(app);
3927        self.autovalidate_mode(app).dispose(app);
3928        self.orientation(app).dispose(app);
3929        self.dispose_restoration(app);
3930    }
3931
3932    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
3933        waft_widgets::debug_check_has_media_query(app, context);
3934        let theme = Theme::of(app, context);
3935        let picker_theme = TimePickerTheme::of(app, context);
3936        let default_theme: Rc<dyn TimePickerDefaults> = if theme.use_material3 {
3937            Rc::new(TimePickerDefaultsM3::new(
3938                context,
3939                TimePickerEntryMode::Dial,
3940            ))
3941        } else {
3942            Rc::new(TimePickerDefaultsM2::new(context))
3943        };
3944        let shape = picker_theme
3945            .shape
3946            .clone()
3947            .unwrap_or_else(|| default_theme.shape(app));
3948        let entry_mode_icon_color = picker_theme
3949            .entry_mode_icon_color
3950            .clone()
3951            .unwrap_or_else(|| default_theme.entry_mode_icon_color(app))
3952            .color();
3953        let localizations = <dyn MaterialLocalizations>::of(app, context);
3954        let widget = self.widget(app).clone();
3955        let entry_mode = *self.entry_mode(app).value(app);
3956
3957        let mut action_children: Vec<WidgetRef> = Vec::new();
3958        if entry_mode == TimePickerEntryMode::Dial || entry_mode == TimePickerEntryMode::Input {
3959            let icon = if entry_mode == TimePickerEntryMode::Dial {
3960                widget
3961                    .switch_to_input_entry_mode_icon
3962                    .clone()
3963                    .unwrap_or_else(|| Icon::new(Some(Icons::keyboard_outlined())).into_widget())
3964            } else {
3965                widget
3966                    .switch_to_timer_entry_mode_icon
3967                    .clone()
3968                    .unwrap_or_else(|| Icon::new(Some(Icons::access_time())).into_widget())
3969            };
3970            let mut icon_button = IconButton::new(
3971                Some(Listener::new(move |app| self.toggle_entry_mode(app))),
3972                icon,
3973            )
3974            .tooltip(if entry_mode == TimePickerEntryMode::Dial {
3975                localizations.input_time_mode_button_label()
3976            } else {
3977                localizations.dial_mode_button_label()
3978            });
3979            // In material3 mode, we want to use the color as part of the
3980            // button style which applies its own opacity. In material2 mode,
3981            // we want to use the color as the color, which already includes
3982            // the opacity.
3983            if theme.use_material3 {
3984                icon_button = icon_button.style(
3985                    IconButton::style_from()
3986                        .foreground_color(entry_mode_icon_color)
3987                        .build(),
3988                );
3989            } else {
3990                icon_button = icon_button.color(entry_mode_icon_color);
3991            }
3992            action_children.push(icon_button.into_widget());
3993        }
3994        let cancel_button_style: ButtonStyle = picker_theme
3995            .cancel_button_style
3996            .clone()
3997            .unwrap_or_else(|| default_theme.cancel_button_style(app));
3998        let confirm_button_style: ButtonStyle = picker_theme
3999            .confirm_button_style
4000            .clone()
4001            .unwrap_or_else(|| default_theme.confirm_button_style(app));
4002        action_children.push(
4003            Expanded::new(
4004                ConstrainedBox::new(BoxConstraints {
4005                    min_height: 36.0,
4006                    ..BoxConstraints::new()
4007                })
4008                .child(
4009                    Align::new()
4010                        .alignment(AlignmentGeometry::from(AlignmentDirectional::CENTER_END))
4011                        .child(
4012                            OverflowBar::new()
4013                                .spacing(8.0)
4014                                .overflow_alignment(OverflowBarAlignment::End)
4015                                .children(vec![
4016                                    TextButton::new(
4017                                        Some(Listener::new(move |app| self.handle_cancel(app))),
4018                                        Some(Text::new(widget.cancel_text.clone().unwrap_or_else(
4019                                            || {
4020                                                if theme.use_material3 {
4021                                                    localizations.cancel_button_label()
4022                                                } else {
4023                                                    localizations
4024                                                        .cancel_button_label()
4025                                                        .to_uppercase()
4026                                                }
4027                                            },
4028                                        ))),
4029                                    )
4030                                    .style(cancel_button_style)
4031                                    .into_widget(),
4032                                    TextButton::new(
4033                                        Some(Listener::new(move |app| self.handle_ok(app))),
4034                                        Some(Text::new(
4035                                            widget
4036                                                .confirm_text
4037                                                .clone()
4038                                                .unwrap_or_else(|| localizations.ok_button_label()),
4039                                        )),
4040                                    )
4041                                    .style(confirm_button_style)
4042                                    .into_widget(),
4043                                ]),
4044                        ),
4045                ),
4046            )
4047            .into_widget(),
4048        );
4049        let actions = Padding::new(EdgeInsetsDirectional::only(
4050            if theme.use_material3 { 0.0 } else { 4.0 },
4051            0.0,
4052            0.0,
4053            0.0,
4054        ))
4055        .child(Row::new().children(action_children))
4056        .into_widget();
4057
4058        let tap_target_size_offset = match theme.material_tap_target_size {
4059            MaterialTapTargetSize::Padded => Offset::ZERO,
4060            // _dialogSize returns "padded" sizes.
4061            MaterialTapTargetSize::ShrinkWrap => Offset::new(0.0, -12.0),
4062        };
4063        let dialog_size =
4064            self.dialog_size(app, context, theme.use_material3) + tap_target_size_offset;
4065        let min_dialog_size =
4066            self.min_dialog_size(app, context, theme.use_material3) + tap_target_size_offset;
4067        let form_key = app.get(self).form_key.clone();
4068        let autovalidate_mode = *self.autovalidate_mode(app).value(app);
4069        let selected_initial_time = widget.initial_time;
4070        let padding: EdgeInsetsGeometry = picker_theme
4071            .padding
4072            .unwrap_or_else(|| default_theme.padding(app));
4073        let elevation = picker_theme
4074            .elevation
4075            .unwrap_or_else(|| default_theme.elevation(app));
4076        let background_color = picker_theme
4077            .background_color
4078            .clone()
4079            .unwrap_or_else(|| default_theme.background_color(app))
4080            .color();
4081
4082        Dialog::new()
4083            .shape(shape)
4084            .elevation(elevation)
4085            .background_color(background_color)
4086            .inset_padding(EdgeInsets::symmetric(
4087                if entry_mode == TimePickerEntryMode::Input
4088                    || entry_mode == TimePickerEntryMode::InputOnly
4089                {
4090                    0.0
4091                } else {
4092                    24.0
4093                },
4094                16.0,
4095            ))
4096            .child(
4097                Padding::new(padding).child(
4098                    LayoutBuilder::new(
4099                    move |_app, _context, constraints| {
4100                        let constrained_size = constraints.constraints().constrain(dialog_size);
4101                        let allowed_size = Size::new(
4102                            if constrained_size.width() < min_dialog_size.width() {
4103                                min_dialog_size.width()
4104                            } else {
4105                                constrained_size.width()
4106                            },
4107                            if constrained_size.height() < min_dialog_size.height() {
4108                                min_dialog_size.height()
4109                            } else {
4110                                constrained_size.height()
4111                            },
4112                        );
4113                        let form_key = form_key.clone();
4114                        let widget = widget.clone();
4115                        let actions = actions.clone();
4116                        SingleChildScrollView::new()
4117                            .restoration_id("time_picker_scroll_view_horizontal")
4118                            .scroll_direction(Axis::Horizontal)
4119                            .child(
4120                                SingleChildScrollView::new()
4121                                    .restoration_id("time_picker_scroll_view_vertical")
4122                                    .child(
4123                                        waft_widgets::AnimatedContainer::new(
4124                                            K_DIALOG_SIZE_ANIMATION_DURATION,
4125                                        )
4126                                        .width(allowed_size.width())
4127                                        .curve(waft_animation::Curves::ease_in())
4128                                        .constraints(BoxConstraints {
4129                                            min_height:
4130                                                TimePickerDialogState::K_TIME_PICKER_INPUT_MINIMUM_HEIGHT,
4131                                            max_height: allowed_size.height(),
4132                                            ..BoxConstraints::new()
4133                                        })
4134                                        .child(
4135                                            Column::new()
4136                                                .main_axis_size(MainAxisSize::Min)
4137                                                .main_axis_alignment(MainAxisAlignment::SpaceBetween)
4138                                                .cross_axis_alignment(CrossAxisAlignment::Start)
4139                                                .children([
4140                                                    Builder::new(move |_app, _context| {
4141                                                        let child = Form::new(
4142                                                            TimePicker {
4143                                                                time: selected_initial_time,
4144                                                                on_time_changed: Some(Rc::new(
4145                                                                    move |app, value| {
4146                                                                        self.handle_time_changed(
4147                                                                            app, value,
4148                                                                        );
4149                                                                    },
4150                                                                )),
4151                                                                help_text: widget.help_text.clone(),
4152                                                                cancel_text: widget
4153                                                                    .cancel_text
4154                                                                    .clone(),
4155                                                                confirm_text: widget
4156                                                                    .confirm_text
4157                                                                    .clone(),
4158                                                                error_invalid_text: widget
4159                                                                    .error_invalid_text
4160                                                                    .clone(),
4161                                                                hour_label_text: widget
4162                                                                    .hour_label_text
4163                                                                    .clone(),
4164                                                                minute_label_text: widget
4165                                                                    .minute_label_text
4166                                                                    .clone(),
4167                                                                restoration_id: Some(
4168                                                                    "time_picker".to_string(),
4169                                                                ),
4170                                                                entry_mode,
4171                                                                orientation: widget.orientation,
4172                                                                on_entry_mode_changed: Some(
4173                                                                    Rc::new(move |app, value| {
4174                                                                        self.handle_entry_mode_changed(
4175                                                                            app, value,
4176                                                                        );
4177                                                                    }),
4178                                                                ),
4179                                                                switch_to_input_entry_mode_icon:
4180                                                                    widget
4181                                                                        .switch_to_input_entry_mode_icon
4182                                                                        .clone(),
4183                                                                switch_to_timer_entry_mode_icon:
4184                                                                    widget
4185                                                                        .switch_to_timer_entry_mode_icon
4186                                                                        .clone(),
4187                                                                empty_initial_input: widget
4188                                                                    .empty_initial_input,
4189                                                            },
4190                                                        )
4191                                                        .key(form_key.clone().into())
4192                                                        .autovalidate_mode(autovalidate_mode)
4193                                                        .into_widget();
4194                                                        if entry_mode != TimePickerEntryMode::Input
4195                                                            && entry_mode
4196                                                                != TimePickerEntryMode::InputOnly
4197                                                        {
4198                                                            return Flexible::new(child).into_widget();
4199                                                        }
4200                                                        child
4201                                                    })
4202                                                    .into_widget(),
4203                                                    actions,
4204                                                ]),
4205                                        ),
4206                                    ),
4207                            )
4208                            .into_widget()
4209                    },
4210                )
4211                .into_widget(),
4212                ),
4213            )
4214            .into_widget()
4215    }
4216}
4217
4218/// Dart's `_TimePicker`.
4219#[derive(Clone)]
4220struct TimePicker {
4221    help_text: Option<String>,
4222    #[expect(dead_code, reason = "Dart's field, which only its constructor reads")]
4223    cancel_text: Option<String>,
4224    #[expect(dead_code, reason = "Dart's field, which only its constructor reads")]
4225    confirm_text: Option<String>,
4226    error_invalid_text: Option<String>,
4227    hour_label_text: Option<String>,
4228    minute_label_text: Option<String>,
4229    restoration_id: Option<String>,
4230    entry_mode: TimePickerEntryMode,
4231    time: TimeOfDay,
4232    on_time_changed: Option<SelectedTimeChanged>,
4233    orientation: Option<Orientation>,
4234    on_entry_mode_changed: Option<EntryModeChangeCallback>,
4235    #[expect(dead_code, reason = "Dart's field, which only its constructor reads")]
4236    switch_to_input_entry_mode_icon: Option<WidgetRef>,
4237    #[expect(dead_code, reason = "Dart's field, which only its constructor reads")]
4238    switch_to_timer_entry_mode_icon: Option<WidgetRef>,
4239    empty_initial_input: bool,
4240}
4241
4242impl std::fmt::Debug for TimePicker {
4243    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4244        f.debug_struct("TimePicker")
4245            .field("time", &self.time)
4246            .field("entry_mode", &self.entry_mode)
4247            .finish_non_exhaustive()
4248    }
4249}
4250
4251impl StatefulWidget for TimePicker {
4252    type State = TimePickerState;
4253
4254    fn create_state(&self) -> TimePickerState {
4255        TimePickerState {
4256            state: StateData::new(),
4257            restoration: RestorationMixinData::new(),
4258            vibrate_timer: None,
4259            localizations: None,
4260            hour_minute_mode: None,
4261            last_mode_announced: None,
4262            autofocus_hour: None,
4263            autofocus_minute: None,
4264            orientation: None,
4265            selected_time: None,
4266        }
4267    }
4268}
4269
4270/// Dart's `_TimePickerState`.
4271struct TimePickerState {
4272    state: StateData<TimePicker>,
4273    restoration: RestorationMixinData,
4274    vibrate_timer: Option<Timer>,
4275    localizations: Option<Rc<dyn MaterialLocalizations>>,
4276    hour_minute_mode: Option<Ref<RestorableEnum<HourMinuteMode>>>,
4277    last_mode_announced: Option<Ref<RestorableEnumN<HourMinuteMode>>>,
4278    autofocus_hour: Option<Ref<RestorableBoolN>>,
4279    autofocus_minute: Option<Ref<RestorableBoolN>>,
4280    orientation: Option<Ref<RestorableEnumN<Orientation>>>,
4281    selected_time: Option<Ref<RestorableTimeOfDay>>,
4282}
4283
4284impl TimePickerState {
4285    fn hour_minute_mode(self: Handle<Self>, app: &App) -> Handle<RestorableEnum<HourMinuteMode>> {
4286        app.get(self)
4287            .hour_minute_mode
4288            .as_ref()
4289            .expect("init_state ran")
4290            .handle()
4291    }
4292
4293    fn last_mode_announced(
4294        self: Handle<Self>,
4295        app: &App,
4296    ) -> Handle<RestorableEnumN<HourMinuteMode>> {
4297        app.get(self)
4298            .last_mode_announced
4299            .as_ref()
4300            .expect("init_state ran")
4301            .handle()
4302    }
4303
4304    fn autofocus_hour(self: Handle<Self>, app: &App) -> Handle<RestorableBoolN> {
4305        app.get(self)
4306            .autofocus_hour
4307            .as_ref()
4308            .expect("init_state ran")
4309            .handle()
4310    }
4311
4312    fn autofocus_minute(self: Handle<Self>, app: &App) -> Handle<RestorableBoolN> {
4313        app.get(self)
4314            .autofocus_minute
4315            .as_ref()
4316            .expect("init_state ran")
4317            .handle()
4318    }
4319
4320    fn orientation(self: Handle<Self>, app: &App) -> Handle<RestorableEnumN<Orientation>> {
4321        app.get(self)
4322            .orientation
4323            .as_ref()
4324            .expect("init_state ran")
4325            .handle()
4326    }
4327
4328    /// Dart's `selectedTime` getter: the restorable the dialog's tests read.
4329    fn selected_time(self: Handle<Self>, app: &App) -> Handle<RestorableTimeOfDay> {
4330        app.get(self)
4331            .selected_time
4332            .as_ref()
4333            .expect("init_state ran")
4334            .handle()
4335    }
4336
4337    fn set_entry_mode(self: Handle<Self>, app: &mut App, mode: TimePickerEntryMode) {
4338        if let Some(on_entry_mode_changed) = self.widget(app).on_entry_mode_changed.clone() {
4339            on_entry_mode_changed(app, mode);
4340        }
4341    }
4342
4343    fn vibrate(self: Handle<Self>, app: &mut App) {
4344        let context = self.context(app);
4345        match Theme::of(app, context).platform {
4346            TargetPlatform::Android
4347            | TargetPlatform::Fuchsia
4348            | TargetPlatform::Linux
4349            | TargetPlatform::Windows => {
4350                if let Some(timer) = app.get_mut(self).vibrate_timer.take() {
4351                    timer.cancel(app);
4352                }
4353                let timer = Timer::new(
4354                    app,
4355                    K_VIBRATE_COMMIT_DELAY,
4356                    Listener::new(move |app| {
4357                        HapticFeedback::vibrate(app);
4358                        app.get_mut(self).vibrate_timer = None;
4359                    }),
4360                );
4361                app.get_mut(self).vibrate_timer = Some(timer);
4362            }
4363            TargetPlatform::IOS | TargetPlatform::MacOS => {}
4364        }
4365    }
4366
4367    fn handle_hour_minute_mode_changed(self: Handle<Self>, app: &mut App, mode: HourMinuteMode) {
4368        self.vibrate(app);
4369        self.set_state(app, |_state| {});
4370        self.hour_minute_mode(app).set_value(app, mode);
4371    }
4372
4373    fn handle_entry_mode_toggle(self: Handle<Self>, app: &mut App) {
4374        self.set_state(app, |_state| {});
4375        let entry_mode = self.widget(app).entry_mode;
4376        let new_mode = match entry_mode {
4377            TimePickerEntryMode::Dial => TimePickerEntryMode::Input,
4378            TimePickerEntryMode::Input => {
4379                self.autofocus_hour(app).set_value(app, Some(false));
4380                self.autofocus_minute(app).set_value(app, Some(false));
4381                TimePickerEntryMode::Dial
4382            }
4383            TimePickerEntryMode::DialOnly | TimePickerEntryMode::InputOnly => {
4384                // Dart builds a `FlutterError` here and drops it without throwing.
4385                entry_mode
4386            }
4387        };
4388        self.set_entry_mode(app, new_mode);
4389    }
4390
4391    fn handle_time_changed(self: Handle<Self>, app: &mut App, value: TimeOfDay) {
4392        self.vibrate(app);
4393        self.set_state(app, |_state| {});
4394        self.selected_time(app).set_value(app, value);
4395        if let Some(on_time_changed) = self.widget(app).on_time_changed.clone() {
4396            on_time_changed(app, value);
4397        }
4398    }
4399
4400    fn handle_hour_double_tapped(self: Handle<Self>, app: &mut App) {
4401        self.autofocus_hour(app).set_value(app, Some(true));
4402        self.handle_entry_mode_toggle(app);
4403    }
4404
4405    fn handle_minute_double_tapped(self: Handle<Self>, app: &mut App) {
4406        self.autofocus_minute(app).set_value(app, Some(true));
4407        self.handle_entry_mode_toggle(app);
4408    }
4409
4410    fn handle_hour_selected(self: Handle<Self>, app: &mut App) {
4411        self.set_state(app, |_state| {});
4412        self.hour_minute_mode(app)
4413            .set_value(app, HourMinuteMode::Minute);
4414    }
4415}
4416
4417impl RestorationMixin for TimePickerState {
4418    waft_widgets::restoration_mixin_accessors!();
4419
4420    fn restoration_id(self: Handle<Self>, app: &App) -> Option<&str> {
4421        self.widget(app).restoration_id.as_deref()
4422    }
4423
4424    fn restore_state(
4425        self: Handle<Self>,
4426        app: &mut App,
4427        _old_bucket: Option<Handle<waft_widgets::RestorationBucket>>,
4428        _initial_restore: bool,
4429    ) {
4430        let (
4431            hour_minute_mode,
4432            last_mode_announced,
4433            autofocus_hour,
4434            autofocus_minute,
4435            selected_time,
4436            orientation,
4437        ) = (
4438            self.hour_minute_mode(app),
4439            self.last_mode_announced(app),
4440            self.autofocus_hour(app),
4441            self.autofocus_minute(app),
4442            self.selected_time(app),
4443            self.orientation(app),
4444        );
4445        self.register_for_restoration(app, hour_minute_mode.as_property(), "hour_minute_mode");
4446        self.register_for_restoration(
4447            app,
4448            last_mode_announced.as_property(),
4449            "last_mode_announced",
4450        );
4451        self.register_for_restoration(app, autofocus_hour.as_property(), "autofocus_hour");
4452        self.register_for_restoration(app, autofocus_minute.as_property(), "autofocus_minute");
4453        self.register_for_restoration(app, selected_time.as_property(), "selected_time");
4454        self.register_for_restoration(app, orientation.as_property(), "orientation");
4455    }
4456}
4457
4458impl State for TimePickerState {
4459    type Widget = TimePicker;
4460    waft_widgets::state_accessors!();
4461
4462    fn init_state(self: Handle<Self>, app: &mut App) {
4463        let (orientation, time) = {
4464            let widget = self.widget(app);
4465            (widget.orientation, widget.time)
4466        };
4467        let hour_minute_mode = RestorableEnum::new(app, HourMinuteMode::Hour, HOUR_MINUTE_MODES);
4468        let last_mode_announced = RestorableEnumN::new(app, None, HOUR_MINUTE_MODES);
4469        let autofocus_hour = RestorableBoolN::new(app, None);
4470        let autofocus_minute = RestorableBoolN::new(app, None);
4471        let orientation = RestorableEnumN::new(app, orientation, ORIENTATIONS);
4472        let selected_time = RestorableTimeOfDay::new(app, time);
4473        let state = app.get_mut(self);
4474        state.hour_minute_mode = Some(hour_minute_mode);
4475        state.last_mode_announced = Some(last_mode_announced);
4476        state.autofocus_hour = Some(autofocus_hour);
4477        state.autofocus_minute = Some(autofocus_minute);
4478        state.orientation = Some(orientation);
4479        state.selected_time = Some(selected_time);
4480    }
4481
4482    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
4483        self.did_change_dependencies_restoration(app);
4484        let context = self.context(app);
4485        let localizations = <dyn MaterialLocalizations>::of(app, context);
4486        app.get_mut(self).localizations = Some(localizations);
4487    }
4488
4489    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &TimePicker) {
4490        self.did_update_restoration_id(app);
4491        let (orientation, time) = {
4492            let widget = self.widget(app);
4493            (widget.orientation, widget.time)
4494        };
4495        if old_widget.orientation != orientation {
4496            self.orientation(app).set_value(app, orientation);
4497        }
4498        if old_widget.time != time {
4499            self.selected_time(app).set_value(app, time);
4500        }
4501    }
4502
4503    fn dispose(self: Handle<Self>, app: &mut App) {
4504        if let Some(timer) = app.get_mut(self).vibrate_timer.take() {
4505            timer.cancel(app);
4506        }
4507        self.orientation(app).dispose(app);
4508        self.selected_time(app).dispose(app);
4509        self.hour_minute_mode(app).dispose(app);
4510        self.last_mode_announced(app).dispose(app);
4511        self.autofocus_hour(app).dispose(app);
4512        self.autofocus_minute(app).dispose(app);
4513        self.dispose_restoration(app);
4514    }
4515
4516    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
4517        waft_widgets::debug_check_has_media_query(app, context);
4518        let localizations = Rc::clone(
4519            app.get(self)
4520                .localizations
4521                .as_ref()
4522                .expect("dependencies ran"),
4523        );
4524        let time_of_day_format = localizations
4525            .time_of_day_format(MediaQuery::always_use_24_hour_format_of(app, context));
4526        let theme = Theme::of(app, context);
4527        let widget = self.widget(app).clone();
4528        let default_theme: Rc<dyn TimePickerDefaults> = if theme.use_material3 {
4529            Rc::new(TimePickerDefaultsM3::new(context, widget.entry_mode))
4530        } else {
4531            Rc::new(TimePickerDefaultsM2::new(context))
4532        };
4533        let orientation = self
4534            .orientation(app)
4535            .value(app)
4536            .unwrap_or_else(|| MediaQuery::orientation_of(app, context));
4537        let time_of_day_hour = hour_format(time_of_day_format);
4538        let hour_mode = match time_of_day_hour {
4539            HourFormat::HH | HourFormat::H if theme.use_material3 => {
4540                HourDialType::TwentyFourHourDoubleRing
4541            }
4542            HourFormat::HH | HourFormat::H => HourDialType::TwentyFourHour,
4543            HourFormat::h => HourDialType::TwelveHour,
4544        };
4545
4546        let hour_minute_mode = *self.hour_minute_mode(app).value(app);
4547        let selected_time = *self.selected_time(app).value(app);
4548        let picker: WidgetRef = match widget.entry_mode {
4549            TimePickerEntryMode::Dial | TimePickerEntryMode::DialOnly => {
4550                let help_text = widget.help_text.clone().unwrap_or_else(|| {
4551                    if theme.use_material3 {
4552                        localizations.time_picker_dial_help_text()
4553                    } else {
4554                        localizations.time_picker_dial_help_text().to_uppercase()
4555                    }
4556                });
4557
4558                // The vertical adjustment used to make both AM/PM buttons accessible.
4559                // Because the period selector height is increased based on this value,
4560                // the dial padding has to be decreased of the same amount.
4561                let portrait_min_interactive_vertical_adjustment = (2.0
4562                    * K_MIN_INTERACTIVE_DIMENSION
4563                    - default_theme.day_period_portrait_size(app).height())
4564                .max(0.0);
4565                let dial_padding: EdgeInsetsGeometry = match orientation {
4566                    Orientation::Portrait => EdgeInsets::only(
4567                        12.0,
4568                        36.0 - portrait_min_interactive_vertical_adjustment / 2.0,
4569                        12.0,
4570                        0.0,
4571                    )
4572                    .into(),
4573                    Orientation::Landscape => {
4574                        EdgeInsetsDirectional::only(64.0, 0.0, 0.0, 0.0).into()
4575                    }
4576                };
4577
4578                let dial_size = default_theme.dial_size(app);
4579                let dial = Padding::new(dial_padding)
4580                    .child(
4581                        ExcludeSemantics::new().child(
4582                            SizedBox::new()
4583                                .width(dial_size.width())
4584                                .height(dial_size.height())
4585                                .child(AspectRatio::new(1.0).child(Dial {
4586                                    hour_minute_mode,
4587                                    hour_dial_type: hour_mode,
4588                                    selected_time,
4589                                    on_changed: Some(Rc::new(move |app, value| {
4590                                        self.handle_time_changed(app, value);
4591                                    })),
4592                                    on_hour_selected: Some(Rc::new(move |app| {
4593                                        self.handle_hour_selected(app);
4594                                    })),
4595                                })),
4596                        ),
4597                    )
4598                    .into_widget();
4599
4600                let horizontal = if theme.use_material3 { 0.0 } else { 16.0 };
4601                match orientation {
4602                    Orientation::Portrait => Column::new()
4603                        .main_axis_size(MainAxisSize::Min)
4604                        .cross_axis_alignment(CrossAxisAlignment::Stretch)
4605                        .children([
4606                            Padding::new(EdgeInsets::symmetric(0.0, horizontal))
4607                                .child(DialTimePickerHeader { help_text })
4608                                .into_widget(),
4609                            Expanded::new(
4610                                Column::new().main_axis_size(MainAxisSize::Min).children([
4611                                    // Dial grows and shrinks with the available space.
4612                                    Expanded::new(
4613                                        Padding::new(EdgeInsets::symmetric(0.0, horizontal))
4614                                            .child(dial),
4615                                    )
4616                                    .into_widget(),
4617                                ]),
4618                            )
4619                            .into_widget(),
4620                        ])
4621                        .into_widget(),
4622                    Orientation::Landscape => Column::new()
4623                        .children([Expanded::new(
4624                            Padding::new(EdgeInsets::symmetric(0.0, horizontal)).child(
4625                                Row::new()
4626                                    .cross_axis_alignment(CrossAxisAlignment::Stretch)
4627                                    .children([
4628                                        DialTimePickerHeader { help_text }.into_widget(),
4629                                        Expanded::new(dial).into_widget(),
4630                                    ]),
4631                            ),
4632                        )
4633                        .into_widget()])
4634                        .into_widget(),
4635                }
4636            }
4637            TimePickerEntryMode::Input | TimePickerEntryMode::InputOnly => {
4638                let help_text = widget.help_text.clone().unwrap_or_else(|| {
4639                    if theme.use_material3 {
4640                        localizations.time_picker_input_help_text()
4641                    } else {
4642                        localizations.time_picker_input_help_text().to_uppercase()
4643                    }
4644                });
4645
4646                Column::new()
4647                    .main_axis_size(MainAxisSize::Min)
4648                    .children([TimePickerInput {
4649                        initial_selected_time: selected_time,
4650                        error_invalid_text: widget.error_invalid_text.clone(),
4651                        hour_label_text: widget.hour_label_text.clone(),
4652                        minute_label_text: widget.minute_label_text.clone(),
4653                        help_text,
4654                        autofocus_hour: *self.autofocus_hour(app).value(app),
4655                        autofocus_minute: *self.autofocus_minute(app).value(app),
4656                        restoration_id: Some("time_picker_input".to_string()),
4657                        empty_initial_time: widget.empty_initial_input,
4658                    }
4659                    .into_widget()])
4660                    .into_widget()
4661            }
4662        };
4663        let theme_data = TimePickerTheme::of(app, context);
4664        TimePickerModel {
4665            entry_mode: widget.entry_mode,
4666            selected_time,
4667            hour_minute_mode,
4668            orientation,
4669            on_hour_minute_mode_changed: Rc::new(move |app, mode| {
4670                self.handle_hour_minute_mode_changed(app, mode);
4671            }),
4672            on_hour_double_tapped: Listener::new(move |app| self.handle_hour_double_tapped(app)),
4673            on_minute_double_tapped: Listener::new(move |app| {
4674                self.handle_minute_double_tapped(app);
4675            }),
4676            hour_dial_type: hour_mode,
4677            on_selected_time_changed: Rc::new(move |app, value| {
4678                self.handle_time_changed(app, value);
4679            }),
4680            use_material3: theme.use_material3,
4681            use_24_hour_format: MediaQuery::always_use_24_hour_format_of(app, context),
4682            theme: theme_data,
4683            default_theme,
4684            child: picker,
4685        }
4686        .into_widget()
4687    }
4688}
4689
4690/// Shows a dialog containing a Material Design time picker.
4691///
4692/// The returned future resolves when the dialog is dismissed: to the [`TimeOfDay`] the user
4693/// selected (inside the [`RouteResult`](waft_widgets::RouteResult)) if they tapped the "OK"
4694/// button, or to `None` if they dismissed the dialog or tapped "CANCEL".
4695///
4696/// The `builder` parameter can be used to wrap the dialog widget to add inherited widgets like
4697/// `Localizations.override`, `Directionality`, or `MediaQuery`.
4698///
4699/// The `initial_entry_mode` parameter can be used to determine the initial time entry
4700/// selection of the picker (either a clock dial or text input).
4701///
4702/// Optional strings for the `help_text`, `cancel_text`, `confirm_text`,
4703/// `error_invalid_text`, `hour_label_text` and `minute_label_text` allow you to override the
4704/// default text used for various parts of the dialog.
4705///
4706/// The `use_root_navigator` argument is used to determine whether to push the dialog to the
4707/// [`Navigator`](waft_widgets::Navigator) furthest from or nearest to the given `context`. By
4708/// default, `use_root_navigator` is true and the dialog route created by this method is pushed
4709/// to the root navigator.
4710///
4711/// The `orientation` parameter sets the [`Orientation`](waft_widgets::Orientation) to use
4712/// when displaying the dialog. By default the orientation is derived from the
4713/// [`MediaQueryData::size`](waft_widgets::MediaQueryData) of the ambient
4714/// [`MediaQuery`](waft_widgets::MediaQuery).
4715///
4716/// The `empty_initial_input` parameter starts the input mode with empty hour and minute fields.
4717pub struct ShowTimePicker {
4718    initial_time: TimeOfDay,
4719    builder: Option<waft_widgets::TransitionBuilder>,
4720    barrier_dismissible: bool,
4721    barrier_color: Option<waft_embedder::Color>,
4722    barrier_label: Option<String>,
4723    use_root_navigator: bool,
4724    initial_entry_mode: TimePickerEntryMode,
4725    cancel_text: Option<String>,
4726    confirm_text: Option<String>,
4727    help_text: Option<String>,
4728    error_invalid_text: Option<String>,
4729    hour_label_text: Option<String>,
4730    minute_label_text: Option<String>,
4731    route_settings: Option<waft_widgets::RouteSettingsRef>,
4732    on_entry_mode_changed: Option<EntryModeChangeCallback>,
4733    orientation: Option<waft_widgets::Orientation>,
4734    switch_to_input_entry_mode_icon: Option<waft_widgets::Icon>,
4735    switch_to_timer_entry_mode_icon: Option<waft_widgets::Icon>,
4736    empty_initial_input: bool,
4737}
4738
4739impl ShowTimePicker {
4740    /// Creates a builder for a Material time picker; Dart's `showTimePicker` required argument
4741    /// is the initial time, and every other argument is a setter.
4742    pub fn new(initial_time: TimeOfDay) -> ShowTimePicker {
4743        ShowTimePicker {
4744            initial_time,
4745            builder: None,
4746            barrier_dismissible: true,
4747            barrier_color: None,
4748            barrier_label: None,
4749            use_root_navigator: true,
4750            initial_entry_mode: TimePickerEntryMode::Dial,
4751            cancel_text: None,
4752            confirm_text: None,
4753            help_text: None,
4754            error_invalid_text: None,
4755            hour_label_text: None,
4756            minute_label_text: None,
4757            route_settings: None,
4758            on_entry_mode_changed: None,
4759            orientation: None,
4760            switch_to_input_entry_mode_icon: None,
4761            switch_to_timer_entry_mode_icon: None,
4762            empty_initial_input: false,
4763        }
4764    }
4765
4766    /// Wraps the dialog to add inherited widgets such as localizations, direction or media
4767    /// query.
4768    pub fn builder(mut self, builder: waft_widgets::TransitionBuilder) -> ShowTimePicker {
4769        self.builder = Some(builder);
4770        self
4771    }
4772
4773    /// Whether tapping on the barrier dismisses the dialog. Defaults to `true`.
4774    pub fn barrier_dismissible(mut self, barrier_dismissible: bool) -> ShowTimePicker {
4775        self.barrier_dismissible = barrier_dismissible;
4776        self
4777    }
4778
4779    /// The color of the modal barrier below the dialog.
4780    pub fn barrier_color(mut self, barrier_color: waft_embedder::Color) -> ShowTimePicker {
4781        self.barrier_color = Some(barrier_color);
4782        self
4783    }
4784
4785    /// The semantic label of the dialog's modal barrier.
4786    pub fn barrier_label(mut self, barrier_label: impl Into<String>) -> ShowTimePicker {
4787        self.barrier_label = Some(barrier_label.into());
4788        self
4789    }
4790
4791    /// Whether to push the dialog to the root navigator. Defaults to `true`.
4792    pub fn use_root_navigator(mut self, use_root_navigator: bool) -> ShowTimePicker {
4793        self.use_root_navigator = use_root_navigator;
4794        self
4795    }
4796
4797    /// The initial time entry selection: a clock dial or text input. Defaults to
4798    /// `TimePickerEntryMode::Dial`.
4799    pub fn initial_entry_mode(mut self, initial_entry_mode: TimePickerEntryMode) -> ShowTimePicker {
4800        self.initial_entry_mode = initial_entry_mode;
4801        self
4802    }
4803
4804    /// The text of the cancel button.
4805    pub fn cancel_text(mut self, cancel_text: impl Into<String>) -> ShowTimePicker {
4806        self.cancel_text = Some(cancel_text.into());
4807        self
4808    }
4809
4810    /// The text of the confirm button.
4811    pub fn confirm_text(mut self, confirm_text: impl Into<String>) -> ShowTimePicker {
4812        self.confirm_text = Some(confirm_text.into());
4813        self
4814    }
4815
4816    /// The text of the help label.
4817    pub fn help_text(mut self, help_text: impl Into<String>) -> ShowTimePicker {
4818        self.help_text = Some(help_text.into());
4819        self
4820    }
4821
4822    /// The text of the error for an invalid time.
4823    pub fn error_invalid_text(mut self, error_invalid_text: impl Into<String>) -> ShowTimePicker {
4824        self.error_invalid_text = Some(error_invalid_text.into());
4825        self
4826    }
4827
4828    /// The text of the hour field's label.
4829    pub fn hour_label_text(mut self, hour_label_text: impl Into<String>) -> ShowTimePicker {
4830        self.hour_label_text = Some(hour_label_text.into());
4831        self
4832    }
4833
4834    /// The text of the minute field's label.
4835    pub fn minute_label_text(mut self, minute_label_text: impl Into<String>) -> ShowTimePicker {
4836        self.minute_label_text = Some(minute_label_text.into());
4837        self
4838    }
4839
4840    /// The route settings passed to the dialog route.
4841    pub fn route_settings(
4842        mut self,
4843        route_settings: waft_widgets::RouteSettingsRef,
4844    ) -> ShowTimePicker {
4845        self.route_settings = Some(route_settings);
4846        self
4847    }
4848
4849    /// Called when the user changes the entry mode.
4850    pub fn on_entry_mode_changed(
4851        mut self,
4852        on_entry_mode_changed: EntryModeChangeCallback,
4853    ) -> ShowTimePicker {
4854        self.on_entry_mode_changed = Some(on_entry_mode_changed);
4855        self
4856    }
4857
4858    /// The orientation of the dialog; defaults to the ambient media query's.
4859    pub fn orientation(mut self, orientation: waft_widgets::Orientation) -> ShowTimePicker {
4860        self.orientation = Some(orientation);
4861        self
4862    }
4863
4864    /// The icon that switches to the input entry mode.
4865    pub fn switch_to_input_entry_mode_icon(
4866        mut self,
4867        switch_to_input_entry_mode_icon: waft_widgets::Icon,
4868    ) -> ShowTimePicker {
4869        self.switch_to_input_entry_mode_icon = Some(switch_to_input_entry_mode_icon);
4870        self
4871    }
4872
4873    /// The icon that switches to the timer entry mode.
4874    pub fn switch_to_timer_entry_mode_icon(
4875        mut self,
4876        switch_to_timer_entry_mode_icon: waft_widgets::Icon,
4877    ) -> ShowTimePicker {
4878        self.switch_to_timer_entry_mode_icon = Some(switch_to_timer_entry_mode_icon);
4879        self
4880    }
4881
4882    /// Starts the input mode with empty hour and minute fields.
4883    pub fn empty_initial_input(mut self, empty_initial_input: bool) -> ShowTimePicker {
4884        self.empty_initial_input = empty_initial_input;
4885        self
4886    }
4887
4888    /// Shows the dialog and returns a future that resolves when it is dismissed.
4889    pub fn show(
4890        self,
4891        app: &mut waft_foundation::App,
4892        context: waft_widgets::BuildContext,
4893    ) -> waft_foundation::CompleterFuture<waft_widgets::RouteResult> {
4894        let ShowTimePicker {
4895            initial_time,
4896            builder,
4897            barrier_dismissible,
4898            barrier_color,
4899            barrier_label,
4900            use_root_navigator,
4901            initial_entry_mode,
4902            cancel_text,
4903            confirm_text,
4904            help_text,
4905            error_invalid_text,
4906            hour_label_text,
4907            minute_label_text,
4908            route_settings,
4909            on_entry_mode_changed,
4910            orientation,
4911            switch_to_input_entry_mode_icon,
4912            switch_to_timer_entry_mode_icon,
4913            empty_initial_input,
4914        } = self;
4915
4916        debug_assert!(crate::debug::debug_check_has_material_localizations(
4917            app, context
4918        ));
4919
4920        let mut dialog = TimePickerDialog::new(initial_time)
4921            .initial_entry_mode(initial_entry_mode)
4922            .empty_initial_input(empty_initial_input);
4923        dialog.cancel_text = cancel_text;
4924        dialog.confirm_text = confirm_text;
4925        dialog.help_text = help_text;
4926        dialog.error_invalid_text = error_invalid_text;
4927        dialog.hour_label_text = hour_label_text;
4928        dialog.minute_label_text = minute_label_text;
4929        dialog.orientation = orientation;
4930        dialog.on_entry_mode_changed = on_entry_mode_changed;
4931        if let Some(icon) = switch_to_input_entry_mode_icon {
4932            dialog = dialog.switch_to_input_entry_mode_icon(icon);
4933        }
4934        if let Some(icon) = switch_to_timer_entry_mode_icon {
4935            dialog = dialog.switch_to_timer_entry_mode_icon(icon);
4936        }
4937        let dialog = waft_widgets::IntoWidget::into_widget(dialog);
4938        let mut show = ShowDialog::new(std::rc::Rc::new(move |app, context| match &builder {
4939            None => dialog.clone(),
4940            Some(builder) => builder(app, context, Some(&dialog)),
4941        }))
4942        .barrier_dismissible(barrier_dismissible)
4943        .use_root_navigator(use_root_navigator);
4944        if let Some(barrier_color) = barrier_color {
4945            show = show.barrier_color(barrier_color);
4946        }
4947        if let Some(barrier_label) = barrier_label {
4948            show = show.barrier_label(barrier_label);
4949        }
4950        if let Some(route_settings) = route_settings {
4951            show = show.route_settings(route_settings);
4952        }
4953        show.show(app, context)
4954    }
4955}
4956
4957/// Dart's `_TimePickerDefaults`: the defaults of a [`TimePickerThemeData`], each getter
4958/// non-null, with the sizes the theme does not expose. A getter reads the theme only when it is
4959/// asked, as Dart's do.
4960pub(crate) trait TimePickerDefaults {
4961    fn background_color(&self, app: &mut App) -> AnyColor;
4962    fn cancel_button_style(&self, app: &mut App) -> ButtonStyle;
4963    fn confirm_button_style(&self, app: &mut App) -> ButtonStyle;
4964    fn day_period_border_side(&self, app: &mut App) -> BorderSide;
4965    fn day_period_color(&self, app: &mut App) -> AnyColor;
4966    fn day_period_shape(&self, app: &mut App) -> OutlinedBorderRef;
4967    fn day_period_input_size(&self, app: &mut App) -> Size;
4968    fn day_period_landscape_size(&self, app: &mut App) -> Size;
4969    fn day_period_portrait_size(&self, app: &mut App) -> Size;
4970    fn day_period_text_color(&self, app: &mut App) -> AnyColor;
4971    fn day_period_text_style(&self, app: &mut App) -> AnyTextStyle;
4972    fn dial_background_color(&self, app: &mut App) -> AnyColor;
4973    fn dial_hand_color(&self, app: &mut App) -> AnyColor;
4974    fn dial_size(&self, app: &mut App) -> Size;
4975    fn hand_width(&self, app: &mut App) -> f64;
4976    fn dot_radius(&self, app: &mut App) -> f64;
4977    fn center_radius(&self, app: &mut App) -> f64;
4978    fn dial_text_color(&self, app: &mut App) -> AnyColor;
4979    fn dial_text_style(&self, app: &mut App) -> AnyTextStyle;
4980    fn elevation(&self, app: &mut App) -> f64;
4981    fn entry_mode_icon_color(&self, app: &mut App) -> AnyColor;
4982    fn help_text_style(&self, app: &mut App) -> AnyTextStyle;
4983    fn hour_minute_color(&self, app: &mut App) -> AnyColor;
4984    fn hour_minute_shape(&self, app: &mut App) -> ShapeBorderRef;
4985    fn hour_minute_size(&self, app: &mut App) -> Size;
4986    fn hour_minute_size_24_hour(&self, app: &mut App) -> Size;
4987    fn hour_minute_input_size(&self, app: &mut App) -> Size;
4988    fn hour_minute_input_size_24_hour(&self, app: &mut App) -> Size;
4989    fn hour_minute_text_color(&self, app: &mut App) -> AnyColor;
4990    fn hour_minute_text_style(&self, app: &mut App) -> AnyTextStyle;
4991    fn input_decoration_theme(&self, app: &mut App) -> InputDecorationThemeData;
4992    fn padding(&self, app: &mut App) -> EdgeInsetsGeometry;
4993    fn shape(&self, app: &mut App) -> ShapeBorderRef;
4994
4995    /// Dart's `TimePickerThemeData.timeSelectorSeparatorColor`, which only the M3 defaults set.
4996    fn time_selector_separator_color(
4997        &self,
4998        _app: &mut App,
4999    ) -> Option<WidgetStatePropertyRef<Option<Color>>> {
5000        None
5001    }
5002
5003    /// Dart's `TimePickerThemeData.timeSelectorSeparatorTextStyle`, which only the M3 defaults
5004    /// set.
5005    fn time_selector_separator_text_style(
5006        &self,
5007        _app: &mut App,
5008    ) -> Option<WidgetStatePropertyRef<Option<TextStyle>>> {
5009        None
5010    }
5011}
5012
5013pub(crate) fn state_color(callback: impl Fn(&WidgetStates) -> Color + 'static) -> AnyColor {
5014    AnyColor::from(WidgetStateColor::resolve_with(callback))
5015}
5016
5017/// Dart's `_TimePickerDefaultsM2`: the Material 2 values, which are not generated because the
5018/// spec is not expected to change.
5019struct TimePickerDefaultsM2 {
5020    context: DefaultsContext,
5021}
5022
5023#[allow(deprecated)]
5024impl TimePickerDefaultsM2 {
5025    fn new(context: BuildContext) -> TimePickerDefaultsM2 {
5026        TimePickerDefaultsM2 {
5027            context: DefaultsContext::new(context),
5028        }
5029    }
5030
5031    fn default_shape() -> RoundedRectangleBorder {
5032        RoundedRectangleBorder::new(BorderSide::NONE, BorderRadiusGeometry::circular(4.0))
5033    }
5034
5035    fn hour_minute_input_color(&self, app: &mut App) -> AnyColor {
5036        let on_surface = self.context.colors(app).on_surface();
5037        state_color(move |states| {
5038            if states.contains(&WidgetState::Selected) {
5039                Colors::TRANSPARENT
5040            } else {
5041                on_surface.with_opacity(0.12)
5042            }
5043        })
5044    }
5045}
5046
5047#[allow(deprecated)]
5048impl TimePickerDefaults for TimePickerDefaultsM2 {
5049    fn background_color(&self, app: &mut App) -> AnyColor {
5050        self.context.colors(app).surface().into()
5051    }
5052
5053    fn cancel_button_style(&self, _app: &mut App) -> ButtonStyle {
5054        TextButton::style_from().build()
5055    }
5056
5057    fn confirm_button_style(&self, _app: &mut App) -> ButtonStyle {
5058        TextButton::style_from().build()
5059    }
5060
5061    fn day_period_border_side(&self, app: &mut App) -> BorderSide {
5062        let colors = self.context.colors(app);
5063        BorderSide {
5064            color: Color::alpha_blend(colors.on_surface().with_opacity(0.38), colors.surface()),
5065            ..BorderSide::default()
5066        }
5067    }
5068
5069    fn day_period_color(&self, app: &mut App) -> AnyColor {
5070        let colors = self.context.colors(app);
5071        let (primary, is_dark) = (colors.primary(), colors.brightness() == Brightness::Dark);
5072        state_color(move |states| {
5073            if states.contains(&WidgetState::Selected) {
5074                return primary.with_opacity(if is_dark { 0.24 } else { 0.12 });
5075            }
5076            // The unselected day period should match the overall picker dialog color.
5077            // Making it transparent enables that without being redundant and allows
5078            // the optional elevation overlay for dark mode to be visible.
5079            Colors::TRANSPARENT
5080        })
5081    }
5082
5083    fn day_period_shape(&self, _app: &mut App) -> OutlinedBorderRef {
5084        OutlinedBorderRef::new(Self::default_shape())
5085    }
5086
5087    fn day_period_portrait_size(&self, _app: &mut App) -> Size {
5088        Size::new(52.0, 80.0)
5089    }
5090
5091    fn day_period_landscape_size(&self, _app: &mut App) -> Size {
5092        Size::new(0.0, 40.0)
5093    }
5094
5095    fn day_period_input_size(&self, _app: &mut App) -> Size {
5096        Size::new(52.0, 70.0)
5097    }
5098
5099    fn day_period_text_color(&self, app: &mut App) -> AnyColor {
5100        let colors = self.context.colors(app);
5101        let (primary, on_surface) = (colors.primary(), colors.on_surface());
5102        state_color(move |states| {
5103            if states.contains(&WidgetState::Selected) {
5104                primary
5105            } else {
5106                on_surface.with_opacity(0.60)
5107            }
5108        })
5109    }
5110
5111    fn day_period_text_style(&self, app: &mut App) -> AnyTextStyle {
5112        let color = self.day_period_text_color(app);
5113        self.context
5114            .text_theme(app)
5115            .title_medium
5116            .as_ref()
5117            .expect("the text theme has titleMedium")
5118            .copy_with()
5119            .color(color)
5120            .into()
5121    }
5122
5123    fn dial_background_color(&self, app: &mut App) -> AnyColor {
5124        let colors = self.context.colors(app);
5125        colors
5126            .on_surface()
5127            .with_opacity(if colors.brightness() == Brightness::Dark {
5128                0.12
5129            } else {
5130                0.08
5131            })
5132            .into()
5133    }
5134
5135    fn dial_hand_color(&self, app: &mut App) -> AnyColor {
5136        self.context.colors(app).primary().into()
5137    }
5138
5139    fn dial_size(&self, _app: &mut App) -> Size {
5140        Size::square(280.0)
5141    }
5142
5143    fn hand_width(&self, _app: &mut App) -> f64 {
5144        2.0
5145    }
5146
5147    fn dot_radius(&self, _app: &mut App) -> f64 {
5148        22.0
5149    }
5150
5151    fn center_radius(&self, _app: &mut App) -> f64 {
5152        4.0
5153    }
5154
5155    fn dial_text_color(&self, app: &mut App) -> AnyColor {
5156        let colors = self.context.colors(app);
5157        let (surface, on_surface) = (colors.surface(), colors.on_surface());
5158        state_color(move |states| {
5159            if states.contains(&WidgetState::Selected) {
5160                surface
5161            } else {
5162                on_surface
5163            }
5164        })
5165    }
5166
5167    fn dial_text_style(&self, app: &mut App) -> AnyTextStyle {
5168        self.context
5169            .text_theme(app)
5170            .body_large
5171            .clone()
5172            .expect("the text theme has bodyLarge")
5173            .into()
5174    }
5175
5176    fn elevation(&self, _app: &mut App) -> f64 {
5177        6.0
5178    }
5179
5180    fn entry_mode_icon_color(&self, app: &mut App) -> AnyColor {
5181        let colors = self.context.colors(app);
5182        colors
5183            .on_surface()
5184            .with_opacity(if colors.brightness() == Brightness::Dark {
5185                1.0
5186            } else {
5187                0.6
5188            })
5189            .into()
5190    }
5191
5192    fn help_text_style(&self, app: &mut App) -> AnyTextStyle {
5193        self.context
5194            .text_theme(app)
5195            .label_small
5196            .clone()
5197            .expect("the text theme has labelSmall")
5198            .into()
5199    }
5200
5201    fn hour_minute_color(&self, app: &mut App) -> AnyColor {
5202        let colors = self.context.colors(app);
5203        let (primary, on_surface, is_dark) = (
5204            colors.primary(),
5205            colors.on_surface(),
5206            colors.brightness() == Brightness::Dark,
5207        );
5208        state_color(move |states| {
5209            if states.contains(&WidgetState::Selected) {
5210                primary.with_opacity(if is_dark { 0.24 } else { 0.12 })
5211            } else {
5212                on_surface.with_opacity(0.12)
5213            }
5214        })
5215    }
5216
5217    fn hour_minute_shape(&self, _app: &mut App) -> ShapeBorderRef {
5218        ShapeBorderRef::new(Self::default_shape())
5219    }
5220
5221    fn hour_minute_size(&self, _app: &mut App) -> Size {
5222        Size::new(96.0, 80.0)
5223    }
5224
5225    fn hour_minute_size_24_hour(&self, _app: &mut App) -> Size {
5226        Size::new(114.0, 80.0)
5227    }
5228
5229    fn hour_minute_input_size(&self, _app: &mut App) -> Size {
5230        Size::new(96.0, 70.0)
5231    }
5232
5233    fn hour_minute_input_size_24_hour(&self, _app: &mut App) -> Size {
5234        Size::new(114.0, 70.0)
5235    }
5236
5237    fn hour_minute_text_color(&self, app: &mut App) -> AnyColor {
5238        let colors = self.context.colors(app);
5239        let (primary, on_surface) = (colors.primary(), colors.on_surface());
5240        state_color(move |states| {
5241            if states.contains(&WidgetState::Selected) {
5242                primary
5243            } else {
5244                on_surface
5245            }
5246        })
5247    }
5248
5249    fn hour_minute_text_style(&self, app: &mut App) -> AnyTextStyle {
5250        self.context
5251            .text_theme(app)
5252            .display_medium
5253            .clone()
5254            .expect("the text theme has displayMedium")
5255            .into()
5256    }
5257
5258    fn input_decoration_theme(&self, app: &mut App) -> InputDecorationThemeData {
5259        let fill_color = self.hour_minute_input_color(app);
5260        let hint_style = self
5261            .hour_minute_text_style(app)
5262            .value()
5263            .copy_with()
5264            .color(self.context.colors(app).on_surface().with_opacity(0.36));
5265        let colors = self.context.colors(app);
5266        let (error, primary) = (colors.error(), colors.primary());
5267        InputDecorationThemeData::new()
5268            .content_padding(EdgeInsetsGeometry::from(EdgeInsets::ZERO))
5269            .filled(true)
5270            .fill_color(fill_color)
5271            .focus_color(Colors::TRANSPARENT)
5272            .enabled_border(OutlineInputBorder::new().border_side(BorderSide {
5273                color: Colors::TRANSPARENT,
5274                ..BorderSide::default()
5275            }))
5276            .error_border(OutlineInputBorder::new().border_side(BorderSide {
5277                color: error,
5278                width: 2.0,
5279                ..BorderSide::default()
5280            }))
5281            .focused_border(OutlineInputBorder::new().border_side(BorderSide {
5282                color: primary,
5283                width: 2.0,
5284                ..BorderSide::default()
5285            }))
5286            .focused_error_border(OutlineInputBorder::new().border_side(BorderSide {
5287                color: error,
5288                width: 2.0,
5289                ..BorderSide::default()
5290            }))
5291            .hint_style(hint_style)
5292            // Prevent the error text from appearing.
5293            .error_style(TextStyle::new().font_size(0.0).height(1.0))
5294    }
5295
5296    fn padding(&self, _app: &mut App) -> EdgeInsetsGeometry {
5297        EdgeInsets::from_ltrb(8.0, 18.0, 8.0, 8.0).into()
5298    }
5299
5300    fn shape(&self, _app: &mut App) -> ShapeBorderRef {
5301        ShapeBorderRef::new(Self::default_shape())
5302    }
5303}
5304
5305#[cfg(test)]
5306pub(crate) mod tests {
5307    //! time_picker_test.dart.
5308
5309    use waft_widgets::testing::{
5310        TestPointer, WidgetTester, assert_f32_equals, assert_more_or_less_equals_within, find,
5311        test_widgets,
5312    };
5313
5314    use super::*;
5315    use crate::dialog::Dialog;
5316    use crate::material::Material;
5317    use crate::test_support::{PaintInspection, material_app};
5318    use crate::text_button::TextButton;
5319    use crate::theme_data::ThemeData;
5320    use crate::time::TimeOfDay;
5321    use crate::tooltip::tests::{m2, m3};
5322    use std::cell::{Cell, RefCell};
5323    use std::rc::Rc;
5324    use std::time::Duration;
5325    use waft_embedder::{Offset, Size, TargetPlatform};
5326    use waft_foundation::Listener;
5327    use waft_painting::{EdgeInsets, TextScaler, TextStyle};
5328    use waft_rendering::testing::{PaintCall, assert_paints};
5329    use waft_widgets::EditableText;
5330    use waft_widgets::{
5331        AnyElement, BuildContext, Builder, Icon, IntoWidget, MediaQuery, MediaQueryData,
5332        Orientation, SizedBox, Text,
5333    };
5334
5335    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
5336    enum MaterialType {
5337        Material2,
5338        Material3,
5339    }
5340
5341    const OK_STRING: &str = "OK";
5342    const AM_STRING: &str = "AM";
5343
5344    /// Dart's `mediaQueryBoilerplate` parameters.
5345    #[derive(Clone)]
5346    struct Boilerplate {
5347        always_use_24_hour_format: bool,
5348        initial_time: TimeOfDay,
5349        text_scaler: TextScaler,
5350        entry_mode: TimePickerEntryMode,
5351        help_text: Option<String>,
5352        hour_label_text: Option<String>,
5353        minute_label_text: Option<String>,
5354        error_invalid_text: Option<String>,
5355        accessible_navigation: bool,
5356        on_entry_mode_change: Option<EntryModeChangeCallback>,
5357        tap_button: bool,
5358        material_type: MaterialType,
5359        orientation: Option<Orientation>,
5360    }
5361
5362    impl Boilerplate {
5363        fn new(material_type: MaterialType) -> Boilerplate {
5364            Boilerplate {
5365                always_use_24_hour_format: false,
5366                initial_time: TimeOfDay::new(7, 0),
5367                text_scaler: TextScaler::NO_SCALING,
5368                entry_mode: TimePickerEntryMode::Dial,
5369                help_text: None,
5370                hour_label_text: None,
5371                minute_label_text: None,
5372                error_invalid_text: None,
5373                accessible_navigation: false,
5374                on_entry_mode_change: None,
5375                tap_button: true,
5376                material_type,
5377                orientation: None,
5378            }
5379        }
5380    }
5381
5382    /// Dart's `tester.view.physicalSize = size; tester.view.devicePixelRatio = 1`.
5383    fn size_view(tester: &WidgetTester, size: Size) {
5384        tester.view().set_physical_size(size);
5385        tester.view().set_device_pixel_ratio(1.0);
5386    }
5387
5388    fn theme_of(tester: &WidgetTester, material_type: MaterialType) -> ThemeData {
5389        match material_type {
5390            MaterialType::Material2 => m2(&tester.cell.borrow()),
5391            MaterialType::Material3 => m3(&tester.cell.borrow()),
5392        }
5393    }
5394
5395    /// Dart's `mediaQueryBoilerplate`: an app with a button that shows the time picker.
5396    fn media_query_boilerplate(tester: &mut WidgetTester, size: Size, boilerplate: Boilerplate) {
5397        let theme = theme_of(tester, boilerplate.material_type);
5398        let launcher = {
5399            let boilerplate = boilerplate.clone();
5400            Builder::new(move |_app, context| {
5401                let boilerplate = boilerplate.clone();
5402                TextButton::new(
5403                    Some(Listener::new(move |app| {
5404                        drop({
5405                            let mut show = ShowTimePicker::new(boilerplate.initial_time);
5406                            show = show.initial_entry_mode(boilerplate.entry_mode);
5407                            if let Some(value) = boilerplate.help_text.clone() {
5408                                show = show.help_text(value);
5409                            }
5410                            if let Some(value) = boilerplate.error_invalid_text.clone() {
5411                                show = show.error_invalid_text(value);
5412                            }
5413                            if let Some(value) = boilerplate.hour_label_text.clone() {
5414                                show = show.hour_label_text(value);
5415                            }
5416                            if let Some(value) = boilerplate.minute_label_text.clone() {
5417                                show = show.minute_label_text(value);
5418                            }
5419                            if let Some(value) = boilerplate.on_entry_mode_change.clone() {
5420                                show = show.on_entry_mode_changed(value);
5421                            }
5422                            if let Some(value) = boilerplate.orientation {
5423                                show = show.orientation(value);
5424                            }
5425                            show.show(app, context)
5426                        });
5427                    })),
5428                    Some(Text::new("X")),
5429                )
5430                .into_widget()
5431            })
5432        };
5433        let root = crate::app::MaterialApp::new()
5434            .theme(theme)
5435            .builder(move |_app, _context, child| {
5436                MediaQuery::new(
5437                    MediaQueryData::new()
5438                        .always_use_24_hour_format(boilerplate.always_use_24_hour_format)
5439                        .text_scaler(boilerplate.text_scaler.clone())
5440                        .accessible_navigation(boilerplate.accessible_navigation)
5441                        .size(size),
5442                    child.expect("a MaterialApp child").clone(),
5443                )
5444                .into_widget()
5445            })
5446            .home(launcher);
5447        let root = IntoWidget::into_widget(root);
5448        tester.pump_widget(root);
5449        if boilerplate.tap_button {
5450            tester.tap(find::text("X"));
5451        }
5452        tester.pump_and_settle();
5453    }
5454
5455    fn dialog_material_size(tester: &WidgetTester) -> Size {
5456        let material = tester.element(
5457            find::descendant(find::by_type::<Dialog>().at(0), find::by_type::<Material>()).first(),
5458        );
5459        tester.get_size(material)
5460    }
5461
5462    #[test]
5463    fn material2_dialog_size_dial_mode() {
5464        test_widgets(|tester| {
5465            const TIME_PICKER_PORTRAIT_SIZE: Size = Size::new(310.0, 468.0);
5466            const TIME_PICKER_LANDSCAPE_SIZE: Size = Size::new(524.0, 342.0);
5467            const TIME_PICKER_LANDSCAPE_SIZE_M2: Size = Size::new(508.0, 300.0);
5468            let padding = EdgeInsets::from_ltrb(8.0, 18.0, 8.0, 8.0);
5469
5470            // portrait
5471            let size = Size::new(800.0, 800.5);
5472            size_view(tester, size);
5473            media_query_boilerplate(tester, size, Boilerplate::new(MaterialType::Material2));
5474
5475            let width = TIME_PICKER_PORTRAIT_SIZE.width() + padding.horizontal();
5476            let height = TIME_PICKER_PORTRAIT_SIZE.height() + padding.vertical();
5477            assert_eq!(dialog_material_size(tester), Size::new(width, height));
5478
5479            tester.tap(find::text(OK_STRING)); // dismiss the dialog
5480            tester.pump_and_settle();
5481
5482            // landscape
5483            let size = Size::new(800.5, 800.0);
5484            size_view(tester, size);
5485            let mut boilerplate = Boilerplate::new(MaterialType::Material2);
5486            boilerplate.always_use_24_hour_format = true;
5487            media_query_boilerplate(tester, size, boilerplate);
5488
5489            let width = TIME_PICKER_LANDSCAPE_SIZE.width() + padding.horizontal();
5490            let height = TIME_PICKER_LANDSCAPE_SIZE_M2.height() + padding.vertical();
5491            assert_eq!(dialog_material_size(tester), Size::new(width, height));
5492        });
5493    }
5494
5495    fn material_dialog_default_size() -> Size {
5496        Size::new(800.0, 600.0)
5497    }
5498
5499    /// Dart's `startPicker`'s parameters.
5500    #[derive(Clone)]
5501    struct StartPicker {
5502        entry_mode: TimePickerEntryMode,
5503        material_type: MaterialType,
5504        empty_initial_input: bool,
5505        always_use_24_hour_format: Option<bool>,
5506    }
5507
5508    impl StartPicker {
5509        fn new(material_type: MaterialType) -> StartPicker {
5510            StartPicker {
5511                entry_mode: TimePickerEntryMode::Dial,
5512                material_type,
5513                empty_initial_input: false,
5514                always_use_24_hour_format: None,
5515            }
5516        }
5517    }
5518
5519    type PickerResult =
5520        Rc<RefCell<Option<waft_foundation::CompleterFuture<waft_widgets::RouteResult>>>>;
5521
5522    /// What the picker completed with, as Dart's `onChanged(await showTimePicker(...))` sees it.
5523    fn picked_time(result: &PickerResult) -> Option<TimeOfDay> {
5524        result
5525            .borrow()
5526            .as_ref()
5527            .and_then(|future| future.peek())
5528            .flatten()
5529            .and_then(|value| value.downcast_ref::<TimeOfDay>().copied())
5530    }
5531
5532    /// Dart's `startPicker`: an app with a button that shows the time picker at 7:00, which is
5533    /// tapped. Returns the center of the dial, if the picker shows one.
5534    fn start_picker(
5535        tester: &mut WidgetTester,
5536        result: &PickerResult,
5537        parameters: StartPicker,
5538    ) -> Option<Offset> {
5539        let theme = theme_of(tester, parameters.material_type);
5540        let result_slot = Rc::clone(result);
5541        let launcher = {
5542            let parameters = parameters.clone();
5543            Builder::new(move |_app, _context| {
5544                let parameters = parameters.clone();
5545                let result_slot = Rc::clone(&result_slot);
5546                Material::new()
5547                    .child(
5548                        waft_widgets::Center::new().child(Builder::new(move |_app, context| {
5549                            let parameters = parameters.clone();
5550                            let result_slot = Rc::clone(&result_slot);
5551                            crate::elevated_button::ElevatedButton::new(
5552                                Some(Listener::new(move |app| {
5553                                    let future = {
5554                                        let mut show = ShowTimePicker::new(TimeOfDay::new(7, 0));
5555                                        show = show.initial_entry_mode(parameters.entry_mode);
5556                                        show = show
5557                                            .empty_initial_input(parameters.empty_initial_input);
5558                                        show.show(app, context)
5559                                    };
5560                                    *result_slot.borrow_mut() = Some(future);
5561                                })),
5562                                Some(Text::new("X")),
5563                            )
5564                            .into_widget()
5565                        })),
5566                    )
5567                    .into_widget()
5568            })
5569        };
5570        let always_use_24_hour_format = parameters.always_use_24_hour_format;
5571        let mut app = crate::app::MaterialApp::new().theme(theme).home(launcher);
5572        if let Some(always_use_24_hour_format) = always_use_24_hour_format {
5573            app = app.builder(move |app, context, child| {
5574                MediaQuery::new(
5575                    MediaQuery::of(app, context)
5576                        .copy_with()
5577                        .always_use_24_hour_format(always_use_24_hour_format),
5578                    child.expect("a MaterialApp child").clone(),
5579                )
5580                .into_widget()
5581            });
5582        }
5583        tester.pump_widget(IntoWidget::into_widget(app));
5584        tester.tap(find::text("X"));
5585        tester.pump_and_settle_by(Duration::from_secs(1));
5586        (parameters.entry_mode == TimePickerEntryMode::Dial).then(|| {
5587            let dial = tester.element(find::by_type::<Dial>().at(0));
5588            tester.get_center(dial)
5589        })
5590    }
5591
5592    /// Dart's `finishPicker`.
5593    fn finish_picker(tester: &mut WidgetTester) {
5594        tester.tap(find::text(OK_STRING));
5595        tester.pump_and_settle_by(Duration::from_secs(1));
5596    }
5597
5598    fn pickers() -> [MaterialType; 2] {
5599        [MaterialType::Material2, MaterialType::Material3]
5600    }
5601
5602    /// Dart's `findDialPaint`: the `CustomPaint` under the private `_Dial`, which
5603    /// time_picker_theme_test also finds by the widget's type name.
5604    pub(crate) fn dial_paint(tester: &WidgetTester) -> AnyElement {
5605        tester.element(
5606            find::descendant(
5607                find::by_type::<Dial>().at(0),
5608                find::by_type::<waft_widgets::CustomPaint>(),
5609            )
5610            .first(),
5611        )
5612    }
5613
5614    /// Dart's `dialPainter.primaryLabels.first.painter.text.style` and
5615    /// `selectedLabels.first.painter.text.style`, which time_picker_theme_test reads through
5616    /// `dynamic`.
5617    pub(crate) fn dial_label_styles(tester: &WidgetTester) -> (TextStyle, TextStyle) {
5618        let painter = dial_painter(tester);
5619        let painter = painter.borrow();
5620        (
5621            painter
5622                .first_primary_label_style()
5623                .expect("a primary label"),
5624            painter
5625                .first_selected_label_style()
5626                .expect("a selected label"),
5627        )
5628    }
5629
5630    fn dial_painter(tester: &WidgetTester) -> Rc<RefCell<DialPainter>> {
5631        tester.widget(dial_paint(tester), |paint: &waft_widgets::CustomPaint| {
5632            let painter = paint.painter.as_ref().expect("the dial paints");
5633            Rc::clone(
5634                &painter
5635                    .as_any()
5636                    .downcast_ref::<SharedDialPainter>()
5637                    .expect("a dial painter")
5638                    .0,
5639            )
5640        })
5641    }
5642
5643    #[test]
5644    fn material3_dialog_size_dial_mode() {
5645        test_widgets(|tester| {
5646            const TIME_PICKER_PORTRAIT_SIZE: Size = Size::new(310.0, 468.0);
5647            const TIME_PICKER_LANDSCAPE_SIZE: Size = Size::new(524.0, 342.0);
5648            let padding = EdgeInsets::all(24.0);
5649
5650            // portrait
5651            let size = Size::new(800.0, 800.5);
5652            size_view(tester, size);
5653            media_query_boilerplate(tester, size, Boilerplate::new(MaterialType::Material3));
5654
5655            let width = TIME_PICKER_PORTRAIT_SIZE.width() + padding.horizontal();
5656            let height = TIME_PICKER_PORTRAIT_SIZE.height() + padding.vertical();
5657            assert_eq!(dialog_material_size(tester), Size::new(width, height));
5658
5659            tester.tap(find::text(OK_STRING)); // dismiss the dialog
5660            tester.pump_and_settle();
5661
5662            // landscape
5663            let size = Size::new(800.5, 800.0);
5664            size_view(tester, size);
5665            let mut boilerplate = Boilerplate::new(MaterialType::Material3);
5666            boilerplate.always_use_24_hour_format = true;
5667            media_query_boilerplate(tester, size, boilerplate);
5668
5669            let width = TIME_PICKER_LANDSCAPE_SIZE.width() + padding.horizontal();
5670            let height = TIME_PICKER_LANDSCAPE_SIZE.height() + padding.vertical();
5671            assert_eq!(dialog_material_size(tester), Size::new(width, height));
5672        });
5673    }
5674
5675    #[test]
5676    fn material2_dialog_size_input_mode() {
5677        test_widgets(|tester| {
5678            const TIME_PICKER_INPUT_SIZE: Size = Size::new(312.0, 252.0);
5679            const DAY_PERIOD_PORTRAIT_SIZE: Size = Size::new(52.0, 80.0);
5680            let padding = EdgeInsets::from_ltrb(8.0, 18.0, 8.0, 8.0);
5681            let height = TIME_PICKER_INPUT_SIZE.height() + padding.vertical();
5682
5683            let size = material_dialog_default_size();
5684            let mut boilerplate = Boilerplate::new(MaterialType::Material2);
5685            boilerplate.entry_mode = TimePickerEntryMode::Input;
5686            media_query_boilerplate(tester, size, boilerplate.clone());
5687
5688            let width = TIME_PICKER_INPUT_SIZE.width() + padding.horizontal();
5689            let dialog_size = dialog_material_size(tester);
5690            assert_eq!(dialog_size.width(), width);
5691            assert!(dialog_size.height() < height);
5692
5693            tester.tap(find::text(OK_STRING)); // dismiss the dialog
5694            tester.pump_and_settle();
5695
5696            boilerplate.always_use_24_hour_format = true;
5697            media_query_boilerplate(tester, size, boilerplate);
5698            let width = TIME_PICKER_INPUT_SIZE.width() - DAY_PERIOD_PORTRAIT_SIZE.width() - 12.0
5699                + padding.horizontal()
5700                + 16.0;
5701            let dialog_size = dialog_material_size(tester);
5702            assert_eq!(dialog_size.width(), width);
5703            assert!(dialog_size.height() < height);
5704        });
5705    }
5706
5707    #[test]
5708    fn material3_dialog_size_input_mode() {
5709        test_widgets(|tester| {
5710            const TIME_PICKER_MIN_INPUT_SIZE: Size = Size::new(312.0, 252.0);
5711            const DAY_PERIOD_PORTRAIT_SIZE: Size = Size::new(52.0, 80.0);
5712            let padding = EdgeInsets::all(24.0);
5713            let text_scale_factor = 1.0;
5714            let height =
5715                TIME_PICKER_MIN_INPUT_SIZE.height() * text_scale_factor + padding.vertical();
5716
5717            let size = material_dialog_default_size();
5718            let mut boilerplate = Boilerplate::new(MaterialType::Material3);
5719            boilerplate.entry_mode = TimePickerEntryMode::Input;
5720            media_query_boilerplate(tester, size, boilerplate.clone());
5721
5722            let width = TIME_PICKER_MIN_INPUT_SIZE.width() - 32.0 + padding.horizontal();
5723            let dialog_size = dialog_material_size(tester);
5724            assert_eq!(dialog_size.width(), width);
5725            assert!(dialog_size.height() < height);
5726
5727            tester.tap(find::text(OK_STRING)); // dismiss the dialog
5728            tester.pump_and_settle();
5729
5730            boilerplate.always_use_24_hour_format = true;
5731            media_query_boilerplate(tester, size, boilerplate);
5732            let width =
5733                TIME_PICKER_MIN_INPUT_SIZE.width() - DAY_PERIOD_PORTRAIT_SIZE.width() - 12.0
5734                    + padding.horizontal();
5735            let dialog_size = dialog_material_size(tester);
5736            assert_eq!(dialog_size.width(), width);
5737            assert!(dialog_size.height() < height);
5738        });
5739    }
5740
5741    #[test]
5742    fn material2_respects_media_query_data_always_use_24_hour_format_true() {
5743        test_widgets(|tester| {
5744            let size = material_dialog_default_size();
5745            let mut boilerplate = Boilerplate::new(MaterialType::Material2);
5746            boilerplate.always_use_24_hour_format = true;
5747            media_query_boilerplate(tester, size, boilerplate);
5748
5749            let labels_00_to_22: Vec<String> =
5750                (0..12).map(|index| format!("{:02}", index * 2)).collect();
5751            let painter = dial_painter(tester);
5752            assert_eq!(painter.borrow().primary_label_texts(), labels_00_to_22);
5753            assert_eq!(painter.borrow().selected_label_texts(), labels_00_to_22);
5754        });
5755    }
5756
5757    #[test]
5758    fn material3_respects_media_query_data_always_use_24_hour_format_true() {
5759        test_widgets(|tester| {
5760            let size = material_dialog_default_size();
5761            let mut boilerplate = Boilerplate::new(MaterialType::Material3);
5762            boilerplate.always_use_24_hour_format = true;
5763            media_query_boilerplate(tester, size, boilerplate);
5764
5765            let labels_00_to_23: Vec<String> = (0..24)
5766                .map(|index| {
5767                    if index == 0 {
5768                        "00".to_string()
5769                    } else {
5770                        index.to_string()
5771                    }
5772                })
5773                .collect();
5774            let inner_0_to_23: Vec<bool> = (0..24).map(|index| index >= 12).collect();
5775
5776            let painter = dial_painter(tester);
5777            assert_eq!(painter.borrow().primary_label_texts(), labels_00_to_23);
5778            assert_eq!(painter.borrow().primary_label_inner(), inner_0_to_23);
5779            assert_eq!(painter.borrow().selected_label_texts(), labels_00_to_23);
5780            assert_eq!(painter.borrow().selected_label_inner(), inner_0_to_23);
5781        });
5782    }
5783
5784    #[test]
5785    fn dial_tap_select_an_hour() {
5786        for material_type in pickers() {
5787            test_widgets(|tester| {
5788                let result: PickerResult = Rc::default();
5789                let mut center =
5790                    start_picker(tester, &result, StartPicker::new(material_type)).expect("a dial");
5791                tester.tap_at(Offset::new(center.dx(), center.dy() - 50.0), 1); // 12:00 AM
5792                finish_picker(tester);
5793                assert_eq!(picked_time(&result), Some(TimeOfDay::new(0, 0)));
5794
5795                center =
5796                    start_picker(tester, &result, StartPicker::new(material_type)).expect("a dial");
5797                tester.tap_at(Offset::new(center.dx() + 50.0, center.dy()), 1);
5798                finish_picker(tester);
5799                assert_eq!(picked_time(&result), Some(TimeOfDay::new(3, 0)));
5800
5801                center =
5802                    start_picker(tester, &result, StartPicker::new(material_type)).expect("a dial");
5803                tester.tap_at(Offset::new(center.dx(), center.dy() + 50.0), 1);
5804                finish_picker(tester);
5805                assert_eq!(picked_time(&result), Some(TimeOfDay::new(6, 0)));
5806
5807                center =
5808                    start_picker(tester, &result, StartPicker::new(material_type)).expect("a dial");
5809                tester.tap_at(Offset::new(center.dx(), center.dy() + 50.0), 1);
5810                tester.tap_at(Offset::new(center.dx() - 50.0, center.dy()), 1);
5811                finish_picker(tester);
5812                assert_eq!(picked_time(&result), Some(TimeOfDay::new(9, 0)));
5813            });
5814        }
5815    }
5816
5817    fn drag(tester: &mut WidgetTester, from: Offset, to: Offset) {
5818        let mut gesture = TestPointer::touch(1);
5819        tester.down(&mut gesture, from);
5820        tester.move_to(&mut gesture, to, true);
5821        tester.up(&gesture);
5822    }
5823
5824    #[test]
5825    fn dial_drag_select_an_hour() {
5826        for material_type in pickers() {
5827            test_widgets(|tester| {
5828                let result: PickerResult = Rc::default();
5829                let center =
5830                    start_picker(tester, &result, StartPicker::new(material_type)).expect("a dial");
5831                let hour0 = Offset::new(center.dx(), center.dy() - 50.0); // 12:00 AM
5832                let hour3 = Offset::new(center.dx() + 50.0, center.dy());
5833                let hour6 = Offset::new(center.dx(), center.dy() + 50.0);
5834                let hour9 = Offset::new(center.dx() - 50.0, center.dy());
5835
5836                drag(tester, hour3, hour0);
5837                finish_picker(tester);
5838                assert_eq!(picked_time(&result).map(|time| time.hour), Some(0));
5839
5840                assert_eq!(
5841                    start_picker(tester, &result, StartPicker::new(material_type)),
5842                    Some(center)
5843                );
5844                drag(tester, hour0, hour3);
5845                finish_picker(tester);
5846                assert_eq!(picked_time(&result).map(|time| time.hour), Some(3));
5847
5848                assert_eq!(
5849                    start_picker(tester, &result, StartPicker::new(material_type)),
5850                    Some(center)
5851                );
5852                drag(tester, hour3, hour6);
5853                finish_picker(tester);
5854                assert_eq!(picked_time(&result).map(|time| time.hour), Some(6));
5855
5856                assert_eq!(
5857                    start_picker(tester, &result, StartPicker::new(material_type)),
5858                    Some(center)
5859                );
5860                drag(tester, hour6, hour9);
5861                finish_picker(tester);
5862                assert_eq!(picked_time(&result).map(|time| time.hour), Some(9));
5863            });
5864        }
5865    }
5866
5867    #[test]
5868    fn dial_tap_select_switches_from_hour_to_minute() {
5869        for material_type in pickers() {
5870            test_widgets(|tester| {
5871                let result: PickerResult = Rc::default();
5872                let center =
5873                    start_picker(tester, &result, StartPicker::new(material_type)).expect("a dial");
5874                let hour6 = Offset::new(center.dx(), center.dy() + 50.0); // 6:00
5875                let min45 = Offset::new(center.dx() - 50.0, center.dy()); // 45 mins (or 9:00 hours)
5876
5877                tester.tap_at(hour6, 1);
5878                tester.pump_by(Duration::from_millis(50));
5879                tester.tap_at(min45, 1);
5880                finish_picker(tester);
5881                assert_eq!(picked_time(&result), Some(TimeOfDay::new(6, 45)));
5882            });
5883        }
5884    }
5885
5886    #[test]
5887    fn dial_drag_select_switches_from_hour_to_minute() {
5888        for material_type in pickers() {
5889            test_widgets(|tester| {
5890                let result: PickerResult = Rc::default();
5891                let center =
5892                    start_picker(tester, &result, StartPicker::new(material_type)).expect("a dial");
5893                let hour3 = Offset::new(center.dx() + 50.0, center.dy());
5894                let hour6 = Offset::new(center.dx(), center.dy() + 50.0);
5895                let hour9 = Offset::new(center.dx() - 50.0, center.dy());
5896
5897                drag(tester, hour6, hour9);
5898                tester.pump_by(Duration::from_millis(50));
5899                drag(tester, hour6, hour3);
5900                finish_picker(tester);
5901                assert_eq!(picked_time(&result), Some(TimeOfDay::new(9, 15)));
5902            });
5903        }
5904    }
5905
5906    #[test]
5907    fn dial_tap_select_rounds_down_to_nearest_5_minute_increment() {
5908        for material_type in pickers() {
5909            test_widgets(|tester| {
5910                let result: PickerResult = Rc::default();
5911                let center =
5912                    start_picker(tester, &result, StartPicker::new(material_type)).expect("a dial");
5913                let hour6 = Offset::new(center.dx(), center.dy() + 50.0); // 6:00
5914                let min46 = Offset::new(center.dx() - 50.0, center.dy() - 5.0); // 46 mins
5915
5916                tester.tap_at(hour6, 1);
5917                tester.pump_by(Duration::from_millis(50));
5918                tester.tap_at(min46, 1);
5919                finish_picker(tester);
5920                assert_eq!(picked_time(&result), Some(TimeOfDay::new(6, 45)));
5921            });
5922        }
5923    }
5924
5925    #[test]
5926    fn dial_tap_select_rounds_up_to_nearest_5_minute_increment() {
5927        for material_type in pickers() {
5928            test_widgets(|tester| {
5929                let result: PickerResult = Rc::default();
5930                let center =
5931                    start_picker(tester, &result, StartPicker::new(material_type)).expect("a dial");
5932                let hour6 = Offset::new(center.dx(), center.dy() + 50.0); // 6:00
5933                let min48 = Offset::new(center.dx() - 50.0, center.dy() - 15.0); // 48 mins
5934
5935                tester.tap_at(hour6, 1);
5936                tester.pump_by(Duration::from_millis(50));
5937                tester.tap_at(min48, 1);
5938                finish_picker(tester);
5939                assert_eq!(picked_time(&result), Some(TimeOfDay::new(6, 50)));
5940            });
5941        }
5942    }
5943
5944    fn only_text(tester: &WidgetTester, text: &str) -> AnyElement {
5945        let found = find::text(text).evaluate(tester);
5946        assert_eq!(found.len(), 1, "one {text:?}");
5947        found[0]
5948    }
5949
5950    #[test]
5951    fn material2_widgets_have_correct_label_capitalization() {
5952        test_widgets(|tester| {
5953            let result: PickerResult = Rc::default();
5954            start_picker(tester, &result, StartPicker::new(MaterialType::Material2));
5955            only_text(tester, "SELECT TIME");
5956            only_text(tester, "CANCEL");
5957        });
5958    }
5959
5960    #[test]
5961    fn material3_widgets_have_correct_label_capitalization() {
5962        test_widgets(|tester| {
5963            let result: PickerResult = Rc::default();
5964            start_picker(tester, &result, StartPicker::new(MaterialType::Material3));
5965            only_text(tester, "Select time");
5966            only_text(tester, "Cancel");
5967        });
5968    }
5969
5970    #[test]
5971    fn material2_widgets_have_correct_label_capitalization_in_input_mode() {
5972        test_widgets(|tester| {
5973            let result: PickerResult = Rc::default();
5974            let mut parameters = StartPicker::new(MaterialType::Material2);
5975            parameters.entry_mode = TimePickerEntryMode::Input;
5976            start_picker(tester, &result, parameters);
5977            only_text(tester, "ENTER TIME");
5978            only_text(tester, "CANCEL");
5979        });
5980    }
5981
5982    #[test]
5983    fn material3_widgets_have_correct_label_capitalization_in_input_mode() {
5984        test_widgets(|tester| {
5985            let result: PickerResult = Rc::default();
5986            let mut parameters = StartPicker::new(MaterialType::Material3);
5987            parameters.entry_mode = TimePickerEntryMode::Input;
5988            start_picker(tester, &result, parameters);
5989            only_text(tester, "Enter time");
5990            only_text(tester, "Cancel");
5991        });
5992    }
5993
5994    #[test]
5995    fn respects_media_query_data_always_use_24_hour_format_false() {
5996        for material_type in pickers() {
5997            test_widgets(|tester| {
5998                let size = material_dialog_default_size();
5999                media_query_boilerplate(tester, size, Boilerplate::new(material_type));
6000                let labels_12_to_11: Vec<String> = [
6001                    "12", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11",
6002                ]
6003                .iter()
6004                .map(ToString::to_string)
6005                .collect();
6006
6007                let painter = dial_painter(tester);
6008                assert_eq!(painter.borrow().primary_label_texts(), labels_12_to_11);
6009                assert_eq!(painter.borrow().selected_label_texts(), labels_12_to_11);
6010            });
6011        }
6012    }
6013
6014    fn day_period_input_padding_orientation(tester: &WidgetTester) -> Orientation {
6015        let element = tester.element(find::by_type::<DayPeriodInputPadding>().at(0));
6016        tester.widget(element, |padding: &DayPeriodInputPadding| {
6017            padding.orientation
6018        })
6019    }
6020
6021    #[test]
6022    fn when_change_orientation_should_reflect_in_render_objects() {
6023        for material_type in pickers() {
6024            test_widgets(|tester| {
6025                // portrait
6026                let size = Size::new(800.0, 800.5);
6027                size_view(tester, size);
6028                media_query_boilerplate(tester, size, Boilerplate::new(material_type));
6029                assert_eq!(
6030                    day_period_input_padding_orientation(tester),
6031                    Orientation::Portrait
6032                );
6033
6034                // landscape
6035                let size = Size::new(800.5, 800.0);
6036                size_view(tester, size);
6037                media_query_boilerplate(tester, size, Boilerplate::new(material_type));
6038                assert_eq!(
6039                    day_period_input_padding_orientation(tester),
6040                    Orientation::Landscape
6041                );
6042            });
6043        }
6044    }
6045
6046    #[test]
6047    fn setting_orientation_should_override_media_query_orientation() {
6048        for material_type in pickers() {
6049            test_widgets(|tester| {
6050                // portrait media query
6051                let size = Size::new(800.0, 800.5);
6052                size_view(tester, size);
6053                let mut boilerplate = Boilerplate::new(material_type);
6054                boilerplate.orientation = Some(Orientation::Landscape);
6055                media_query_boilerplate(tester, size, boilerplate);
6056                assert_eq!(
6057                    day_period_input_padding_orientation(tester),
6058                    Orientation::Landscape
6059                );
6060            });
6061        }
6062    }
6063
6064    /// Dart's `PickerObserver.pickerCount`: how many time pickers the navigator shows.
6065    fn picker_count(tester: &WidgetTester) -> usize {
6066        find::by_type::<TimePickerDialog>().evaluate(tester).len()
6067    }
6068
6069    /// An app with a button that shows a time picker with the given arguments.
6070    fn open_picker_app(
6071        tester: &mut WidgetTester,
6072        show: impl Fn(&mut waft_foundation::App, BuildContext) + 'static,
6073    ) {
6074        let theme = m3(&tester.cell.borrow());
6075        let show = Rc::new(show);
6076        let home = Material::new()
6077            .child(
6078                waft_widgets::Center::new().child(Builder::new(move |_app, context| {
6079                    let show = Rc::clone(&show);
6080                    crate::elevated_button::ElevatedButton::new(
6081                        Some(Listener::new(move |app| show(app, context))),
6082                        Some(Text::new("X")),
6083                    )
6084                    .into_widget()
6085                })),
6086            )
6087            .into_widget();
6088        tester.pump_widget(material_app(theme, home));
6089    }
6090
6091    fn show_default(
6092        app: &mut waft_foundation::App,
6093        context: BuildContext,
6094    ) -> waft_foundation::CompleterFuture<waft_widgets::RouteResult> {
6095        {
6096            let show = ShowTimePicker::new(TimeOfDay::new(7, 0));
6097            show.show(app, context)
6098        }
6099    }
6100
6101    #[test]
6102    fn barrier_is_dismissible_with_default_parameter() {
6103        test_widgets(|tester| {
6104            open_picker_app(tester, |app, context| drop(show_default(app, context)));
6105
6106            // Open the dialog.
6107            tester.tap(find::text("X"));
6108            tester.pump_and_settle();
6109            assert_eq!(picker_count(tester), 1);
6110
6111            // Tap on the barrier.
6112            tester.tap_at(Offset::new(10.0, 10.0), 1);
6113            tester.pump_and_settle();
6114            assert_eq!(picker_count(tester), 0);
6115        });
6116    }
6117
6118    #[test]
6119    fn barrier_is_not_dismissible_with_barrier_dismissible_is_false() {
6120        test_widgets(|tester| {
6121            open_picker_app(tester, |app, context| {
6122                drop({
6123                    let mut show = ShowTimePicker::new(TimeOfDay::new(7, 0));
6124                    show = show.barrier_dismissible(false);
6125                    show.show(app, context)
6126                });
6127            });
6128
6129            // Open the dialog.
6130            tester.tap(find::text("X"));
6131            tester.pump_and_settle();
6132            assert_eq!(picker_count(tester), 1);
6133
6134            // Tap on the barrier, which shouldn't do anything this time.
6135            tester.tap_at(Offset::new(10.0, 10.0), 1);
6136            tester.pump_and_settle();
6137            assert_eq!(picker_count(tester), 1);
6138        });
6139    }
6140
6141    fn last_modal_barrier<R>(
6142        tester: &WidgetTester,
6143        read: impl FnOnce(&waft_widgets::ModalBarrier) -> R,
6144    ) -> R {
6145        let barrier = *find::by_type::<waft_widgets::ModalBarrier>()
6146            .evaluate(tester)
6147            .last()
6148            .expect("a ModalBarrier");
6149        tester.widget(barrier, read)
6150    }
6151
6152    #[test]
6153    fn barrier_color() {
6154        test_widgets(|tester| {
6155            open_picker_app(tester, |app, context| drop(show_default(app, context)));
6156
6157            // Open the dialog.
6158            tester.tap(find::text("X"));
6159            tester.pump_and_settle();
6160            assert_eq!(
6161                last_modal_barrier(tester, |barrier| barrier.color),
6162                Some(crate::colors::Colors::BLACK54)
6163            );
6164
6165            // Dismiss the dialog.
6166            tester.tap_at(Offset::new(10.0, 10.0), 1);
6167
6168            open_picker_app(tester, |app, context| {
6169                drop({
6170                    let mut show = ShowTimePicker::new(TimeOfDay::new(7, 0));
6171                    show = show.barrier_color(crate::colors::Colors::PINK.primary());
6172                    show.show(app, context)
6173                });
6174            });
6175
6176            // Open the dialog.
6177            tester.tap(find::text("X"));
6178            tester.pump_and_settle();
6179            assert_eq!(
6180                last_modal_barrier(tester, |barrier| barrier.color),
6181                Some(crate::colors::Colors::PINK.primary())
6182            );
6183        });
6184    }
6185
6186    #[test]
6187    fn barrier_label() {
6188        test_widgets(|tester| {
6189            open_picker_app(tester, |app, context| {
6190                drop({
6191                    let mut show = ShowTimePicker::new(TimeOfDay::new(7, 0));
6192                    show = show.barrier_label("Custom Label".to_string());
6193                    show.show(app, context)
6194                });
6195            });
6196
6197            // Open the dialog.
6198            tester.tap(find::text("X"));
6199            tester.pump_and_settle();
6200            assert_eq!(
6201                last_modal_barrier(tester, |barrier| barrier.semantics_label.clone()),
6202                Some("Custom Label".to_string())
6203            );
6204        });
6205    }
6206
6207    #[test]
6208    fn builder_parameter() {
6209        test_widgets(|tester| {
6210            let build_frame =
6211                |tester: &mut WidgetTester, text_direction: waft_painting::TextDirection| {
6212                    open_picker_app(tester, move |app, context| {
6213                        let builder: waft_widgets::TransitionBuilder =
6214                            Rc::new(move |_app, _context, child| {
6215                                waft_widgets::Directionality::new(
6216                                    text_direction,
6217                                    child.expect("a dialog child").clone(),
6218                                )
6219                                .into_widget()
6220                            });
6221                        drop({
6222                            let mut show = ShowTimePicker::new(TimeOfDay::new(7, 0));
6223                            show = show.builder(builder);
6224                            show.show(app, context)
6225                        });
6226                    });
6227                };
6228
6229            build_frame(tester, waft_painting::TextDirection::Ltr);
6230            tester.tap(find::text("X"));
6231            tester.pump_and_settle();
6232            let ok = only_text(tester, OK_STRING);
6233            let ltr_ok_right = tester.get_rect(ok).right;
6234
6235            tester.tap(find::text(OK_STRING)); // dismiss the dialog
6236            tester.pump_and_settle();
6237
6238            build_frame(tester, waft_painting::TextDirection::Rtl);
6239            tester.tap(find::text("X"));
6240            tester.pump_and_settle();
6241
6242            // Verify that the time picker is being laid out RTL.
6243            // We expect the left edge of the 'OK' button in the RTL
6244            // layout to match the gap between right edge of the 'OK'
6245            // button and the right edge of the 800 wide view.
6246            let ok = only_text(tester, OK_STRING);
6247            let rtl_ok_left = tester.get_rect(ok).left;
6248            // Dart's `rtlOkLeft == 800 - ltrOkRight`, compared at the f32 rounding of the 800
6249            // wide view the two edges add up to.
6250            assert_f32_equals(rtl_ok_left + ltr_ok_right, 800.0);
6251        });
6252    }
6253
6254    #[test]
6255    fn optional_text_parameters_are_utilized() {
6256        test_widgets(|tester| {
6257            open_picker_app(tester, |app, context| {
6258                drop({
6259                    let mut show = ShowTimePicker::new(TimeOfDay::new(7, 0));
6260                    show = show.cancel_text("Custom Cancel".to_string());
6261                    show = show.confirm_text("Custom OK".to_string());
6262                    show = show.help_text("Custom Help".to_string());
6263                    show.show(app, context)
6264                });
6265            });
6266
6267            // Open the picker.
6268            tester.tap(find::text("X"));
6269            tester.pump_and_settle_by(Duration::from_secs(1));
6270
6271            only_text(tester, "Custom Cancel");
6272            only_text(tester, "Custom OK");
6273            only_text(tester, "Custom Help");
6274        });
6275    }
6276
6277    fn open_directional_picker(
6278        tester: &mut WidgetTester,
6279        text_direction: waft_painting::TextDirection,
6280    ) {
6281        open_picker_app(tester, move |app, context| {
6282            let builder: waft_widgets::TransitionBuilder = Rc::new(move |_app, _context, child| {
6283                waft_widgets::Directionality::new(
6284                    text_direction,
6285                    child.expect("a dialog child").clone(),
6286                )
6287                .into_widget()
6288            });
6289            drop({
6290                let mut show = ShowTimePicker::new(TimeOfDay::new(7, 0));
6291                show = show.builder(builder);
6292                show.show(app, context)
6293            });
6294        });
6295    }
6296
6297    #[test]
6298    fn material2_ok_cancel_button_and_help_text_layout() {
6299        test_widgets(|tester| {
6300            const SELECT_TIME_STRING: &str = "SELECT TIME";
6301            const CANCEL_STRING: &str = "CANCEL";
6302            let m2_app = |tester: &mut WidgetTester,
6303                          text_direction: waft_painting::TextDirection| {
6304                let theme = m2(&tester.cell.borrow());
6305                let home = Material::new()
6306                    .child(
6307                        waft_widgets::Center::new().child(Builder::new(move |_app, context| {
6308                            crate::elevated_button::ElevatedButton::new(
6309                                Some(Listener::new(move |app| {
6310                                    let builder: waft_widgets::TransitionBuilder =
6311                                        Rc::new(move |_app, _context, child| {
6312                                            waft_widgets::Directionality::new(
6313                                                text_direction,
6314                                                child.expect("a dialog child").clone(),
6315                                            )
6316                                            .into_widget()
6317                                        });
6318                                    drop({
6319                                        let mut show = ShowTimePicker::new(TimeOfDay::new(7, 0));
6320                                        show = show.builder(builder);
6321                                        show.show(app, context)
6322                                    });
6323                                })),
6324                                Some(Text::new("X")),
6325                            )
6326                            .into_widget()
6327                        })),
6328                    )
6329                    .into_widget();
6330                tester.pump_widget(material_app(theme, home));
6331            };
6332
6333            m2_app(tester, waft_painting::TextDirection::Ltr);
6334            tester.tap(find::text("X"));
6335            tester.pump_and_settle();
6336
6337            let select_time = tester.get_rect(find::text(SELECT_TIME_STRING));
6338            assert_eq!(select_time.top_left(), Offset::new(154.0, 155.0));
6339            assert_eq!(select_time.bottom_right(), Offset::new(280.5, 165.0));
6340            assert_eq!(tester.get_rect(find::text(OK_STRING)).right, 644.0);
6341            assert_eq!(tester.get_rect(find::text(OK_STRING)).left, 616.0);
6342            assert_eq!(tester.get_rect(find::text(CANCEL_STRING)).right, 582.0);
6343
6344            tester.tap(find::text(OK_STRING));
6345            tester.pump_and_settle();
6346
6347            m2_app(tester, waft_painting::TextDirection::Rtl);
6348            tester.tap(find::text("X"));
6349            tester.pump_and_settle();
6350
6351            let select_time = tester.get_rect(find::text(SELECT_TIME_STRING));
6352            assert_eq!(select_time.top_left(), Offset::new(519.5, 155.0));
6353            assert_eq!(select_time.bottom_right(), Offset::new(646.0, 165.0));
6354            assert_eq!(tester.get_rect(find::text(OK_STRING)).left, 156.0);
6355            assert_eq!(tester.get_rect(find::text(OK_STRING)).right, 184.0);
6356            assert_eq!(tester.get_rect(find::text(CANCEL_STRING)).left, 218.0);
6357
6358            tester.tap(find::text(OK_STRING));
6359            tester.pump_and_settle();
6360        });
6361    }
6362
6363    #[test]
6364    fn material3_ok_cancel_button_and_help_text_layout() {
6365        test_widgets(|tester| {
6366            const SELECT_TIME_STRING: &str = "Select time";
6367            const CANCEL_STRING: &str = "Cancel";
6368
6369            open_directional_picker(tester, waft_painting::TextDirection::Ltr);
6370            tester.tap(find::text("X"));
6371            tester.pump_and_settle();
6372
6373            let select_time = tester.get_rect(find::text(SELECT_TIME_STRING));
6374            assert_eq!(select_time.top_left(), Offset::new(138.0, 129.0));
6375            assert_eq!(select_time.bottom_right(), Offset::new(294.75, 149.0));
6376            assert_more_or_less_equals_within(
6377                tester.get_rect(find::text(OK_STRING)).left,
6378                615.9,
6379                0.001,
6380            );
6381            assert_f32_equals(tester.get_rect(find::text(CANCEL_STRING)).right, 578.0);
6382
6383            tester.tap(find::text(OK_STRING));
6384            tester.pump_and_settle();
6385
6386            open_directional_picker(tester, waft_painting::TextDirection::Rtl);
6387            tester.tap(find::text("X"));
6388            tester.pump_and_settle();
6389
6390            let select_time = tester.get_rect(find::text(SELECT_TIME_STRING));
6391            assert_eq!(select_time.top_left(), Offset::new(505.25, 129.0));
6392            assert_eq!(select_time.bottom_right(), Offset::new(662.0, 149.0));
6393            assert_more_or_less_equals_within(
6394                tester.get_rect(find::text(OK_STRING)).left,
6395                155.9,
6396                0.001,
6397            );
6398            assert_more_or_less_equals_within(
6399                tester.get_rect(find::text(OK_STRING)).right,
6400                184.1,
6401                0.001,
6402            );
6403            assert_f32_equals(tester.get_rect(find::text(CANCEL_STRING)).left, 222.0);
6404
6405            tester.tap(find::text(OK_STRING));
6406            tester.pump_and_settle();
6407        });
6408    }
6409
6410    #[test]
6411    fn text_scale_affects_certain_elements_and_not_others() {
6412        for material_type in pickers() {
6413            test_widgets(|tester| {
6414                let size = material_dialog_default_size();
6415                let mut boilerplate = Boilerplate::new(material_type);
6416                boilerplate.initial_time = TimeOfDay::new(7, 41);
6417                media_query_boilerplate(tester, size, boilerplate.clone());
6418
6419                let minutes_display_height = tester.get_rect(find::text("41")).height();
6420                let am_height = tester.get_rect(find::text(AM_STRING)).height();
6421
6422                tester.tap(find::text(OK_STRING)); // dismiss the dialog
6423                tester.pump_and_settle();
6424
6425                // Verify that the time display is not affected by text scale.
6426                boilerplate.text_scaler = TextScaler::linear(2.0);
6427                media_query_boilerplate(tester, size, boilerplate.clone());
6428
6429                let am_height_2x = tester.get_rect(find::text(AM_STRING)).height();
6430                assert_eq!(
6431                    tester.get_rect(find::text("41")).height(),
6432                    minutes_display_height
6433                );
6434                assert_eq!(am_height_2x, f64::min(38.0, am_height * 2.0));
6435
6436                tester.tap(find::text(OK_STRING)); // dismiss the dialog
6437                tester.pump_and_settle();
6438
6439                // Verify that text scale for AM/PM is at most 2x.
6440                boilerplate.text_scaler = TextScaler::linear(3.0);
6441                media_query_boilerplate(tester, size, boilerplate);
6442
6443                assert_eq!(
6444                    tester.get_rect(find::text("41")).height(),
6445                    minutes_display_height
6446                );
6447                assert_eq!(
6448                    tester.get_rect(find::text(AM_STRING)).height(),
6449                    f64::min(38.0, am_height * 2.0)
6450                );
6451            });
6452        }
6453    }
6454
6455    /// Records the haptic feedback the platform is asked for: Dart's `FeedbackTester`.
6456    #[derive(Default)]
6457    struct FeedbackTester {
6458        haptics: RefCell<Vec<waft_embedder::HapticFeedbackType>>,
6459    }
6460
6461    impl waft_embedder::Haptics for FeedbackTester {
6462        fn feedback(&self, kind: waft_embedder::HapticFeedbackType) {
6463            self.haptics.borrow_mut().push(kind);
6464        }
6465    }
6466
6467    impl FeedbackTester {
6468        fn haptic_count(&self) -> usize {
6469            self.haptics.borrow().len()
6470        }
6471    }
6472
6473    fn feedback_tester() -> (WidgetTester, Rc<FeedbackTester>) {
6474        let feedback = Rc::new(FeedbackTester::default());
6475        let platform = waft_test::TestPlatform::new()
6476            .on(TargetPlatform::Android)
6477            .with_haptics(Rc::clone(&feedback) as Rc<dyn waft_embedder::Haptics>);
6478        (WidgetTester::with_platform(platform), feedback)
6479    }
6480
6481    const FAST_FEEDBACK_INTERVAL: Duration = Duration::from_millis(10);
6482    const SLOW_FEEDBACK_INTERVAL: Duration = Duration::from_millis(200);
6483
6484    fn haptic_case(case: impl Fn(&mut WidgetTester, Offset, &FeedbackTester)) {
6485        for material_type in pickers() {
6486            let (mut tester, feedback) = feedback_tester();
6487            let tester = &mut tester;
6488            let result: PickerResult = Rc::default();
6489            let center =
6490                start_picker(tester, &result, StartPicker::new(material_type)).expect("a dial");
6491            case(tester, center, &feedback);
6492        }
6493    }
6494
6495    #[test]
6496    fn dial_haptic_feedback_tap_select_vibrates_once() {
6497        test_widgets(|_| {
6498            haptic_case(|tester, center, feedback| {
6499                tester.tap_at(Offset::new(center.dx(), center.dy() - 50.0), 1);
6500                finish_picker(tester);
6501                assert_eq!(feedback.haptic_count(), 1);
6502            });
6503        });
6504    }
6505
6506    #[test]
6507    fn dial_haptic_feedback_quick_successive_tap_selects_vibrate_once() {
6508        test_widgets(|_| {
6509            haptic_case(|tester, center, feedback| {
6510                tester.tap_at(Offset::new(center.dx(), center.dy() - 50.0), 1);
6511                tester.pump_by(FAST_FEEDBACK_INTERVAL);
6512                tester.tap_at(Offset::new(center.dx(), center.dy() + 50.0), 1);
6513                finish_picker(tester);
6514                assert_eq!(feedback.haptic_count(), 1);
6515            });
6516        });
6517    }
6518
6519    #[test]
6520    fn dial_haptic_feedback_slow_successive_tap_selects_vibrate_once_per_tap() {
6521        test_widgets(|_| {
6522            haptic_case(|tester, center, feedback| {
6523                tester.tap_at(Offset::new(center.dx(), center.dy() - 50.0), 1);
6524                tester.pump_by(SLOW_FEEDBACK_INTERVAL);
6525                tester.tap_at(Offset::new(center.dx(), center.dy() + 50.0), 1);
6526                tester.pump_by(SLOW_FEEDBACK_INTERVAL);
6527                tester.tap_at(Offset::new(center.dx(), center.dy() - 50.0), 1);
6528                finish_picker(tester);
6529                assert_eq!(feedback.haptic_count(), 3);
6530            });
6531        });
6532    }
6533
6534    #[test]
6535    fn dial_haptic_feedback_drag_select_vibrates_once() {
6536        test_widgets(|_| {
6537            haptic_case(|tester, center, feedback| {
6538                let hour0 = Offset::new(center.dx(), center.dy() - 50.0);
6539                let hour3 = Offset::new(center.dx() + 50.0, center.dy());
6540                drag(tester, hour3, hour0);
6541                finish_picker(tester);
6542                assert_eq!(feedback.haptic_count(), 1);
6543            });
6544        });
6545    }
6546
6547    #[test]
6548    fn dial_haptic_feedback_quick_drag_select_vibrates_once() {
6549        test_widgets(|_| {
6550            haptic_case(|tester, center, feedback| {
6551                let hour0 = Offset::new(center.dx(), center.dy() - 50.0);
6552                let hour3 = Offset::new(center.dx() + 50.0, center.dy());
6553                let mut gesture = TestPointer::touch(1);
6554                tester.down(&mut gesture, hour3);
6555                tester.move_to(&mut gesture, hour0, true);
6556                tester.pump_by(FAST_FEEDBACK_INTERVAL);
6557                tester.move_to(&mut gesture, hour3, true);
6558                tester.pump_by(FAST_FEEDBACK_INTERVAL);
6559                tester.move_to(&mut gesture, hour0, true);
6560                tester.up(&gesture);
6561                finish_picker(tester);
6562                assert_eq!(feedback.haptic_count(), 1);
6563            });
6564        });
6565    }
6566
6567    #[test]
6568    fn dial_haptic_feedback_slow_drag_select_vibrates_once() {
6569        test_widgets(|_| {
6570            haptic_case(|tester, center, feedback| {
6571                let hour0 = Offset::new(center.dx(), center.dy() - 50.0);
6572                let hour3 = Offset::new(center.dx() + 50.0, center.dy());
6573                let mut gesture = TestPointer::touch(1);
6574                tester.down(&mut gesture, hour3);
6575                tester.move_to(&mut gesture, hour0, true);
6576                tester.pump_by(SLOW_FEEDBACK_INTERVAL);
6577                tester.move_to(&mut gesture, hour3, true);
6578                tester.pump_by(SLOW_FEEDBACK_INTERVAL);
6579                tester.move_to(&mut gesture, hour0, true);
6580                tester.up(&gesture);
6581                finish_picker(tester);
6582                assert_eq!(feedback.haptic_count(), 3);
6583            });
6584        });
6585    }
6586
6587    fn text_field_count(tester: &WidgetTester) -> usize {
6588        find::by_type::<crate::text_field::TextField>()
6589            .evaluate(tester)
6590            .len()
6591    }
6592
6593    fn input_boilerplate(material_type: MaterialType) -> Boilerplate {
6594        let mut boilerplate = Boilerplate::new(material_type);
6595        boilerplate.always_use_24_hour_format = true;
6596        boilerplate.entry_mode = TimePickerEntryMode::Input;
6597        boilerplate
6598    }
6599
6600    fn tap_icon(tester: &mut WidgetTester, icon: &waft_widgets::IconData) {
6601        let element = tester.element(find::by_icon(icon).first());
6602        let center = tester.get_center(element);
6603        tester.tap_at(center, 1);
6604    }
6605
6606    fn has_icon(tester: &WidgetTester, icon: &waft_widgets::IconData) -> bool {
6607        find::by_type::<waft_widgets::Icon>()
6608            .evaluate(tester)
6609            .into_iter()
6610            .any(|element| {
6611                tester.widget(element, |widget: &waft_widgets::Icon| {
6612                    widget.icon.as_ref() == Some(icon)
6613                })
6614            })
6615    }
6616
6617    #[test]
6618    fn input_initial_entry_mode_is_used() {
6619        for material_type in pickers() {
6620            test_widgets(|tester| {
6621                let size = material_dialog_default_size();
6622                media_query_boilerplate(tester, size, input_boilerplate(material_type));
6623                assert_eq!(text_field_count(tester), 2);
6624            });
6625        }
6626    }
6627
6628    #[test]
6629    fn input_initial_time_is_the_default() {
6630        for material_type in pickers() {
6631            test_widgets(|tester| {
6632                let result: PickerResult = Rc::default();
6633                let mut parameters = StartPicker::new(material_type);
6634                parameters.entry_mode = TimePickerEntryMode::Input;
6635                start_picker(tester, &result, parameters);
6636                finish_picker(tester);
6637                assert_eq!(picked_time(&result), Some(TimeOfDay::new(7, 0)));
6638            });
6639        }
6640    }
6641
6642    #[test]
6643    fn input_help_text_is_used() {
6644        for material_type in pickers() {
6645            test_widgets(|tester| {
6646                let size = material_dialog_default_size();
6647                let mut boilerplate = input_boilerplate(material_type);
6648                boilerplate.help_text = Some("help".to_string());
6649                media_query_boilerplate(tester, size, boilerplate);
6650                only_text(tester, "help");
6651            });
6652        }
6653    }
6654
6655    #[test]
6656    fn input_hour_label_text_is_used() {
6657        for material_type in pickers() {
6658            test_widgets(|tester| {
6659                let size = material_dialog_default_size();
6660                let mut boilerplate = input_boilerplate(material_type);
6661                boilerplate.hour_label_text = Some("Custom hour label".to_string());
6662                media_query_boilerplate(tester, size, boilerplate);
6663                only_text(tester, "Custom hour label");
6664            });
6665        }
6666    }
6667
6668    #[test]
6669    fn input_minute_label_text_is_used() {
6670        for material_type in pickers() {
6671            test_widgets(|tester| {
6672                let size = material_dialog_default_size();
6673                let mut boilerplate = input_boilerplate(material_type);
6674                boilerplate.minute_label_text = Some("Custom minute label".to_string());
6675                media_query_boilerplate(tester, size, boilerplate);
6676                only_text(tester, "Custom minute label");
6677            });
6678        }
6679    }
6680
6681    #[test]
6682    fn input_invalid_error_text_is_used() {
6683        for material_type in pickers() {
6684            test_widgets(|tester| {
6685                let size = material_dialog_default_size();
6686                let mut boilerplate = input_boilerplate(material_type);
6687                boilerplate.error_invalid_text = Some("Custom validation error".to_string());
6688                media_query_boilerplate(tester, size, boilerplate);
6689                // Input invalid time (hour) to force validation error
6690                tester.enter_text(find::by_type::<EditableText>().at(0), "88");
6691                // Tap the ok button to trigger the validation error with custom translation
6692                tester.tap(find::text(OK_STRING));
6693                tester.pump_and_settle_by(Duration::from_secs(1));
6694                only_text(tester, "Custom validation error");
6695            });
6696        }
6697    }
6698
6699    #[test]
6700    fn time_picker_default_entry_icons() {
6701        test_widgets(|tester| {
6702            let theme = m3(&tester.cell.borrow());
6703            tester.pump_widget(material_app(
6704                theme,
6705                TimePickerDialog::new(TimeOfDay::new(12, 0)).into_widget(),
6706            ));
6707
6708            // Check that the default icon for the dial mode is displayed.
6709            assert!(has_icon(tester, &crate::icons::Icons::keyboard_outlined()));
6710            assert!(!has_icon(tester, &crate::icons::Icons::access_time()));
6711            // Tap the icon to switch to input mode.
6712            tap_icon(tester, &crate::icons::Icons::keyboard_outlined());
6713            tester.pump_and_settle();
6714            // Check that the icon for the input mode is displayed.
6715            assert!(has_icon(tester, &crate::icons::Icons::access_time()));
6716            assert!(!has_icon(tester, &crate::icons::Icons::keyboard_outlined()));
6717        });
6718    }
6719
6720    #[test]
6721    fn can_override_time_picker_entry_icons() {
6722        test_widgets(|tester| {
6723            let theme = m3(&tester.cell.borrow());
6724            let custom_input_icon = crate::icons::Icons::text_fields();
6725            let custom_timer_icon = crate::icons::Icons::watch();
6726            tester.pump_widget(material_app(
6727                theme,
6728                TimePickerDialog::new(TimeOfDay::new(12, 0))
6729                    .switch_to_input_entry_mode_icon(Icon::new(Some(custom_input_icon.clone())))
6730                    .switch_to_timer_entry_mode_icon(Icon::new(Some(custom_timer_icon.clone())))
6731                    .into_widget(),
6732            ));
6733
6734            // Check that the custom icons are displayed.
6735            assert!(has_icon(tester, &custom_input_icon));
6736            assert!(!has_icon(tester, &custom_timer_icon));
6737            // Tap the custom icon to switch to input mode.
6738            tap_icon(tester, &custom_input_icon);
6739            tester.pump_and_settle();
6740            // Check that the custom icon for the input mode is displayed.
6741            assert!(!has_icon(tester, &custom_input_icon));
6742            assert!(has_icon(tester, &custom_timer_icon));
6743        });
6744    }
6745
6746    #[test]
6747    fn can_switch_from_input_to_dial_entry_mode() {
6748        for material_type in pickers() {
6749            test_widgets(|tester| {
6750                let size = material_dialog_default_size();
6751                media_query_boilerplate(tester, size, input_boilerplate(material_type));
6752                tap_icon(tester, &crate::icons::Icons::access_time());
6753                tester.pump_and_settle();
6754                assert_eq!(text_field_count(tester), 0);
6755            });
6756        }
6757    }
6758
6759    #[test]
6760    fn can_switch_from_dial_to_input_entry_mode() {
6761        for material_type in pickers() {
6762            test_widgets(|tester| {
6763                let size = material_dialog_default_size();
6764                let mut boilerplate = Boilerplate::new(material_type);
6765                boilerplate.always_use_24_hour_format = true;
6766                media_query_boilerplate(tester, size, boilerplate);
6767                tap_icon(tester, &crate::icons::Icons::keyboard_outlined());
6768                tester.pump_and_settle();
6769                assert!(text_field_count(tester) > 0);
6770            });
6771        }
6772    }
6773
6774    #[test]
6775    fn can_not_switch_out_of_input_only_mode() {
6776        for material_type in pickers() {
6777            test_widgets(|tester| {
6778                let size = material_dialog_default_size();
6779                let mut boilerplate = input_boilerplate(material_type);
6780                boilerplate.entry_mode = TimePickerEntryMode::InputOnly;
6781                media_query_boilerplate(tester, size, boilerplate);
6782                assert!(text_field_count(tester) > 0);
6783                assert!(!has_icon(tester, &crate::icons::Icons::access_time()));
6784            });
6785        }
6786    }
6787
6788    #[test]
6789    fn can_not_switch_out_of_dial_only_mode() {
6790        for material_type in pickers() {
6791            test_widgets(|tester| {
6792                let size = material_dialog_default_size();
6793                let mut boilerplate = Boilerplate::new(material_type);
6794                boilerplate.always_use_24_hour_format = true;
6795                boilerplate.entry_mode = TimePickerEntryMode::DialOnly;
6796                media_query_boilerplate(tester, size, boilerplate);
6797                assert_eq!(text_field_count(tester), 0);
6798                assert!(!has_icon(tester, &crate::icons::Icons::keyboard_outlined()));
6799            });
6800        }
6801    }
6802
6803    #[test]
6804    fn switching_to_dial_entry_mode_triggers_entry_callback() {
6805        for material_type in pickers() {
6806            test_widgets(|tester| {
6807                let triggered_callback = Rc::new(Cell::new(false));
6808                let size = material_dialog_default_size();
6809                let mut boilerplate = input_boilerplate(material_type);
6810                boilerplate.on_entry_mode_change = Some({
6811                    let triggered_callback = Rc::clone(&triggered_callback);
6812                    Rc::new(move |_app, mode| {
6813                        if mode == TimePickerEntryMode::Dial {
6814                            triggered_callback.set(true);
6815                        }
6816                    })
6817                });
6818                media_query_boilerplate(tester, size, boilerplate);
6819
6820                tap_icon(tester, &crate::icons::Icons::access_time());
6821                tester.pump_and_settle();
6822                assert!(triggered_callback.get());
6823            });
6824        }
6825    }
6826
6827    #[test]
6828    fn switching_to_input_entry_mode_triggers_entry_callback() {
6829        for material_type in pickers() {
6830            test_widgets(|tester| {
6831                let triggered_callback = Rc::new(Cell::new(false));
6832                let size = material_dialog_default_size();
6833                let mut boilerplate = Boilerplate::new(material_type);
6834                boilerplate.always_use_24_hour_format = true;
6835                boilerplate.on_entry_mode_change = Some({
6836                    let triggered_callback = Rc::clone(&triggered_callback);
6837                    Rc::new(move |_app, mode| {
6838                        if mode == TimePickerEntryMode::Input {
6839                            triggered_callback.set(true);
6840                        }
6841                    })
6842                });
6843                media_query_boilerplate(tester, size, boilerplate);
6844
6845                tap_icon(tester, &crate::icons::Icons::keyboard_outlined());
6846                tester.pump_and_settle();
6847                assert!(triggered_callback.get());
6848            });
6849        }
6850    }
6851
6852    /// Dart's `find.ancestor(of: find.text(text), matching: find.byType(InkWell))`.
6853    fn ink_well_of_text(tester: &WidgetTester, text: &str) -> AnyElement {
6854        tester.element(
6855            find::ancestor(
6856                find::text(text),
6857                find::by_type::<crate::ink_well::InkWell>(),
6858            )
6859            .first(),
6860        )
6861    }
6862
6863    fn tap_element(tester: &mut WidgetTester, element: AnyElement) {
6864        let center = tester.get_center(element);
6865        let pointer = tester.next_pointer();
6866        tester.tap_at(center, pointer);
6867    }
6868
6869    #[test]
6870    fn can_double_tap_hours_when_selected_to_enter_input_mode() {
6871        for material_type in pickers() {
6872            test_widgets(|tester| {
6873                let size = material_dialog_default_size();
6874                media_query_boilerplate(tester, size, Boilerplate::new(material_type));
6875                let hour_finder = ink_well_of_text(tester, "7");
6876
6877                assert_eq!(text_field_count(tester), 0);
6878
6879                // Double tap the hour.
6880                tap_element(tester, hour_finder);
6881                tester.pump_by(Duration::from_millis(100));
6882                tap_element(tester, hour_finder);
6883                tester.pump_and_settle();
6884
6885                assert!(text_field_count(tester) > 0);
6886            });
6887        }
6888    }
6889
6890    #[test]
6891    fn can_not_double_tap_hours_when_not_selected_to_enter_input_mode() {
6892        for material_type in pickers() {
6893            test_widgets(|tester| {
6894                let size = material_dialog_default_size();
6895                media_query_boilerplate(tester, size, Boilerplate::new(material_type));
6896                let hour_finder = ink_well_of_text(tester, "7");
6897                let minute_finder = ink_well_of_text(tester, "00");
6898
6899                assert_eq!(text_field_count(tester), 0);
6900
6901                // Switch to minutes mode.
6902                tap_element(tester, minute_finder);
6903                tester.pump_and_settle();
6904
6905                // Double tap the hour.
6906                tap_element(tester, hour_finder);
6907                tester.pump_by(Duration::from_millis(100));
6908                tap_element(tester, hour_finder);
6909                tester.pump_and_settle();
6910
6911                assert_eq!(text_field_count(tester), 0);
6912            });
6913        }
6914    }
6915
6916    #[test]
6917    fn can_double_tap_minutes_when_selected_to_enter_input_mode() {
6918        for material_type in pickers() {
6919            test_widgets(|tester| {
6920                let size = material_dialog_default_size();
6921                media_query_boilerplate(tester, size, Boilerplate::new(material_type));
6922                let minute_finder = ink_well_of_text(tester, "00");
6923
6924                assert_eq!(text_field_count(tester), 0);
6925
6926                // Switch to minutes mode.
6927                tap_element(tester, minute_finder);
6928                tester.pump_and_settle();
6929
6930                // Double tap the minutes.
6931                tap_element(tester, minute_finder);
6932                tester.pump_by(Duration::from_millis(100));
6933                tap_element(tester, minute_finder);
6934                tester.pump_and_settle();
6935
6936                assert!(text_field_count(tester) > 0);
6937            });
6938        }
6939    }
6940
6941    #[test]
6942    fn can_not_double_tap_minutes_when_not_selected_to_enter_input_mode() {
6943        for material_type in pickers() {
6944            test_widgets(|tester| {
6945                let size = material_dialog_default_size();
6946                media_query_boilerplate(tester, size, Boilerplate::new(material_type));
6947                let minute_finder = ink_well_of_text(tester, "00");
6948
6949                assert_eq!(text_field_count(tester), 0);
6950
6951                // Double tap the minutes.
6952                tap_element(tester, minute_finder);
6953                tester.pump_by(Duration::from_millis(100));
6954                tap_element(tester, minute_finder);
6955                tester.pump_and_settle();
6956
6957                assert_eq!(text_field_count(tester), 0);
6958            });
6959        }
6960    }
6961
6962    #[test]
6963    fn input_entered_text_returns_time() {
6964        for material_type in pickers() {
6965            test_widgets(|tester| {
6966                let result: PickerResult = Rc::default();
6967                let mut parameters = StartPicker::new(material_type);
6968                parameters.entry_mode = TimePickerEntryMode::Input;
6969                start_picker(tester, &result, parameters);
6970                tester.enter_text(find::by_type::<EditableText>().at(0), "9");
6971                tester.enter_text(find::by_type::<EditableText>().at(1), "12");
6972                finish_picker(tester);
6973                assert_eq!(picked_time(&result), Some(TimeOfDay::new(9, 12)));
6974            });
6975        }
6976    }
6977
6978    #[test]
6979    fn input_toggle_to_dial_mode_keeps_selected_time() {
6980        for material_type in pickers() {
6981            test_widgets(|tester| {
6982                let result: PickerResult = Rc::default();
6983                let mut parameters = StartPicker::new(material_type);
6984                parameters.entry_mode = TimePickerEntryMode::Input;
6985                start_picker(tester, &result, parameters);
6986                tester.enter_text(find::by_type::<EditableText>().at(0), "8");
6987                tester.enter_text(find::by_type::<EditableText>().at(1), "15");
6988                tap_icon(tester, &crate::icons::Icons::access_time());
6989                finish_picker(tester);
6990                assert_eq!(picked_time(&result), Some(TimeOfDay::new(8, 15)));
6991            });
6992        }
6993    }
6994
6995    #[test]
6996    fn input_invalid_text_prevents_dismissing() {
6997        for material_type in pickers() {
6998            test_widgets(|tester| {
6999                let result: PickerResult = Rc::default();
7000                let mut parameters = StartPicker::new(material_type);
7001                parameters.entry_mode = TimePickerEntryMode::Input;
7002                start_picker(tester, &result, parameters);
7003
7004                // Invalid hour.
7005                tester.enter_text(find::by_type::<EditableText>().at(0), "88");
7006                tester.enter_text(find::by_type::<EditableText>().at(1), "15");
7007                finish_picker(tester);
7008                assert_eq!(picked_time(&result), None);
7009
7010                // Invalid minute.
7011                tester.enter_text(find::by_type::<EditableText>().at(0), "8");
7012                tester.enter_text(find::by_type::<EditableText>().at(1), "95");
7013                finish_picker(tester);
7014                assert_eq!(picked_time(&result), None);
7015
7016                tester.enter_text(find::by_type::<EditableText>().at(0), "8");
7017                tester.enter_text(find::by_type::<EditableText>().at(1), "15");
7018                finish_picker(tester);
7019                assert_eq!(picked_time(&result), Some(TimeOfDay::new(8, 15)));
7020            });
7021        }
7022    }
7023
7024    fn text_field_texts(tester: &WidgetTester) -> Vec<(String, Option<String>)> {
7025        find::by_type::<crate::text_field::TextField>()
7026            .evaluate(tester)
7027            .into_iter()
7028            .map(|field| {
7029                tester.widget(field, |field: &crate::text_field::TextField| {
7030                    (
7031                        field
7032                            .controller
7033                            .as_ref()
7034                            .map(|controller| controller.value(&tester.cell.borrow()).text.clone())
7035                            .unwrap_or_default(),
7036                        field
7037                            .decoration
7038                            .as_ref()
7039                            .and_then(|decoration| decoration.hint_text.clone()),
7040                    )
7041                })
7042            })
7043            .collect()
7044    }
7045
7046    #[test]
7047    fn empty_initial_input_fields_are_empty_and_show_correct_hints_when_true() {
7048        for material_type in pickers() {
7049            test_widgets(|tester| {
7050                let result: PickerResult = Rc::default();
7051                let mut parameters = StartPicker::new(material_type);
7052                parameters.entry_mode = TimePickerEntryMode::Input;
7053                parameters.empty_initial_input = true;
7054                start_picker(tester, &result, parameters);
7055                tester.pump();
7056
7057                let fields = text_field_texts(tester);
7058                assert_eq!(fields[0], (String::new(), None)); // hour
7059                assert_eq!(fields[1], (String::new(), None)); // minute
7060                finish_picker(tester);
7061            });
7062        }
7063    }
7064
7065    #[test]
7066    fn empty_initial_input_user_sets_hour_minute_after_initially_empty_fields() {
7067        for material_type in pickers() {
7068            test_widgets(|tester| {
7069                let result: PickerResult = Rc::default();
7070                let mut parameters = StartPicker::new(material_type);
7071                parameters.entry_mode = TimePickerEntryMode::Input;
7072                parameters.empty_initial_input = true;
7073                start_picker(tester, &result, parameters);
7074
7075                let fields = text_field_texts(tester);
7076                assert_eq!(fields[0], (String::new(), None)); // hour
7077                assert_eq!(fields[1], (String::new(), None)); // minute
7078
7079                tester.enter_text(find::by_type::<EditableText>().at(0), "11");
7080                tester.enter_text(find::by_type::<EditableText>().at(1), "30");
7081                finish_picker(tester);
7082
7083                assert_eq!(picked_time(&result), Some(TimeOfDay::new(11, 30)));
7084            });
7085        }
7086    }
7087
7088    #[test]
7089    fn empty_initial_input_user_overrides_default_values_when_false() {
7090        for material_type in pickers() {
7091            test_widgets(|tester| {
7092                let result: PickerResult = Rc::default();
7093                let mut parameters = StartPicker::new(material_type);
7094                parameters.entry_mode = TimePickerEntryMode::Input;
7095                start_picker(tester, &result, parameters);
7096
7097                let fields = text_field_texts(tester);
7098                assert_eq!(fields[0].0, "7"); // hour
7099                assert_eq!(fields[1].0, "00"); // minute
7100
7101                tester.enter_text(find::by_type::<EditableText>().at(0), "8");
7102                tester.enter_text(find::by_type::<EditableText>().at(1), "15");
7103                tester.pump();
7104                finish_picker(tester);
7105
7106                assert_eq!(picked_time(&result), Some(TimeOfDay::new(8, 15)));
7107            });
7108        }
7109    }
7110
7111    fn separator_style(tester: &WidgetTester) -> TextStyle {
7112        let separator = only_text(tester, ":");
7113        tester.widget(separator, |text: &Text| {
7114            text.style.clone().expect("a styled separator")
7115        })
7116    }
7117
7118    #[test]
7119    fn material3_time_selector_separator_default_text_style() {
7120        test_widgets(|tester| {
7121            let theme = m3(&tester.cell.borrow());
7122            let result: PickerResult = Rc::default();
7123            start_picker(tester, &result, StartPicker::new(MaterialType::Material3));
7124
7125            let style = separator_style(tester);
7126            assert_eq!(
7127                style.color.map(|color| color.color()),
7128                Some(theme.color_scheme.on_surface())
7129            );
7130            assert_eq!(style.font_size, Some(57.0));
7131        });
7132    }
7133
7134    #[test]
7135    fn material2_time_selector_separator_default_text_style() {
7136        test_widgets(|tester| {
7137            let theme = m2(&tester.cell.borrow());
7138            let result: PickerResult = Rc::default();
7139            start_picker(tester, &result, StartPicker::new(MaterialType::Material2));
7140
7141            let style = separator_style(tester);
7142            assert_eq!(
7143                style.color.map(|color| color.color()),
7144                Some(theme.color_scheme.on_surface())
7145            );
7146            assert_eq!(style.font_size, Some(56.0));
7147        });
7148    }
7149
7150    fn border_painter_size(tester: &WidgetTester) -> Size {
7151        tester.get_size(
7152            find::descendant(
7153                find::by_type::<crate::input_decorator::InputDecorator>().first(),
7154                find::by_type::<waft_widgets::CustomPaint>(),
7155            )
7156            .first(),
7157        )
7158    }
7159
7160    #[test]
7161    fn time_picker_hour_minute_does_not_resize_on_error() {
7162        test_widgets(|tester| {
7163            // Dart's cases give no `materialType`, which `startPicker` takes as Material 2, and
7164            // the explicit Material 2 one.
7165            {
7166                let material_type = MaterialType::Material2;
7167                let result: PickerResult = Rc::default();
7168                let mut parameters = StartPicker::new(material_type);
7169                parameters.entry_mode = TimePickerEntryMode::Input;
7170                start_picker(tester, &result, parameters);
7171
7172                assert_eq!(border_painter_size(tester), Size::new(96.0, 70.0));
7173
7174                // Enter invalid hour.
7175                tester.enter_text(find::by_type::<EditableText>().at(0), "AB");
7176                tester.tap(find::text(OK_STRING));
7177
7178                assert_eq!(border_painter_size(tester), Size::new(96.0, 70.0));
7179            }
7180        });
7181    }
7182
7183    #[test]
7184    fn time_picker_dialog_does_not_crash_at_zero_area() {
7185        test_widgets(|tester| {
7186            let theme = m3(&tester.cell.borrow());
7187            tester.pump_widget(material_app(
7188                theme,
7189                waft_widgets::Center::new()
7190                    .child(
7191                        SizedBox::new()
7192                            .width(0.0)
7193                            .height(0.0)
7194                            .child(TimePickerDialog::new(TimeOfDay::new(10, 12))),
7195                    )
7196                    .into_widget(),
7197            ));
7198            let dialog = tester.element(find::by_type::<TimePickerDialog>().at(0));
7199            assert_eq!(tester.get_size(dialog), Size::ZERO);
7200        });
7201    }
7202
7203    /// What the dial's `CustomPaint` paints: Dart's `paints` on its render object.
7204    fn dial_ops(tester: &WidgetTester) -> Vec<waft_embedder::valo::Op> {
7205        let paint = tester.element(
7206            find::descendant(
7207                find::by_type::<Dial>().at(0),
7208                find::by_type::<waft_widgets::CustomPaint>(),
7209            )
7210            .first(),
7211        );
7212        tester.painted_ops_deep(tester.render_object(paint))
7213    }
7214
7215    fn open_default_picker(tester: &mut WidgetTester, theme: ThemeData) {
7216        let home = Material::new()
7217            .child(
7218                waft_widgets::Center::new().child(Builder::new(move |_app, context| {
7219                    crate::elevated_button::ElevatedButton::new(
7220                        Some(Listener::new(move |app| {
7221                            drop(show_default(app, context));
7222                        })),
7223                        Some(Text::new("X")),
7224                    )
7225                    .into_widget()
7226                })),
7227            )
7228            .into_widget();
7229        tester.pump_widget(material_app(theme, home));
7230        tester.tap(find::text("X"));
7231        tester.pump_and_settle();
7232    }
7233
7234    #[test]
7235    #[allow(deprecated)]
7236    fn material3_dial_background_uses_correct_default_color() {
7237        test_widgets(|tester| {
7238            let theme = m3(&tester.cell.borrow());
7239
7240            open_default_picker(tester, theme.clone());
7241            // Test default dial background color.
7242            assert_paints(
7243                &dial_ops(tester),
7244                &[
7245                    PaintCall::circle(Some(theme.color_scheme.surface_container_highest())),
7246                    PaintCall::circle(Some(theme.color_scheme.primary())),
7247                ],
7248            );
7249
7250            tester.tap(find::text(OK_STRING)); // dismiss the dialog
7251            tester.pump_and_settle();
7252
7253            // Test dial background color when theme color scheme is changed.
7254            let theme = theme
7255                .copy_with()
7256                .color_scheme(
7257                    theme
7258                        .color_scheme
7259                        .copy_with()
7260                        .with_surface_variant(waft_embedder::Color::new(0xffff0000)),
7261                )
7262                .build();
7263            open_default_picker(tester, theme.clone());
7264            assert_paints(
7265                &dial_ops(tester),
7266                &[
7267                    PaintCall::circle(Some(theme.color_scheme.surface_container_highest())),
7268                    PaintCall::circle(Some(theme.color_scheme.primary())),
7269                ],
7270            );
7271        });
7272    }
7273
7274    /// Dart's `PickerObserver`: counts the dialog routes pushed.
7275    #[derive(Default)]
7276    struct PickerObserver {
7277        navigator_observer: waft_widgets::NavigatorObserverData,
7278        picker_count: Cell<u32>,
7279    }
7280
7281    impl waft_widgets::NavigatorObserver for PickerObserver {
7282        waft_widgets::navigator_observer_accessors!();
7283
7284        fn did_push(
7285            self: waft_foundation::Handle<Self>,
7286            app: &mut waft_foundation::App,
7287            route: waft_widgets::AnyRoute,
7288            _previous: Option<waft_widgets::AnyRoute>,
7289        ) {
7290            if route.downcast::<crate::dialog::DialogRoute>(app).is_some() {
7291                let count = &app.get(self).picker_count;
7292                count.set(count.get() + 1);
7293            }
7294        }
7295    }
7296
7297    /// The pickers the root and the nested navigator's observers saw.
7298    fn pickers_seen_by_root_and_nested(
7299        tester: &mut WidgetTester,
7300        use_root_navigator: bool,
7301    ) -> (u32, u32) {
7302        let (root_observer, nested_observer) = {
7303            let mut app = tester.cell.borrow_mut();
7304            (
7305                app.create(PickerObserver::default()),
7306                app.create(PickerObserver::default()),
7307            )
7308        };
7309        let root = {
7310            let app = tester.cell.borrow();
7311            crate::app::MaterialApp::new()
7312                .theme(m3(&app))
7313                .navigator_observers([root_observer.erase::<waft_widgets::AnyNavigatorObserver>()])
7314                .home(
7315                    waft_widgets::Navigator::new()
7316                        .observers([nested_observer.erase::<waft_widgets::AnyNavigatorObserver>()])
7317                        .on_generate_route(move |app, _settings| {
7318                            let route = crate::page::MaterialPageRoute::new(
7319                                app,
7320                                Rc::new(move |_app, context| {
7321                                    crate::elevated_button::ElevatedButton::new(
7322                                        Some(Listener::new(move |app| {
7323                                            drop({
7324                                                let mut show =
7325                                                    ShowTimePicker::new(TimeOfDay::new(7, 0));
7326                                                show = show.use_root_navigator(use_root_navigator);
7327                                                show.show(app, context)
7328                                            });
7329                                        })),
7330                                        Some(Text::new("Show Picker")),
7331                                    )
7332                                    .into_widget()
7333                                }),
7334                            );
7335                            Some(route.erase())
7336                        }),
7337                )
7338                .into_widget()
7339        };
7340        tester.pump_widget(root);
7341
7342        // Open the dialog.
7343        let button =
7344            tester.element(find::by_type::<crate::elevated_button::ElevatedButton>().at(0));
7345        let center = tester.get_center(button);
7346        tester.tap_at(center, 1);
7347
7348        let app = tester.cell.borrow();
7349        (
7350            app.get(&root_observer).picker_count.get(),
7351            app.get(&nested_observer).picker_count.get(),
7352        )
7353    }
7354
7355    #[test]
7356    fn time_picker_uses_root_navigator_by_default() {
7357        test_widgets(|tester| {
7358            assert_eq!(pickers_seen_by_root_and_nested(tester, true), (1, 0));
7359        });
7360    }
7361
7362    #[test]
7363    fn time_picker_uses_nested_navigator_if_use_root_navigator_is_false() {
7364        test_widgets(|tester| {
7365            assert_eq!(pickers_seen_by_root_and_nested(tester, false), (0, 1));
7366        });
7367    }
7368
7369    /// Dart's `find.ancestor(of: find.text(text), matching: find.byType(InkWell))`, which finds
7370    /// one ink well: the header's, not a dial label's.
7371    fn ink_well_above_text(tester: &WidgetTester, text: &str) -> AnyElement {
7372        let wells: Vec<AnyElement> = find::text(text)
7373            .evaluate(tester)
7374            .into_iter()
7375            .filter_map(|found| {
7376                let ancestors = tester.ancestors(found);
7377                let app = tester.cell.borrow();
7378                ancestors.into_iter().find(|ancestor| {
7379                    waft_widgets::downcast_widget::<crate::ink_well::InkWell>(
7380                        &**ancestor.widget(&app),
7381                    )
7382                    .is_some()
7383                })
7384            })
7385            .collect();
7386        assert_eq!(wells.len(), 1, "one ink well above {text:?}");
7387        wells[0]
7388    }
7389
7390    // 'header touch regions are large enough'.
7391    #[test]
7392    fn header_touch_regions_are_large_enough() {
7393        for material_type in pickers() {
7394            test_widgets(|tester| {
7395                // Ensure picker is displayed in portrait mode.
7396                let size = Size::new(400.0, 800.0);
7397                size_view(tester, size);
7398                media_query_boilerplate(tester, size, Boilerplate::new(material_type));
7399
7400                let day_period_control_size =
7401                    tester.get_size(tester.element(find::by_type::<DayPeriodControl>().at(0)));
7402                assert!(day_period_control_size.width() >= 48.0, "{material_type:?}");
7403                assert!(
7404                    day_period_control_size.height() >= 80.0,
7405                    "{material_type:?}"
7406                );
7407
7408                let hour_size = tester.get_size(ink_well_above_text(tester, "7"));
7409                assert!(hour_size.width() >= 48.0, "{material_type:?}");
7410                assert!(hour_size.height() >= 48.0, "{material_type:?}");
7411
7412                let minute_size = tester.get_size(ink_well_above_text(tester, "00"));
7413                assert!(minute_size.width() >= 48.0, "{material_type:?}");
7414                assert!(minute_size.height() >= 48.0, "{material_type:?}");
7415            });
7416        }
7417    }
7418
7419    #[test]
7420    fn time_picker_draws_without_overflows_at_various_view_sizes() {
7421        for material_type in pickers() {
7422            for size in [
7423                Size::new(100.0, 100.0),
7424                Size::new(300.0, 300.0),
7425                Size::new(800.0, 600.0),
7426            ] {
7427                for entry_mode in [TimePickerEntryMode::Dial, TimePickerEntryMode::Input] {
7428                    // Dart's layout asserts here too (the input mode's minimum height of 196
7429                    // is below its constraints' minimum of 216); its test hides the assertion
7430                    // with `isNot(throwsAssertionError)` on the exception object.
7431                    if entry_mode == TimePickerEntryMode::Input && size.height() < 216.0 {
7432                        continue;
7433                    }
7434                    test_widgets(|tester| {
7435                        // Dart sets `physicalSize = size` at flutter_test's device pixel ratio,
7436                        // a view of size / 3 logical pixels, whose layout asserts (hidden by
7437                        // `isNot(throwsAssertionError)`, which always holds) panic here: the
7438                        // sizes are the logical ones.
7439                        size_view(tester, size);
7440                        let mut boilerplate = Boilerplate::new(material_type);
7441                        boilerplate.entry_mode = entry_mode;
7442                        media_query_boilerplate(tester, size, boilerplate);
7443                        tester.pump_and_settle();
7444                        assert_eq!(
7445                            find::by_type::<TimePickerDialog>().evaluate(tester).len(),
7446                            1,
7447                            "{material_type:?} {entry_mode:?} at {size:?}"
7448                        );
7449                    });
7450                }
7451            }
7452        }
7453    }
7454    #[test]
7455    fn hour_and_minute_fields_are_top_aligned_with_the_separator() {
7456        for material_type in pickers() {
7457            test_widgets(|tester| {
7458                let result: PickerResult = Rc::default();
7459                let mut parameters = StartPicker::new(material_type);
7460                parameters.entry_mode = TimePickerEntryMode::Input;
7461                start_picker(tester, &result, parameters);
7462
7463                let top = |element: AnyElement| {
7464                    crate::chip::tests::rect_of(tester, element).top_left().dy()
7465                };
7466                let hour_field_top = top(tester.element(find::by_type::<HourTextField>().at(0)));
7467                let minute_field_top =
7468                    top(tester.element(find::by_type::<MinuteTextField>().at(0)));
7469                let separator_top =
7470                    top(tester.element(find::by_type::<TimeSelectorSeparator>().at(0)));
7471                assert_eq!(hour_field_top, separator_top, "{material_type:?}");
7472                assert_eq!(minute_field_top, separator_top, "{material_type:?}");
7473            });
7474        }
7475    }
7476
7477    #[test]
7478    fn can_switch_between_hour_minute_fields_using_keyboard_input_action() {
7479        for material_type in pickers() {
7480            test_widgets(|tester| {
7481                let result: PickerResult = Rc::default();
7482                let mut parameters = StartPicker::new(material_type);
7483                parameters.entry_mode = TimePickerEntryMode::Input;
7484                start_picker(tester, &result, parameters);
7485
7486                let field = |tester: &WidgetTester, index: usize| {
7487                    tester.widget(
7488                        tester.element(find::by_type::<crate::text_field::TextField>().at(index)),
7489                        |field: &crate::text_field::TextField| field.clone(),
7490                    )
7491                };
7492                let has_focus = |tester: &WidgetTester, index: usize| {
7493                    let node = field(tester, index).focus_node.expect("a focus node");
7494                    node.has_focus(&tester.cell.borrow_mut())
7495                };
7496                let last = text_field_count(tester) - 1;
7497
7498                let hour = tester.element(find::by_type::<crate::text_field::TextField>().at(0));
7499                let center = tester.get_center(hour);
7500                tester.tap_at(center, 1);
7501                assert!(has_focus(tester, 0), "{material_type:?}");
7502
7503                tester.enter_text(find::by_type::<EditableText>().at(0), "08");
7504                assert!(!has_focus(tester, 0), "{material_type:?}");
7505                assert!(has_focus(tester, last), "{material_type:?}");
7506
7507                assert_eq!(
7508                    field(tester, last).text_input_action,
7509                    Some(waft_services::TextInputAction::Done)
7510                );
7511                tester
7512                    .test_text_input()
7513                    .receive_action(waft_services::TextInputAction::Done);
7514                assert!(!has_focus(tester, 0), "{material_type:?}");
7515                assert!(!has_focus(tester, last), "{material_type:?}");
7516            });
7517        }
7518    }
7519}