Skip to main content

waft_material/
date_picker.rs

1//! Flutter counterpart: material_ui's `date_picker.dart`.
2//!
3//! The date picker dialogs and the builders that show them: [`ShowDatePicker`] with
4//! [`DatePickerDialog`], and [`ShowDateRangePicker`] with [`DateRangePickerDialog`].
5
6use crate::action_buttons::CloseButton;
7use crate::app_bar::AppBar;
8use crate::calendar_date_picker::{
9    CalendarDatePicker, CalendarDatePickerDayBuilder, CalendarDatePickerWeekdayBuilder,
10};
11use crate::date::{
12    CalendarDelegate, DatePickerEntryMode, DatePickerMode, DateTimeRange,
13    GregorianCalendarDelegate, is_day_before,
14};
15use crate::date_picker_theme::DatePickerTheme;
16use crate::dialog::{Dialog, ShowDialog};
17use crate::divider::{Divider, VerticalDivider};
18use crate::icon_button::IconButton;
19use crate::icons::Icons;
20use crate::ink_well::InkResponse;
21use crate::input_border::{InputBorderRef, OutlineInputBorder, UnderlineInputBorder};
22use crate::input_date_picker_form_field::InputDatePickerFormField;
23use crate::input_decorator::{InputDecoration, InputDecorationTheme};
24use crate::material::Material;
25use crate::material_localizations::MaterialLocalizations;
26use crate::scaffold::Scaffold;
27use crate::text_button::TextButton;
28use crate::text_field::TextField;
29use crate::theme::Theme;
30use std::any::TypeId;
31use std::collections::HashMap;
32use std::fmt;
33use std::rc::Rc;
34use std::time::Duration;
35use waft_animation::Curves;
36use waft_embedder::{
37    Canvas, Clip, Color, Locale, Paint, Rect, Size, TargetPlatform, TextSelection,
38};
39use waft_foundation::{
40    App, CompleterFuture, DateTime, Handle, ListenableObject, Listener, Ref, UniqueKey,
41    ValueChanged,
42};
43use waft_painting::{
44    Alignment, AlignmentDirectional, AlignmentGeometry, BorderSide, CircleBorder, EdgeInsets,
45    EdgeInsetsDirectional, EdgeInsetsGeometry, OutlinedBorderRef, ShapeBorderRef, ShapeDecoration,
46    TextOverflow, TextStyle, axis_direction_is_reversed,
47};
48use waft_rendering::{
49    BoxConstraints, CrossAxisAlignment, CustomPainter, MainAxisAlignment, MainAxisSize,
50    SliverConstraints, SliverGridDelegate, SliverGridGeometry, SliverGridLayout,
51};
52use waft_services::{HapticFeedback, LogicalKeyboardKey, TextInputType};
53use waft_widgets::{
54    ActionRef, Align, AnimatedContainer, AutovalidateMode, BuildContext, Builder, CallbackAction,
55    Center, ColoredBox, Column, ConstrainedBox, Container, CustomPaint, CustomScrollView,
56    DirectionalFocusIntent, Directionality, ExcludeSemantics, Expanded, Flexible, FocusNode,
57    FocusNodeLeaf, FocusableActionDetector, Form, FormState, GlobalKey, GridView, Icon, IconTheme,
58    IconThemeData, InheritedWidget, IntentRef, IntoWidget, KeyRef, LayoutBuilder, LimitedBox,
59    Localizations, MediaQuery, Navigator, NextFocusIntent, Orientation, OverflowBar, Padding,
60    PreferredSize, PreferredSizeWidgetRef, PreviousFocusIntent, RestorableBool,
61    RestorableDateTimeN, RestorableEnum, RestorableProperty, RestorableValue, RestorationMixin,
62    RestorationMixinData, RouteResult, RouteSettingsRef, Row, SafeArea, ScrollController,
63    ScrollControllerLeaf, ScrollPositionAlignmentPolicy, Scrollable, SelectableDayPredicate,
64    Semantics, ShortcutActivatorRef, ShortcutMap, Shortcuts, SingleActivator, SizedBox,
65    SliverChildListDelegate, SliverList, Spacer, State, StateData, StatefulWidget, StatelessWidget,
66    Text, TextDirection, TextEditingController, TextEditingControllerLeaf, TransitionBuilder,
67    TraversalDirection, WidgetRef, WidgetStateProperty, WidgetStates, WidgetStatesController,
68};
69
70const CALENDAR_PORTRAIT_DIALOG_SIZE_M2: Size = Size::new(330.0, 518.0);
71const CALENDAR_PORTRAIT_DIALOG_SIZE_M3: Size = Size::new(360.0, 568.0);
72const CALENDAR_LANDSCAPE_DIALOG_SIZE: Size = Size::new(496.0, 346.0);
73const INPUT_PORTRAIT_DIALOG_SIZE_M2: Size = Size::new(330.0, 270.0);
74const INPUT_PORTRAIT_DIALOG_SIZE_M3: Size = Size::new(328.0, 270.0);
75const INPUT_LANDSCAPE_DIALOG_SIZE: Size = Size::new(496.0, 160.0);
76const INPUT_RANGE_LANDSCAPE_DIALOG_SIZE: Size = Size::new(496.0, 164.0);
77const DIALOG_SIZE_ANIMATION_DURATION: Duration = Duration::from_millis(200);
78const INPUT_FORM_PORTRAIT_HEIGHT: f64 = 98.0;
79const INPUT_FORM_LANDSCAPE_HEIGHT: f64 = 108.0;
80
81// 3.0 is the maximum scale factor on mobile phones. As of 07/30/24, iOS goes up to a max of
82// 3.310 on each of 2 flavors of text scaling, and Android goes up to 2.0 on its text scaling.
83const MAX_TEXT_SCALE_FACTOR: f64 = 3.0;
84
85// Max scale factor for the range pickers, whose layout does not have space to grow.
86const MAX_RANGE_TEXT_SCALE_FACTOR: f64 = 1.3;
87
88// Max scale factor for the header, which fits in a fixed-height container.
89const MAX_HEADER_TEXT_SCALE_FACTOR: f64 = 1.6;
90
91// Max scale factor for the header when it has an entry mode button.
92const MAX_HEADER_WITH_ENTRY_TEXT_SCALE_FACTOR: f64 = 1.4;
93
94const MAX_HELP_PORTRAIT_TEXT_SCALE_FACTOR: f64 = 1.6;
95const MAX_HELP_LANDSCAPE_TEXT_SCALE_FACTOR: f64 = 1.4;
96
97// 14 is a common font size used to compute the effective text scale.
98const FONT_SIZE_TO_SCALE: f64 = 14.0;
99
100/// Shows a dialog containing a Material Design date picker.
101///
102/// The returned future resolves when the user closes the dialog. If the user cancels the dialog,
103/// it resolves with null; otherwise it resolves to the selected [`DateTime`] (inside the
104/// [`RouteResult`]).
105///
106/// An optional `initial_date` tells the picker which date to open on; with none the picker
107/// shows the input mode without a date. The `first_date` is the earliest allowable date and the
108/// `last_date` the latest. The `initial_date`, if given, must not be outside that range, and
109/// must satisfy the `selectable_day_predicate`.
110///
111/// The `current_date` represents the current day (i.e. today). This date will be highlighted in
112/// the day grid. If null, the date of `calendar_delegate.now()` will be used.
113///
114/// An optional `initial_entry_mode` argument can be used to display the date picker in the
115/// [`DatePickerEntryMode::Calendar`] (a calendar month grid) or [`DatePickerEntryMode::Input`]
116/// (a text input field) mode. It defaults to [`DatePickerEntryMode::Calendar`].
117///
118/// An optional `selectable_day_predicate` function can be passed in to customize the days to
119/// enable for selection. If provided, only the days that `selectable_day_predicate` returns
120/// true for will be selectable.
121///
122/// The following optional string parameters allow you to override the default text used for
123/// various parts of the dialog: `help_text`, `cancel_text`, `confirm_text`, `error_format_text`,
124/// `error_invalid_text`, `field_hint_text` and `field_label_text`.
125///
126/// An optional `locale` argument can be used to set the locale for the date picker. It defaults
127/// to the ambient locale provided by [`Localizations`].
128///
129/// An optional `text_direction` argument can be used to set the text direction
130/// ([`TextDirection::Ltr`] or [`TextDirection::Rtl`]) for the date picker. It defaults to the
131/// ambient text direction provided by `Directionality`.
132///
133/// The `builder` parameter can be used to wrap the dialog widget to add inherited widgets like
134/// [`Theme`](crate::Theme).
135///
136/// An optional `initial_date_picker_mode` argument can be used to have the calendar
137/// date picker initially appear in the [`DatePickerMode::Year`] or [`DatePickerMode::Day`]
138/// mode. It defaults to [`DatePickerMode::Day`].
139///
140/// The `on_date_picker_mode_change` callback is called when the user toggles the entry mode.
141///
142/// The `calendar_delegate` provides the calendar the dialog works in; it defaults to the
143/// Gregorian calendar.
144///
145/// Dart's `anchorPoint` waits for `ShowDialog` to take one.
146pub struct ShowDatePicker {
147    initial_date: Option<DateTime>,
148    first_date: DateTime,
149    last_date: DateTime,
150    current_date: Option<DateTime>,
151    initial_entry_mode: DatePickerEntryMode,
152    selectable_day_predicate: Option<SelectableDayPredicate>,
153    help_text: Option<String>,
154    cancel_text: Option<String>,
155    confirm_text: Option<String>,
156    locale: Option<Locale>,
157    barrier_dismissible: bool,
158    barrier_color: Option<Color>,
159    barrier_label: Option<String>,
160    use_root_navigator: bool,
161    route_settings: Option<RouteSettingsRef>,
162    text_direction: Option<TextDirection>,
163    builder: Option<TransitionBuilder>,
164    initial_date_picker_mode: DatePickerMode,
165    error_format_text: Option<String>,
166    error_invalid_text: Option<String>,
167    field_hint_text: Option<String>,
168    field_label_text: Option<String>,
169    keyboard_type: Option<TextInputType>,
170    on_date_picker_mode_change: Option<ValueChanged<DatePickerEntryMode>>,
171    switch_to_input_entry_mode_icon: Option<WidgetRef>,
172    switch_to_calendar_entry_mode_icon: Option<WidgetRef>,
173    day_builder: Option<CalendarDatePickerDayBuilder>,
174    weekday_builder: Option<CalendarDatePickerWeekdayBuilder>,
175    calendar_delegate: Rc<dyn CalendarDelegate>,
176}
177
178impl ShowDatePicker {
179    /// Creates a builder for a Material date picker; Dart's `showDatePicker` required arguments
180    /// are the first and last dates, and every other argument is a setter.
181    pub fn new(first_date: DateTime, last_date: DateTime) -> ShowDatePicker {
182        ShowDatePicker {
183            initial_date: None,
184            first_date,
185            last_date,
186            current_date: None,
187            initial_entry_mode: DatePickerEntryMode::Calendar,
188            selectable_day_predicate: None,
189            help_text: None,
190            cancel_text: None,
191            confirm_text: None,
192            locale: None,
193            barrier_dismissible: true,
194            barrier_color: None,
195            barrier_label: None,
196            use_root_navigator: true,
197            route_settings: None,
198            text_direction: None,
199            builder: None,
200            initial_date_picker_mode: DatePickerMode::Day,
201            error_format_text: None,
202            error_invalid_text: None,
203            field_hint_text: None,
204            field_label_text: None,
205            keyboard_type: None,
206            on_date_picker_mode_change: None,
207            switch_to_input_entry_mode_icon: None,
208            switch_to_calendar_entry_mode_icon: None,
209            day_builder: None,
210            weekday_builder: None,
211            calendar_delegate: Rc::new(GregorianCalendarDelegate),
212        }
213    }
214
215    /// Which date the picker opens on; with none, it opens in the input mode without a date.
216    pub fn initial_date(mut self, initial_date: DateTime) -> ShowDatePicker {
217        self.initial_date = Some(initial_date);
218        self
219    }
220
221    /// The current day, highlighted in the day grid; defaults to the calendar delegate's today.
222    pub fn current_date(mut self, current_date: DateTime) -> ShowDatePicker {
223        self.current_date = Some(current_date);
224        self
225    }
226
227    /// The entry mode the picker opens in. Defaults to `DatePickerEntryMode::Calendar`.
228    pub fn initial_entry_mode(mut self, initial_entry_mode: DatePickerEntryMode) -> ShowDatePicker {
229        self.initial_entry_mode = initial_entry_mode;
230        self
231    }
232
233    /// Which days may be selected.
234    pub fn selectable_day_predicate(
235        mut self,
236        selectable_day_predicate: SelectableDayPredicate,
237    ) -> ShowDatePicker {
238        self.selectable_day_predicate = Some(selectable_day_predicate);
239        self
240    }
241
242    /// The text of the help label.
243    pub fn help_text(mut self, help_text: impl Into<String>) -> ShowDatePicker {
244        self.help_text = Some(help_text.into());
245        self
246    }
247
248    /// The text of the cancel button.
249    pub fn cancel_text(mut self, cancel_text: impl Into<String>) -> ShowDatePicker {
250        self.cancel_text = Some(cancel_text.into());
251        self
252    }
253
254    /// The text of the confirm button.
255    pub fn confirm_text(mut self, confirm_text: impl Into<String>) -> ShowDatePicker {
256        self.confirm_text = Some(confirm_text.into());
257        self
258    }
259
260    /// The locale of the date picker; defaults to the ambient locale.
261    pub fn locale(mut self, locale: Locale) -> ShowDatePicker {
262        self.locale = Some(locale);
263        self
264    }
265
266    /// Whether tapping on the barrier dismisses the dialog. Defaults to `true`.
267    pub fn barrier_dismissible(mut self, barrier_dismissible: bool) -> ShowDatePicker {
268        self.barrier_dismissible = barrier_dismissible;
269        self
270    }
271
272    /// The color of the modal barrier below the dialog.
273    pub fn barrier_color(mut self, barrier_color: Color) -> ShowDatePicker {
274        self.barrier_color = Some(barrier_color);
275        self
276    }
277
278    /// The semantic label of the dialog's modal barrier.
279    pub fn barrier_label(mut self, barrier_label: impl Into<String>) -> ShowDatePicker {
280        self.barrier_label = Some(barrier_label.into());
281        self
282    }
283
284    /// Whether to push the dialog to the root navigator. Defaults to `true`.
285    pub fn use_root_navigator(mut self, use_root_navigator: bool) -> ShowDatePicker {
286        self.use_root_navigator = use_root_navigator;
287        self
288    }
289
290    /// The route settings passed to the dialog route.
291    pub fn route_settings(mut self, route_settings: RouteSettingsRef) -> ShowDatePicker {
292        self.route_settings = Some(route_settings);
293        self
294    }
295
296    /// The text direction of the date picker; defaults to the ambient direction.
297    pub fn text_direction(mut self, text_direction: TextDirection) -> ShowDatePicker {
298        self.text_direction = Some(text_direction);
299        self
300    }
301
302    /// Wraps the dialog to add inherited widgets such as a theme.
303    pub fn builder(mut self, builder: TransitionBuilder) -> ShowDatePicker {
304        self.builder = Some(builder);
305        self
306    }
307
308    /// The mode the calendar opens in. Defaults to `DatePickerMode::Day`.
309    pub fn initial_date_picker_mode(
310        mut self,
311        initial_date_picker_mode: DatePickerMode,
312    ) -> ShowDatePicker {
313        self.initial_date_picker_mode = initial_date_picker_mode;
314        self
315    }
316
317    /// The text of the error for an unparseable date.
318    pub fn error_format_text(mut self, error_format_text: impl Into<String>) -> ShowDatePicker {
319        self.error_format_text = Some(error_format_text.into());
320        self
321    }
322
323    /// The text of the error for an invalid date.
324    pub fn error_invalid_text(mut self, error_invalid_text: impl Into<String>) -> ShowDatePicker {
325        self.error_invalid_text = Some(error_invalid_text.into());
326        self
327    }
328
329    /// The hint text of the input field.
330    pub fn field_hint_text(mut self, field_hint_text: impl Into<String>) -> ShowDatePicker {
331        self.field_hint_text = Some(field_hint_text.into());
332        self
333    }
334
335    /// The label text of the input field.
336    pub fn field_label_text(mut self, field_label_text: impl Into<String>) -> ShowDatePicker {
337        self.field_label_text = Some(field_label_text.into());
338        self
339    }
340
341    /// The keyboard type of the input field.
342    pub fn keyboard_type(mut self, keyboard_type: TextInputType) -> ShowDatePicker {
343        self.keyboard_type = Some(keyboard_type);
344        self
345    }
346
347    /// Called when the user toggles the entry mode.
348    pub fn on_date_picker_mode_change(
349        mut self,
350        on_date_picker_mode_change: ValueChanged<DatePickerEntryMode>,
351    ) -> ShowDatePicker {
352        self.on_date_picker_mode_change = Some(on_date_picker_mode_change);
353        self
354    }
355
356    /// The icon that switches to the input entry mode.
357    #[cfg_attr(debug_assertions, track_caller)]
358    pub fn switch_to_input_entry_mode_icon<K>(
359        mut self,
360        switch_to_input_entry_mode_icon: impl IntoWidget<K>,
361    ) -> ShowDatePicker {
362        self.switch_to_input_entry_mode_icon = Some(switch_to_input_entry_mode_icon.into_widget());
363        self
364    }
365
366    /// The icon that switches to the calendar entry mode.
367    #[cfg_attr(debug_assertions, track_caller)]
368    pub fn switch_to_calendar_entry_mode_icon<K>(
369        mut self,
370        switch_to_calendar_entry_mode_icon: impl IntoWidget<K>,
371    ) -> ShowDatePicker {
372        self.switch_to_calendar_entry_mode_icon =
373            Some(switch_to_calendar_entry_mode_icon.into_widget());
374        self
375    }
376
377    /// Builds a day cell.
378    pub fn day_builder(mut self, day_builder: CalendarDatePickerDayBuilder) -> ShowDatePicker {
379        self.day_builder = Some(day_builder);
380        self
381    }
382
383    /// Builds a weekday header cell.
384    pub fn weekday_builder(
385        mut self,
386        weekday_builder: CalendarDatePickerWeekdayBuilder,
387    ) -> ShowDatePicker {
388        self.weekday_builder = Some(weekday_builder);
389        self
390    }
391
392    /// The calendar the dialog works in. Defaults to the Gregorian calendar.
393    pub fn calendar_delegate(
394        mut self,
395        calendar_delegate: Rc<dyn CalendarDelegate>,
396    ) -> ShowDatePicker {
397        self.calendar_delegate = calendar_delegate;
398        self
399    }
400
401    /// Shows the dialog and returns a future that resolves when the user closes it.
402    pub fn show(self, app: &mut App, context: BuildContext) -> CompleterFuture<RouteResult> {
403        let ShowDatePicker {
404            initial_date,
405            first_date,
406            last_date,
407            current_date,
408            initial_entry_mode,
409            selectable_day_predicate,
410            help_text,
411            cancel_text,
412            confirm_text,
413            locale,
414            barrier_dismissible,
415            barrier_color,
416            barrier_label,
417            use_root_navigator,
418            route_settings,
419            text_direction,
420            builder,
421            initial_date_picker_mode,
422            error_format_text,
423            error_invalid_text,
424            field_hint_text,
425            field_label_text,
426            keyboard_type,
427            on_date_picker_mode_change,
428            switch_to_input_entry_mode_icon,
429            switch_to_calendar_entry_mode_icon,
430            day_builder,
431            weekday_builder,
432            calendar_delegate,
433        } = self;
434        let initial_date = initial_date.map(|date| calendar_delegate.date_only(app, &date));
435        let first_date = calendar_delegate.date_only(app, &first_date);
436        let last_date = calendar_delegate.date_only(app, &last_date);
437        assert!(
438            !last_date.is_before(&first_date),
439            "lastDate {} must be on or after firstDate {}.",
440            last_date.to_string(app),
441            first_date.to_string(app)
442        );
443        assert!(
444            initial_date.is_none_or(|date| !date.is_before(&first_date)),
445            "initialDate {:?} must be on or after firstDate {}.",
446            initial_date.map(|date| date.to_string(app)),
447            first_date.to_string(app)
448        );
449        assert!(
450            initial_date.is_none_or(|date| !date.is_after(&last_date)),
451            "initialDate {:?} must be on or before lastDate {}.",
452            initial_date.map(|date| date.to_string(app)),
453            last_date.to_string(app)
454        );
455        assert!(
456            selectable_day_predicate
457                .as_ref()
458                .zip(initial_date)
459                .is_none_or(|(predicate, date)| predicate(app, date)),
460            "Provided initialDate {initial_date:?} must satisfy provided selectableDayPredicate."
461        );
462        debug_assert!(crate::debug::debug_check_has_material_localizations(
463            app, context
464        ));
465
466        let mut dialog = DatePickerDialog::new(first_date, last_date)
467            .initial_entry_mode(initial_entry_mode)
468            .initial_calendar_mode(initial_date_picker_mode)
469            .calendar_delegate(Rc::clone(&calendar_delegate));
470        dialog.initial_date = initial_date;
471        dialog.current_date = current_date;
472        dialog.selectable_day_predicate = selectable_day_predicate;
473        dialog.help_text = help_text;
474        dialog.cancel_text = cancel_text;
475        dialog.confirm_text = confirm_text;
476        dialog.error_format_text = error_format_text;
477        dialog.error_invalid_text = error_invalid_text;
478        dialog.field_hint_text = field_hint_text;
479        dialog.field_label_text = field_label_text;
480        dialog.keyboard_type = keyboard_type;
481        dialog.on_date_picker_mode_change = on_date_picker_mode_change;
482        dialog.switch_to_input_entry_mode_icon = switch_to_input_entry_mode_icon;
483        dialog.switch_to_calendar_entry_mode_icon = switch_to_calendar_entry_mode_icon;
484        dialog.day_builder = day_builder;
485        dialog.weekday_builder = weekday_builder;
486        let mut dialog = dialog.into_widget();
487
488        if let Some(text_direction) = text_direction {
489            dialog = Directionality::new(text_direction, dialog).into_widget();
490        }
491
492        if let Some(locale) = locale {
493            dialog = Localizations::r#override(app, context)
494                .locale(locale)
495                .child(dialog)
496                .into_widget();
497        } else if let Some(locale) = DatePickerTheme::of(app, context).locale {
498            dialog = Localizations::r#override(app, context)
499                .locale(locale)
500                .child(dialog)
501                .into_widget();
502        }
503
504        let mut show = ShowDialog::new(Rc::new(move |app, context| match &builder {
505            None => dialog.clone(),
506            Some(builder) => builder(app, context, Some(&dialog)),
507        }))
508        .barrier_dismissible(barrier_dismissible)
509        .use_root_navigator(use_root_navigator);
510        if let Some(barrier_color) = barrier_color {
511            show = show.barrier_color(barrier_color);
512        }
513        if let Some(barrier_label) = barrier_label {
514            show = show.barrier_label(barrier_label);
515        }
516        if let Some(route_settings) = route_settings {
517            show = show.route_settings(route_settings);
518        }
519        show.show(app, context)
520    }
521}
522
523const ENTRY_MODES: [DatePickerEntryMode; 4] = [
524    DatePickerEntryMode::Calendar,
525    DatePickerEntryMode::Input,
526    DatePickerEntryMode::CalendarOnly,
527    DatePickerEntryMode::InputOnly,
528];
529const AUTOVALIDATE_MODES: [AutovalidateMode; 4] = [
530    AutovalidateMode::Disabled,
531    AutovalidateMode::Always,
532    AutovalidateMode::OnUserInteraction,
533    AutovalidateMode::OnUnfocus,
534];
535
536/// A Material-style date picker dialog.
537///
538/// It displays a calendar grid of days, allowing the user to select a date, and a button to
539/// switch to a text field where a date can be typed.
540///
541/// It is used by [`ShowDatePicker`], which should usually be used
542/// rather than creating a [`DatePickerDialog`] directly.
543///
544/// See also: [`CalendarDatePicker`], [`InputDatePickerFormField`], [`ShowDatePicker`],
545/// [`DateRangePickerDialog`](crate::DateRangePickerDialog).
546///
547/// [`ShowDatePicker`]: crate::ShowDatePicker
548#[derive(Clone)]
549pub struct DatePickerDialog {
550    pub key: Option<waft_widgets::KeyRef>,
551
552    /// The initially selected [`DateTime`] that the picker should display.
553    ///
554    /// If this is null, there is no selected date. A date must be selected to submit the dialog.
555    pub initial_date: Option<DateTime>,
556
557    /// The earliest allowable [`DateTime`] that the user can select.
558    pub first_date: DateTime,
559
560    /// The latest allowable [`DateTime`] that the user can select.
561    pub last_date: DateTime,
562
563    /// The [`DateTime`] representing today. It will be highlighted in the day grid. If null,
564    /// the date of the calendar delegate's [`now`](CalendarDelegate::now) is used.
565    pub current_date: Option<DateTime>,
566
567    /// The initial mode of date entry method for the date picker dialog.
568    ///
569    /// See [`DatePickerEntryMode`] for the different data entry modes.
570    pub initial_entry_mode: DatePickerEntryMode,
571
572    /// Function to provide full control over which [`DateTime`] can be selected.
573    pub selectable_day_predicate: Option<SelectableDayPredicate>,
574
575    /// The text that is displayed on the cancel button.
576    pub cancel_text: Option<String>,
577
578    /// The text that is displayed on the confirm button.
579    pub confirm_text: Option<String>,
580
581    /// The text that is displayed at the top of the header.
582    ///
583    /// This is used to indicate to the user what they are selecting a date for.
584    pub help_text: Option<String>,
585
586    /// The initial display of the calendar picker.
587    pub initial_calendar_mode: DatePickerMode,
588
589    /// The error text displayed if the entered date is not in the correct format.
590    pub error_format_text: Option<String>,
591
592    /// The error text displayed if the date is not valid.
593    ///
594    /// A date is not valid if it is earlier than [`first_date`](Self::first_date), later than
595    /// [`last_date`](Self::last_date), or doesn't pass the
596    /// [`selectable_day_predicate`](Self::selectable_day_predicate).
597    pub error_invalid_text: Option<String>,
598
599    /// The hint text displayed in the [`TextField`](crate::TextField).
600    ///
601    /// If this is null, it will default to the date format string. For example, 'mm/dd/yyyy'
602    /// for en_US.
603    pub field_hint_text: Option<String>,
604
605    /// The label text displayed in the [`TextField`](crate::TextField).
606    ///
607    /// If this is null, it will default to the words representing the date format string. For
608    /// example, 'Enter Date' for en_US.
609    pub field_label_text: Option<String>,
610
611    /// The keyboard type of the [`TextField`](crate::TextField).
612    ///
613    /// If this is null, it will default to [`TextInputType::datetime`].
614    pub keyboard_type: Option<TextInputType>,
615
616    /// Restoration ID to save and restore the state of the [`DatePickerDialog`].
617    ///
618    /// If it is non-null, the date picker will persist and restore the date selected on the
619    /// dialog.
620    ///
621    /// The state of this widget is persisted in a `RestorationBucket` claimed from the
622    /// surrounding `RestorationScope` using the provided restoration ID.
623    pub restoration_id: Option<String>,
624
625    /// Called when the [`DatePickerDialog`] is toggled between
626    /// [`DatePickerEntryMode::Calendar`] and [`DatePickerEntryMode::Input`].
627    pub on_date_picker_mode_change: Option<ValueChanged<DatePickerEntryMode>>,
628
629    /// An optional icon that, when pressed, switches from the calendar to the text input.
630    pub switch_to_input_entry_mode_icon: Option<WidgetRef>,
631
632    /// An optional icon that, when pressed, switches from the text input to the calendar.
633    pub switch_to_calendar_entry_mode_icon: Option<WidgetRef>,
634
635    /// The padding that surrounds the dialog.
636    pub inset_padding: EdgeInsets,
637
638    /// Called to construct the widget for a day in the calendar grid.
639    pub day_builder: Option<CalendarDatePickerDayBuilder>,
640
641    /// Called to construct the widget for a weekday header.
642    pub weekday_builder: Option<CalendarDatePickerWeekdayBuilder>,
643
644    /// The calendar the dialog works in.
645    pub calendar_delegate: Rc<dyn CalendarDelegate>,
646}
647
648impl DatePickerDialog {
649    /// Creates a [`DatePickerDialog`]. Dart's optional named arguments are the fluent setters.
650    ///
651    /// The dates are kept as given; the calendar delegate truncates each to its day where the
652    /// dialog reads it, as Dart's constructor truncates them.
653    pub fn new(first_date: DateTime, last_date: DateTime) -> DatePickerDialog {
654        let calendar_delegate: Rc<dyn CalendarDelegate> = Rc::new(GregorianCalendarDelegate);
655        DatePickerDialog {
656            key: None,
657            initial_date: None,
658            first_date,
659            last_date,
660            current_date: None,
661            initial_entry_mode: DatePickerEntryMode::Calendar,
662            selectable_day_predicate: None,
663            cancel_text: None,
664            confirm_text: None,
665            help_text: None,
666            initial_calendar_mode: DatePickerMode::Day,
667            error_format_text: None,
668            error_invalid_text: None,
669            field_hint_text: None,
670            field_label_text: None,
671            keyboard_type: None,
672            restoration_id: None,
673            on_date_picker_mode_change: None,
674            switch_to_input_entry_mode_icon: None,
675            switch_to_calendar_entry_mode_icon: None,
676            inset_padding: EdgeInsets::symmetric(24.0, 16.0),
677            day_builder: None,
678            weekday_builder: None,
679            calendar_delegate,
680        }
681    }
682
683    /// Dart's constructor asserts on the dates, by their days, which are read in the local time
684    /// zone: run in `init_state` and `did_update_widget`, for every widget the state is given,
685    /// since a constructor has no [`App`].
686    fn debug_check_dates(&self, app: &App) {
687        debug_assert!(
688            !is_day_before(app, &self.last_date, &self.first_date),
689            "lastDate {} must be on or after firstDate {}.",
690            self.last_date.to_string(app),
691            self.first_date.to_string(app)
692        );
693        debug_assert!(
694            self.initial_date
695                .is_none_or(|date| !is_day_before(app, &date, &self.first_date)),
696            "initialDate {:?} must be on or after firstDate {}.",
697            self.initial_date.map(|date| date.to_string(app)),
698            self.first_date.to_string(app)
699        );
700        debug_assert!(
701            self.initial_date
702                .is_none_or(|date| !is_day_before(app, &self.last_date, &date)),
703            "initialDate {:?} must be on or before lastDate {}.",
704            self.initial_date.map(|date| date.to_string(app)),
705            self.last_date.to_string(app)
706        );
707    }
708
709    /// Dart's `initialDate` field, as its constructor fills it: the day of the date given.
710    pub fn effective_initial_date(&self, app: &App) -> Option<DateTime> {
711        self.initial_date
712            .map(|date| self.calendar_delegate.date_only(app, &date))
713    }
714
715    /// Dart's constructor assert that the initial day satisfies `selectableDayPredicate`, which
716    /// takes the day `date_only` makes, so it runs once the `App` is at hand.
717    fn debug_check_initial_date_is_selectable(&self, app: &App) {
718        debug_assert!(
719            self.selectable_day_predicate
720                .as_ref()
721                .zip(self.effective_initial_date(app))
722                .is_none_or(|(predicate, date)| predicate(app, date)),
723            "Provided initialDate {:?} must satisfy provided selectableDayPredicate",
724            self.effective_initial_date(app)
725        );
726    }
727
728    /// Dart `DatePickerDialog(key:)`.
729    pub fn key(mut self, key: waft_widgets::KeyRef) -> DatePickerDialog {
730        self.key = Some(key);
731        self
732    }
733
734    /// Dart `DatePickerDialog(initialDate:)`.
735    pub fn initial_date(mut self, initial_date: DateTime) -> DatePickerDialog {
736        self.initial_date = Some(initial_date);
737        self
738    }
739
740    /// Dart `DatePickerDialog(currentDate:)`.
741    pub fn current_date(mut self, current_date: DateTime) -> DatePickerDialog {
742        self.current_date = Some(current_date);
743        self
744    }
745
746    /// Dart `DatePickerDialog(initialEntryMode:)`.
747    pub fn initial_entry_mode(
748        mut self,
749        initial_entry_mode: DatePickerEntryMode,
750    ) -> DatePickerDialog {
751        self.initial_entry_mode = initial_entry_mode;
752        self
753    }
754
755    /// Dart `DatePickerDialog(selectableDayPredicate:)`.
756    pub fn selectable_day_predicate(
757        mut self,
758        selectable_day_predicate: SelectableDayPredicate,
759    ) -> DatePickerDialog {
760        self.selectable_day_predicate = Some(selectable_day_predicate);
761        self
762    }
763
764    /// Dart `DatePickerDialog(initialCalendarMode:)`.
765    pub fn initial_calendar_mode(
766        mut self,
767        initial_calendar_mode: DatePickerMode,
768    ) -> DatePickerDialog {
769        self.initial_calendar_mode = initial_calendar_mode;
770        self
771    }
772
773    /// Dart `DatePickerDialog(restorationId:)`.
774    pub fn restoration_id(mut self, restoration_id: impl Into<String>) -> DatePickerDialog {
775        self.restoration_id = Some(restoration_id.into());
776        self
777    }
778
779    /// Dart `DatePickerDialog(insetPadding:)`.
780    pub fn inset_padding(mut self, inset_padding: EdgeInsets) -> DatePickerDialog {
781        self.inset_padding = inset_padding;
782        self
783    }
784
785    /// Dart `DatePickerDialog(calendarDelegate:)`.
786    pub fn calendar_delegate(
787        mut self,
788        calendar_delegate: Rc<dyn CalendarDelegate>,
789    ) -> DatePickerDialog {
790        self.calendar_delegate = calendar_delegate;
791        self
792    }
793}
794
795impl StatefulWidget for DatePickerDialog {
796    type State = DatePickerDialogState;
797
798    fn key(&self) -> Option<&waft_widgets::KeyRef> {
799        self.key.as_ref()
800    }
801
802    fn create_state(&self) -> DatePickerDialogState {
803        DatePickerDialogState {
804            state: StateData::new(),
805            restoration: RestorationMixinData::new(),
806            selected_date: None,
807            entry_mode: None,
808            autovalidate_mode: None,
809            calendar_picker_key: GlobalKey::new(),
810            form_key: GlobalKey::new(),
811        }
812    }
813}
814
815/// Dart's `_DatePickerDialogState`.
816pub struct DatePickerDialogState {
817    state: StateData<DatePickerDialog>,
818    restoration: RestorationMixinData,
819    selected_date: Option<Ref<RestorableDateTimeN>>,
820    entry_mode: Option<Ref<RestorableEnum<DatePickerEntryMode>>>,
821    autovalidate_mode: Option<Ref<RestorableEnum<AutovalidateMode>>>,
822    calendar_picker_key: GlobalKey,
823    form_key: GlobalKey,
824}
825
826impl DatePickerDialogState {
827    fn selected_date(self: Handle<Self>, app: &App) -> Handle<RestorableDateTimeN> {
828        app.get(self)
829            .selected_date
830            .as_ref()
831            .expect("init_state ran")
832            .handle()
833    }
834
835    fn entry_mode(self: Handle<Self>, app: &App) -> Handle<RestorableEnum<DatePickerEntryMode>> {
836        app.get(self)
837            .entry_mode
838            .as_ref()
839            .expect("init_state ran")
840            .handle()
841    }
842
843    fn autovalidate_mode(
844        self: Handle<Self>,
845        app: &App,
846    ) -> Handle<RestorableEnum<AutovalidateMode>> {
847        app.get(self)
848            .autovalidate_mode
849            .as_ref()
850            .expect("init_state ran")
851            .handle()
852    }
853
854    fn handle_ok(self: Handle<Self>, app: &mut App) {
855        let entry_mode = *self.entry_mode(app).value(app);
856        if entry_mode == DatePickerEntryMode::Input || entry_mode == DatePickerEntryMode::InputOnly
857        {
858            let form_key = app.get(self).form_key.clone();
859            let form = form_key
860                .current_state::<FormState>(app)
861                .expect("the form is mounted");
862            if !form.validate(app) {
863                self.set_state(app, |_state| {});
864                self.autovalidate_mode(app)
865                    .set_value(app, AutovalidateMode::Always);
866                return;
867            }
868            form.save(app);
869        }
870        let context = self.context(app);
871        let selected_date = *self.selected_date(app).value(app);
872        Navigator::pop(
873            app,
874            context,
875            selected_date.map(|date| Rc::new(date) as Rc<dyn std::any::Any>),
876        );
877    }
878
879    fn handle_cancel(self: Handle<Self>, app: &mut App) {
880        let context = self.context(app);
881        Navigator::pop(app, context, None);
882    }
883
884    fn handle_on_date_picker_mode_change(self: Handle<Self>, app: &mut App) {
885        if let Some(callback) = self.widget(app).on_date_picker_mode_change.clone() {
886            let entry_mode = *self.entry_mode(app).value(app);
887            callback(app, entry_mode);
888        }
889    }
890
891    fn handle_entry_mode_toggle(self: Handle<Self>, app: &mut App) {
892        self.set_state(app, |_state| {});
893        match *self.entry_mode(app).value(app) {
894            DatePickerEntryMode::Calendar => {
895                self.autovalidate_mode(app)
896                    .set_value(app, AutovalidateMode::Disabled);
897                self.entry_mode(app)
898                    .set_value(app, DatePickerEntryMode::Input);
899                self.handle_on_date_picker_mode_change(app);
900            }
901            DatePickerEntryMode::Input => {
902                let form_key = app.get(self).form_key.clone();
903                form_key
904                    .current_state::<FormState>(app)
905                    .expect("the form is mounted")
906                    .save(app);
907                self.entry_mode(app)
908                    .set_value(app, DatePickerEntryMode::Calendar);
909                self.handle_on_date_picker_mode_change(app);
910            }
911            DatePickerEntryMode::CalendarOnly | DatePickerEntryMode::InputOnly => {
912                debug_assert!(
913                    false,
914                    "Can not change entry mode from {:?}",
915                    *self.entry_mode(app).value(app)
916                );
917            }
918        }
919    }
920
921    fn handle_date_changed(self: Handle<Self>, app: &mut App, date: DateTime) {
922        self.set_state(app, |_state| {});
923        self.selected_date(app).set_value(app, Some(date));
924    }
925
926    fn dialog_size(self: Handle<Self>, app: &mut App, context: BuildContext) -> Size {
927        let use_material3 = Theme::of(app, context).use_material3;
928        let is_calendar = matches!(
929            *self.entry_mode(app).value(app),
930            DatePickerEntryMode::Calendar | DatePickerEntryMode::CalendarOnly
931        );
932        match (is_calendar, MediaQuery::orientation_of(app, context)) {
933            (true, Orientation::Portrait) if use_material3 => CALENDAR_PORTRAIT_DIALOG_SIZE_M3,
934            (false, Orientation::Portrait) if use_material3 => INPUT_PORTRAIT_DIALOG_SIZE_M3,
935            (true, Orientation::Portrait) => CALENDAR_PORTRAIT_DIALOG_SIZE_M2,
936            (false, Orientation::Portrait) => INPUT_PORTRAIT_DIALOG_SIZE_M2,
937            (true, Orientation::Landscape) => CALENDAR_LANDSCAPE_DIALOG_SIZE,
938            (false, Orientation::Landscape) => INPUT_LANDSCAPE_DIALOG_SIZE,
939        }
940    }
941
942    fn form_shortcut_map() -> waft_widgets::ShortcutMap {
943        // Pressing enter on the field will move focus to the next field or control.
944        vec![(
945            Rc::new(waft_widgets::SingleActivator::new(
946                waft_services::LogicalKeyboardKey::ENTER,
947            )),
948            Rc::new(waft_widgets::NextFocusIntent::new()),
949        )]
950    }
951}
952
953impl RestorationMixin for DatePickerDialogState {
954    waft_widgets::restoration_mixin_accessors!();
955
956    fn restoration_id(self: Handle<Self>, app: &App) -> Option<&str> {
957        self.widget(app).restoration_id.as_deref()
958    }
959
960    fn restore_state(
961        self: Handle<Self>,
962        app: &mut App,
963        _old_bucket: Option<Handle<waft_widgets::RestorationBucket>>,
964        _initial_restore: bool,
965    ) {
966        let (selected_date, autovalidate_mode, entry_mode) = (
967            self.selected_date(app),
968            self.autovalidate_mode(app),
969            self.entry_mode(app),
970        );
971        self.register_for_restoration(app, selected_date.as_property(), "selected_date");
972        self.register_for_restoration(app, autovalidate_mode.as_property(), "autovalidateMode");
973        self.register_for_restoration(app, entry_mode.as_property(), "calendar_entry_mode");
974    }
975}
976
977impl State for DatePickerDialogState {
978    type Widget = DatePickerDialog;
979    waft_widgets::state_accessors!();
980
981    fn init_state(self: Handle<Self>, app: &mut App) {
982        let widget = self.widget(app).clone();
983        widget.debug_check_dates(app);
984        widget.debug_check_initial_date_is_selectable(app);
985        let initial_date = widget.effective_initial_date(app);
986        let selected_date = RestorableDateTimeN::new(app, initial_date);
987        let entry_mode = RestorableEnum::new(app, widget.initial_entry_mode, ENTRY_MODES);
988        let autovalidate_mode =
989            RestorableEnum::new(app, AutovalidateMode::Disabled, AUTOVALIDATE_MODES);
990        let state = app.get_mut(self);
991        state.selected_date = Some(selected_date);
992        state.entry_mode = Some(entry_mode);
993        state.autovalidate_mode = Some(autovalidate_mode);
994    }
995
996    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
997        self.did_change_dependencies_restoration(app);
998    }
999
1000    fn did_update_widget(self: Handle<Self>, app: &mut App, _old_widget: &DatePickerDialog) {
1001        let widget = self.widget(app);
1002        widget.debug_check_dates(app);
1003        widget.debug_check_initial_date_is_selectable(app);
1004        self.did_update_restoration_id(app);
1005    }
1006
1007    fn dispose(self: Handle<Self>, app: &mut App) {
1008        self.selected_date(app).dispose(app);
1009        self.entry_mode(app).dispose(app);
1010        self.autovalidate_mode(app).dispose(app);
1011        self.dispose_restoration(app);
1012    }
1013
1014    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1015        let theme = Theme::of(app, context);
1016        let use_material3 = theme.use_material3;
1017        let localizations = <dyn MaterialLocalizations>::of(app, context);
1018        let orientation = MediaQuery::orientation_of(app, context);
1019        let is_landscape_orientation = orientation == Orientation::Landscape;
1020        let date_picker_theme = DatePickerTheme::of(app, context);
1021        let defaults = DatePickerTheme::defaults(app, context);
1022        let text_theme = theme.text_theme.clone();
1023        let widget = self.widget(app).clone();
1024        let entry_mode = *self.entry_mode(app).value(app);
1025        let selected_date = *self.selected_date(app).value(app);
1026        let autovalidate_mode = *self.autovalidate_mode(app).value(app);
1027
1028        // There's no M3 spec for a landscape layout input (not calendar) date picker. To
1029        // ensure that the date displayed in the input date picker's header fits in landscape
1030        // mode, we override the M3 default here.
1031        let mut headline_style: Option<TextStyle>;
1032        if use_material3 {
1033            headline_style = date_picker_theme
1034                .header_headline_style
1035                .clone()
1036                .or_else(|| defaults.header_headline_style(app));
1037            if matches!(
1038                entry_mode,
1039                DatePickerEntryMode::Input | DatePickerEntryMode::InputOnly
1040            ) && orientation == Orientation::Landscape
1041            {
1042                headline_style = text_theme.headline_small.clone();
1043            }
1044        } else {
1045            headline_style = if is_landscape_orientation {
1046                text_theme.headline_small.clone()
1047            } else {
1048                text_theme.headline_medium.clone()
1049            };
1050        }
1051        let header_foreground_color = date_picker_theme
1052            .header_foreground_color
1053            .or_else(|| defaults.header_foreground_color(app));
1054        headline_style = headline_style.map(|style| match header_foreground_color {
1055            Some(color) => style.copy_with().color(color),
1056            None => style,
1057        });
1058
1059        let cancel_button_style = date_picker_theme
1060            .cancel_button_style
1061            .clone()
1062            .or_else(|| defaults.cancel_button_style(app));
1063        let confirm_button_style = date_picker_theme
1064            .confirm_button_style
1065            .clone()
1066            .or_else(|| defaults.confirm_button_style(app));
1067        let mut cancel_button = TextButton::new(
1068            Some(Listener::new(move |app| self.handle_cancel(app))),
1069            Some(Text::new(widget.cancel_text.clone().unwrap_or_else(|| {
1070                if use_material3 {
1071                    localizations.cancel_button_label()
1072                } else {
1073                    localizations.cancel_button_label().to_uppercase()
1074                }
1075            }))),
1076        );
1077        if let Some(style) = cancel_button_style {
1078            cancel_button = cancel_button.style(style);
1079        }
1080        let mut confirm_button = TextButton::new(
1081            Some(Listener::new(move |app| self.handle_ok(app))),
1082            Some(Text::new(
1083                widget
1084                    .confirm_text
1085                    .clone()
1086                    .unwrap_or_else(|| localizations.ok_button_label()),
1087            )),
1088        );
1089        if let Some(style) = confirm_button_style {
1090            confirm_button = confirm_button.style(style);
1091        }
1092        let actions = ConstrainedBox::new(BoxConstraints {
1093            min_height: 52.0,
1094            ..BoxConstraints::new()
1095        })
1096        .child(MediaQuery::with_clamped_text_scaling(
1097            None,
1098            0.0,
1099            if is_landscape_orientation {
1100                1.6
1101            } else {
1102                MAX_TEXT_SCALE_FACTOR
1103            },
1104            Padding::new(EdgeInsets::symmetric(0.0, 8.0)).child(
1105                Align::new()
1106                    .alignment(AlignmentGeometry::from(AlignmentDirectional::CENTER_END))
1107                    .child(OverflowBar::new().spacing(8.0).children(vec![
1108                        cancel_button.into_widget(),
1109                        confirm_button.into_widget(),
1110                    ])),
1111            ),
1112        ))
1113        .into_widget();
1114
1115        let calendar_picker_key = app.get(self).calendar_picker_key.clone();
1116        let form_key = app.get(self).form_key.clone();
1117        let make_calendar_date_picker = {
1118            let widget = widget.clone();
1119            move || -> WidgetRef {
1120                let mut picker = CalendarDatePicker::new(
1121                    selected_date,
1122                    widget.first_date,
1123                    widget.last_date,
1124                    Rc::new(move |app, date| self.handle_date_changed(app, date)),
1125                )
1126                .calendar_delegate(Rc::clone(&widget.calendar_delegate))
1127                .key(calendar_picker_key.clone().into())
1128                .initial_calendar_mode(widget.initial_calendar_mode);
1129                if let Some(current_date) = widget.current_date {
1130                    picker = picker.current_date(current_date);
1131                }
1132                if let Some(predicate) = widget.selectable_day_predicate.clone() {
1133                    picker = picker.selectable_day_predicate(predicate);
1134                }
1135                if let Some(day_builder) = widget.day_builder.clone() {
1136                    picker = picker.day_builder(day_builder);
1137                }
1138                if let Some(weekday_builder) = widget.weekday_builder.clone() {
1139                    picker = picker.weekday_builder(weekday_builder);
1140                }
1141                picker.into_widget()
1142            }
1143        };
1144        let make_input_date_picker = {
1145            let widget = widget.clone();
1146            move || -> WidgetRef {
1147                let mut field = InputDatePickerFormField::new(widget.first_date, widget.last_date)
1148                    .calendar_delegate(Rc::clone(&widget.calendar_delegate))
1149                    .on_date_submitted(Rc::new(move |app, date| {
1150                        self.handle_date_changed(app, date);
1151                    }))
1152                    .on_date_saved(Rc::new(move |app, date| {
1153                        self.handle_date_changed(app, date);
1154                    }))
1155                    .autofocus(true);
1156                if let Some(initial_date) = selected_date {
1157                    field = field.initial_date(initial_date);
1158                }
1159                if let Some(predicate) = widget.selectable_day_predicate.clone() {
1160                    field = field.selectable_day_predicate(predicate);
1161                }
1162                if let Some(text) = widget.error_format_text.clone() {
1163                    field = field.error_format_text(text);
1164                }
1165                if let Some(text) = widget.error_invalid_text.clone() {
1166                    field = field.error_invalid_text(text);
1167                }
1168                if let Some(text) = widget.field_hint_text.clone() {
1169                    field = field.field_hint_text(text);
1170                }
1171                if let Some(text) = widget.field_label_text.clone() {
1172                    field = field.field_label_text(text);
1173                }
1174                if let Some(keyboard_type) = widget.keyboard_type {
1175                    field = field.keyboard_type(keyboard_type);
1176                }
1177                Form::new(
1178                    SizedBox::new()
1179                        .height(if orientation == Orientation::Portrait {
1180                            INPUT_FORM_PORTRAIT_HEIGHT
1181                        } else {
1182                            INPUT_FORM_LANDSCAPE_HEIGHT
1183                        })
1184                        .child(
1185                            Padding::new(EdgeInsets::symmetric(0.0, 24.0)).child(Shortcuts::new(
1186                                DatePickerDialogState::form_shortcut_map(),
1187                                Column::new()
1188                                    .main_axis_alignment(MainAxisAlignment::Center)
1189                                    .children([Flexible::new(
1190                                        MediaQuery::with_clamped_text_scaling(
1191                                            None, 0.0, 2.0, field,
1192                                        ),
1193                                    )
1194                                    .into_widget()]),
1195                            )),
1196                        ),
1197                )
1198                .key(form_key.clone().into())
1199                .autovalidate_mode(autovalidate_mode)
1200                .into_widget()
1201            }
1202        };
1203
1204        let (picker, entry_mode_button): (WidgetRef, Option<WidgetRef>) = match entry_mode {
1205            DatePickerEntryMode::Calendar => {
1206                let mut button = IconButton::new(
1207                    Some(Listener::new(move |app| self.handle_entry_mode_toggle(app))),
1208                    widget
1209                        .switch_to_input_entry_mode_icon
1210                        .clone()
1211                        .unwrap_or_else(|| {
1212                            Icon::new(Some(if use_material3 {
1213                                Icons::edit_outlined()
1214                            } else {
1215                                Icons::edit()
1216                            }))
1217                            .into_widget()
1218                        }),
1219                )
1220                .tooltip(localizations.input_date_mode_button_label());
1221                if let Some(color) = header_foreground_color {
1222                    button = button.color(color);
1223                }
1224                (make_calendar_date_picker(), Some(button.into_widget()))
1225            }
1226            DatePickerEntryMode::CalendarOnly => (make_calendar_date_picker(), None),
1227            DatePickerEntryMode::Input => {
1228                let mut button = IconButton::new(
1229                    Some(Listener::new(move |app| self.handle_entry_mode_toggle(app))),
1230                    widget
1231                        .switch_to_calendar_entry_mode_icon
1232                        .clone()
1233                        .unwrap_or_else(|| Icon::new(Some(Icons::calendar_today())).into_widget()),
1234                )
1235                .tooltip(localizations.calendar_mode_button_label());
1236                if let Some(color) = header_foreground_color {
1237                    button = button.color(color);
1238                }
1239                (make_input_date_picker(), Some(button.into_widget()))
1240            }
1241            DatePickerEntryMode::InputOnly => (make_input_date_picker(), None),
1242        };
1243
1244        let header = DatePickerHeader {
1245            help_text: widget.help_text.clone().unwrap_or_else(|| {
1246                if use_material3 {
1247                    localizations.date_picker_help_text()
1248                } else {
1249                    localizations.date_picker_help_text().to_uppercase()
1250                }
1251            }),
1252            title_text: match selected_date {
1253                None => String::new(),
1254                Some(date) => {
1255                    widget
1256                        .calendar_delegate
1257                        .format_medium_date(app, &date, &*localizations)
1258                }
1259            },
1260            title_semantics_label: None,
1261            title_style: headline_style,
1262            orientation,
1263            is_short: orientation == Orientation::Landscape,
1264            entry_mode_button,
1265        }
1266        .into_widget();
1267
1268        // Constrain the textScaleFactor to the largest supported value to prevent layout
1269        // issues.
1270        let text_scale_factor = MediaQuery::text_scaler_of(app, context)
1271            .clamp(0.0, MAX_TEXT_SCALE_FACTOR)
1272            .scale(FONT_SIZE_TO_SCALE)
1273            / FONT_SIZE_TO_SCALE;
1274        let dialog_size = self.dialog_size(app, context) * text_scale_factor;
1275        let dialog_theme = theme.dialog_theme.clone();
1276        let divider_color = date_picker_theme.divider_color;
1277
1278        let mut dialog = Dialog::new()
1279            .elevation(if use_material3 {
1280                date_picker_theme
1281                    .elevation
1282                    .or_else(|| defaults.elevation(app))
1283                    .expect("the defaults give an elevation")
1284            } else {
1285                date_picker_theme
1286                    .elevation
1287                    .or(dialog_theme.elevation)
1288                    .unwrap_or(24.0)
1289            })
1290            .inset_padding(widget.inset_padding)
1291            .clip_behavior(Clip::AntiAlias);
1292        if let Some(color) = date_picker_theme
1293            .background_color
1294            .or_else(|| defaults.background_color(app))
1295        {
1296            dialog = dialog.background_color(color);
1297        }
1298        if let Some(color) = date_picker_theme
1299            .shadow_color
1300            .or_else(|| defaults.shadow_color(app))
1301        {
1302            dialog = dialog.shadow_color(color);
1303        }
1304        if let Some(color) = date_picker_theme
1305            .surface_tint_color
1306            .or_else(|| defaults.surface_tint_color(app))
1307        {
1308            dialog = dialog.surface_tint_color(color);
1309        }
1310        let shape = if use_material3 {
1311            date_picker_theme
1312                .shape
1313                .clone()
1314                .or_else(|| defaults.shape(app))
1315        } else {
1316            date_picker_theme
1317                .shape
1318                .clone()
1319                .or_else(|| dialog_theme.shape.clone())
1320                .or_else(|| defaults.shape(app))
1321        };
1322        if let Some(shape) = shape {
1323            dialog = dialog.shape(shape);
1324        }
1325
1326        dialog
1327            .child(
1328                AnimatedContainer::new(DIALOG_SIZE_ANIMATION_DURATION)
1329                    .width(dialog_size.width())
1330                    .height(dialog_size.height())
1331                    .curve(Curves::ease_in())
1332                    .child(MediaQuery::with_clamped_text_scaling(
1333                        None,
1334                        0.0,
1335                        MAX_TEXT_SCALE_FACTOR,
1336                        LayoutBuilder::new(move |_app, _context, constraints| {
1337                            let portrait_dialog_size = if use_material3 {
1338                                INPUT_PORTRAIT_DIALOG_SIZE_M3
1339                            } else {
1340                                INPUT_PORTRAIT_DIALOG_SIZE_M2
1341                            };
1342                            // Make sure the portrait dialog can fit the contents comfortably
1343                            // when resized from the landscape dialog.
1344                            let is_fully_portrait = constraints.constraints().max_height
1345                                >= dialog_size.height().min(portrait_dialog_size.height());
1346                            match orientation {
1347                                Orientation::Portrait => {
1348                                    let is_input_mode = matches!(
1349                                        entry_mode,
1350                                        DatePickerEntryMode::InputOnly | DatePickerEntryMode::Input
1351                                    );
1352                                    // When the portrait dialog does not fit vertically, hide
1353                                    // the header when the entry mode is input, or hide the
1354                                    // picker when the entry mode is not input.
1355                                    let show_header = is_fully_portrait || !is_input_mode;
1356                                    let show_picker = is_fully_portrait || is_input_mode;
1357                                    let mut children: Vec<WidgetRef> = Vec::new();
1358                                    if show_header {
1359                                        children.push(header.clone());
1360                                    }
1361                                    if use_material3 {
1362                                        let mut divider = Divider::new().height(0.0);
1363                                        if let Some(color) = divider_color {
1364                                            divider = divider.color(color);
1365                                        }
1366                                        children.push(divider.into_widget());
1367                                    }
1368                                    if show_picker {
1369                                        children.push(Expanded::new(picker.clone()).into_widget());
1370                                        children.push(actions.clone());
1371                                    }
1372                                    Column::new()
1373                                        .main_axis_size(MainAxisSize::Min)
1374                                        .cross_axis_alignment(CrossAxisAlignment::Stretch)
1375                                        .children(children)
1376                                        .into_widget()
1377                                }
1378                                Orientation::Landscape => {
1379                                    let mut children = vec![header.clone()];
1380                                    if use_material3 {
1381                                        let mut divider = VerticalDivider::new().width(0.0);
1382                                        if let Some(color) = divider_color {
1383                                            divider = divider.color(color);
1384                                        }
1385                                        children.push(divider.into_widget());
1386                                    }
1387                                    children.push(
1388                                        Flexible::new(
1389                                            Column::new()
1390                                                .main_axis_size(MainAxisSize::Min)
1391                                                .cross_axis_alignment(CrossAxisAlignment::Stretch)
1392                                                .children([
1393                                                    Expanded::new(picker.clone()).into_widget(),
1394                                                    actions.clone(),
1395                                                ]),
1396                                        )
1397                                        .into_widget(),
1398                                    );
1399                                    Row::new()
1400                                        .main_axis_size(MainAxisSize::Min)
1401                                        .cross_axis_alignment(CrossAxisAlignment::Stretch)
1402                                        .children(children)
1403                                        .into_widget()
1404                                }
1405                            }
1406                        })
1407                        .into_widget(),
1408                    )),
1409            )
1410            .into_widget()
1411    }
1412}
1413
1414impl std::fmt::Debug for DatePickerDialog {
1415    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1416        f.debug_struct("DatePickerDialog")
1417            .field("initial_date", &self.initial_date)
1418            .field("first_date", &self.first_date)
1419            .field("last_date", &self.last_date)
1420            .field("current_date", &self.current_date)
1421            .field("initial_entry_mode", &self.initial_entry_mode)
1422            .field("initial_calendar_mode", &self.initial_calendar_mode)
1423            .field("restoration_id", &self.restoration_id)
1424            .finish_non_exhaustive()
1425    }
1426}
1427
1428const DATE_PICKER_HEADER_LANDSCAPE_WIDTH: f64 = 152.0;
1429const DATE_PICKER_HEADER_PORTRAIT_HEIGHT: f64 = 120.0;
1430const HEADER_PADDING_LANDSCAPE: f64 = 16.0;
1431
1432/// Dart's `_DatePickerHeader`.
1433#[derive(Clone, Debug)]
1434struct DatePickerHeader {
1435    help_text: String,
1436    title_text: String,
1437    title_semantics_label: Option<String>,
1438    title_style: Option<TextStyle>,
1439    orientation: Orientation,
1440    is_short: bool,
1441    entry_mode_button: Option<WidgetRef>,
1442}
1443
1444impl StatelessWidget for DatePickerHeader {
1445    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
1446        let theme = Theme::of(app, context);
1447        let date_picker_theme = DatePickerTheme::of(app, context);
1448        let defaults = DatePickerTheme::defaults(app, context);
1449        let background_color = date_picker_theme
1450            .header_background_color
1451            .or_else(|| defaults.header_background_color(app));
1452        let foreground_color = date_picker_theme
1453            .header_foreground_color
1454            .or_else(|| defaults.header_foreground_color(app));
1455        let help_style = date_picker_theme
1456            .header_help_style
1457            .clone()
1458            .or_else(|| defaults.header_help_style(app))
1459            .map(|style| match foreground_color {
1460                Some(color) => style.copy_with().color(color),
1461                None => style,
1462            });
1463        let text_scaler = MediaQuery::text_scaler_of(app, context);
1464        let current_scale = text_scaler.scale(FONT_SIZE_TO_SCALE) / FONT_SIZE_TO_SCALE;
1465        let max_header_text_scale_factor = current_scale.min(if self.entry_mode_button.is_some() {
1466            MAX_HEADER_WITH_ENTRY_TEXT_SCALE_FACTOR
1467        } else {
1468            MAX_HEADER_TEXT_SCALE_FACTOR
1469        });
1470        let text_scale_factor = text_scaler
1471            .clamp(0.0, max_header_text_scale_factor)
1472            .scale(FONT_SIZE_TO_SCALE)
1473            / FONT_SIZE_TO_SCALE;
1474        let scaled_font_size = text_scaler.scale(
1475            self.title_style
1476                .as_ref()
1477                .and_then(|style| style.font_size)
1478                .unwrap_or(32.0),
1479        );
1480        let header_scale_factor = if text_scale_factor > 1.0 {
1481            text_scale_factor
1482        } else {
1483            1.0
1484        };
1485
1486        let mut help = Text::new(self.help_text.clone())
1487            .max_lines(1)
1488            .overflow(TextOverflow::Ellipsis)
1489            .text_scaler(text_scaler.clamp(
1490                0.0,
1491                text_scale_factor.min(if self.orientation == Orientation::Portrait {
1492                    MAX_HELP_PORTRAIT_TEXT_SCALE_FACTOR
1493                } else {
1494                    MAX_HELP_LANDSCAPE_TEXT_SCALE_FACTOR
1495                }),
1496            ));
1497        if let Some(help_style) = help_style {
1498            help = help.style(help_style);
1499        }
1500        let mut title = Text::new(self.title_text.clone())
1501            .semantics_label(
1502                self.title_semantics_label
1503                    .clone()
1504                    .unwrap_or_else(|| self.title_text.clone()),
1505            )
1506            .max_lines(if self.orientation == Orientation::Portrait {
1507                if scaled_font_size > 70.0 { 2 } else { 1 }
1508            } else if scaled_font_size > 40.0 {
1509                3
1510            } else {
1511                2
1512            })
1513            .overflow(TextOverflow::Ellipsis)
1514            .text_scaler(text_scaler.clamp(0.0, text_scale_factor));
1515        if let Some(title_style) = self.title_style.clone() {
1516            title = title.style(title_style);
1517        }
1518
1519        let font_scale_adjusted_header_height = if header_scale_factor > 1.3 {
1520            header_scale_factor - 0.2
1521        } else {
1522            1.0
1523        };
1524
1525        let mut material = Material::new();
1526        if let Some(background_color) = background_color {
1527            material = material.color(background_color);
1528        }
1529        match self.orientation {
1530            Orientation::Portrait => {
1531                let mut title_row = vec![Expanded::new(title).into_widget()];
1532                if let Some(entry_mode_button) = &self.entry_mode_button {
1533                    title_row.push(
1534                        Semantics::new()
1535                            .container(true)
1536                            .child(entry_mode_button.clone())
1537                            .into_widget(),
1538                    );
1539                }
1540                Semantics::new()
1541                    .container(true)
1542                    .child(
1543                        SizedBox::new()
1544                            .height(
1545                                DATE_PICKER_HEADER_PORTRAIT_HEIGHT
1546                                    * font_scale_adjusted_header_height,
1547                            )
1548                            .child(
1549                                material.child(
1550                                    Padding::new(EdgeInsetsDirectional::only(
1551                                        24.0, 0.0, 12.0, 12.0,
1552                                    ))
1553                                    .child(
1554                                        Column::new()
1555                                            .cross_axis_alignment(CrossAxisAlignment::Start)
1556                                            .children([
1557                                                SizedBox::new().height(16.0).into_widget(),
1558                                                help.into_widget(),
1559                                                Flexible::new(SizedBox::new().height(38.0))
1560                                                    .into_widget(),
1561                                                Row::new().children(title_row).into_widget(),
1562                                            ]),
1563                                    ),
1564                                ),
1565                            ),
1566                    )
1567                    .into_widget()
1568            }
1569            Orientation::Landscape => {
1570                let mut children = vec![
1571                    SizedBox::new().height(16.0).into_widget(),
1572                    Padding::new(EdgeInsets::symmetric(0.0, HEADER_PADDING_LANDSCAPE))
1573                        .child(help)
1574                        .into_widget(),
1575                    SizedBox::new()
1576                        .height(if self.is_short { 16.0 } else { 56.0 })
1577                        .into_widget(),
1578                    Expanded::new(
1579                        Padding::new(EdgeInsets::symmetric(0.0, HEADER_PADDING_LANDSCAPE))
1580                            .child(title),
1581                    )
1582                    .into_widget(),
1583                ];
1584                if let Some(entry_mode_button) = &self.entry_mode_button {
1585                    children.push(
1586                        Padding::new(if theme.use_material3 {
1587                            EdgeInsetsGeometry::directional(8.0, 0.0, 4.0, 6.0)
1588                        } else {
1589                            EdgeInsetsGeometry::symmetric(0.0, 4.0)
1590                        })
1591                        .child(
1592                            Semantics::new()
1593                                .container(true)
1594                                .child(entry_mode_button.clone()),
1595                        )
1596                        .into_widget(),
1597                    );
1598                }
1599                Semantics::new()
1600                    .container(true)
1601                    .child(
1602                        SizedBox::new()
1603                            .width(DATE_PICKER_HEADER_LANDSCAPE_WIDTH)
1604                            .child(
1605                                material.child(
1606                                    Column::new()
1607                                        .cross_axis_alignment(CrossAxisAlignment::Start)
1608                                        .children(children),
1609                                ),
1610                            ),
1611                    )
1612                    .into_widget()
1613            }
1614        }
1615    }
1616}
1617
1618/// Signature for predicates for enabling a day in a date range picker.
1619///
1620/// It receives the day, and the start and end of the selected range (either may be null).
1621/// Days for which it returns false are not selectable.
1622pub type SelectableDayForRangePredicate =
1623    Rc<dyn Fn(&App, DateTime, Option<DateTime>, Option<DateTime>) -> bool>;
1624
1625/// Shows a full screen modal dialog containing a Material Design date range picker.
1626///
1627/// The returned future resolves when the user closes the dialog. If the user cancels the
1628/// dialog, it resolves with null; otherwise it resolves to the selected [`DateTimeRange`]
1629/// (inside the [`RouteResult`]).
1630///
1631/// The `initial_date_range` is the range the picker opens with. The `first_date` and `last_date`
1632/// are the allowable range of dates. The `current_date` is highlighted in the day grid; with
1633/// none, the delegate's `now()` is used.
1634///
1635/// The `initial_entry_mode` chooses between the calendar and the text input.
1636///
1637/// The `selectable_day_predicate` customizes the days enabled for selection.
1638///
1639/// Dart's `anchorPoint` waits for `ShowDialog` to take one.
1640pub struct ShowDateRangePicker {
1641    initial_date_range: Option<DateTimeRange>,
1642    first_date: DateTime,
1643    last_date: DateTime,
1644    current_date: Option<DateTime>,
1645    initial_entry_mode: DatePickerEntryMode,
1646    help_text: Option<String>,
1647    cancel_text: Option<String>,
1648    confirm_text: Option<String>,
1649    save_text: Option<String>,
1650    error_format_text: Option<String>,
1651    error_invalid_text: Option<String>,
1652    error_invalid_range_text: Option<String>,
1653    field_start_hint_text: Option<String>,
1654    field_end_hint_text: Option<String>,
1655    field_start_label_text: Option<String>,
1656    field_end_label_text: Option<String>,
1657    locale: Option<Locale>,
1658    barrier_dismissible: bool,
1659    barrier_color: Option<Color>,
1660    barrier_label: Option<String>,
1661    use_root_navigator: bool,
1662    route_settings: Option<RouteSettingsRef>,
1663    text_direction: Option<TextDirection>,
1664    builder: Option<TransitionBuilder>,
1665    keyboard_type: TextInputType,
1666    switch_to_input_entry_mode_icon: Option<WidgetRef>,
1667    switch_to_calendar_entry_mode_icon: Option<WidgetRef>,
1668    selectable_day_predicate: Option<SelectableDayForRangePredicate>,
1669    calendar_delegate: Rc<dyn CalendarDelegate>,
1670}
1671
1672impl ShowDateRangePicker {
1673    /// Creates a builder for a Material date range picker; Dart's `showDateRangePicker`
1674    /// required arguments are the first and last dates, and every other argument is a setter.
1675    pub fn new(first_date: DateTime, last_date: DateTime) -> ShowDateRangePicker {
1676        ShowDateRangePicker {
1677            initial_date_range: None,
1678            first_date,
1679            last_date,
1680            current_date: None,
1681            initial_entry_mode: DatePickerEntryMode::Calendar,
1682            help_text: None,
1683            cancel_text: None,
1684            confirm_text: None,
1685            save_text: None,
1686            error_format_text: None,
1687            error_invalid_text: None,
1688            error_invalid_range_text: None,
1689            field_start_hint_text: None,
1690            field_end_hint_text: None,
1691            field_start_label_text: None,
1692            field_end_label_text: None,
1693            locale: None,
1694            barrier_dismissible: true,
1695            barrier_color: None,
1696            barrier_label: None,
1697            use_root_navigator: true,
1698            route_settings: None,
1699            text_direction: None,
1700            builder: None,
1701            keyboard_type: TextInputType::DATETIME,
1702            switch_to_input_entry_mode_icon: None,
1703            switch_to_calendar_entry_mode_icon: None,
1704            selectable_day_predicate: None,
1705            calendar_delegate: Rc::new(GregorianCalendarDelegate),
1706        }
1707    }
1708
1709    /// The range the picker opens with.
1710    pub fn initial_date_range(mut self, initial_date_range: DateTimeRange) -> ShowDateRangePicker {
1711        self.initial_date_range = Some(initial_date_range);
1712        self
1713    }
1714
1715    /// The current day, highlighted in the day grid; defaults to the calendar delegate's today.
1716    pub fn current_date(mut self, current_date: DateTime) -> ShowDateRangePicker {
1717        self.current_date = Some(current_date);
1718        self
1719    }
1720
1721    /// The entry mode the picker opens in. Defaults to `DatePickerEntryMode::Calendar`.
1722    pub fn initial_entry_mode(
1723        mut self,
1724        initial_entry_mode: DatePickerEntryMode,
1725    ) -> ShowDateRangePicker {
1726        self.initial_entry_mode = initial_entry_mode;
1727        self
1728    }
1729
1730    /// The text of the help label.
1731    pub fn help_text(mut self, help_text: impl Into<String>) -> ShowDateRangePicker {
1732        self.help_text = Some(help_text.into());
1733        self
1734    }
1735
1736    /// The text of the cancel button.
1737    pub fn cancel_text(mut self, cancel_text: impl Into<String>) -> ShowDateRangePicker {
1738        self.cancel_text = Some(cancel_text.into());
1739        self
1740    }
1741
1742    /// The text of the confirm button.
1743    pub fn confirm_text(mut self, confirm_text: impl Into<String>) -> ShowDateRangePicker {
1744        self.confirm_text = Some(confirm_text.into());
1745        self
1746    }
1747
1748    /// The text of the save button.
1749    pub fn save_text(mut self, save_text: impl Into<String>) -> ShowDateRangePicker {
1750        self.save_text = Some(save_text.into());
1751        self
1752    }
1753
1754    /// The text of the error for an unparseable date.
1755    pub fn error_format_text(
1756        mut self,
1757        error_format_text: impl Into<String>,
1758    ) -> ShowDateRangePicker {
1759        self.error_format_text = Some(error_format_text.into());
1760        self
1761    }
1762
1763    /// The text of the error for an invalid date.
1764    pub fn error_invalid_text(
1765        mut self,
1766        error_invalid_text: impl Into<String>,
1767    ) -> ShowDateRangePicker {
1768        self.error_invalid_text = Some(error_invalid_text.into());
1769        self
1770    }
1771
1772    /// The text of the error for an invalid range.
1773    pub fn error_invalid_range_text(
1774        mut self,
1775        error_invalid_range_text: impl Into<String>,
1776    ) -> ShowDateRangePicker {
1777        self.error_invalid_range_text = Some(error_invalid_range_text.into());
1778        self
1779    }
1780
1781    /// The hint text of the start field.
1782    pub fn field_start_hint_text(
1783        mut self,
1784        field_start_hint_text: impl Into<String>,
1785    ) -> ShowDateRangePicker {
1786        self.field_start_hint_text = Some(field_start_hint_text.into());
1787        self
1788    }
1789
1790    /// The hint text of the end field.
1791    pub fn field_end_hint_text(
1792        mut self,
1793        field_end_hint_text: impl Into<String>,
1794    ) -> ShowDateRangePicker {
1795        self.field_end_hint_text = Some(field_end_hint_text.into());
1796        self
1797    }
1798
1799    /// The label text of the start field.
1800    pub fn field_start_label_text(
1801        mut self,
1802        field_start_label_text: impl Into<String>,
1803    ) -> ShowDateRangePicker {
1804        self.field_start_label_text = Some(field_start_label_text.into());
1805        self
1806    }
1807
1808    /// The label text of the end field.
1809    pub fn field_end_label_text(
1810        mut self,
1811        field_end_label_text: impl Into<String>,
1812    ) -> ShowDateRangePicker {
1813        self.field_end_label_text = Some(field_end_label_text.into());
1814        self
1815    }
1816
1817    /// The locale of the date picker; defaults to the ambient locale.
1818    pub fn locale(mut self, locale: Locale) -> ShowDateRangePicker {
1819        self.locale = Some(locale);
1820        self
1821    }
1822
1823    /// Whether tapping on the barrier dismisses the dialog. Defaults to `true`.
1824    pub fn barrier_dismissible(mut self, barrier_dismissible: bool) -> ShowDateRangePicker {
1825        self.barrier_dismissible = barrier_dismissible;
1826        self
1827    }
1828
1829    /// The color of the modal barrier below the dialog.
1830    pub fn barrier_color(mut self, barrier_color: Color) -> ShowDateRangePicker {
1831        self.barrier_color = Some(barrier_color);
1832        self
1833    }
1834
1835    /// The semantic label of the dialog's modal barrier.
1836    pub fn barrier_label(mut self, barrier_label: impl Into<String>) -> ShowDateRangePicker {
1837        self.barrier_label = Some(barrier_label.into());
1838        self
1839    }
1840
1841    /// Whether to push the dialog to the root navigator. Defaults to `true`.
1842    pub fn use_root_navigator(mut self, use_root_navigator: bool) -> ShowDateRangePicker {
1843        self.use_root_navigator = use_root_navigator;
1844        self
1845    }
1846
1847    /// The route settings passed to the dialog route.
1848    pub fn route_settings(mut self, route_settings: RouteSettingsRef) -> ShowDateRangePicker {
1849        self.route_settings = Some(route_settings);
1850        self
1851    }
1852
1853    /// The text direction of the date picker; defaults to the ambient direction.
1854    pub fn text_direction(mut self, text_direction: TextDirection) -> ShowDateRangePicker {
1855        self.text_direction = Some(text_direction);
1856        self
1857    }
1858
1859    /// Wraps the dialog to add inherited widgets such as a theme.
1860    pub fn builder(mut self, builder: TransitionBuilder) -> ShowDateRangePicker {
1861        self.builder = Some(builder);
1862        self
1863    }
1864
1865    /// The keyboard type of the input fields. Defaults to `TextInputType::DATETIME`.
1866    pub fn keyboard_type(mut self, keyboard_type: TextInputType) -> ShowDateRangePicker {
1867        self.keyboard_type = keyboard_type;
1868        self
1869    }
1870
1871    /// The icon that switches to the input entry mode.
1872    #[cfg_attr(debug_assertions, track_caller)]
1873    pub fn switch_to_input_entry_mode_icon<K>(
1874        mut self,
1875        switch_to_input_entry_mode_icon: impl IntoWidget<K>,
1876    ) -> ShowDateRangePicker {
1877        self.switch_to_input_entry_mode_icon = Some(switch_to_input_entry_mode_icon.into_widget());
1878        self
1879    }
1880
1881    /// The icon that switches to the calendar entry mode.
1882    #[cfg_attr(debug_assertions, track_caller)]
1883    pub fn switch_to_calendar_entry_mode_icon<K>(
1884        mut self,
1885        switch_to_calendar_entry_mode_icon: impl IntoWidget<K>,
1886    ) -> ShowDateRangePicker {
1887        self.switch_to_calendar_entry_mode_icon =
1888            Some(switch_to_calendar_entry_mode_icon.into_widget());
1889        self
1890    }
1891
1892    /// Which days may be selected.
1893    pub fn selectable_day_predicate(
1894        mut self,
1895        selectable_day_predicate: SelectableDayForRangePredicate,
1896    ) -> ShowDateRangePicker {
1897        self.selectable_day_predicate = Some(selectable_day_predicate);
1898        self
1899    }
1900
1901    /// The calendar the dialog works in. Defaults to the Gregorian calendar.
1902    pub fn calendar_delegate(
1903        mut self,
1904        calendar_delegate: Rc<dyn CalendarDelegate>,
1905    ) -> ShowDateRangePicker {
1906        self.calendar_delegate = calendar_delegate;
1907        self
1908    }
1909
1910    /// Shows the dialog and returns a future that resolves when the user closes it.
1911    pub fn show(self, app: &mut App, context: BuildContext) -> CompleterFuture<RouteResult> {
1912        let ShowDateRangePicker {
1913            initial_date_range,
1914            first_date,
1915            last_date,
1916            current_date,
1917            initial_entry_mode,
1918            help_text,
1919            cancel_text,
1920            confirm_text,
1921            save_text,
1922            error_format_text,
1923            error_invalid_text,
1924            error_invalid_range_text,
1925            field_start_hint_text,
1926            field_end_hint_text,
1927            field_start_label_text,
1928            field_end_label_text,
1929            locale,
1930            barrier_dismissible,
1931            barrier_color,
1932            barrier_label,
1933            use_root_navigator,
1934            route_settings,
1935            text_direction,
1936            builder,
1937            keyboard_type,
1938            switch_to_input_entry_mode_icon,
1939            switch_to_calendar_entry_mode_icon,
1940            selectable_day_predicate,
1941            calendar_delegate,
1942        } = self;
1943
1944        let initial_date_range =
1945            initial_date_range.map(|range| calendar_delegate.dates_only(app, &range));
1946        let first_date = calendar_delegate.date_only(app, &first_date);
1947        let last_date = calendar_delegate.date_only(app, &last_date);
1948        assert!(
1949            !last_date.is_before(&first_date),
1950            "lastDate {} must be on or after firstDate {}.",
1951            last_date.to_string(app),
1952            first_date.to_string(app)
1953        );
1954        if let Some(range) = &initial_date_range {
1955            assert!(
1956                !range.start.is_before(&first_date),
1957                "initialDateRange's start date must be on or after firstDate {}.",
1958                first_date.to_string(app)
1959            );
1960            assert!(
1961                !range.end.is_before(&first_date),
1962                "initialDateRange's end date must be on or after firstDate {}.",
1963                first_date.to_string(app)
1964            );
1965            assert!(
1966                !range.start.is_after(&last_date),
1967                "initialDateRange's start date must be on or before lastDate {}.",
1968                last_date.to_string(app)
1969            );
1970            assert!(
1971                !range.end.is_after(&last_date),
1972                "initialDateRange's end date must be on or before lastDate {}.",
1973                last_date.to_string(app)
1974            );
1975            if let Some(predicate) = &selectable_day_predicate {
1976                assert!(
1977                    predicate(app, range.start, Some(range.start), Some(range.end)),
1978                    "initialDateRange's start date must be selectable."
1979                );
1980                assert!(
1981                    predicate(app, range.end, Some(range.start), Some(range.end)),
1982                    "initialDateRange's end date must be selectable."
1983                );
1984            }
1985        }
1986        let current_date = calendar_delegate.date_only(
1987            app,
1988            &current_date.unwrap_or_else(|| calendar_delegate.now(app)),
1989        );
1990        debug_assert!(crate::debug::debug_check_has_material_localizations(
1991            app, context
1992        ));
1993
1994        let mut dialog = DateRangePickerDialog::new(first_date, last_date)
1995            .calendar_delegate(Rc::clone(&calendar_delegate))
1996            .initial_entry_mode(initial_entry_mode)
1997            .keyboard_type(keyboard_type);
1998        dialog.initial_date_range = initial_date_range;
1999        dialog.current_date_value = Some(current_date);
2000        dialog.selectable_day_predicate = selectable_day_predicate;
2001        dialog.help_text = help_text;
2002        dialog.cancel_text = cancel_text;
2003        dialog.confirm_text = confirm_text;
2004        dialog.save_text = save_text;
2005        dialog.error_format_text = error_format_text;
2006        dialog.error_invalid_text = error_invalid_text;
2007        dialog.error_invalid_range_text = error_invalid_range_text;
2008        dialog.field_start_hint_text = field_start_hint_text;
2009        dialog.field_end_hint_text = field_end_hint_text;
2010        dialog.field_start_label_text = field_start_label_text;
2011        dialog.field_end_label_text = field_end_label_text;
2012        dialog.switch_to_input_entry_mode_icon = switch_to_input_entry_mode_icon;
2013        dialog.switch_to_calendar_entry_mode_icon = switch_to_calendar_entry_mode_icon;
2014        let mut dialog = dialog.into_widget();
2015
2016        if let Some(text_direction) = text_direction {
2017            dialog = Directionality::new(text_direction, dialog).into_widget();
2018        }
2019
2020        if let Some(locale) = locale {
2021            dialog = Localizations::r#override(app, context)
2022                .locale(locale)
2023                .child(dialog)
2024                .into_widget();
2025        }
2026
2027        let mut show = ShowDialog::new(Rc::new(move |app, context| match &builder {
2028            None => dialog.clone(),
2029            Some(builder) => builder(app, context, Some(&dialog)),
2030        }))
2031        .barrier_dismissible(barrier_dismissible)
2032        .use_safe_area(false)
2033        .use_root_navigator(use_root_navigator);
2034        if let Some(barrier_color) = barrier_color {
2035            show = show.barrier_color(barrier_color);
2036        }
2037        if let Some(barrier_label) = barrier_label {
2038            show = show.barrier_label(barrier_label);
2039        }
2040        if let Some(route_settings) = route_settings {
2041            show = show.route_settings(route_settings);
2042        }
2043        show.show(app, context)
2044    }
2045}
2046
2047/// Dart's `_formatRangeStartDate`.
2048fn format_range_start_date(
2049    app: &App,
2050    localizations: &dyn MaterialLocalizations,
2051    calendar_delegate: &dyn CalendarDelegate,
2052    start_date: Option<&DateTime>,
2053    end_date: Option<&DateTime>,
2054) -> String {
2055    match start_date {
2056        None => localizations.date_range_start_label(),
2057        Some(start) if end_date.is_none_or(|end| start.year(app) == end.year(app)) => {
2058            calendar_delegate.format_short_month_day(app, start, localizations)
2059        }
2060        Some(start) => calendar_delegate.format_short_date(app, start, localizations),
2061    }
2062}
2063
2064/// Dart's `_formatRangeEndDate`.
2065fn format_range_end_date(
2066    app: &App,
2067    localizations: &dyn MaterialLocalizations,
2068    calendar_delegate: &dyn CalendarDelegate,
2069    start_date: Option<&DateTime>,
2070    end_date: Option<&DateTime>,
2071    current_date: &DateTime,
2072) -> String {
2073    match end_date {
2074        None => localizations.date_range_end_label(),
2075        Some(end)
2076            if start_date.is_some_and(|start| {
2077                start.year(app) == end.year(app) && start.year(app) == current_date.year(app)
2078            }) =>
2079        {
2080            calendar_delegate.format_short_month_day(app, end, localizations)
2081        }
2082        Some(end) => calendar_delegate.format_short_date(app, end, localizations),
2083    }
2084}
2085
2086/// A Material-style date range picker dialog.
2087///
2088/// It is used by [`ShowDateRangePicker`], which should usually be used rather than
2089/// creating a [`DateRangePickerDialog`] directly.
2090#[derive(Clone)]
2091pub struct DateRangePickerDialog {
2092    pub key: Option<waft_widgets::KeyRef>,
2093
2094    /// The date range that the date range picker starts with when it opens.
2095    ///
2096    /// If an initial date range is provided, [`DateTimeRange::start`] and [`DateTimeRange::end`]
2097    /// must both fall within the [`first_date`](Self::first_date) and
2098    /// [`last_date`](Self::last_date) range.
2099    pub initial_date_range: Option<DateTimeRange>,
2100
2101    /// The earliest allowable date on the date range.
2102    pub first_date: DateTime,
2103
2104    /// The latest allowable date on the date range.
2105    pub last_date: DateTime,
2106
2107    /// The [`current_date`](Self::current_date) value given, if any; the getter truncates it.
2108    pub current_date_value: Option<DateTime>,
2109
2110    /// The initial mode of date entry method for the date range picker dialog.
2111    pub initial_entry_mode: DatePickerEntryMode,
2112
2113    /// The label on the cancel button for the text input mode.
2114    pub cancel_text: Option<String>,
2115
2116    /// The label on the "OK" button for the text input mode.
2117    pub confirm_text: Option<String>,
2118
2119    /// The label on the save button for the fullscreen calendar mode.
2120    pub save_text: Option<String>,
2121
2122    /// The label displayed at the top of the dialog.
2123    pub help_text: Option<String>,
2124
2125    /// Error text used to indicate the entered date range is invalid.
2126    pub error_invalid_range_text: Option<String>,
2127
2128    /// Error text used to indicate the entered date format is invalid.
2129    pub error_format_text: Option<String>,
2130
2131    /// Error text used to indicate that an entered date is outside the allowed range.
2132    pub error_invalid_text: Option<String>,
2133
2134    /// Hint text shown when the start date field is empty.
2135    pub field_start_hint_text: Option<String>,
2136
2137    /// Hint text shown when the end date field is empty.
2138    pub field_end_hint_text: Option<String>,
2139
2140    /// Label used for the start date input field in the input mode.
2141    pub field_start_label_text: Option<String>,
2142
2143    /// Label used for the end date input field in the input mode.
2144    pub field_end_label_text: Option<String>,
2145
2146    /// The keyboard type of the date fields.
2147    pub keyboard_type: TextInputType,
2148
2149    /// Restoration ID to save and restore the state of the [`DateRangePickerDialog`].
2150    pub restoration_id: Option<String>,
2151
2152    /// An optional icon that, when pressed, switches from the calendar to the text input.
2153    pub switch_to_input_entry_mode_icon: Option<WidgetRef>,
2154
2155    /// An optional icon that, when pressed, switches from the text input to the calendar.
2156    pub switch_to_calendar_entry_mode_icon: Option<WidgetRef>,
2157
2158    /// Function to provide full control over which [`DateTime`] can be selected.
2159    pub selectable_day_predicate: Option<SelectableDayForRangePredicate>,
2160
2161    /// The calendar the dialog works in.
2162    pub calendar_delegate: Rc<dyn CalendarDelegate>,
2163}
2164
2165impl DateRangePickerDialog {
2166    /// Creates a [`DateRangePickerDialog`]. Dart's optional named arguments are the fluent
2167    /// setters.
2168    pub fn new(first_date: DateTime, last_date: DateTime) -> DateRangePickerDialog {
2169        DateRangePickerDialog {
2170            key: None,
2171            initial_date_range: None,
2172            first_date,
2173            last_date,
2174            current_date_value: None,
2175            initial_entry_mode: DatePickerEntryMode::Calendar,
2176            cancel_text: None,
2177            confirm_text: None,
2178            save_text: None,
2179            help_text: None,
2180            error_invalid_range_text: None,
2181            error_format_text: None,
2182            error_invalid_text: None,
2183            field_start_hint_text: None,
2184            field_end_hint_text: None,
2185            field_start_label_text: None,
2186            field_end_label_text: None,
2187            keyboard_type: TextInputType::DATETIME,
2188            restoration_id: None,
2189            switch_to_input_entry_mode_icon: None,
2190            switch_to_calendar_entry_mode_icon: None,
2191            selectable_day_predicate: None,
2192            calendar_delegate: Rc::new(GregorianCalendarDelegate),
2193        }
2194    }
2195
2196    /// The [`DateTime`] representing today. It will be highlighted in the day grid.
2197    pub fn current_date(&self, app: &App) -> DateTime {
2198        self.calendar_delegate.date_only(
2199            app,
2200            &self
2201                .current_date_value
2202                .unwrap_or_else(|| self.calendar_delegate.now(app)),
2203        )
2204    }
2205
2206    /// Dart `DateRangePickerDialog(key:)`.
2207    pub fn key(mut self, key: waft_widgets::KeyRef) -> DateRangePickerDialog {
2208        self.key = Some(key);
2209        self
2210    }
2211
2212    /// Dart `DateRangePickerDialog(initialDateRange:)`.
2213    pub fn initial_date_range(
2214        mut self,
2215        initial_date_range: DateTimeRange,
2216    ) -> DateRangePickerDialog {
2217        self.initial_date_range = Some(initial_date_range);
2218        self
2219    }
2220
2221    /// Dart `DateRangePickerDialog(currentDate:)`.
2222    pub fn with_current_date(mut self, current_date: DateTime) -> DateRangePickerDialog {
2223        self.current_date_value = Some(current_date);
2224        self
2225    }
2226
2227    /// Dart `DateRangePickerDialog(initialEntryMode:)`.
2228    pub fn initial_entry_mode(
2229        mut self,
2230        initial_entry_mode: DatePickerEntryMode,
2231    ) -> DateRangePickerDialog {
2232        self.initial_entry_mode = initial_entry_mode;
2233        self
2234    }
2235
2236    /// Dart `DateRangePickerDialog(keyboardType:)`.
2237    pub fn keyboard_type(mut self, keyboard_type: TextInputType) -> DateRangePickerDialog {
2238        self.keyboard_type = keyboard_type;
2239        self
2240    }
2241
2242    /// Dart `DateRangePickerDialog(restorationId:)`.
2243    pub fn restoration_id(mut self, restoration_id: impl Into<String>) -> DateRangePickerDialog {
2244        self.restoration_id = Some(restoration_id.into());
2245        self
2246    }
2247
2248    /// Dart `DateRangePickerDialog(selectableDayPredicate:)`.
2249    pub fn selectable_day_predicate(
2250        mut self,
2251        selectable_day_predicate: SelectableDayForRangePredicate,
2252    ) -> DateRangePickerDialog {
2253        self.selectable_day_predicate = Some(selectable_day_predicate);
2254        self
2255    }
2256
2257    /// Dart `DateRangePickerDialog(calendarDelegate:)`.
2258    pub fn calendar_delegate(
2259        mut self,
2260        calendar_delegate: Rc<dyn CalendarDelegate>,
2261    ) -> DateRangePickerDialog {
2262        self.calendar_delegate = calendar_delegate;
2263        self
2264    }
2265}
2266
2267impl fmt::Debug for DateRangePickerDialog {
2268    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2269        f.debug_struct("DateRangePickerDialog")
2270            .field("initial_date_range", &self.initial_date_range)
2271            .field("first_date", &self.first_date)
2272            .field("last_date", &self.last_date)
2273            .field("initial_entry_mode", &self.initial_entry_mode)
2274            .field("restoration_id", &self.restoration_id)
2275            .finish_non_exhaustive()
2276    }
2277}
2278
2279impl StatefulWidget for DateRangePickerDialog {
2280    type State = DateRangePickerDialogState;
2281
2282    fn key(&self) -> Option<&waft_widgets::KeyRef> {
2283        self.key.as_ref()
2284    }
2285
2286    fn create_state(&self) -> DateRangePickerDialogState {
2287        DateRangePickerDialogState {
2288            state: StateData::new(),
2289            restoration: RestorationMixinData::new(),
2290            entry_mode: None,
2291            selected_start: None,
2292            selected_end: None,
2293            auto_validate: None,
2294            calendar_picker_key: waft_widgets::GlobalKey::new(),
2295            input_picker_key: waft_widgets::GlobalKey::new(),
2296        }
2297    }
2298}
2299
2300/// Dart's `_DateRangePickerDialogState`.
2301pub struct DateRangePickerDialogState {
2302    state: StateData<DateRangePickerDialog>,
2303    restoration: RestorationMixinData,
2304    entry_mode: Option<Ref<RestorableEnum<DatePickerEntryMode>>>,
2305    selected_start: Option<Ref<RestorableDateTimeN>>,
2306    selected_end: Option<Ref<RestorableDateTimeN>>,
2307    auto_validate: Option<Ref<RestorableBool>>,
2308    calendar_picker_key: waft_widgets::GlobalKey,
2309    input_picker_key: waft_widgets::GlobalKey,
2310}
2311
2312impl DateRangePickerDialogState {
2313    fn entry_mode(self: Handle<Self>, app: &App) -> Handle<RestorableEnum<DatePickerEntryMode>> {
2314        app.get(self)
2315            .entry_mode
2316            .as_ref()
2317            .expect("init_state ran")
2318            .handle()
2319    }
2320
2321    fn selected_start(self: Handle<Self>, app: &App) -> Handle<RestorableDateTimeN> {
2322        app.get(self)
2323            .selected_start
2324            .as_ref()
2325            .expect("init_state ran")
2326            .handle()
2327    }
2328
2329    fn selected_end(self: Handle<Self>, app: &App) -> Handle<RestorableDateTimeN> {
2330        app.get(self)
2331            .selected_end
2332            .as_ref()
2333            .expect("init_state ran")
2334            .handle()
2335    }
2336
2337    fn auto_validate(self: Handle<Self>, app: &App) -> Handle<RestorableBool> {
2338        app.get(self)
2339            .auto_validate
2340            .as_ref()
2341            .expect("init_state ran")
2342            .handle()
2343    }
2344
2345    fn has_selected_date_range(self: Handle<Self>, app: &App) -> bool {
2346        self.selected_start(app).value(app).is_some() && self.selected_end(app).value(app).is_some()
2347    }
2348
2349    fn handle_ok(self: Handle<Self>, app: &mut App) {
2350        let entry_mode = *self.entry_mode(app).value(app);
2351        if entry_mode == DatePickerEntryMode::Input || entry_mode == DatePickerEntryMode::InputOnly
2352        {
2353            let input_picker_key = app.get(self).input_picker_key.clone();
2354            let picker = input_picker_key
2355                .current_state::<InputDateRangePickerState>(app)
2356                .expect("the input picker is mounted");
2357            if !picker.validate(app) {
2358                self.set_state(app, |_state| {});
2359                self.auto_validate(app).set_value(app, true);
2360                return;
2361            }
2362        }
2363        let selected_range = match (
2364            *self.selected_start(app).value(app),
2365            *self.selected_end(app).value(app),
2366        ) {
2367            (Some(start), Some(end)) => {
2368                Some(Rc::new(DateTimeRange::new(start, end)) as Rc<dyn std::any::Any>)
2369            }
2370            _ => None,
2371        };
2372        let context = self.context(app);
2373        Navigator::pop(app, context, selected_range);
2374    }
2375
2376    fn handle_cancel(self: Handle<Self>, app: &mut App) {
2377        let context = self.context(app);
2378        Navigator::pop(app, context, None);
2379    }
2380
2381    fn is_day_selectable(self: Handle<Self>, app: &App, day: DateTime) -> bool {
2382        let widget = self.widget(app);
2383        if day.is_before(&widget.first_date) || day.is_after(&widget.last_date) {
2384            return false;
2385        }
2386        match &widget.selectable_day_predicate {
2387            None => true,
2388            Some(predicate) => predicate(
2389                app,
2390                day,
2391                *self.selected_start(app).value(app),
2392                *self.selected_end(app).value(app),
2393            ),
2394        }
2395    }
2396
2397    fn handle_entry_mode_toggle(self: Handle<Self>, app: &mut App) {
2398        self.set_state(app, |_state| {});
2399        match *self.entry_mode(app).value(app) {
2400            DatePickerEntryMode::Calendar => {
2401                self.auto_validate(app).set_value(app, false);
2402                self.entry_mode(app)
2403                    .set_value(app, DatePickerEntryMode::Input);
2404            }
2405            DatePickerEntryMode::Input => {
2406                // Validate the range dates
2407                let start = *self.selected_start(app).value(app);
2408                let end = *self.selected_end(app).value(app);
2409                if let (Some(start), Some(end)) = (start, end)
2410                    && start.is_after(&end)
2411                {
2412                    self.selected_end(app).set_value(app, None);
2413                }
2414                if let Some(start) = *self.selected_start(app).value(app)
2415                    && !self.is_day_selectable(app, start)
2416                {
2417                    self.selected_start(app).set_value(app, None);
2418                    // With no valid start date, having an end date makes no sense for the UI.
2419                    self.selected_end(app).set_value(app, None);
2420                } else if let Some(end) = *self.selected_end(app).value(app)
2421                    && !self.is_day_selectable(app, end)
2422                {
2423                    self.selected_end(app).set_value(app, None);
2424                }
2425                self.entry_mode(app)
2426                    .set_value(app, DatePickerEntryMode::Calendar);
2427            }
2428            DatePickerEntryMode::CalendarOnly | DatePickerEntryMode::InputOnly => {
2429                debug_assert!(
2430                    false,
2431                    "Can not change entry mode from {:?}",
2432                    *self.entry_mode(app).value(app)
2433                );
2434            }
2435        }
2436    }
2437
2438    fn handle_start_date_changed(self: Handle<Self>, app: &mut App, date: Option<DateTime>) {
2439        self.set_state(app, |_state| {});
2440        self.selected_start(app).set_value(app, date);
2441    }
2442
2443    fn handle_end_date_changed(self: Handle<Self>, app: &mut App, date: Option<DateTime>) {
2444        self.set_state(app, |_state| {});
2445        self.selected_end(app).set_value(app, date);
2446    }
2447}
2448
2449impl RestorationMixin for DateRangePickerDialogState {
2450    waft_widgets::restoration_mixin_accessors!();
2451
2452    fn restoration_id(self: Handle<Self>, app: &App) -> Option<&str> {
2453        self.widget(app).restoration_id.as_deref()
2454    }
2455
2456    fn restore_state(
2457        self: Handle<Self>,
2458        app: &mut App,
2459        _old_bucket: Option<Handle<waft_widgets::RestorationBucket>>,
2460        _initial_restore: bool,
2461    ) {
2462        let (entry_mode, selected_start, selected_end, auto_validate) = (
2463            self.entry_mode(app),
2464            self.selected_start(app),
2465            self.selected_end(app),
2466            self.auto_validate(app),
2467        );
2468        self.register_for_restoration(app, entry_mode.as_property(), "entry_mode");
2469        self.register_for_restoration(app, selected_start.as_property(), "selected_start");
2470        self.register_for_restoration(app, selected_end.as_property(), "selected_end");
2471        self.register_for_restoration(app, auto_validate.as_property(), "autovalidate");
2472    }
2473}
2474
2475impl State for DateRangePickerDialogState {
2476    type Widget = DateRangePickerDialog;
2477    waft_widgets::state_accessors!();
2478
2479    fn init_state(self: Handle<Self>, app: &mut App) {
2480        let widget = self.widget(app).clone();
2481        let entry_mode = RestorableEnum::new(app, widget.initial_entry_mode, ENTRY_MODES);
2482        let selected_start =
2483            RestorableDateTimeN::new(app, widget.initial_date_range.map(|range| range.start));
2484        let selected_end =
2485            RestorableDateTimeN::new(app, widget.initial_date_range.map(|range| range.end));
2486        let auto_validate = RestorableBool::new(app, false);
2487        let state = app.get_mut(self);
2488        state.entry_mode = Some(entry_mode);
2489        state.selected_start = Some(selected_start);
2490        state.selected_end = Some(selected_end);
2491        state.auto_validate = Some(auto_validate);
2492    }
2493
2494    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
2495        self.did_change_dependencies_restoration(app);
2496    }
2497
2498    fn did_update_widget(self: Handle<Self>, app: &mut App, _old_widget: &DateRangePickerDialog) {
2499        self.did_update_restoration_id(app);
2500    }
2501
2502    fn dispose(self: Handle<Self>, app: &mut App) {
2503        self.entry_mode(app).dispose(app);
2504        self.selected_start(app).dispose(app);
2505        self.selected_end(app).dispose(app);
2506        self.auto_validate(app).dispose(app);
2507        self.dispose_restoration(app);
2508    }
2509
2510    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
2511        let theme = Theme::of(app, context);
2512        let use_material3 = theme.use_material3;
2513        let orientation = MediaQuery::orientation_of(app, context);
2514        let localizations = <dyn MaterialLocalizations>::of(app, context);
2515        let date_picker_theme = DatePickerTheme::of(app, context);
2516        let defaults = DatePickerTheme::defaults(app, context);
2517        let widget = self.widget(app).clone();
2518        let entry_mode = *self.entry_mode(app).value(app);
2519        let selected_start = *self.selected_start(app).value(app);
2520        let selected_end = *self.selected_end(app).value(app);
2521        let auto_validate = *self.auto_validate(app).value(app);
2522        let show_entry_mode_button = matches!(
2523            entry_mode,
2524            DatePickerEntryMode::Calendar | DatePickerEntryMode::Input
2525        );
2526
2527        let contents: WidgetRef;
2528        let size: Size;
2529        let elevation: f64;
2530        let shadow_color: Option<Color>;
2531        let surface_tint_color: Option<Color>;
2532        let shape: Option<ShapeBorderRef>;
2533        let inset_padding: EdgeInsets;
2534        match entry_mode {
2535            DatePickerEntryMode::Calendar | DatePickerEntryMode::CalendarOnly => {
2536                let entry_mode_button = show_entry_mode_button.then(|| {
2537                    IconButton::new(
2538                        Some(Listener::new(move |app| self.handle_entry_mode_toggle(app))),
2539                        widget
2540                            .switch_to_input_entry_mode_icon
2541                            .clone()
2542                            .unwrap_or_else(|| {
2543                                Icon::new(Some(if use_material3 {
2544                                    Icons::edit_outlined()
2545                                } else {
2546                                    Icons::edit()
2547                                }))
2548                                .into_widget()
2549                            }),
2550                    )
2551                    .padding(EdgeInsets::ZERO.into())
2552                    .tooltip(localizations.input_date_mode_button_label())
2553                    .into_widget()
2554                });
2555                let calendar_picker_key = app.get(self).calendar_picker_key.clone();
2556                contents = CalendarRangePickerDialog {
2557                    key: Some(calendar_picker_key.into()),
2558                    calendar_delegate: Rc::clone(&widget.calendar_delegate),
2559                    selected_start_date: selected_start,
2560                    selected_end_date: selected_end,
2561                    first_date: widget.first_date,
2562                    last_date: widget.last_date,
2563                    selectable_day_predicate: widget.selectable_day_predicate.clone(),
2564                    current_date: widget.current_date(app),
2565                    on_start_date_changed: Rc::new(move |app, date| {
2566                        self.handle_start_date_changed(app, date);
2567                    }),
2568                    on_end_date_changed: Rc::new(move |app, date| {
2569                        self.handle_end_date_changed(app, date);
2570                    }),
2571                    on_confirm: self
2572                        .has_selected_date_range(app)
2573                        .then(|| Listener::new(move |app| self.handle_ok(app))),
2574                    on_cancel: Listener::new(move |app| self.handle_cancel(app)),
2575                    entry_mode_button,
2576                    confirm_text: widget.save_text.clone().unwrap_or_else(|| {
2577                        if use_material3 {
2578                            localizations.save_button_label()
2579                        } else {
2580                            localizations.save_button_label().to_uppercase()
2581                        }
2582                    }),
2583                    help_text: widget.help_text.clone().unwrap_or_else(|| {
2584                        if use_material3 {
2585                            localizations.date_range_picker_help_text()
2586                        } else {
2587                            localizations.date_range_picker_help_text().to_uppercase()
2588                        }
2589                    }),
2590                }
2591                .into_widget();
2592                size = MediaQuery::size_of(app, context);
2593                inset_padding = EdgeInsets::ZERO;
2594                elevation = date_picker_theme
2595                    .range_picker_elevation
2596                    .or_else(|| defaults.range_picker_elevation(app))
2597                    .expect("the defaults give a range picker elevation");
2598                shadow_color = date_picker_theme
2599                    .range_picker_shadow_color
2600                    .or_else(|| defaults.range_picker_shadow_color(app));
2601                surface_tint_color = date_picker_theme
2602                    .range_picker_surface_tint_color
2603                    .or_else(|| defaults.range_picker_surface_tint_color(app));
2604                shape = date_picker_theme
2605                    .range_picker_shape
2606                    .clone()
2607                    .or_else(|| defaults.range_picker_shape(app));
2608            }
2609            DatePickerEntryMode::Input | DatePickerEntryMode::InputOnly => {
2610                let entry_mode_button = show_entry_mode_button.then(|| {
2611                    IconButton::new(
2612                        Some(Listener::new(move |app| self.handle_entry_mode_toggle(app))),
2613                        widget
2614                            .switch_to_calendar_entry_mode_icon
2615                            .clone()
2616                            .unwrap_or_else(|| {
2617                                Icon::new(Some(Icons::calendar_today())).into_widget()
2618                            }),
2619                    )
2620                    .padding(EdgeInsets::ZERO.into())
2621                    .tooltip(localizations.calendar_mode_button_label())
2622                    .into_widget()
2623                });
2624                let input_picker_key = app.get(self).input_picker_key.clone();
2625                let picker = SizedBox::new()
2626                    .height(if orientation == Orientation::Portrait {
2627                        INPUT_FORM_PORTRAIT_HEIGHT
2628                    } else {
2629                        INPUT_FORM_LANDSCAPE_HEIGHT
2630                    })
2631                    .child(
2632                        Padding::new(EdgeInsets::symmetric(0.0, 24.0)).child(
2633                            Column::new().children([
2634                                Spacer::new().into_widget(),
2635                                InputDateRangePicker {
2636                                    key: Some(input_picker_key.into()),
2637                                    calendar_delegate: Rc::clone(&widget.calendar_delegate),
2638                                    initial_start_date: selected_start,
2639                                    initial_end_date: selected_end,
2640                                    first_date: widget.first_date,
2641                                    last_date: widget.last_date,
2642                                    selectable_day_predicate: widget
2643                                        .selectable_day_predicate
2644                                        .clone(),
2645                                    on_start_date_changed: Some(Rc::new(move |app, date| {
2646                                        self.handle_start_date_changed(app, date);
2647                                    })),
2648                                    on_end_date_changed: Some(Rc::new(move |app, date| {
2649                                        self.handle_end_date_changed(app, date);
2650                                    })),
2651                                    autofocus: true,
2652                                    autovalidate: auto_validate,
2653                                    help_text: widget.help_text.clone(),
2654                                    error_invalid_range_text: widget
2655                                        .error_invalid_range_text
2656                                        .clone(),
2657                                    error_format_text: widget.error_format_text.clone(),
2658                                    error_invalid_text: widget.error_invalid_text.clone(),
2659                                    field_start_hint_text: widget.field_start_hint_text.clone(),
2660                                    field_end_hint_text: widget.field_end_hint_text.clone(),
2661                                    field_start_label_text: widget.field_start_label_text.clone(),
2662                                    field_end_label_text: widget.field_end_label_text.clone(),
2663                                    keyboard_type: widget.keyboard_type,
2664                                }
2665                                .into_widget(),
2666                                Spacer::new().into_widget(),
2667                            ]),
2668                        ),
2669                    )
2670                    .into_widget();
2671                contents = InputDateRangePickerDialog {
2672                    calendar_delegate: Rc::clone(&widget.calendar_delegate),
2673                    selected_start_date: selected_start,
2674                    selected_end_date: selected_end,
2675                    current_date: widget.current_date(app),
2676                    picker,
2677                    on_confirm: Listener::new(move |app| self.handle_ok(app)),
2678                    on_cancel: Listener::new(move |app| self.handle_cancel(app)),
2679                    entry_mode_button,
2680                    confirm_text: widget
2681                        .confirm_text
2682                        .clone()
2683                        .unwrap_or_else(|| localizations.ok_button_label()),
2684                    cancel_text: widget.cancel_text.clone().unwrap_or_else(|| {
2685                        if use_material3 {
2686                            localizations.cancel_button_label()
2687                        } else {
2688                            localizations.cancel_button_label().to_uppercase()
2689                        }
2690                    }),
2691                    help_text: widget.help_text.clone().unwrap_or_else(|| {
2692                        if use_material3 {
2693                            localizations.date_range_picker_help_text()
2694                        } else {
2695                            localizations.date_range_picker_help_text().to_uppercase()
2696                        }
2697                    }),
2698                }
2699                .into_widget();
2700                let dialog_theme = theme.dialog_theme.clone();
2701                size = if orientation == Orientation::Portrait {
2702                    if use_material3 {
2703                        INPUT_PORTRAIT_DIALOG_SIZE_M3
2704                    } else {
2705                        INPUT_PORTRAIT_DIALOG_SIZE_M2
2706                    }
2707                } else {
2708                    INPUT_RANGE_LANDSCAPE_DIALOG_SIZE
2709                };
2710                elevation = if use_material3 {
2711                    date_picker_theme
2712                        .elevation
2713                        .or_else(|| defaults.elevation(app))
2714                        .expect("the defaults give an elevation")
2715                } else {
2716                    date_picker_theme
2717                        .elevation
2718                        .or(dialog_theme.elevation)
2719                        .unwrap_or(24.0)
2720                };
2721                shadow_color = date_picker_theme
2722                    .shadow_color
2723                    .or_else(|| defaults.shadow_color(app));
2724                surface_tint_color = date_picker_theme
2725                    .surface_tint_color
2726                    .or_else(|| defaults.surface_tint_color(app));
2727                shape = if use_material3 {
2728                    date_picker_theme
2729                        .shape
2730                        .clone()
2731                        .or_else(|| defaults.shape(app))
2732                } else {
2733                    date_picker_theme
2734                        .shape
2735                        .clone()
2736                        .or_else(|| dialog_theme.shape.clone())
2737                        .or_else(|| defaults.shape(app))
2738                };
2739                inset_padding = EdgeInsets::symmetric(24.0, 16.0);
2740            }
2741        }
2742
2743        let mut dialog = Dialog::new()
2744            .inset_padding(inset_padding)
2745            .elevation(elevation)
2746            .clip_behavior(Clip::AntiAlias);
2747        if let Some(color) = date_picker_theme
2748            .background_color
2749            .or_else(|| defaults.background_color(app))
2750        {
2751            dialog = dialog.background_color(color);
2752        }
2753        if let Some(color) = shadow_color {
2754            dialog = dialog.shadow_color(color);
2755        }
2756        if let Some(color) = surface_tint_color {
2757            dialog = dialog.surface_tint_color(color);
2758        }
2759        if let Some(shape) = shape {
2760            dialog = dialog.shape(shape);
2761        }
2762        dialog
2763            .child(
2764                AnimatedContainer::new(DIALOG_SIZE_ANIMATION_DURATION)
2765                    .width(size.width())
2766                    .height(size.height())
2767                    .curve(Curves::ease_in())
2768                    .child(MediaQuery::with_clamped_text_scaling(
2769                        None,
2770                        0.0,
2771                        MAX_RANGE_TEXT_SCALE_FACTOR,
2772                        Builder::new(move |_app, _context| contents.clone()),
2773                    )),
2774            )
2775            .into_widget()
2776    }
2777}
2778
2779const MONTH_SCROLL_DURATION: Duration = Duration::from_millis(200);
2780
2781const MONTH_ITEM_HEADER_HEIGHT: f64 = 58.0;
2782const MONTH_ITEM_FOOTER_HEIGHT: f64 = 12.0;
2783const MONTH_ITEM_ROW_HEIGHT: f64 = 42.0;
2784const MONTH_ITEM_SPACE_BETWEEN_ROWS: f64 = 8.0;
2785const HORIZONTAL_PADDING: f64 = 8.0;
2786const MAX_CALENDAR_WIDTH_LANDSCAPE: f64 = 384.0;
2787const MAX_CALENDAR_WIDTH_PORTRAIT: f64 = 480.0;
2788
2789/// Dart's `_CalendarRangePickerDialog`.
2790#[derive(Clone)]
2791struct CalendarRangePickerDialog {
2792    key: Option<KeyRef>,
2793    calendar_delegate: Rc<dyn CalendarDelegate>,
2794    selected_start_date: Option<DateTime>,
2795    selected_end_date: Option<DateTime>,
2796    first_date: DateTime,
2797    last_date: DateTime,
2798    selectable_day_predicate: Option<SelectableDayForRangePredicate>,
2799    current_date: DateTime,
2800    on_start_date_changed: ValueChanged<Option<DateTime>>,
2801    on_end_date_changed: ValueChanged<Option<DateTime>>,
2802    on_confirm: Option<Listener>,
2803    on_cancel: Listener,
2804    entry_mode_button: Option<WidgetRef>,
2805    confirm_text: String,
2806    help_text: String,
2807}
2808
2809impl fmt::Debug for CalendarRangePickerDialog {
2810    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2811        f.debug_struct("CalendarRangePickerDialog")
2812            .field("selected_start_date", &self.selected_start_date)
2813            .field("selected_end_date", &self.selected_end_date)
2814            .finish_non_exhaustive()
2815    }
2816}
2817
2818fn apply_color(style: Option<TextStyle>, color: Option<Color>) -> Option<TextStyle> {
2819    style.map(|style| match color {
2820        Some(color) => style.copy_with().color(color),
2821        None => style,
2822    })
2823}
2824
2825impl StatelessWidget for CalendarRangePickerDialog {
2826    fn key(&self) -> Option<&KeyRef> {
2827        self.key.as_ref()
2828    }
2829
2830    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
2831        let theme = Theme::of(app, context);
2832        let use_material3 = theme.use_material3;
2833        let localizations = <dyn MaterialLocalizations>::of(app, context);
2834        let orientation = MediaQuery::orientation_of(app, context);
2835        let theme_data = DatePickerTheme::of(app, context);
2836        let defaults = DatePickerTheme::defaults(app, context);
2837        let dialog_background = theme_data
2838            .range_picker_background_color
2839            .or_else(|| defaults.range_picker_background_color(app));
2840        let header_background = theme_data
2841            .range_picker_header_background_color
2842            .or_else(|| defaults.range_picker_header_background_color(app));
2843        let header_foreground = theme_data
2844            .range_picker_header_foreground_color
2845            .or_else(|| defaults.range_picker_header_foreground_color(app));
2846        #[allow(deprecated)]
2847        let header_disabled_foreground = header_foreground.map(|color| color.with_opacity(0.38));
2848        let headline_style = theme_data
2849            .range_picker_header_headline_style
2850            .clone()
2851            .or_else(|| defaults.range_picker_header_headline_style(app));
2852        let headline_help_style = apply_color(
2853            theme_data
2854                .range_picker_header_help_style
2855                .clone()
2856                .or_else(|| defaults.range_picker_header_help_style(app)),
2857            header_foreground,
2858        );
2859        let start_date_text = format_range_start_date(
2860            app,
2861            &*localizations,
2862            &*self.calendar_delegate,
2863            self.selected_start_date.as_ref(),
2864            self.selected_end_date.as_ref(),
2865        );
2866        let end_date_text = format_range_end_date(
2867            app,
2868            &*localizations,
2869            &*self.calendar_delegate,
2870            self.selected_start_date.as_ref(),
2871            self.selected_end_date.as_ref(),
2872            &self.calendar_delegate.now(app),
2873        );
2874        let start_date_style = apply_color(
2875            headline_style.clone(),
2876            if self.selected_start_date.is_some() {
2877                header_foreground
2878            } else {
2879                header_disabled_foreground
2880            },
2881        );
2882        let end_date_style = apply_color(
2883            headline_style,
2884            if self.selected_end_date.is_some() {
2885                header_foreground
2886            } else {
2887                header_disabled_foreground
2888            },
2889        );
2890        let mut button_style = TextButton::style_from();
2891        if let Some(color) = header_foreground {
2892            button_style = button_style.foreground_color(color);
2893        }
2894        if let Some(color) = header_disabled_foreground {
2895            button_style = button_style.disabled_foreground_color(color);
2896        }
2897        let button_style = button_style.build();
2898        let mut icon_theme = IconThemeData::new();
2899        if let Some(color) = header_foreground {
2900            icon_theme = icon_theme.color(color);
2901        }
2902
2903        let styled = |text: String, style: Option<TextStyle>| {
2904            let text = Text::new(text);
2905            match style {
2906                Some(style) => text.style(style),
2907                None => text,
2908            }
2909        };
2910
2911        let mut actions: Vec<WidgetRef> = Vec::new();
2912        if orientation == Orientation::Landscape
2913            && let Some(entry_mode_button) = &self.entry_mode_button
2914        {
2915            actions.push(entry_mode_button.clone());
2916        }
2917        actions.push(
2918            TextButton::new(
2919                self.on_confirm.clone(),
2920                Some(Text::new(self.confirm_text.clone())),
2921            )
2922            .style(button_style)
2923            .into_widget(),
2924        );
2925        actions.push(SizedBox::new().width(8.0).into_widget());
2926
2927        let mut bottom_row: Vec<WidgetRef> = vec![
2928            SizedBox::new()
2929                .width(if MediaQuery::width_of(app, context) < 360.0 {
2930                    42.0
2931                } else {
2932                    72.0
2933                })
2934                .into_widget(),
2935            Expanded::new(
2936                Semantics::new()
2937                    .label(format!(
2938                        "{} {start_date_text} to {end_date_text}",
2939                        self.help_text
2940                    ))
2941                    .exclude_semantics(true)
2942                    .child(
2943                        Column::new()
2944                            .cross_axis_alignment(CrossAxisAlignment::Start)
2945                            .children([
2946                                styled(self.help_text.clone(), headline_help_style)
2947                                    .max_lines(1)
2948                                    .overflow(TextOverflow::Ellipsis)
2949                                    .into_widget(),
2950                                SizedBox::new().height(8.0).into_widget(),
2951                                waft_widgets::Row::new()
2952                                    .children([
2953                                        styled(start_date_text.clone(), start_date_style.clone())
2954                                            .max_lines(1)
2955                                            .overflow(TextOverflow::Ellipsis)
2956                                            .into_widget(),
2957                                        styled(" \u{2013} ".to_string(), start_date_style)
2958                                            .into_widget(),
2959                                        waft_widgets::Flexible::new(
2960                                            styled(end_date_text.clone(), end_date_style)
2961                                                .max_lines(1)
2962                                                .overflow(TextOverflow::Ellipsis),
2963                                        )
2964                                        .into_widget(),
2965                                    ])
2966                                    .into_widget(),
2967                                SizedBox::new().height(16.0).into_widget(),
2968                            ]),
2969                    ),
2970            )
2971            .into_widget(),
2972        ];
2973        if orientation == Orientation::Portrait
2974            && let Some(entry_mode_button) = &self.entry_mode_button
2975        {
2976            bottom_row.push(
2977                Padding::new(EdgeInsets::symmetric(0.0, 8.0))
2978                    .child(IconTheme::new(
2979                        icon_theme.clone(),
2980                        entry_mode_button.clone(),
2981                    ))
2982                    .into_widget(),
2983            );
2984        }
2985
2986        let mut app_bar = AppBar::new()
2987            .icon_theme(icon_theme.clone())
2988            .actions_icon_theme(icon_theme)
2989            .leading(CloseButton::new().on_pressed(self.on_cancel.clone()))
2990            .actions(actions)
2991            .bottom(PreferredSizeWidgetRef::new(PreferredSize::new(
2992                Size::new(f64::INFINITY, 64.0),
2993                waft_widgets::Row::new().children(bottom_row),
2994            )));
2995        if use_material3 {
2996            app_bar = app_bar.elevation(0.0).scrolled_under_elevation(0.0);
2997        }
2998        if let Some(color) = header_background {
2999            app_bar = app_bar.background_color(color);
3000        }
3001        let mut scaffold = Scaffold::new()
3002            .app_bar(PreferredSizeWidgetRef::new(app_bar))
3003            .body(CalendarDateRangePicker {
3004                initial_start_date: self.selected_start_date,
3005                initial_end_date: self.selected_end_date,
3006                first_date: self.first_date,
3007                last_date: self.last_date,
3008                current_date: self.current_date,
3009                on_start_date_changed: Some(Rc::clone(&self.on_start_date_changed)),
3010                on_end_date_changed: Some(Rc::clone(&self.on_end_date_changed)),
3011                selectable_day_predicate: self.selectable_day_predicate.clone(),
3012                calendar_delegate: Rc::clone(&self.calendar_delegate),
3013            });
3014        if let Some(color) = dialog_background {
3015            scaffold = scaffold.background_color(color);
3016        }
3017        SafeArea::new(scaffold)
3018            .top(false)
3019            .left(false)
3020            .right(false)
3021            .into_widget()
3022    }
3023}
3024
3025/// Dart's `_CalendarDateRangePicker`.
3026#[derive(Clone)]
3027struct CalendarDateRangePicker {
3028    initial_start_date: Option<DateTime>,
3029    initial_end_date: Option<DateTime>,
3030    first_date: DateTime,
3031    last_date: DateTime,
3032    selectable_day_predicate: Option<SelectableDayForRangePredicate>,
3033    current_date: DateTime,
3034    on_start_date_changed: Option<ValueChanged<Option<DateTime>>>,
3035    on_end_date_changed: Option<ValueChanged<Option<DateTime>>>,
3036    calendar_delegate: Rc<dyn CalendarDelegate>,
3037}
3038
3039impl fmt::Debug for CalendarDateRangePicker {
3040    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3041        f.debug_struct("CalendarDateRangePicker")
3042            .field("initial_start_date", &self.initial_start_date)
3043            .field("initial_end_date", &self.initial_end_date)
3044            .finish_non_exhaustive()
3045    }
3046}
3047
3048impl StatefulWidget for CalendarDateRangePicker {
3049    type State = CalendarDateRangePickerState;
3050
3051    fn create_state(&self) -> CalendarDateRangePickerState {
3052        debug_assert!(
3053            self.initial_start_date
3054                .zip(self.initial_end_date)
3055                .is_none_or(|(start, end)| !start.is_after(&end)),
3056            "initialStartDate must be on or before initialEndDate."
3057        );
3058        debug_assert!(
3059            !self.last_date.is_before(&self.first_date),
3060            "firstDate must be on or before lastDate."
3061        );
3062        CalendarDateRangePickerState {
3063            state: StateData::new(),
3064            scroll_view_key: GlobalKey::new(),
3065            sliver_after_key: UniqueKey::new(),
3066            start_date: self.initial_start_date,
3067            end_date: self.initial_end_date,
3068            initial_month_index: 0,
3069            controller: None,
3070            show_week_bottom_divider: false,
3071        }
3072    }
3073}
3074
3075/// Dart's `_CalendarDateRangePickerState`.
3076struct CalendarDateRangePickerState {
3077    state: StateData<CalendarDateRangePicker>,
3078    scroll_view_key: GlobalKey,
3079    sliver_after_key: UniqueKey,
3080    start_date: Option<DateTime>,
3081    end_date: Option<DateTime>,
3082    initial_month_index: i32,
3083    /// Created in `init_state`, because a state is created without the [`App`].
3084    controller: Option<Ref<ScrollController>>,
3085    show_week_bottom_divider: bool,
3086}
3087
3088impl CalendarDateRangePickerState {
3089    fn controller(self: Handle<Self>, app: &App) -> Ref<ScrollController> {
3090        app.get(self)
3091            .controller
3092            .clone()
3093            .expect("created in init_state")
3094    }
3095
3096    fn scroll_listener(self: Handle<Self>, app: &mut App) {
3097        let controller = self.controller(app).handle();
3098        let position = controller.position(app);
3099        let at_start = controller.offset(app) <= position.min_scroll_extent(app);
3100        if at_start {
3101            self.set_state(app, |_| {});
3102            app.get_mut(self).show_week_bottom_divider = false;
3103        } else if !app.get(self).show_week_bottom_divider {
3104            self.set_state(app, |_| {});
3105            app.get_mut(self).show_week_bottom_divider = true;
3106        }
3107    }
3108
3109    fn number_of_months(self: Handle<Self>, app: &App) -> i32 {
3110        let widget = self.widget(app);
3111        widget
3112            .calendar_delegate
3113            .month_delta(app, &widget.first_date, &widget.last_date)
3114            + 1
3115    }
3116
3117    fn vibrate(self: Handle<Self>, app: &mut App) {
3118        let context = self.context(app);
3119        match Theme::of(app, context).platform {
3120            TargetPlatform::Android
3121            | TargetPlatform::Fuchsia
3122            | TargetPlatform::Linux
3123            | TargetPlatform::Windows => HapticFeedback::vibrate(app),
3124            TargetPlatform::IOS | TargetPlatform::MacOS => {}
3125        }
3126    }
3127
3128    // This updates the selected date range using this logic:
3129    //
3130    // * From the unselected state, selecting one date creates the start date.
3131    //   * If the next selection is before the start date, reset date range and
3132    //     set the start date to that selection.
3133    //   * If the next selection is on or after the start date, set the end date
3134    //     to that selection.
3135    // * After both start and end dates are selected, any subsequent selection
3136    //   resets the date range and sets start date to that selection.
3137    fn update_selection(self: Handle<Self>, app: &mut App, date: DateTime) {
3138        self.vibrate(app);
3139        self.set_state(app, |_| {});
3140        let (start_date, end_date) = (app.get(self).start_date, app.get(self).end_date);
3141        let widget = self.widget(app).clone();
3142        if start_date.is_some_and(|start| !date.is_before(&start)) && end_date.is_none() {
3143            app.get_mut(self).end_date = Some(date);
3144            if let Some(on_end_date_changed) = &widget.on_end_date_changed {
3145                on_end_date_changed(app, Some(date));
3146            }
3147        } else {
3148            app.get_mut(self).start_date = Some(date);
3149            if let Some(on_start_date_changed) = &widget.on_start_date_changed {
3150                on_start_date_changed(app, Some(date));
3151            }
3152            if end_date.is_some() {
3153                app.get_mut(self).end_date = None;
3154                if let Some(on_end_date_changed) = &widget.on_end_date_changed {
3155                    on_end_date_changed(app, None);
3156                }
3157            }
3158        }
3159    }
3160
3161    fn build_month_item(
3162        self: Handle<Self>,
3163        app: &mut App,
3164        index: i32,
3165        before_initial_month: bool,
3166    ) -> WidgetRef {
3167        let initial_month_index = app.get(self).initial_month_index;
3168        let month_index = if before_initial_month {
3169            initial_month_index - index - 1
3170        } else {
3171            initial_month_index + index
3172        };
3173        let widget = self.widget(app).clone();
3174        let month =
3175            widget
3176                .calendar_delegate
3177                .add_months_to_month_date(app, &widget.first_date, month_index);
3178        MonthItem {
3179            calendar_delegate: Rc::clone(&widget.calendar_delegate),
3180            selected_date_start: app.get(self).start_date,
3181            selected_date_end: app.get(self).end_date,
3182            current_date: widget.current_date,
3183            first_date: widget.first_date,
3184            last_date: widget.last_date,
3185            displayed_month: month,
3186            on_changed: Rc::new(move |app, date| self.update_selection(app, date)),
3187            selectable_day_predicate: widget.selectable_day_predicate.clone(),
3188        }
3189        .into_widget()
3190    }
3191}
3192
3193impl fmt::Debug for CalendarDateRangePickerState {
3194    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3195        f.debug_struct("CalendarDateRangePickerState")
3196            .field("start_date", &self.start_date)
3197            .field("end_date", &self.end_date)
3198            .finish_non_exhaustive()
3199    }
3200}
3201
3202impl State for CalendarDateRangePickerState {
3203    type Widget = CalendarDateRangePicker;
3204    waft_widgets::state_accessors!();
3205
3206    fn init_state(self: Handle<Self>, app: &mut App) {
3207        let controller = ScrollController::new(app, 0.0, true, None, None, None);
3208        controller
3209            .handle()
3210            .add_listener(app, Listener::handle_method(self, Self::scroll_listener));
3211        app.get_mut(self).controller = Some(controller);
3212
3213        // Calculate the index for the initially displayed month. This is needed to divide the
3214        // list of months into two `SliverList`s.
3215        let widget = self.widget(app).clone();
3216        let initial_date = widget.initial_start_date.unwrap_or(widget.current_date);
3217        let mut initial_month_index = 0;
3218        if !initial_date.is_before(&widget.first_date) && !initial_date.is_after(&widget.last_date)
3219        {
3220            initial_month_index =
3221                widget
3222                    .calendar_delegate
3223                    .month_delta(app, &widget.first_date, &initial_date);
3224        }
3225        let state = app.get_mut(self);
3226        state.initial_month_index = initial_month_index;
3227        state.show_week_bottom_divider = initial_month_index != 0;
3228    }
3229
3230    fn dispose(self: Handle<Self>, app: &mut App) {
3231        self.controller(app).handle().dispose(app);
3232    }
3233
3234    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
3235        let widget = self.widget(app).clone();
3236        let state = app.get(self);
3237        let (start_date, show_divider) = (state.start_date, state.show_week_bottom_divider);
3238        let scroll_view_key = state.scroll_view_key.clone();
3239        let sliver_after_key = state.sliver_after_key;
3240        let initial_month_index = state.initial_month_index;
3241        let number_of_months = self.number_of_months(app);
3242        let controller = self.controller(app);
3243
3244        let mut children: Vec<WidgetRef> = vec![DayHeaders.into_widget()];
3245        if show_divider {
3246            children.push(Divider::new().height(0.0).into_widget());
3247        }
3248        children.push(
3249            Expanded::new(CalendarKeyboardNavigator {
3250                calendar_delegate: Rc::clone(&widget.calendar_delegate),
3251                first_date: widget.first_date,
3252                last_date: widget.last_date,
3253                initial_focused_day: start_date
3254                    .or(widget.initial_start_date)
3255                    .unwrap_or(widget.current_date),
3256                // In order to prevent performance issues when displaying the correct initial
3257                // month, 2 `SliverList`s are used to split the months. The first item in the
3258                // second SliverList is the initial month to be displayed.
3259                child: CustomScrollView::new()
3260                    .key(scroll_view_key.into())
3261                    .controller(controller.into_erased())
3262                    .center(sliver_after_key.into())
3263                    .slivers([
3264                        SliverList::builder(move |app, _context, index| {
3265                            if index >= initial_month_index {
3266                                return None;
3267                            }
3268                            Some(self.build_month_item(app, index, true))
3269                        })
3270                        .into_widget(),
3271                        SliverList::builder(move |app, _context, index| {
3272                            if index >= number_of_months - initial_month_index {
3273                                return None;
3274                            }
3275                            Some(self.build_month_item(app, index, false))
3276                        })
3277                        .key(sliver_after_key.into())
3278                        .into_widget(),
3279                    ])
3280                    .into_widget(),
3281            })
3282            .into_widget(),
3283        );
3284        Column::new().children(children).into_widget()
3285    }
3286}
3287
3288/// Dart's `_CalendarKeyboardNavigator`.
3289#[derive(Clone)]
3290struct CalendarKeyboardNavigator {
3291    child: WidgetRef,
3292    first_date: DateTime,
3293    last_date: DateTime,
3294    initial_focused_day: DateTime,
3295    calendar_delegate: Rc<dyn CalendarDelegate>,
3296}
3297
3298impl fmt::Debug for CalendarKeyboardNavigator {
3299    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3300        f.debug_struct("CalendarKeyboardNavigator")
3301            .field("initial_focused_day", &self.initial_focused_day)
3302            .finish_non_exhaustive()
3303    }
3304}
3305
3306impl StatefulWidget for CalendarKeyboardNavigator {
3307    type State = CalendarKeyboardNavigatorState;
3308
3309    fn create_state(&self) -> CalendarKeyboardNavigatorState {
3310        CalendarKeyboardNavigatorState {
3311            state: StateData::new(),
3312            shortcut_map: Vec::new(),
3313            action_map: HashMap::new(),
3314            day_grid_focus: None,
3315            day_traversal_direction: None,
3316            focused_day: None,
3317        }
3318    }
3319}
3320
3321struct CalendarKeyboardNavigatorState {
3322    state: StateData<CalendarKeyboardNavigator>,
3323    shortcut_map: ShortcutMap,
3324    action_map: HashMap<TypeId, ActionRef>,
3325    day_grid_focus: Option<Ref<FocusNode>>,
3326    day_traversal_direction: Option<TraversalDirection>,
3327    focused_day: Option<DateTime>,
3328}
3329
3330fn directional_shortcut(
3331    key: LogicalKeyboardKey,
3332    direction: TraversalDirection,
3333) -> (ShortcutActivatorRef, IntentRef) {
3334    (
3335        Rc::new(SingleActivator::new(key)) as ShortcutActivatorRef,
3336        Rc::new(DirectionalFocusIntent::new(direction)) as IntentRef,
3337    )
3338}
3339
3340fn direction_offset(direction: TraversalDirection) -> i32 {
3341    match direction {
3342        TraversalDirection::Up => -DateTime::DAYS_PER_WEEK,
3343        TraversalDirection::Right => 1,
3344        TraversalDirection::Down => DateTime::DAYS_PER_WEEK,
3345        TraversalDirection::Left => -1,
3346    }
3347}
3348
3349impl CalendarKeyboardNavigatorState {
3350    fn day_grid_focus(self: Handle<Self>, app: &App) -> Ref<FocusNode> {
3351        app.get(self)
3352            .day_grid_focus
3353            .clone()
3354            .expect("created in init_state")
3355    }
3356
3357    fn handle_grid_focus_change(self: Handle<Self>, app: &mut App, focused: bool) {
3358        self.set_state(app, |_| {});
3359        if focused && app.get(self).focused_day.is_none() {
3360            let initial_focused_day = self.widget(app).initial_focused_day;
3361            app.get_mut(self).focused_day = Some(initial_focused_day);
3362        }
3363    }
3364
3365    fn handle_grid_next_focus(self: Handle<Self>, app: &mut App) {
3366        let day_grid_focus = self.day_grid_focus(app).handle();
3367        day_grid_focus.request_focus(app, None);
3368        day_grid_focus.as_node().next_focus(app);
3369    }
3370
3371    fn handle_grid_previous_focus(self: Handle<Self>, app: &mut App) {
3372        let day_grid_focus = self.day_grid_focus(app).handle();
3373        day_grid_focus.request_focus(app, None);
3374        day_grid_focus.as_node().previous_focus(app);
3375    }
3376
3377    fn handle_direction_focus(self: Handle<Self>, app: &mut App, direction: TraversalDirection) {
3378        let focused_day = app
3379            .get(self)
3380            .focused_day
3381            .expect("a focused day when navigating by direction");
3382        self.set_state(app, |_| {});
3383        if let Some(next_date) = self.next_date_in_direction(app, &focused_day, direction) {
3384            let state = app.get_mut(self);
3385            state.focused_day = Some(next_date);
3386            state.day_traversal_direction = Some(direction);
3387        }
3388    }
3389
3390    fn day_direction_offset(
3391        traversal_direction: TraversalDirection,
3392        text_direction: TextDirection,
3393    ) -> i32 {
3394        let mut traversal_direction = traversal_direction;
3395        // Swap left and right if the text direction if RTL
3396        if text_direction == TextDirection::Rtl {
3397            if traversal_direction == TraversalDirection::Left {
3398                traversal_direction = TraversalDirection::Right;
3399            } else if traversal_direction == TraversalDirection::Right {
3400                traversal_direction = TraversalDirection::Left;
3401            }
3402        }
3403        direction_offset(traversal_direction)
3404    }
3405
3406    fn next_date_in_direction(
3407        self: Handle<Self>,
3408        app: &mut App,
3409        date: &DateTime,
3410        direction: TraversalDirection,
3411    ) -> Option<DateTime> {
3412        let context = self.context(app);
3413        let text_direction = Directionality::of(app, context);
3414        let widget = self.widget(app);
3415        let next_date = widget.calendar_delegate.add_days_to_date(
3416            app,
3417            date,
3418            Self::day_direction_offset(direction, text_direction),
3419        );
3420        if !next_date.is_before(&widget.first_date) && !next_date.is_after(&widget.last_date) {
3421            return Some(next_date);
3422        }
3423        None
3424    }
3425}
3426
3427impl fmt::Debug for CalendarKeyboardNavigatorState {
3428    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3429        f.debug_struct("CalendarKeyboardNavigatorState")
3430            .field("focused_day", &self.focused_day)
3431            .finish_non_exhaustive()
3432    }
3433}
3434
3435impl State for CalendarKeyboardNavigatorState {
3436    type Widget = CalendarKeyboardNavigator;
3437    waft_widgets::state_accessors!();
3438
3439    fn init_state(self: Handle<Self>, app: &mut App) {
3440        let shortcut_map: ShortcutMap = vec![
3441            directional_shortcut(LogicalKeyboardKey::ARROW_LEFT, TraversalDirection::Left),
3442            directional_shortcut(LogicalKeyboardKey::ARROW_RIGHT, TraversalDirection::Right),
3443            directional_shortcut(LogicalKeyboardKey::ARROW_DOWN, TraversalDirection::Down),
3444            directional_shortcut(LogicalKeyboardKey::ARROW_UP, TraversalDirection::Up),
3445        ];
3446        let next_focus = CallbackAction::<NextFocusIntent>::new(
3447            app,
3448            Rc::new(move |app: &mut App, _intent: &NextFocusIntent| {
3449                self.handle_grid_next_focus(app);
3450                None
3451            }),
3452        );
3453        let previous_focus = CallbackAction::<PreviousFocusIntent>::new(
3454            app,
3455            Rc::new(move |app: &mut App, _intent: &PreviousFocusIntent| {
3456                self.handle_grid_previous_focus(app);
3457                None
3458            }),
3459        );
3460        let directional_focus = CallbackAction::<DirectionalFocusIntent>::new(
3461            app,
3462            Rc::new(move |app: &mut App, intent: &DirectionalFocusIntent| {
3463                self.handle_direction_focus(app, intent.direction);
3464                None
3465            }),
3466        );
3467        let mut action_map = HashMap::new();
3468        action_map.insert(TypeId::of::<NextFocusIntent>(), next_focus.into_erased());
3469        action_map.insert(
3470            TypeId::of::<PreviousFocusIntent>(),
3471            previous_focus.into_erased(),
3472        );
3473        action_map.insert(
3474            TypeId::of::<DirectionalFocusIntent>(),
3475            directional_focus.into_erased(),
3476        );
3477        let day_grid_focus = FocusNode::new(app);
3478        day_grid_focus
3479            .handle()
3480            .set_debug_label(app, Some("Day Grid".to_string()));
3481        let state = app.get_mut(self);
3482        state.shortcut_map = shortcut_map;
3483        state.action_map = action_map;
3484        state.day_grid_focus = Some(day_grid_focus);
3485    }
3486
3487    fn dispose(self: Handle<Self>, app: &mut App) {
3488        self.day_grid_focus(app).handle().dispose(app);
3489    }
3490
3491    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
3492        let widget = self.widget(app).clone();
3493        let day_grid_focus = self.day_grid_focus(app);
3494        let has_focus = day_grid_focus.handle().has_focus(app);
3495        let state = app.get(self);
3496        let (shortcuts, actions) = (state.shortcut_map.clone(), state.action_map.clone());
3497        let (date, scroll_direction) = (
3498            if has_focus { state.focused_day } else { None },
3499            if has_focus {
3500                state.day_traversal_direction
3501            } else {
3502                None
3503            },
3504        );
3505        FocusableActionDetector::new(FocusedDate {
3506            child: widget.child.clone(),
3507            date,
3508            day: date.map(|date| widget.calendar_delegate.date_only(app, &date)),
3509            scroll_direction,
3510        })
3511        .shortcuts(shortcuts)
3512        .actions(actions)
3513        .focus_node(day_grid_focus.into_erased())
3514        .on_focus_change(move |app, focused| self.handle_grid_focus_change(app, focused))
3515        .into_widget()
3516    }
3517}
3518
3519/// Dart's `_FocusedDate` of date_picker.dart.
3520#[derive(Debug)]
3521struct FocusedDate {
3522    child: WidgetRef,
3523    date: Option<DateTime>,
3524    /// `date`'s day, `calendarDelegate.dateOnly(date)`, made where the widget is built: two of
3525    /// them are equal where Dart's `calendarDelegate.isSameDay` holds for the dates.
3526    day: Option<DateTime>,
3527    scroll_direction: Option<TraversalDirection>,
3528}
3529
3530impl FocusedDate {
3531    fn maybe_of(
3532        app: &mut App,
3533        context: BuildContext,
3534    ) -> Option<(Option<DateTime>, Option<TraversalDirection>)> {
3535        context
3536            .depend_on_inherited_widget_of_exact_type::<FocusedDate>(app)
3537            .map(|focused| (focused.date, focused.scroll_direction))
3538    }
3539}
3540
3541impl InheritedWidget for FocusedDate {
3542    fn child(&self) -> &WidgetRef {
3543        &self.child
3544    }
3545
3546    fn key(&self) -> Option<&KeyRef> {
3547        None
3548    }
3549
3550    fn update_should_notify(&self, old_widget: &FocusedDate) -> bool {
3551        self.day != old_widget.day || self.scroll_direction != old_widget.scroll_direction
3552    }
3553}
3554
3555/// Dart's `_DayHeaders`.
3556#[derive(Clone, Copy, Debug)]
3557struct DayHeaders;
3558
3559impl StatelessWidget for DayHeaders {
3560    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
3561        let theme_data = Theme::of(app, context);
3562        let color_scheme = &theme_data.color_scheme;
3563        let text_style = apply_color(
3564            theme_data.text_theme.title_small.clone(),
3565            Some(color_scheme.on_surface()),
3566        )
3567        .expect("the text theme has titleSmall");
3568        let localizations = <dyn MaterialLocalizations>::of(app, context);
3569        let narrow_weekdays = localizations.narrow_weekdays();
3570        let mut labels: Vec<WidgetRef> = vec![SizedBox::shrink().into_widget()];
3571        let mut i = localizations.first_day_of_week_index();
3572        while labels.len() < DateTime::DAYS_PER_WEEK as usize + 1 {
3573            labels.push(
3574                ExcludeSemantics::new()
3575                    .child(Center::new().child(
3576                        Text::new(narrow_weekdays[i as usize].clone()).style(text_style.clone()),
3577                    ))
3578                    .into_widget(),
3579            );
3580            i = (i + 1) % DateTime::DAYS_PER_WEEK;
3581        }
3582        labels.push(SizedBox::shrink().into_widget());
3583
3584        ConstrainedBox::new(BoxConstraints {
3585            max_width: if MediaQuery::orientation_of(app, context) == Orientation::Landscape {
3586                MAX_CALENDAR_WIDTH_LANDSCAPE
3587            } else {
3588                MAX_CALENDAR_WIDTH_PORTRAIT
3589            },
3590            max_height: MONTH_ITEM_ROW_HEIGHT,
3591            ..BoxConstraints::new()
3592        })
3593        .child(
3594            GridView::custom(
3595                Rc::new(MonthItemGridDelegate),
3596                SliverChildListDelegate::new(labels)
3597                    .add_repaint_boundaries(false)
3598                    .into_delegate(),
3599            )
3600            .shrink_wrap(true),
3601        )
3602        .into_widget()
3603    }
3604}
3605
3606/// Dart's `_MonthItemGridDelegate`.
3607#[derive(Clone, Copy, Debug)]
3608struct MonthItemGridDelegate;
3609
3610impl SliverGridDelegate for MonthItemGridDelegate {
3611    fn get_layout(&self, constraints: SliverConstraints) -> Box<dyn SliverGridLayout> {
3612        let tile_width = ((constraints.cross_axis_extent - 2.0 * HORIZONTAL_PADDING)
3613            / f64::from(DateTime::DAYS_PER_WEEK))
3614        .max(0.0);
3615        Box::new(MonthSliverGridLayout {
3616            cross_axis_count: DateTime::DAYS_PER_WEEK + 2,
3617            day_child_width: tile_width,
3618            edge_child_width: HORIZONTAL_PADDING,
3619            reverse_cross_axis: axis_direction_is_reversed(constraints.cross_axis_direction),
3620        })
3621    }
3622
3623    fn should_relayout(&self, _old_delegate: &dyn SliverGridDelegate) -> bool {
3624        false
3625    }
3626
3627    fn as_any(&self) -> &dyn std::any::Any {
3628        self
3629    }
3630}
3631
3632/// Dart's `_MonthSliverGridLayout`.
3633#[derive(Clone, Copy, Debug)]
3634struct MonthSliverGridLayout {
3635    cross_axis_count: i32,
3636    day_child_width: f64,
3637    edge_child_width: f64,
3638    reverse_cross_axis: bool,
3639}
3640
3641impl MonthSliverGridLayout {
3642    fn row_height() -> f64 {
3643        MONTH_ITEM_ROW_HEIGHT + MONTH_ITEM_SPACE_BETWEEN_ROWS
3644    }
3645
3646    fn child_height() -> f64 {
3647        MONTH_ITEM_ROW_HEIGHT
3648    }
3649
3650    fn cross_axis_offset(&self, cross_axis_start: f64, is_padding: bool) -> f64 {
3651        if self.reverse_cross_axis {
3652            return (f64::from(self.cross_axis_count - 2) * self.day_child_width
3653                + 2.0 * self.edge_child_width)
3654                - cross_axis_start
3655                - if is_padding {
3656                    self.edge_child_width
3657                } else {
3658                    self.day_child_width
3659                };
3660        }
3661        cross_axis_start
3662    }
3663}
3664
3665impl SliverGridLayout for MonthSliverGridLayout {
3666    fn get_min_child_index_for_scroll_offset(&self, scroll_offset: f64) -> i32 {
3667        self.cross_axis_count * (scroll_offset / Self::row_height()).trunc() as i32
3668    }
3669
3670    fn get_max_child_index_for_scroll_offset(&self, scroll_offset: f64) -> i32 {
3671        let main_axis_count = (scroll_offset / Self::row_height()).ceil() as i32;
3672        0.max(self.cross_axis_count * main_axis_count - 1)
3673    }
3674
3675    fn get_geometry_for_child_index(&self, index: i32) -> SliverGridGeometry {
3676        let adjusted_index = index % self.cross_axis_count;
3677        let is_edge = adjusted_index == 0 || adjusted_index == self.cross_axis_count - 1;
3678        let cross_axis_start = 0.0_f64
3679            .max(f64::from(adjusted_index - 1) * self.day_child_width + self.edge_child_width);
3680        SliverGridGeometry {
3681            scroll_offset: f64::from(index / self.cross_axis_count) * Self::row_height(),
3682            cross_axis_offset: self.cross_axis_offset(cross_axis_start, is_edge),
3683            main_axis_extent: Self::child_height(),
3684            cross_axis_extent: if is_edge {
3685                self.edge_child_width
3686            } else {
3687                self.day_child_width
3688            },
3689        }
3690    }
3691
3692    fn compute_max_scroll_offset(&self, child_count: i32) -> f64 {
3693        debug_assert!(child_count >= 0);
3694        let main_axis_count = ((child_count - 1) / self.cross_axis_count) + 1;
3695        let main_axis_spacing = Self::row_height() - Self::child_height();
3696        Self::row_height() * f64::from(main_axis_count) - main_axis_spacing
3697    }
3698}
3699
3700/// Dart's `_MonthItem`.
3701#[derive(Clone)]
3702struct MonthItem {
3703    selected_date_start: Option<DateTime>,
3704    selected_date_end: Option<DateTime>,
3705    current_date: DateTime,
3706    on_changed: ValueChanged<DateTime>,
3707    first_date: DateTime,
3708    last_date: DateTime,
3709    displayed_month: DateTime,
3710    selectable_day_predicate: Option<SelectableDayForRangePredicate>,
3711    calendar_delegate: Rc<dyn CalendarDelegate>,
3712}
3713
3714impl fmt::Debug for MonthItem {
3715    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3716        f.debug_struct("MonthItem")
3717            .field("displayed_month", &self.displayed_month)
3718            .finish_non_exhaustive()
3719    }
3720}
3721
3722impl StatefulWidget for MonthItem {
3723    type State = MonthItemState;
3724
3725    fn create_state(&self) -> MonthItemState {
3726        debug_assert!(!self.first_date.is_after(&self.last_date));
3727        debug_assert!(
3728            self.selected_date_start
3729                .zip(self.selected_date_end)
3730                .is_none_or(|(start, end)| !start.is_after(&end))
3731        );
3732        MonthItemState {
3733            state: StateData::new(),
3734            day_focus_nodes: Vec::new(),
3735        }
3736    }
3737}
3738
3739struct MonthItemState {
3740    state: StateData<MonthItem>,
3741    /// Created in `init_state`, because a state is created without the [`App`].
3742    day_focus_nodes: Vec<Ref<FocusNode>>,
3743}
3744
3745impl MonthItemState {
3746    fn highlight_color(self: Handle<Self>, app: &mut App, context: BuildContext) -> Color {
3747        DatePickerTheme::of(app, context)
3748            .range_selection_background_color
3749            .or_else(|| {
3750                DatePickerTheme::defaults(app, context).range_selection_background_color(app)
3751            })
3752            .expect("the defaults give a range selection background color")
3753    }
3754
3755    fn day_focus_changed(self: Handle<Self>, app: &mut App, focused: bool) {
3756        if !focused {
3757            return;
3758        }
3759        let context = self.context(app);
3760        let Some((_, Some(focus_direction))) = FocusedDate::maybe_of(app, context) else {
3761            return;
3762        };
3763        let policy = match focus_direction {
3764            TraversalDirection::Up | TraversalDirection::Left => {
3765                ScrollPositionAlignmentPolicy::KeepVisibleAtStart
3766            }
3767            TraversalDirection::Right | TraversalDirection::Down => {
3768                ScrollPositionAlignmentPolicy::KeepVisibleAtEnd
3769            }
3770        };
3771        let primary_focus = waft_widgets::FocusManager::instance(app).primary_focus(app);
3772        if let Some(primary_focus_context) = primary_focus.and_then(|node| node.context(app)) {
3773            Scrollable::ensure_visible(
3774                app,
3775                primary_focus_context,
3776                0.0,
3777                MONTH_SCROLL_DURATION,
3778                Curves::linear(),
3779                policy,
3780            );
3781        }
3782    }
3783
3784    fn build_day_item(
3785        self: Handle<Self>,
3786        app: &mut App,
3787        context: BuildContext,
3788        day_to_build: DateTime,
3789    ) -> WidgetRef {
3790        let widget = self.widget(app).clone();
3791        let day = day_to_build.day(app);
3792        let is_disabled = day_to_build.is_after(&widget.last_date)
3793            || day_to_build.is_before(&widget.first_date)
3794            || widget
3795                .selectable_day_predicate
3796                .as_ref()
3797                .is_some_and(|predicate| {
3798                    !predicate(
3799                        app,
3800                        day_to_build,
3801                        widget.selected_date_start,
3802                        widget.selected_date_end,
3803                    )
3804                });
3805        let is_range_selected =
3806            widget.selected_date_start.is_some() && widget.selected_date_end.is_some();
3807        let is_selected_day_start = widget
3808            .selected_date_start
3809            .is_some_and(|start| day_to_build.is_at_same_moment_as(&start));
3810        let is_selected_day_end = widget
3811            .selected_date_end
3812            .is_some_and(|end| day_to_build.is_at_same_moment_as(&end));
3813        let is_in_range = match (widget.selected_date_start, widget.selected_date_end) {
3814            (Some(start), Some(end)) => {
3815                day_to_build.is_after(&start) && day_to_build.is_before(&end)
3816            }
3817            _ => false,
3818        };
3819        let is_one_day_range =
3820            is_range_selected && widget.selected_date_start == widget.selected_date_end;
3821        let is_today = widget.calendar_delegate.is_same_day(
3822            app,
3823            Some(&widget.current_date),
3824            Some(&day_to_build),
3825        );
3826        let highlight_color = self.highlight_color(app, context);
3827        let focus_node = app.get(self).day_focus_nodes[(day - 1) as usize].clone();
3828
3829        DayItem {
3830            calendar_delegate: Rc::clone(&widget.calendar_delegate),
3831            day: day_to_build,
3832            focus_node,
3833            on_changed: Rc::clone(&widget.on_changed),
3834            on_focus_change: Rc::new(move |app, focused| self.day_focus_changed(app, focused)),
3835            highlight_color,
3836            is_disabled,
3837            is_range_selected,
3838            is_selected_day_start,
3839            is_selected_day_end,
3840            is_in_range,
3841            is_one_day_range,
3842            is_today,
3843        }
3844        .into_widget()
3845    }
3846
3847    fn build_edge_box(
3848        self: Handle<Self>,
3849        app: &mut App,
3850        context: BuildContext,
3851        is_highlighted: bool,
3852    ) -> WidgetRef {
3853        let empty = LimitedBox::new()
3854            .max_width(0.0)
3855            .max_height(0.0)
3856            .child(SizedBox::expand())
3857            .into_widget();
3858        if is_highlighted {
3859            ColoredBox::new(self.highlight_color(app, context))
3860                .child(empty)
3861                .into_widget()
3862        } else {
3863            empty
3864        }
3865    }
3866}
3867
3868impl fmt::Debug for MonthItemState {
3869    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3870        f.write_str("MonthItemState")
3871    }
3872}
3873
3874impl State for MonthItemState {
3875    type Widget = MonthItem;
3876    waft_widgets::state_accessors!();
3877
3878    fn init_state(self: Handle<Self>, app: &mut App) {
3879        let widget = self.widget(app).clone();
3880        let days_in_month = widget.calendar_delegate.get_days_in_month(
3881            widget.displayed_month.year(app),
3882            widget.displayed_month.month(app),
3883        );
3884        let nodes: Vec<Ref<FocusNode>> = (0..days_in_month)
3885            .map(|index| {
3886                let node = FocusNode::new(app);
3887                node.handle().set_skip_traversal(app, true);
3888                node.handle()
3889                    .set_debug_label(app, Some(format!("Day {}", index + 1)));
3890                node
3891            })
3892            .collect();
3893        app.get_mut(self).day_focus_nodes = nodes;
3894    }
3895
3896    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
3897        // Check to see if the focused date is in this month, if so focus it.
3898        let context = self.context(app);
3899        let focused_date = FocusedDate::maybe_of(app, context).and_then(|(date, _)| date);
3900        let widget = self.widget(app).clone();
3901        if let Some(focused_date) = focused_date
3902            && widget.calendar_delegate.is_same_month(
3903                app,
3904                Some(&widget.displayed_month),
3905                Some(&focused_date),
3906            )
3907        {
3908            let node = app.get(self).day_focus_nodes[(focused_date.day(app) - 1) as usize].clone();
3909            node.handle().request_focus(app, None);
3910        }
3911    }
3912
3913    fn dispose(self: Handle<Self>, app: &mut App) {
3914        for node in app.get(self).day_focus_nodes.clone() {
3915            node.handle().dispose(app);
3916        }
3917    }
3918
3919    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
3920        let theme_data = Theme::of(app, context);
3921        let text_theme = theme_data.text_theme.clone();
3922        let localizations = <dyn MaterialLocalizations>::of(app, context);
3923        let widget = self.widget(app).clone();
3924        let delegate = Rc::clone(&widget.calendar_delegate);
3925        let year = widget.displayed_month.year(app);
3926        let month = widget.displayed_month.month(app);
3927        let days_in_month = delegate.get_days_in_month(year, month);
3928        let day_offset = delegate.first_day_offset(app, year, month, &*localizations);
3929        let weeks = ((days_in_month + day_offset) as f64 / f64::from(DateTime::DAYS_PER_WEEK))
3930            .ceil() as i32;
3931        let grid_height = f64::from(weeks) * MONTH_ITEM_ROW_HEIGHT
3932            + f64::from(weeks - 1) * MONTH_ITEM_SPACE_BETWEEN_ROWS;
3933        let empty = || {
3934            LimitedBox::new()
3935                .max_width(0.0)
3936                .max_height(0.0)
3937                .child(SizedBox::expand())
3938                .into_widget()
3939        };
3940        let mut day_items: Vec<WidgetRef> = Vec::new();
3941
3942        // 1-based day of month, e.g. 1-31 for January, and 1-29 for February on a leap year.
3943        for day in (1 - day_offset)..=days_in_month {
3944            if day < 1 {
3945                day_items.push(empty());
3946            } else {
3947                let day_to_build = delegate.get_day(app, year, month, day);
3948                day_items.push(self.build_day_item(app, context, day_to_build));
3949            }
3950        }
3951
3952        // Add the leading/trailing edge containers to each week in order to correctly extend
3953        // the range highlight.
3954        let mut padded_day_items: Vec<WidgetRef> = Vec::new();
3955        for i in 0..weeks {
3956            let start = (i * DateTime::DAYS_PER_WEEK) as usize;
3957            let end = ((start as i32 + DateTime::DAYS_PER_WEEK) as usize).min(day_items.len());
3958            let mut week_list: Vec<WidgetRef> = day_items[start..end].to_vec();
3959
3960            let date_after_leading_padding =
3961                delegate.get_day(app, year, month, start as i32 - day_offset + 1);
3962            // Only color the edge container if it is after the start date and on/before the
3963            // end date.
3964            let is_leading_in_range = !(day_offset > 0 && i == 0)
3965                && match (widget.selected_date_start, widget.selected_date_end) {
3966                    (Some(range_start), Some(range_end)) => {
3967                        date_after_leading_padding.is_after(&range_start)
3968                            && !date_after_leading_padding.is_after(&range_end)
3969                    }
3970                    _ => false,
3971                };
3972            week_list.insert(0, self.build_edge_box(app, context, is_leading_in_range));
3973
3974            // Only add a trailing edge container if it is for a full week and not a partial
3975            // week.
3976            if end < day_items.len()
3977                || (end == day_items.len()
3978                    && day_items
3979                        .len()
3980                        .is_multiple_of(DateTime::DAYS_PER_WEEK as usize))
3981            {
3982                let date_before_trailing_padding =
3983                    delegate.get_day(app, year, month, end as i32 - day_offset);
3984                // Only color the edge container if it is on/after the start date and before
3985                // the end date.
3986                let is_trailing_in_range =
3987                    match (widget.selected_date_start, widget.selected_date_end) {
3988                        (Some(range_start), Some(range_end)) => {
3989                            !date_before_trailing_padding.is_before(&range_start)
3990                                && date_before_trailing_padding.is_before(&range_end)
3991                        }
3992                        _ => false,
3993                    };
3994                week_list.push(self.build_edge_box(app, context, is_trailing_in_range));
3995            }
3996
3997            padded_day_items.extend(week_list);
3998        }
3999
4000        let max_width = if MediaQuery::orientation_of(app, context) == Orientation::Landscape {
4001            MAX_CALENDAR_WIDTH_LANDSCAPE
4002        } else {
4003            MAX_CALENDAR_WIDTH_PORTRAIT
4004        };
4005        let month_style = apply_color(
4006            text_theme.body_medium.clone(),
4007            Some(theme_data.color_scheme.on_surface()),
4008        )
4009        .expect("the text theme has bodyMedium");
4010        Column::new()
4011            .children([
4012                ConstrainedBox::new(BoxConstraints {
4013                    max_width,
4014                    min_height: MONTH_ITEM_HEADER_HEIGHT,
4015                    max_height: MONTH_ITEM_HEADER_HEIGHT,
4016                    ..BoxConstraints::new()
4017                })
4018                .child(
4019                    Padding::new(EdgeInsets::symmetric(0.0, 16.0)).child(
4020                        Align::new()
4021                            .alignment(AlignmentGeometry::from(AlignmentDirectional::CENTER_START))
4022                            .child(
4023                                ExcludeSemantics::new().child(
4024                                    Text::new(delegate.format_month_year(
4025                                        app,
4026                                        &widget.displayed_month,
4027                                        &*localizations,
4028                                    ))
4029                                    .style(month_style),
4030                                ),
4031                            ),
4032                    ),
4033                )
4034                .into_widget(),
4035                ConstrainedBox::new(BoxConstraints {
4036                    max_width,
4037                    max_height: grid_height,
4038                    ..BoxConstraints::new()
4039                })
4040                .child(
4041                    GridView::custom(
4042                        Rc::new(MonthItemGridDelegate),
4043                        SliverChildListDelegate::new(padded_day_items)
4044                            .add_repaint_boundaries(false)
4045                            .into_delegate(),
4046                    )
4047                    .physics(Rc::new(waft_widgets::NeverScrollableScrollPhysics::new())),
4048                )
4049                .into_widget(),
4050                SizedBox::new()
4051                    .height(MONTH_ITEM_FOOTER_HEIGHT)
4052                    .into_widget(),
4053            ])
4054            .into_widget()
4055    }
4056}
4057
4058/// Dart's `_DayItem`.
4059#[derive(Clone)]
4060struct DayItem {
4061    day: DateTime,
4062    focus_node: Ref<FocusNode>,
4063    on_changed: ValueChanged<DateTime>,
4064    on_focus_change: ValueChanged<bool>,
4065    highlight_color: Color,
4066    is_disabled: bool,
4067    is_range_selected: bool,
4068    is_selected_day_start: bool,
4069    is_selected_day_end: bool,
4070    is_in_range: bool,
4071    is_one_day_range: bool,
4072    is_today: bool,
4073    calendar_delegate: Rc<dyn CalendarDelegate>,
4074}
4075
4076impl fmt::Debug for DayItem {
4077    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4078        f.debug_struct("DayItem")
4079            .field("day", &self.day)
4080            .finish_non_exhaustive()
4081    }
4082}
4083
4084impl StatefulWidget for DayItem {
4085    type State = DayItemState;
4086
4087    fn create_state(&self) -> DayItemState {
4088        DayItemState {
4089            state: StateData::new(),
4090            states_controller: None,
4091        }
4092    }
4093}
4094
4095struct DayItemState {
4096    state: StateData<DayItem>,
4097    /// Created in `init_state`, because a state is created without the [`App`].
4098    states_controller: Option<Ref<WidgetStatesController>>,
4099}
4100
4101impl DayItemState {
4102    fn states_controller(self: Handle<Self>, app: &App) -> Ref<WidgetStatesController> {
4103        app.get(self)
4104            .states_controller
4105            .clone()
4106            .expect("created in init_state")
4107    }
4108}
4109
4110impl fmt::Debug for DayItemState {
4111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4112        f.write_str("DayItemState")
4113    }
4114}
4115
4116impl State for DayItemState {
4117    type Widget = DayItem;
4118    waft_widgets::state_accessors!();
4119
4120    fn init_state(self: Handle<Self>, app: &mut App) {
4121        let controller = WidgetStatesController::new(app, None);
4122        app.get_mut(self).states_controller = Some(controller);
4123    }
4124
4125    fn dispose(self: Handle<Self>, app: &mut App) {
4126        self.states_controller(app).handle().dispose(app);
4127    }
4128
4129    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
4130        let theme = Theme::of(app, context);
4131        let color_scheme = theme.color_scheme.clone();
4132        let text_theme = theme.text_theme.clone();
4133        let localizations = <dyn MaterialLocalizations>::of(app, context);
4134        let date_picker_theme = DatePickerTheme::of(app, context);
4135        let defaults = DatePickerTheme::defaults(app, context);
4136        let text_direction = Directionality::of(app, context);
4137        let widget = self.widget(app).clone();
4138        let highlight_color = widget.highlight_color;
4139
4140        let mut decoration: Option<ShapeDecoration> = None;
4141        let mut item_style = text_theme.body_medium.clone();
4142
4143        let mut states = WidgetStates::new();
4144        if widget.is_disabled {
4145            states.insert(waft_widgets::WidgetState::Disabled);
4146        }
4147        if widget.is_selected_day_start || widget.is_selected_day_end {
4148            states.insert(waft_widgets::WidgetState::Selected);
4149        }
4150        let states_controller = self.states_controller(app);
4151        states_controller.handle().set_value(app, states.clone());
4152
4153        let resolve_color =
4154            |property: Option<waft_widgets::WidgetStatePropertyRef<Option<Color>>>,
4155             default: Option<waft_widgets::WidgetStatePropertyRef<Option<Color>>>,
4156             states: &WidgetStates| {
4157                property
4158                    .and_then(|property| property.resolve(states))
4159                    .or_else(|| default.and_then(|property| property.resolve(states)))
4160            };
4161        let day_foreground_color = resolve_color(
4162            date_picker_theme.day_foreground_color.clone(),
4163            defaults.day_foreground_color(app),
4164            &states,
4165        );
4166        let day_background_color = resolve_color(
4167            date_picker_theme.day_background_color.clone(),
4168            defaults.day_background_color(app),
4169            &states,
4170        );
4171        let is_in_range = widget.is_in_range;
4172        let (theme_range_overlay, defaults_range_overlay) = (
4173            date_picker_theme.range_selection_overlay_color.clone(),
4174            defaults.range_selection_overlay_color(app),
4175        );
4176        let (theme_day_overlay, defaults_day_overlay) = (
4177            date_picker_theme.day_overlay_color.clone(),
4178            defaults.day_overlay_color(app),
4179        );
4180        let day_overlay_color =
4181            <dyn WidgetStateProperty<Option<Color>>>::resolve_with(move |states: &WidgetStates| {
4182                let (theme_property, default_property) = if is_in_range {
4183                    (theme_range_overlay.clone(), defaults_range_overlay.clone())
4184                } else {
4185                    (theme_day_overlay.clone(), defaults_day_overlay.clone())
4186                };
4187                theme_property
4188                    .and_then(|property| property.resolve(states))
4189                    .or_else(|| default_property.and_then(|property| property.resolve(states)))
4190            });
4191        let day_shape: OutlinedBorderRef = date_picker_theme
4192            .day_shape
4193            .clone()
4194            .and_then(|property| property.resolve(&states))
4195            .or_else(|| {
4196                defaults
4197                    .day_shape(app)
4198                    .and_then(|property| property.resolve(&states))
4199            })
4200            .unwrap_or_else(|| OutlinedBorderRef::new(CircleBorder::default()));
4201
4202        let mut highlight_painter: Option<HighlightPainter> = None;
4203        if widget.is_selected_day_start || widget.is_selected_day_end {
4204            // The selected start and end dates get a custom shaped background highlight, and a
4205            // contrasting text color.
4206            item_style = apply_color(item_style, day_foreground_color);
4207            let mut shape_decoration =
4208                ShapeDecoration::new(ShapeBorderRef::from(day_shape.clone()));
4209            if let Some(color) = day_background_color {
4210                shape_decoration = shape_decoration.color(color);
4211            }
4212            decoration = Some(shape_decoration);
4213
4214            if widget.is_range_selected && !widget.is_one_day_range {
4215                let style = if widget.is_selected_day_start {
4216                    HighlightPainterStyle::HighlightTrailing
4217                } else {
4218                    HighlightPainterStyle::HighlightLeading
4219                };
4220                highlight_painter = Some(HighlightPainter {
4221                    color: highlight_color,
4222                    style,
4223                    text_direction: Some(text_direction),
4224                });
4225            }
4226        } else if widget.is_in_range {
4227            // The days within the range get a light background highlight.
4228            highlight_painter = Some(HighlightPainter {
4229                color: highlight_color,
4230                style: HighlightPainterStyle::HighlightAll,
4231                text_direction: Some(text_direction),
4232            });
4233            if widget.is_disabled {
4234                #[allow(deprecated)]
4235                let disabled = color_scheme.on_surface().with_opacity(0.38);
4236                item_style = apply_color(item_style, Some(disabled));
4237            }
4238        } else if widget.is_disabled {
4239            #[allow(deprecated)]
4240            let disabled = color_scheme.on_surface().with_opacity(0.38);
4241            item_style = apply_color(item_style, Some(disabled));
4242        } else if widget.is_today {
4243            // The current day gets a different text color and a custom shape border.
4244            item_style = apply_color(item_style, Some(color_scheme.primary()));
4245            let today_side: BorderSide = date_picker_theme
4246                .today_border
4247                .or_else(|| defaults.today_border(app))
4248                .expect("the defaults give a today border")
4249                .copy_with(Some(color_scheme.primary()), None, None, None);
4250            decoration = Some(ShapeDecoration::new(ShapeBorderRef::from(
4251                day_shape.copy_with(Some(today_side)),
4252            )));
4253        }
4254
4255        let day_text = localizations.format_decimal(i64::from(widget.day.day(app)));
4256
4257        // We want the day of month to be spoken first irrespective of the locale-specific
4258        // preferences or TextDirection. This is because an accessibility user is more likely
4259        // to be interested in the day of month before the rest of the date, as they are
4260        // looking for the day of month. To do that we prepend day of month to the formatted
4261        // full date.
4262        let semantic_label_suffix = if widget.is_today {
4263            format!(", {}", localizations.current_date_label())
4264        } else {
4265            String::new()
4266        };
4267        let mut semantic_label = format!(
4268            "{day_text}, {}{semantic_label_suffix}",
4269            widget
4270                .calendar_delegate
4271                .format_full_date(app, &widget.day, &*localizations)
4272        );
4273        if widget.is_selected_day_start {
4274            semantic_label = localizations.date_range_start_date_semantic_label(&semantic_label);
4275        } else if widget.is_selected_day_end {
4276            semantic_label = localizations.date_range_end_date_semantic_label(&semantic_label);
4277        }
4278
4279        let mut text = Text::new(day_text);
4280        if let Some(item_style) = item_style {
4281            text = text.style(item_style);
4282        }
4283        let mut container = Container::new()
4284            .alignment(AlignmentGeometry::from(Alignment::CENTER))
4285            .child(
4286                Semantics::new()
4287                    .label(semantic_label)
4288                    .selected(widget.is_selected_day_start || widget.is_selected_day_end)
4289                    .child(ExcludeSemantics::new().child(text)),
4290            );
4291        if let Some(decoration) = decoration {
4292            container = container.decoration(decoration);
4293        }
4294        let mut day_widget = container.into_widget();
4295
4296        if let Some(highlight_painter) = highlight_painter {
4297            day_widget = CustomPaint::new()
4298                .painter(highlight_painter)
4299                .child(day_widget)
4300                .into_widget();
4301        }
4302
4303        if !widget.is_disabled {
4304            let (on_changed, day) = (Rc::clone(&widget.on_changed), widget.day);
4305            let on_focus_change = Rc::clone(&widget.on_focus_change);
4306            day_widget = InkResponse::new()
4307                .focus_node(widget.focus_node.clone().into_erased())
4308                .on_tap(Listener::new(move |app: &mut App| on_changed(app, day)))
4309                .custom_border(day_shape)
4310                .contained_ink_well(true)
4311                .states_controller(states_controller)
4312                .overlay_color(day_overlay_color)
4313                .on_focus_change(on_focus_change)
4314                .child(day_widget)
4315                .into_widget();
4316        }
4317
4318        day_widget
4319    }
4320}
4321
4322/// Dart's `_HighlightPainterStyle`.
4323#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4324enum HighlightPainterStyle {
4325    /// Paint nothing.
4326    None,
4327
4328    /// Paint a rectangle that occupies the leading half of the space.
4329    HighlightLeading,
4330
4331    /// Paint a rectangle that occupies the trailing half of the space.
4332    HighlightTrailing,
4333
4334    /// Paint a rectangle that occupies all available space.
4335    HighlightAll,
4336}
4337
4338/// Dart's `_HighlightPainter`.
4339#[derive(Clone, Copy, Debug)]
4340struct HighlightPainter {
4341    color: Color,
4342    style: HighlightPainterStyle,
4343    text_direction: Option<TextDirection>,
4344}
4345
4346impl CustomPainter for HighlightPainter {
4347    fn paint(&self, _app: &mut App, canvas: &mut Canvas, size: Size) {
4348        if self.style == HighlightPainterStyle::None {
4349            return;
4350        }
4351
4352        let paint = Paint::from_color(self.color.into());
4353
4354        let rtl = match self.text_direction {
4355            Some(TextDirection::Rtl) | None => true,
4356            Some(TextDirection::Ltr) => false,
4357        };
4358
4359        match self.style {
4360            HighlightPainterStyle::HighlightLeading if rtl => {
4361                canvas.draw_rect(
4362                    Rect::from_ltwh(size.width() / 2.0, 0.0, size.width() / 2.0, size.height()),
4363                    &paint,
4364                );
4365            }
4366            HighlightPainterStyle::HighlightTrailing if !rtl => {
4367                canvas.draw_rect(
4368                    Rect::from_ltwh(size.width() / 2.0, 0.0, size.width() / 2.0, size.height()),
4369                    &paint,
4370                );
4371            }
4372            HighlightPainterStyle::HighlightLeading | HighlightPainterStyle::HighlightTrailing => {
4373                canvas.draw_rect(
4374                    Rect::from_ltwh(0.0, 0.0, size.width() / 2.0, size.height()),
4375                    &paint,
4376                );
4377            }
4378            HighlightPainterStyle::HighlightAll => {
4379                canvas.draw_rect(
4380                    Rect::from_ltwh(0.0, 0.0, size.width(), size.height()),
4381                    &paint,
4382                );
4383            }
4384            HighlightPainterStyle::None => {}
4385        }
4386    }
4387
4388    fn should_repaint(&self, _app: &App, _old_delegate: &dyn CustomPainter) -> bool {
4389        false
4390    }
4391
4392    fn as_any(&self) -> &dyn std::any::Any {
4393        self
4394    }
4395}
4396
4397/// Dart's `_InputDateRangePickerDialog`.
4398#[derive(Clone)]
4399struct InputDateRangePickerDialog {
4400    calendar_delegate: Rc<dyn CalendarDelegate>,
4401    selected_start_date: Option<DateTime>,
4402    selected_end_date: Option<DateTime>,
4403    current_date: DateTime,
4404    picker: WidgetRef,
4405    on_confirm: Listener,
4406    on_cancel: Listener,
4407    entry_mode_button: Option<WidgetRef>,
4408    confirm_text: String,
4409    cancel_text: String,
4410    help_text: String,
4411}
4412
4413impl fmt::Debug for InputDateRangePickerDialog {
4414    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4415        f.debug_struct("InputDateRangePickerDialog")
4416            .field("selected_start_date", &self.selected_start_date)
4417            .field("selected_end_date", &self.selected_end_date)
4418            .finish_non_exhaustive()
4419    }
4420}
4421
4422impl InputDateRangePickerDialog {
4423    fn format_date_range(
4424        &self,
4425        app: &mut App,
4426        context: BuildContext,
4427        start: Option<&DateTime>,
4428        end: Option<&DateTime>,
4429        now: &DateTime,
4430    ) -> String {
4431        let localizations = <dyn MaterialLocalizations>::of(app, context);
4432        let start_text =
4433            format_range_start_date(app, &*localizations, &*self.calendar_delegate, start, end);
4434        let end_text = format_range_end_date(
4435            app,
4436            &*localizations,
4437            &*self.calendar_delegate,
4438            start,
4439            end,
4440            now,
4441        );
4442        if start.is_none() || end.is_none() {
4443            return localizations.unspecified_date_range();
4444        }
4445        match Directionality::of(app, context) {
4446            TextDirection::Rtl => format!("{end_text} \u{2013} {start_text}"),
4447            TextDirection::Ltr => format!("{start_text} \u{2013} {end_text}"),
4448        }
4449    }
4450}
4451
4452impl StatelessWidget for InputDateRangePickerDialog {
4453    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
4454        let theme = Theme::of(app, context);
4455        let use_material3 = theme.use_material3;
4456        let localizations = <dyn MaterialLocalizations>::of(app, context);
4457        let orientation = MediaQuery::orientation_of(app, context);
4458        let date_picker_theme = DatePickerTheme::of(app, context);
4459        let defaults = DatePickerTheme::defaults(app, context);
4460
4461        // There's no M3 spec for a landscape layout input (not calendar) date range picker. To
4462        // ensure that the date range displayed in the input date range picker's header fits in
4463        // landscape mode, we override the M3 default here.
4464        let mut headline_style: Option<TextStyle> = if orientation == Orientation::Portrait {
4465            date_picker_theme
4466                .header_headline_style
4467                .clone()
4468                .or_else(|| defaults.header_headline_style(app))
4469        } else {
4470            theme.text_theme.headline_small.clone()
4471        };
4472        let header_foreground_color = date_picker_theme
4473            .header_foreground_color
4474            .or_else(|| defaults.header_foreground_color(app));
4475        headline_style = headline_style.map(|style| match header_foreground_color {
4476            Some(color) => style.copy_with().color(color),
4477            None => style,
4478        });
4479
4480        let date_text = self.format_date_range(
4481            app,
4482            context,
4483            self.selected_start_date.as_ref(),
4484            self.selected_end_date.as_ref(),
4485            &self.current_date,
4486        );
4487        let semantic_date_text = match (self.selected_start_date, self.selected_end_date) {
4488            (Some(start), Some(end)) => format!(
4489                "{} \u{2013} {}",
4490                self.calendar_delegate
4491                    .format_medium_date(app, &start, &*localizations),
4492                self.calendar_delegate
4493                    .format_medium_date(app, &end, &*localizations)
4494            ),
4495            _ => String::new(),
4496        };
4497
4498        let header = DatePickerHeader {
4499            help_text: self.help_text.clone(),
4500            title_text: date_text,
4501            title_semantics_label: Some(semantic_date_text),
4502            title_style: headline_style,
4503            orientation,
4504            is_short: orientation == Orientation::Landscape,
4505            entry_mode_button: self.entry_mode_button.clone(),
4506        }
4507        .into_widget();
4508
4509        let actions = ConstrainedBox::new(BoxConstraints {
4510            min_height: 52.0,
4511            ..BoxConstraints::new()
4512        })
4513        .child(
4514            Padding::new(EdgeInsets::symmetric(0.0, 8.0)).child(
4515                Align::new()
4516                    .alignment(AlignmentGeometry::from(AlignmentDirectional::CENTER_END))
4517                    .child(OverflowBar::new().spacing(8.0).children(vec![
4518                        TextButton::new(
4519                            Some(self.on_cancel.clone()),
4520                            Some(Text::new(self.cancel_text.clone())),
4521                        )
4522                        .into_widget(),
4523                        TextButton::new(
4524                            Some(self.on_confirm.clone()),
4525                            Some(Text::new(self.confirm_text.clone())),
4526                        )
4527                        .into_widget(),
4528                    ])),
4529            ),
4530        )
4531        .into_widget();
4532
4533        let text_scale_factor = MediaQuery::text_scaler_of(app, context)
4534            .clamp(0.0, MAX_RANGE_TEXT_SCALE_FACTOR)
4535            .scale(FONT_SIZE_TO_SCALE)
4536            / FONT_SIZE_TO_SCALE;
4537        let dialog_size = (if use_material3 {
4538            INPUT_PORTRAIT_DIALOG_SIZE_M3
4539        } else {
4540            INPUT_PORTRAIT_DIALOG_SIZE_M2
4541        }) * text_scale_factor;
4542        let picker = self.picker.clone();
4543        match orientation {
4544            Orientation::Portrait => LayoutBuilder::new(move |_app, _context, constraints| {
4545                let portrait_dialog_size = if use_material3 {
4546                    INPUT_PORTRAIT_DIALOG_SIZE_M3
4547                } else {
4548                    INPUT_PORTRAIT_DIALOG_SIZE_M2
4549                };
4550                // Make sure the portrait dialog can fit the contents comfortably when resized
4551                // from the landscape dialog.
4552                let is_fully_portrait = constraints.constraints().max_height
4553                    >= dialog_size.height().min(portrait_dialog_size.height());
4554                let mut children = Vec::new();
4555                // When the portrait dialog does not fit vertically, hide the header.
4556                if is_fully_portrait {
4557                    children.push(header.clone());
4558                }
4559                children.push(Expanded::new(picker.clone()).into_widget());
4560                children.push(actions.clone());
4561                waft_widgets::Column::new()
4562                    .main_axis_size(MainAxisSize::Min)
4563                    .cross_axis_alignment(CrossAxisAlignment::Stretch)
4564                    .children(children)
4565                    .into_widget()
4566            })
4567            .into_widget(),
4568            Orientation::Landscape => Row::new()
4569                .main_axis_size(MainAxisSize::Min)
4570                .cross_axis_alignment(CrossAxisAlignment::Stretch)
4571                .children([
4572                    header,
4573                    Flexible::new(
4574                        waft_widgets::Column::new()
4575                            .main_axis_size(MainAxisSize::Min)
4576                            .cross_axis_alignment(CrossAxisAlignment::Stretch)
4577                            .children([Expanded::new(picker).into_widget(), actions]),
4578                    )
4579                    .into_widget(),
4580                ])
4581                .into_widget(),
4582        }
4583    }
4584}
4585
4586/// Dart's `_InputDateRangePicker`.
4587#[derive(Clone)]
4588struct InputDateRangePicker {
4589    key: Option<waft_widgets::KeyRef>,
4590    calendar_delegate: Rc<dyn CalendarDelegate>,
4591    initial_start_date: Option<DateTime>,
4592    initial_end_date: Option<DateTime>,
4593    first_date: DateTime,
4594    last_date: DateTime,
4595    selectable_day_predicate: Option<SelectableDayForRangePredicate>,
4596    on_start_date_changed: Option<ValueChanged<Option<DateTime>>>,
4597    on_end_date_changed: Option<ValueChanged<Option<DateTime>>>,
4598    autofocus: bool,
4599    autovalidate: bool,
4600    #[expect(dead_code, reason = "Dart's field is declared and never read either")]
4601    help_text: Option<String>,
4602    error_invalid_range_text: Option<String>,
4603    error_format_text: Option<String>,
4604    error_invalid_text: Option<String>,
4605    field_start_hint_text: Option<String>,
4606    field_end_hint_text: Option<String>,
4607    field_start_label_text: Option<String>,
4608    field_end_label_text: Option<String>,
4609    keyboard_type: TextInputType,
4610}
4611
4612impl fmt::Debug for InputDateRangePicker {
4613    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4614        f.debug_struct("InputDateRangePicker")
4615            .field("initial_start_date", &self.initial_start_date)
4616            .field("initial_end_date", &self.initial_end_date)
4617            .finish_non_exhaustive()
4618    }
4619}
4620
4621impl StatefulWidget for InputDateRangePicker {
4622    type State = InputDateRangePickerState;
4623
4624    fn key(&self) -> Option<&waft_widgets::KeyRef> {
4625        self.key.as_ref()
4626    }
4627
4628    fn create_state(&self) -> InputDateRangePickerState {
4629        InputDateRangePickerState {
4630            state: StateData::new(),
4631            start_controller: None,
4632            end_controller: None,
4633            // Dart's initializers, which `init_state` runs with the `App`.
4634            start_date: None,
4635            end_date: None,
4636            start_error_text: None,
4637            end_error_text: None,
4638            auto_selected: false,
4639        }
4640    }
4641}
4642
4643/// Dart's `_InputDateRangePickerState`.
4644struct InputDateRangePickerState {
4645    state: StateData<InputDateRangePicker>,
4646    /// Created in `init_state`, because a state is created without the [`App`].
4647    start_controller: Option<Ref<TextEditingController>>,
4648    end_controller: Option<Ref<TextEditingController>>,
4649    start_date: Option<DateTime>,
4650    end_date: Option<DateTime>,
4651    start_error_text: Option<String>,
4652    end_error_text: Option<String>,
4653    auto_selected: bool,
4654}
4655
4656impl InputDateRangePickerState {
4657    fn start_controller(self: Handle<Self>, app: &App) -> Ref<TextEditingController> {
4658        app.get(self)
4659            .start_controller
4660            .clone()
4661            .expect("created in init_state")
4662    }
4663
4664    fn end_controller(self: Handle<Self>, app: &App) -> Ref<TextEditingController> {
4665        app.get(self)
4666            .end_controller
4667            .clone()
4668            .expect("created in init_state")
4669    }
4670
4671    /// Dart's `validate`.
4672    fn validate(self: Handle<Self>, app: &mut App) -> bool {
4673        let mut start_error = self.validate_date(app, app.get(self).start_date);
4674        let end_error = self.validate_date(app, app.get(self).end_date);
4675        if start_error.is_none() && end_error.is_none() {
4676            let state = app.get(self);
4677            if state
4678                .start_date
4679                .expect("a valid start date")
4680                .is_after(&state.end_date.expect("a valid end date"))
4681            {
4682                start_error = Some(
4683                    self.widget(app)
4684                        .error_invalid_range_text
4685                        .clone()
4686                        .unwrap_or_else(|| {
4687                            let context = self.context(app);
4688                            <dyn MaterialLocalizations>::of(app, context).invalid_date_range_label()
4689                        }),
4690                );
4691            }
4692        }
4693        self.set_state(app, |_| {});
4694        let valid = start_error.is_none() && end_error.is_none();
4695        let state = app.get_mut(self);
4696        state.start_error_text = start_error;
4697        state.end_error_text = end_error;
4698        valid
4699    }
4700
4701    fn parse_date(self: Handle<Self>, app: &mut App, text: &str) -> Option<DateTime> {
4702        let context = self.context(app);
4703        let localizations = <dyn MaterialLocalizations>::of(app, context);
4704        self.widget(app)
4705            .calendar_delegate
4706            .parse_compact_date(app, Some(text), &*localizations)
4707    }
4708
4709    fn validate_date(self: Handle<Self>, app: &mut App, date: Option<DateTime>) -> Option<String> {
4710        let context = self.context(app);
4711        match date {
4712            None => Some(
4713                self.widget(app)
4714                    .error_format_text
4715                    .clone()
4716                    .unwrap_or_else(|| {
4717                        <dyn MaterialLocalizations>::of(app, context).invalid_date_format_label()
4718                    }),
4719            ),
4720            Some(date) if !self.is_day_selectable(app, date) => Some(
4721                self.widget(app)
4722                    .error_invalid_text
4723                    .clone()
4724                    .unwrap_or_else(|| {
4725                        <dyn MaterialLocalizations>::of(app, context).date_out_of_range_label()
4726                    }),
4727            ),
4728            Some(_) => None,
4729        }
4730    }
4731
4732    fn is_day_selectable(self: Handle<Self>, app: &App, day: DateTime) -> bool {
4733        let widget = self.widget(app);
4734        if day.is_before(&widget.first_date) || day.is_after(&widget.last_date) {
4735            return false;
4736        }
4737        match &widget.selectable_day_predicate {
4738            None => true,
4739            Some(predicate) => {
4740                let state = app.get(self);
4741                predicate(app, day, state.start_date, state.end_date)
4742            }
4743        }
4744    }
4745
4746    fn update_controller(
4747        self: Handle<Self>,
4748        app: &mut App,
4749        controller: Ref<TextEditingController>,
4750        text: &str,
4751        select_text: bool,
4752    ) {
4753        let mut value = controller
4754            .handle()
4755            .value(app)
4756            .clone()
4757            .text(text.to_string());
4758        if select_text {
4759            value = value.selection(TextSelection::new(0, text.encode_utf16().count() as i32));
4760        }
4761        controller.handle().set_value(app, value);
4762    }
4763
4764    fn handle_start_changed(self: Handle<Self>, app: &mut App, text: String) {
4765        let date = self.parse_date(app, &text);
4766        self.set_state(app, |_| {});
4767        app.get_mut(self).start_date = date;
4768        if let Some(on_start_date_changed) = self.widget(app).on_start_date_changed.clone() {
4769            on_start_date_changed(app, date);
4770        }
4771        if self.widget(app).autovalidate {
4772            self.validate(app);
4773        }
4774    }
4775
4776    fn handle_end_changed(self: Handle<Self>, app: &mut App, text: String) {
4777        let date = self.parse_date(app, &text);
4778        self.set_state(app, |_| {});
4779        app.get_mut(self).end_date = date;
4780        if let Some(on_end_date_changed) = self.widget(app).on_end_date_changed.clone() {
4781            on_end_date_changed(app, date);
4782        }
4783        if self.widget(app).autovalidate {
4784            self.validate(app);
4785        }
4786    }
4787}
4788
4789impl fmt::Debug for InputDateRangePickerState {
4790    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4791        f.debug_struct("InputDateRangePickerState")
4792            .field("start_date", &self.start_date)
4793            .field("end_date", &self.end_date)
4794            .finish_non_exhaustive()
4795    }
4796}
4797
4798impl State for InputDateRangePickerState {
4799    type Widget = InputDateRangePicker;
4800    waft_widgets::state_accessors!();
4801
4802    fn init_state(self: Handle<Self>, app: &mut App) {
4803        let (start_date, end_date) = {
4804            let widget = self.widget(app);
4805            let day = |date: DateTime| widget.calendar_delegate.date_only(app, &date);
4806            (
4807                widget.initial_start_date.map(day),
4808                widget.initial_end_date.map(day),
4809            )
4810        };
4811        let start_controller = TextEditingController::new(app);
4812        let end_controller = TextEditingController::new(app);
4813        let state = app.get_mut(self);
4814        state.start_date = start_date;
4815        state.end_date = end_date;
4816        state.start_controller = Some(start_controller);
4817        state.end_controller = Some(end_controller);
4818    }
4819
4820    fn dispose(self: Handle<Self>, app: &mut App) {
4821        self.start_controller(app).handle().dispose(app);
4822        self.end_controller(app).handle().dispose(app);
4823    }
4824
4825    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
4826        let context = self.context(app);
4827        let localizations = <dyn MaterialLocalizations>::of(app, context);
4828        let (calendar_delegate, autofocus) = {
4829            let widget = self.widget(app);
4830            (Rc::clone(&widget.calendar_delegate), widget.autofocus)
4831        };
4832        if let Some(start_date) = app.get(self).start_date {
4833            let text = calendar_delegate.format_compact_date(app, &start_date, &*localizations);
4834            let select_text = autofocus && !app.get(self).auto_selected;
4835            let controller = self.start_controller(app);
4836            self.update_controller(app, controller, &text, select_text);
4837            app.get_mut(self).auto_selected = select_text;
4838        }
4839        if let Some(end_date) = app.get(self).end_date {
4840            let text = calendar_delegate.format_compact_date(app, &end_date, &*localizations);
4841            let controller = self.end_controller(app);
4842            self.update_controller(app, controller, &text, false);
4843        }
4844    }
4845
4846    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
4847        let theme = Theme::of(app, context);
4848        let use_material3 = theme.use_material3;
4849        let localizations = <dyn MaterialLocalizations>::of(app, context);
4850        let input_theme = InputDecorationTheme::of(app, context);
4851        let input_border = input_theme.border.clone().unwrap_or_else(|| {
4852            if use_material3 {
4853                InputBorderRef::new(OutlineInputBorder::new())
4854            } else {
4855                InputBorderRef::new(UnderlineInputBorder::new())
4856            }
4857        });
4858        let widget = self.widget(app).clone();
4859        let start_error_text = app.get(self).start_error_text.clone();
4860        let end_error_text = app.get(self).end_error_text.clone();
4861        let input_formatters = widget
4862            .calendar_delegate
4863            .keyboard_input_formatters(&*localizations);
4864
4865        let mut start_decoration = InputDecoration::new()
4866            .border(input_border.clone())
4867            .filled(input_theme.filled)
4868            .hint_text(
4869                widget
4870                    .field_start_hint_text
4871                    .clone()
4872                    .unwrap_or_else(|| widget.calendar_delegate.date_help_text(&*localizations)),
4873            )
4874            .label_text(
4875                widget
4876                    .field_start_label_text
4877                    .clone()
4878                    .unwrap_or_else(|| localizations.date_range_start_label()),
4879            );
4880        if let Some(error_text) = start_error_text {
4881            start_decoration = start_decoration.error_text(error_text);
4882        }
4883        let mut end_decoration = InputDecoration::new()
4884            .border(input_border)
4885            .filled(input_theme.filled)
4886            .hint_text(
4887                widget
4888                    .field_end_hint_text
4889                    .clone()
4890                    .unwrap_or_else(|| widget.calendar_delegate.date_help_text(&*localizations)),
4891            )
4892            .label_text(
4893                widget
4894                    .field_end_label_text
4895                    .clone()
4896                    .unwrap_or_else(|| localizations.date_range_end_label()),
4897            );
4898        if let Some(error_text) = end_error_text {
4899            end_decoration = end_decoration.error_text(error_text);
4900        }
4901
4902        let mut start_field = TextField::new()
4903            .controller(self.start_controller(app).erase())
4904            .decoration(Some(start_decoration))
4905            .keyboard_type(widget.keyboard_type)
4906            .on_changed(move |app, text| self.handle_start_changed(app, text))
4907            .autofocus(widget.autofocus);
4908        let mut end_field = TextField::new()
4909            .controller(self.end_controller(app).erase())
4910            .decoration(Some(end_decoration))
4911            .keyboard_type(widget.keyboard_type)
4912            .on_changed(move |app, text| self.handle_end_changed(app, text));
4913        if let Some(input_formatters) = input_formatters {
4914            start_field = start_field.input_formatters(input_formatters.clone());
4915            end_field = end_field.input_formatters(input_formatters);
4916        }
4917
4918        Row::new()
4919            .cross_axis_alignment(CrossAxisAlignment::Start)
4920            .children([
4921                Expanded::new(start_field).into_widget(),
4922                SizedBox::new().width(8.0).into_widget(),
4923                Expanded::new(end_field).into_widget(),
4924            ])
4925            .into_widget()
4926    }
4927}
4928
4929#[cfg(test)]
4930pub(crate) mod tests {
4931    //! date_picker_test.dart and date_range_picker_test.dart: the dialogs a user sees, picks a date
4932    //! or a range in and confirms or cancels.
4933
4934    use waft_widgets::testing::{
4935        TestPointer, WidgetTester, expect, find, finds_n_widgets, finds_nothing, finds_one_widget,
4936        test_widgets,
4937    };
4938
4939    use super::*;
4940    use crate::date::{DateTimeRange, GregorianCalendarDelegate};
4941    use crate::dialog::Dialog;
4942    use crate::elevated_button::ElevatedButton;
4943    use crate::icons::Icons;
4944    use crate::material::Material;
4945    use crate::test_support::{local_date, material_app};
4946    use crate::text_field::TextField;
4947    use crate::theme_data::ThemeData;
4948    use crate::tooltip::tests::{m2, m3};
4949    use std::cell::RefCell;
4950    use std::rc::Rc;
4951    use waft_embedder::{Offset, Size};
4952    use waft_foundation::{DateTime, Listener};
4953    use waft_painting::{BorderRadiusGeometry, BorderSide, RoundedRectangleBorder, ShapeBorderRef};
4954    use waft_services::{LogicalKeyboardKey, PhysicalKeyboardKey};
4955    use waft_widgets::{AnyElement, Builder, Center, EditableText, IntoWidget, Text};
4956
4957    /// Dart's `tester.widget<TextField>(find.byType(TextField)).controller!.text`: the text of
4958    /// the first `TextField`'s controller.
4959    pub(crate) fn text_field_controller_text(tester: &WidgetTester) -> String {
4960        let field = tester.element(find::by_type::<TextField>().at(0));
4961        let controller = tester.widget(field, |field: &TextField| {
4962            field.controller.clone().expect("a controller")
4963        });
4964        controller.text_value(&tester.cell.borrow()).to_owned()
4965    }
4966
4967    pub(super) type PickerResult = Rc<RefCell<Option<CompleterFuture<RouteResult>>>>;
4968
4969    /// Dart's `tester.view.physicalSize = size; tester.view.devicePixelRatio = 1.0`.
4970    pub(super) fn size_view(tester: &WidgetTester, size: Size) {
4971        tester.view().set_physical_size(size);
4972        tester.view().set_device_pixel_ratio(1.0);
4973    }
4974
4975    /// Dart's `wideWindowSize` and `narrowWindowSize`, set as the physical size at a device pixel
4976    /// ratio of 1, so the logical size here.
4977    pub(super) const WIDE_WINDOW_SIZE: Size = Size::new(1920.0, 1080.0);
4978    pub(super) const NARROW_WINDOW_SIZE: Size = Size::new(1070.0, 1770.0);
4979
4980    /// The variables of date_picker_test.dart's `setUp`, which each case may change.
4981    #[derive(Clone)]
4982    pub(super) struct DatePickerOptions {
4983        pub(super) first_date: DateTime,
4984        pub(super) last_date: DateTime,
4985        pub(super) initial_date: Option<DateTime>,
4986        pub(super) today: DateTime,
4987        pub(super) selectable_day_predicate: Option<waft_widgets::SelectableDayPredicate>,
4988        pub(super) initial_entry_mode: DatePickerEntryMode,
4989        pub(super) initial_calendar_mode: DatePickerMode,
4990        pub(super) cancel_text: Option<String>,
4991        pub(super) confirm_text: Option<String>,
4992        pub(super) error_format_text: Option<String>,
4993        pub(super) error_invalid_text: Option<String>,
4994        pub(super) field_hint_text: Option<String>,
4995        pub(super) field_label_text: Option<String>,
4996        pub(super) help_text: Option<String>,
4997        pub(super) use_material3: bool,
4998        pub(super) current_mode: Rc<RefCell<DatePickerEntryMode>>,
4999        pub(super) builder: Option<waft_widgets::TransitionBuilder>,
5000        pub(super) keyboard_type: Option<waft_services::TextInputType>,
5001        pub(super) day_builder: Option<crate::calendar_date_picker::CalendarDatePickerDayBuilder>,
5002        pub(super) weekday_builder:
5003            Option<crate::calendar_date_picker::CalendarDatePickerWeekdayBuilder>,
5004        pub(super) calendar_delegate: Rc<dyn CalendarDelegate>,
5005    }
5006
5007    impl DatePickerOptions {
5008        pub(super) fn new() -> DatePickerOptions {
5009            DatePickerOptions {
5010                first_date: local_date(2001, 1, 1),
5011                last_date: local_date(2031, 12, 31),
5012                initial_date: Some(local_date(2016, 1, 15)),
5013                today: local_date(2016, 1, 3),
5014                selectable_day_predicate: None,
5015                initial_entry_mode: DatePickerEntryMode::Calendar,
5016                initial_calendar_mode: DatePickerMode::Day,
5017                cancel_text: None,
5018                confirm_text: None,
5019                error_format_text: None,
5020                error_invalid_text: None,
5021                field_hint_text: None,
5022                field_label_text: None,
5023                help_text: None,
5024                use_material3: false,
5025                current_mode: Rc::new(RefCell::new(DatePickerEntryMode::Calendar)),
5026                builder: None,
5027                keyboard_type: None,
5028                day_builder: None,
5029                weekday_builder: None,
5030                calendar_delegate: Rc::new(GregorianCalendarDelegate),
5031            }
5032        }
5033    }
5034
5035    /// Dart's `prepareDatePicker`: an app with a button, tapped, that shows the date picker.
5036    pub(super) fn prepare_date_picker(
5037        tester: &mut WidgetTester,
5038        options: &DatePickerOptions,
5039    ) -> PickerResult {
5040        let theme: ThemeData = if options.use_material3 {
5041            m3(&tester.cell.borrow())
5042        } else {
5043            m2(&tester.cell.borrow())
5044        };
5045        let result: PickerResult = Rc::default();
5046        let launcher = {
5047            let (options, result) = (options.clone(), Rc::clone(&result));
5048            Builder::new(move |_app, _context| {
5049                let (options, result) = (options.clone(), Rc::clone(&result));
5050                Material::new()
5051                    .child(Center::new().child(Builder::new(move |_app, context| {
5052                        let (options, result) = (options.clone(), Rc::clone(&result));
5053                        ElevatedButton::new(
5054                            Some(Listener::new(move |app| {
5055                                let current_mode = Rc::clone(&options.current_mode);
5056                                let mut show =
5057                                    ShowDatePicker::new(options.first_date, options.last_date)
5058                                        .initial_entry_mode(options.initial_entry_mode)
5059                                        .initial_date_picker_mode(options.initial_calendar_mode)
5060                                        .calendar_delegate(Rc::clone(&options.calendar_delegate));
5061                                if let Some(initial_date) = options.initial_date {
5062                                    show = show.initial_date(initial_date);
5063                                }
5064                                show = show.current_date(options.today);
5065                                if let Some(predicate) = options.selectable_day_predicate.clone() {
5066                                    show = show.selectable_day_predicate(predicate);
5067                                }
5068                                if let Some(help_text) = options.help_text.clone() {
5069                                    show = show.help_text(help_text);
5070                                }
5071                                if let Some(cancel_text) = options.cancel_text.clone() {
5072                                    show = show.cancel_text(cancel_text);
5073                                }
5074                                if let Some(confirm_text) = options.confirm_text.clone() {
5075                                    show = show.confirm_text(confirm_text);
5076                                }
5077                                if let Some(builder) = options.builder.clone() {
5078                                    show = show.builder(builder);
5079                                }
5080                                if let Some(error_format_text) = options.error_format_text.clone() {
5081                                    show = show.error_format_text(error_format_text);
5082                                }
5083                                if let Some(error_invalid_text) = options.error_invalid_text.clone()
5084                                {
5085                                    show = show.error_invalid_text(error_invalid_text);
5086                                }
5087                                if let Some(field_hint_text) = options.field_hint_text.clone() {
5088                                    show = show.field_hint_text(field_hint_text);
5089                                }
5090                                if let Some(field_label_text) = options.field_label_text.clone() {
5091                                    show = show.field_label_text(field_label_text);
5092                                }
5093                                if let Some(keyboard_type) = options.keyboard_type {
5094                                    show = show.keyboard_type(keyboard_type);
5095                                }
5096                                show =
5097                                    show.on_date_picker_mode_change(Rc::new(move |_app, value| {
5098                                        *current_mode.borrow_mut() = value;
5099                                    }));
5100                                if let Some(day_builder) = options.day_builder.clone() {
5101                                    show = show.day_builder(day_builder);
5102                                }
5103                                if let Some(weekday_builder) = options.weekday_builder.clone() {
5104                                    show = show.weekday_builder(weekday_builder);
5105                                }
5106                                let future = show.show(app, context);
5107                                *result.borrow_mut() = Some(future);
5108                            })),
5109                            Some(Text::new("Go")),
5110                        )
5111                        .into_widget()
5112                    })))
5113                    .into_widget()
5114            })
5115        };
5116        tester.pump_widget(material_app(theme, launcher.into_widget()));
5117        tester.tap(find::text("Go"));
5118        tester.pump_and_settle();
5119        result
5120    }
5121
5122    /// Dart's `await tester.tap(find.byIcon(icon)); await tester.pumpAndSettle();`.
5123    pub(super) fn tap_icon(tester: &mut WidgetTester, icon: &waft_widgets::IconData) {
5124        tester.tap(find::by_icon(icon));
5125        tester.pump_and_settle();
5126    }
5127
5128    pub(super) fn text_field_count(tester: &WidgetTester) -> usize {
5129        find::by_type::<TextField>().evaluate(tester).len()
5130    }
5131
5132    /// What the date picker completed with.
5133    pub(super) fn picked_date(result: &PickerResult) -> Option<DateTime> {
5134        result
5135            .borrow()
5136            .as_ref()
5137            .and_then(|future| future.peek())
5138            .flatten()
5139            .and_then(|value| value.downcast_ref::<DateTime>().copied())
5140    }
5141
5142    pub(super) fn picked_range(result: &PickerResult) -> Option<DateTimeRange> {
5143        result
5144            .borrow()
5145            .as_ref()
5146            .and_then(|future| future.peek())
5147            .flatten()
5148            .and_then(|value| value.downcast_ref::<DateTimeRange>().copied())
5149    }
5150
5151    pub(super) fn is_completed(result: &PickerResult) -> bool {
5152        result
5153            .borrow()
5154            .as_ref()
5155            .is_some_and(|future| future.peek().is_some())
5156    }
5157
5158    /// Dart's `find.text(text), findsOneWidget`.
5159    pub(super) fn has_text(tester: &WidgetTester, text: &str) -> bool {
5160        find::text(text).evaluate(tester).len() == 1
5161    }
5162
5163    /// Dart's `find.text(text), findsNothing`.
5164    pub(super) fn has_no_text(tester: &WidgetTester, text: &str) -> bool {
5165        find::text(text).evaluate(tester).is_empty()
5166    }
5167
5168    pub(super) fn dialog_container_size(tester: &WidgetTester) -> Size {
5169        let container = tester.element(find::by_type::<waft_widgets::AnimatedContainer>().at(0));
5170        tester.get_size(container)
5171    }
5172
5173    #[test]
5174    fn material3_default_dialog_size() {
5175        test_widgets(|tester| {
5176            let mut options = DatePickerOptions::new();
5177            options.use_material3 = true;
5178
5179            // Test landscape layout.
5180            size_view(tester, WIDE_WINDOW_SIZE);
5181            prepare_date_picker(tester, &options);
5182            assert_eq!(
5183                dialog_container_size(tester),
5184                CALENDAR_LANDSCAPE_DIALOG_SIZE
5185            );
5186
5187            // Test portrait layout.
5188            size_view(tester, NARROW_WINDOW_SIZE);
5189            prepare_date_picker(tester, &options);
5190            assert_eq!(
5191                dialog_container_size(tester),
5192                CALENDAR_PORTRAIT_DIALOG_SIZE_M3
5193            );
5194        });
5195    }
5196
5197    #[test]
5198    fn material3_uses_sentence_case_labels() {
5199        test_widgets(|tester| {
5200            let mut options = DatePickerOptions::new();
5201            options.use_material3 = true;
5202            prepare_date_picker(tester, &options);
5203            assert!(has_text(tester, "Select date"));
5204        });
5205    }
5206
5207    #[test]
5208    fn cancel_confirm_and_help_text_is_used() {
5209        test_widgets(|tester| {
5210            let mut options = DatePickerOptions::new();
5211            options.cancel_text = Some("nope".to_string());
5212            options.confirm_text = Some("yep".to_string());
5213            options.help_text = Some("help".to_string());
5214            prepare_date_picker(tester, &options);
5215            assert!(has_text(tester, "nope"));
5216            assert!(has_text(tester, "yep"));
5217            assert!(has_text(tester, "help"));
5218        });
5219    }
5220
5221    #[test]
5222    fn initial_date_is_the_default() {
5223        test_widgets(|tester| {
5224            let result = prepare_date_picker(tester, &DatePickerOptions::new());
5225            tester.tap(find::text("OK"));
5226            tester.pump_and_settle();
5227            assert_eq!(picked_date(&result), Some(local_date(2016, 1, 15)));
5228        });
5229    }
5230
5231    #[test]
5232    fn can_cancel() {
5233        test_widgets(|tester| {
5234            let result = prepare_date_picker(tester, &DatePickerOptions::new());
5235            tester.tap(find::text("CANCEL"));
5236            tester.pump_and_settle();
5237            assert!(is_completed(&result));
5238            assert_eq!(picked_date(&result), None);
5239        });
5240    }
5241
5242    #[test]
5243    fn can_switch_from_calendar_to_input_entry_mode() {
5244        test_widgets(|tester| {
5245            prepare_date_picker(tester, &DatePickerOptions::new());
5246            assert_eq!(text_field_count(tester), 0);
5247            tap_icon(tester, &Icons::edit());
5248            assert_eq!(text_field_count(tester), 1);
5249        });
5250    }
5251
5252    #[test]
5253    fn can_switch_from_input_to_calendar_entry_mode() {
5254        test_widgets(|tester| {
5255            let mut options = DatePickerOptions::new();
5256            options.initial_entry_mode = DatePickerEntryMode::Input;
5257            prepare_date_picker(tester, &options);
5258            assert_eq!(text_field_count(tester), 1);
5259            tap_icon(tester, &Icons::calendar_today());
5260            assert_eq!(text_field_count(tester), 0);
5261        });
5262    }
5263
5264    #[test]
5265    fn can_not_switch_out_of_calendar_only_mode() {
5266        test_widgets(|tester| {
5267            let mut options = DatePickerOptions::new();
5268            options.initial_entry_mode = DatePickerEntryMode::CalendarOnly;
5269            prepare_date_picker(tester, &options);
5270            assert_eq!(text_field_count(tester), 0);
5271            assert!(find::by_icon(&Icons::edit()).evaluate(tester).is_empty());
5272        });
5273    }
5274
5275    #[test]
5276    fn can_not_switch_out_of_input_only_mode() {
5277        test_widgets(|tester| {
5278            let mut options = DatePickerOptions::new();
5279            options.initial_entry_mode = DatePickerEntryMode::InputOnly;
5280            prepare_date_picker(tester, &options);
5281            assert_eq!(text_field_count(tester), 1);
5282            assert!(
5283                find::by_icon(&Icons::calendar_today())
5284                    .evaluate(tester)
5285                    .is_empty()
5286            );
5287        });
5288    }
5289
5290    #[test]
5291    fn switching_to_input_mode_keeps_selected_date() {
5292        test_widgets(|tester| {
5293            let result = prepare_date_picker(tester, &DatePickerOptions::new());
5294            tester.tap(find::text("12"));
5295            tap_icon(tester, &Icons::edit());
5296            tester.tap(find::text("OK"));
5297            tester.pump_and_settle();
5298            assert_eq!(picked_date(&result), Some(local_date(2016, 1, 12)));
5299        });
5300    }
5301
5302    #[test]
5303    fn callback_on_toggle_of_date_picker_mode() {
5304        test_widgets(|tester| {
5305            let options = DatePickerOptions::new();
5306            prepare_date_picker(tester, &options);
5307            tap_icon(tester, &Icons::edit());
5308            assert_eq!(*options.current_mode.borrow(), DatePickerEntryMode::Input);
5309            assert_eq!(text_field_count(tester), 1);
5310            tap_icon(tester, &Icons::calendar_today());
5311            assert_eq!(
5312                *options.current_mode.borrow(),
5313                DatePickerEntryMode::Calendar
5314            );
5315            assert_eq!(text_field_count(tester), 0);
5316        });
5317    }
5318
5319    #[test]
5320    fn can_select_a_day() {
5321        test_widgets(|tester| {
5322            let result = prepare_date_picker(tester, &DatePickerOptions::new());
5323            tester.tap(find::text("12"));
5324            tester.tap(find::text("OK"));
5325            tester.pump_and_settle();
5326            assert_eq!(picked_date(&result), Some(local_date(2016, 1, 12)));
5327        });
5328    }
5329
5330    #[test]
5331    fn can_select_a_day_with_no_initial_date() {
5332        test_widgets(|tester| {
5333            let mut options = DatePickerOptions::new();
5334            options.initial_date = None;
5335            let result = prepare_date_picker(tester, &options);
5336            tester.tap(find::text("12"));
5337            tester.tap(find::text("OK"));
5338            tester.pump_and_settle();
5339            assert_eq!(picked_date(&result), Some(local_date(2016, 1, 12)));
5340        });
5341    }
5342
5343    #[test]
5344    fn only_predicate_days_are_selectable() {
5345        test_widgets(|tester| {
5346            let mut options = DatePickerOptions::new();
5347            options.initial_date = Some(local_date(2017, 1, 16));
5348            options.first_date = local_date(2017, 1, 10);
5349            options.last_date = local_date(2017, 1, 20);
5350            options.selectable_day_predicate = Some(Rc::new(|app, day| day.day(app) % 2 == 0));
5351            let result = prepare_date_picker(tester, &options);
5352            tester.tap(find::text("13")); // Odd, doesn't work.
5353            tester.tap(find::text("10")); // Even, works.
5354            tester.tap(find::text("17")); // Odd, doesn't work.
5355            tester.tap(find::text("OK"));
5356            tester.pump_and_settle();
5357            assert_eq!(picked_date(&result), Some(local_date(2017, 1, 10)));
5358        });
5359    }
5360
5361    #[test]
5362    fn input_mode_initial_entry_mode_is_used() {
5363        test_widgets(|tester| {
5364            let mut options = DatePickerOptions::new();
5365            options.initial_entry_mode = DatePickerEntryMode::Input;
5366            prepare_date_picker(tester, &options);
5367            assert_eq!(text_field_count(tester), 1);
5368        });
5369    }
5370
5371    #[test]
5372    fn input_mode_hint_label_and_help_text_is_used() {
5373        test_widgets(|tester| {
5374            let mut options = DatePickerOptions::new();
5375            options.initial_entry_mode = DatePickerEntryMode::Input;
5376            options.cancel_text = Some("nope".to_string());
5377            options.confirm_text = Some("yep".to_string());
5378            options.field_hint_text = Some("hint".to_string());
5379            options.field_label_text = Some("label".to_string());
5380            options.help_text = Some("help".to_string());
5381            prepare_date_picker(tester, &options);
5382            assert!(has_text(tester, "nope"));
5383            assert!(has_text(tester, "yep"));
5384            assert!(has_text(tester, "hint"));
5385            assert!(has_text(tester, "label"));
5386            assert!(has_text(tester, "help"));
5387        });
5388    }
5389
5390    #[test]
5391    fn input_mode_initial_date_is_the_default() {
5392        test_widgets(|tester| {
5393            let mut options = DatePickerOptions::new();
5394            options.initial_entry_mode = DatePickerEntryMode::Input;
5395            let result = prepare_date_picker(tester, &options);
5396            tester.tap(find::text("OK"));
5397            tester.pump_and_settle();
5398            assert_eq!(picked_date(&result), Some(local_date(2016, 1, 15)));
5399        });
5400    }
5401
5402    #[test]
5403    fn input_mode_toggle_to_calendar_mode_keeps_selected_date() {
5404        test_widgets(|tester| {
5405            let mut options = DatePickerOptions::new();
5406            options.initial_entry_mode = DatePickerEntryMode::Input;
5407            let result = prepare_date_picker(tester, &options);
5408            tester.enter_text(find::by_type::<EditableText>().at(0), "12/25/2016");
5409            tap_icon(tester, &Icons::calendar_today());
5410            tester.tap(find::text("OK"));
5411            tester.pump_and_settle();
5412            assert_eq!(picked_date(&result), Some(local_date(2016, 12, 25)));
5413        });
5414    }
5415
5416    #[test]
5417    fn input_mode_entered_text_returns_date() {
5418        test_widgets(|tester| {
5419            let mut options = DatePickerOptions::new();
5420            options.initial_entry_mode = DatePickerEntryMode::Input;
5421            let result = prepare_date_picker(tester, &options);
5422            tester.enter_text(find::by_type::<EditableText>().at(0), "12/25/2016");
5423            tester.tap(find::text("OK"));
5424            tester.pump_and_settle();
5425            assert_eq!(picked_date(&result), Some(local_date(2016, 12, 25)));
5426        });
5427    }
5428
5429    #[test]
5430    fn input_mode_too_short_entered_text_shows_error() {
5431        test_widgets(|tester| {
5432            let mut options = DatePickerOptions::new();
5433            options.initial_entry_mode = DatePickerEntryMode::Input;
5434            options.error_format_text = Some("oops".to_string());
5435            prepare_date_picker(tester, &options);
5436            tester.pump_and_settle();
5437            tester.enter_text(find::by_type::<EditableText>().at(0), "1225");
5438            assert!(has_no_text(tester, "oops"));
5439
5440            tester.tap(find::text("OK"));
5441            tester.pump_and_settle();
5442            assert!(has_text(tester, "oops"));
5443        });
5444    }
5445
5446    #[test]
5447    fn input_mode_bad_format_entered_text_shows_error() {
5448        test_widgets(|tester| {
5449            let mut options = DatePickerOptions::new();
5450            options.initial_entry_mode = DatePickerEntryMode::Input;
5451            options.error_format_text = Some("oops".to_string());
5452            prepare_date_picker(tester, &options);
5453            tester.pump_and_settle();
5454            tester.enter_text(
5455                find::by_type::<EditableText>().at(0),
5456                "20 days, 3 months, 2003",
5457            );
5458            // Dart's `find.text` finds the `EditableText` showing it; `find_text` reads `Text` only.
5459            assert_eq!(
5460                text_field_controller_text(tester),
5461                "20 days, 3 months, 2003"
5462            );
5463            assert!(has_no_text(tester, "oops"));
5464
5465            tester.tap(find::text("OK"));
5466            tester.pump_and_settle();
5467            assert!(has_text(tester, "oops"));
5468        });
5469    }
5470
5471    #[test]
5472    fn input_mode_invalid_entered_text_shows_error() {
5473        test_widgets(|tester| {
5474            let mut options = DatePickerOptions::new();
5475            options.initial_entry_mode = DatePickerEntryMode::Input;
5476            options.error_invalid_text = Some("oops".to_string());
5477            prepare_date_picker(tester, &options);
5478            tester.pump_and_settle();
5479            tester.enter_text(find::by_type::<EditableText>().at(0), "08/10/1969");
5480            assert!(has_no_text(tester, "oops"));
5481
5482            tester.tap(find::text("OK"));
5483            tester.pump_and_settle();
5484            assert!(has_text(tester, "oops"));
5485        });
5486    }
5487
5488    #[test]
5489    fn input_only_mode_should_validate_date() {
5490        test_widgets(|tester| {
5491            let mut options = DatePickerOptions::new();
5492            options.initial_entry_mode = DatePickerEntryMode::InputOnly;
5493            prepare_date_picker(tester, &options);
5494            // Enter text input mode and type an invalid date to get error.
5495            tester.enter_text(find::by_type::<EditableText>().at(0), "1234567");
5496            tester.tap(find::text("OK"));
5497            tester.pump_and_settle();
5498            assert!(has_text(tester, "Invalid format."));
5499        });
5500    }
5501
5502    // The Material 2 'Default dialog size'.
5503    #[test]
5504    fn material2_default_dialog_size() {
5505        test_widgets(|tester| {
5506            let options = DatePickerOptions::new();
5507
5508            // Test landscape layout.
5509            size_view(tester, WIDE_WINDOW_SIZE);
5510            prepare_date_picker(tester, &options);
5511            assert_eq!(
5512                dialog_container_size(tester),
5513                CALENDAR_LANDSCAPE_DIALOG_SIZE
5514            );
5515
5516            // Test portrait layout.
5517            size_view(tester, NARROW_WINDOW_SIZE);
5518            prepare_date_picker(tester, &options);
5519            assert_eq!(
5520                dialog_container_size(tester),
5521                CALENDAR_PORTRAIT_DIALOG_SIZE_M2
5522            );
5523        });
5524    }
5525
5526    pub(super) fn range(start: (i32, i32, i32), end: (i32, i32, i32)) -> DateTimeRange {
5527        DateTimeRange::new(
5528            local_date(start.0, start.1, start.2),
5529            local_date(end.0, end.1, end.2),
5530        )
5531    }
5532
5533    #[derive(Clone, Copy)]
5534    pub(super) enum Arrow {
5535        Left,
5536        Right,
5537        Up,
5538        Down,
5539    }
5540
5541    pub(super) fn dialog_material(tester: &WidgetTester) -> AnyElement {
5542        tester.element(
5543            find::descendant(find::by_type::<Dialog>().at(0), find::by_type::<Material>()).first(),
5544        )
5545    }
5546
5547    pub(super) fn rounded(radius: f64) -> ShapeBorderRef {
5548        ShapeBorderRef::new(RoundedRectangleBorder::new(
5549            BorderSide::NONE,
5550            BorderRadiusGeometry::circular(radius),
5551        ))
5552    }
5553
5554    pub(super) fn top_left(tester: &WidgetTester, element: AnyElement) -> Offset {
5555        tester.get_rect(element).top_left()
5556    }
5557
5558    pub(super) fn bottom_left(tester: &WidgetTester, element: AnyElement) -> Offset {
5559        let rect = tester.get_rect(element);
5560        Offset::new(rect.left, rect.bottom)
5561    }
5562
5563    pub(super) fn bottom_right(tester: &WidgetTester, element: AnyElement) -> Offset {
5564        let rect = tester.get_rect(element);
5565        Offset::new(rect.right, rect.bottom)
5566    }
5567
5568    pub(super) fn header_font_size(tester: &WidgetTester, text: &str) -> Option<f64> {
5569        tester.widget(tester.element(find::text(text)), |text: &Text| {
5570            text.style.as_ref().and_then(|style| style.font_size)
5571        })
5572    }
5573
5574    pub(super) fn press(
5575        tester: &mut WidgetTester,
5576        physical: PhysicalKeyboardKey,
5577        logical: LogicalKeyboardKey,
5578    ) {
5579        tester.send_key_event(physical, logical);
5580    }
5581
5582    pub(super) fn tab(tester: &mut WidgetTester) {
5583        press(tester, PhysicalKeyboardKey::TAB, LogicalKeyboardKey::TAB);
5584    }
5585
5586    pub(super) fn tabs(tester: &mut WidgetTester, count: usize) {
5587        for _ in 0..count {
5588            tab(tester);
5589        }
5590    }
5591
5592    pub(super) fn space(tester: &mut WidgetTester) {
5593        press(
5594            tester,
5595            PhysicalKeyboardKey::SPACE,
5596            LogicalKeyboardKey::SPACE,
5597        );
5598    }
5599
5600    pub(super) fn arrows(tester: &mut WidgetTester, keys: &[Arrow]) {
5601        for key in keys {
5602            let (physical, logical) = match key {
5603                Arrow::Left => (
5604                    PhysicalKeyboardKey::ARROW_LEFT,
5605                    LogicalKeyboardKey::ARROW_LEFT,
5606                ),
5607                Arrow::Right => (
5608                    PhysicalKeyboardKey::ARROW_RIGHT,
5609                    LogicalKeyboardKey::ARROW_RIGHT,
5610                ),
5611                Arrow::Up => (PhysicalKeyboardKey::ARROW_UP, LogicalKeyboardKey::ARROW_UP),
5612                Arrow::Down => (
5613                    PhysicalKeyboardKey::ARROW_DOWN,
5614                    LogicalKeyboardKey::ARROW_DOWN,
5615                ),
5616            };
5617            press(tester, physical, logical);
5618        }
5619    }
5620
5621    pub(super) fn icon_button_of(
5622        tester: &WidgetTester,
5623        icon: &waft_widgets::IconData,
5624    ) -> AnyElement {
5625        tester.element(
5626            find::ancestor(
5627                find::by_icon(icon).first(),
5628                find::by_type::<crate::icon_button::IconButton>(),
5629            )
5630            .first(),
5631        )
5632    }
5633
5634    mod dialog {
5635        //! date_picker_test.dart: the dialog's properties, its routes and barrier, its layout, the
5636        //! selection of days, months and years, the keyboard navigation and the calendar delegates.
5637
5638        use crate::test_support::local_date;
5639        use waft_widgets::testing::assert_f32_equals;
5640
5641        use std::cell::Cell;
5642        use std::rc::Rc;
5643
5644        use waft_embedder::{Offset, Size};
5645        use waft_foundation::{App, DateTime, Handle, Listener};
5646        use waft_painting::{
5647            BorderRadiusGeometry, BorderSide, EdgeInsets, RoundedRectangleBorder, TextDirection,
5648        };
5649        use waft_services::{LogicalKeyboardKey, PhysicalKeyboardKey, TextInputType};
5650        use waft_widgets::{
5651            AnyElement, BuildContext, Builder, Center, Icon, IntoWidget, ModalBarrier, SizedBox,
5652            Text, TransitionBuilder,
5653        };
5654
5655        use super::*;
5656        use super::{
5657            DatePickerOptions, has_no_text, has_text, picked_date, prepare_date_picker, size_view,
5658            tap_icon, text_field_count,
5659        };
5660        use crate::colors::Colors;
5661        use crate::date::GregorianCalendarDelegate;
5662        use crate::dialog::Dialog;
5663        use crate::elevated_button::ElevatedButton;
5664        use crate::icons::Icons;
5665        use crate::material::Material;
5666        use crate::material_localizations::MaterialLocalizations;
5667        use crate::test_support::{PaintInspection, material_app};
5668
5669        use crate::text_field::TextField;
5670        use crate::theme_data::ThemeData;
5671        use crate::tooltip::tests::{m2, m3};
5672        use waft_rendering::testing::{PaintCall, assert_paints, paints};
5673
5674        /// The arguments of the `showDatePicker` calls that are not `prepareDatePicker`'s.
5675        #[derive(Clone)]
5676        struct Show {
5677            initial_entry_mode: DatePickerEntryMode,
5678            builder: Option<TransitionBuilder>,
5679            barrier_dismissible: bool,
5680            barrier_color: Option<waft_embedder::Color>,
5681            barrier_label: Option<String>,
5682            use_root_navigator: bool,
5683            switch_to_input_entry_mode_icon: Option<fn() -> Icon>,
5684            switch_to_calendar_entry_mode_icon: Option<fn() -> Icon>,
5685            calendar_delegate: Rc<dyn CalendarDelegate>,
5686            /// `(initialDate, firstDate, lastDate)`, when not `DateTime.now()`, 2018 and 2030.
5687            dates: Option<(DateTime, DateTime, DateTime)>,
5688            /// Where the future of the shown picker goes.
5689            result: Option<super::PickerResult>,
5690        }
5691
5692        impl Show {
5693            fn new() -> Show {
5694                Show {
5695                    initial_entry_mode: DatePickerEntryMode::Calendar,
5696                    builder: None,
5697                    barrier_dismissible: true,
5698                    barrier_color: None,
5699                    barrier_label: None,
5700                    use_root_navigator: true,
5701                    switch_to_input_entry_mode_icon: None,
5702                    switch_to_calendar_entry_mode_icon: None,
5703                    calendar_delegate: Rc::new(GregorianCalendarDelegate),
5704                    dates: None,
5705                    result: None,
5706                }
5707            }
5708
5709            /// `showDatePicker(initialDate: DateTime.now(), firstDate: DateTime(2018),
5710            /// lastDate: DateTime(2030), ...)`.
5711            fn show(&self, app: &mut App, context: BuildContext) -> CompleterFuture<RouteResult> {
5712                let (initial_date, first_date, last_date) = self.dates.unwrap_or((
5713                    DateTime::now(),
5714                    DateTime::new(app, 2018, 1, 1),
5715                    DateTime::new(app, 2030, 1, 1),
5716                ));
5717                let mut show = ShowDatePicker::new(first_date, last_date)
5718                    .initial_date(initial_date)
5719                    .initial_entry_mode(self.initial_entry_mode)
5720                    .barrier_dismissible(self.barrier_dismissible)
5721                    .use_root_navigator(self.use_root_navigator)
5722                    .calendar_delegate(Rc::clone(&self.calendar_delegate));
5723                if let Some(barrier_color) = self.barrier_color {
5724                    show = show.barrier_color(barrier_color);
5725                }
5726                if let Some(barrier_label) = self.barrier_label.clone() {
5727                    show = show.barrier_label(barrier_label);
5728                }
5729                if let Some(builder) = self.builder.clone() {
5730                    show = show.builder(builder);
5731                }
5732                if let Some(icon) = self.switch_to_input_entry_mode_icon {
5733                    show = show.switch_to_input_entry_mode_icon(icon());
5734                }
5735                if let Some(icon) = self.switch_to_calendar_entry_mode_icon {
5736                    show = show.switch_to_calendar_entry_mode_icon(icon());
5737                }
5738                let future = show.show(app, context);
5739                if let Some(result) = &self.result {
5740                    *result.borrow_mut() = Some(future.clone());
5741                }
5742                future
5743            }
5744        }
5745
5746        /// An app with a button labelled `label` that shows a date picker.
5747        fn open_app(tester: &mut WidgetTester, material3: bool, label: &'static str, show: Show) {
5748            let theme = if material3 {
5749                m3(&tester.cell.borrow())
5750            } else {
5751                m2(&tester.cell.borrow())
5752            };
5753            open_app_with_theme(tester, theme, label, show);
5754        }
5755
5756        fn open_app_with_theme(
5757            tester: &mut WidgetTester,
5758            theme: ThemeData,
5759            label: &'static str,
5760            show: Show,
5761        ) {
5762            let home = Material::new()
5763                .child(Center::new().child(Builder::new(move |_app, context| {
5764                    let show = show.clone();
5765                    ElevatedButton::new(
5766                        Some(Listener::new(move |app| drop(show.show(app, context)))),
5767                        Some(Text::new(label)),
5768                    )
5769                    .into_widget()
5770                })))
5771                .into_widget();
5772            tester.pump_widget(material_app(theme, home));
5773        }
5774
5775        fn sized_box_builder() -> TransitionBuilder {
5776            Rc::new(|_app, _context, _child| SizedBox::shrink().into_widget())
5777        }
5778
5779        fn directionality_builder(text_direction: TextDirection) -> TransitionBuilder {
5780            Rc::new(move |_app, _context, child| {
5781                waft_widgets::Directionality::new(
5782                    text_direction,
5783                    child.expect("a dialog child").clone(),
5784                )
5785                .into_widget()
5786            })
5787        }
5788
5789        /// Dart's `_DatePickerObserver`: how many dialog routes the navigator shows.
5790        #[derive(Default)]
5791        struct DatePickerObserver {
5792            navigator_observer: waft_widgets::NavigatorObserverData,
5793            date_picker_count: Cell<i32>,
5794        }
5795
5796        impl waft_widgets::NavigatorObserver for DatePickerObserver {
5797            waft_widgets::navigator_observer_accessors!();
5798
5799            fn did_push(
5800                self: Handle<Self>,
5801                app: &mut App,
5802                route: waft_widgets::AnyRoute,
5803                _previous: Option<waft_widgets::AnyRoute>,
5804            ) {
5805                if route.downcast::<crate::dialog::DialogRoute>(app).is_some() {
5806                    let count = &app.get(self).date_picker_count;
5807                    count.set(count.get() + 1);
5808                }
5809            }
5810
5811            fn did_pop(
5812                self: Handle<Self>,
5813                app: &mut App,
5814                route: waft_widgets::AnyRoute,
5815                _previous: Option<waft_widgets::AnyRoute>,
5816            ) {
5817                if route.downcast::<crate::dialog::DialogRoute>(app).is_some() {
5818                    let count = &app.get(self).date_picker_count;
5819                    count.set(count.get() - 1);
5820                }
5821            }
5822        }
5823
5824        #[test]
5825        fn forwards_day_builder_and_weekday_builder_to_the_calendar() {
5826            test_widgets(|tester| {
5827                let mut options = DatePickerOptions::new();
5828                options.day_builder = Some(Rc::new(|app, _context, details| {
5829                    if details.day.day(app) == 1 {
5830                        Text::new("Custom day 1").into_widget()
5831                    } else {
5832                        details.child
5833                    }
5834                }));
5835                options.weekday_builder = Some(Rc::new(|_app, _context, details| {
5836                    if details.weekday == DateTime::SUNDAY {
5837                        Text::new("Custom Sunday").into_widget()
5838                    } else {
5839                        details.child
5840                    }
5841                }));
5842                prepare_date_picker(tester, &options);
5843                expect(tester, &find::text("Custom day 1"), finds_one_widget());
5844                expect(tester, &find::text("Custom Sunday"), finds_one_widget());
5845            });
5846        }
5847
5848        #[test]
5849        fn material3_default_dialog_properties() {
5850            test_widgets(|tester| {
5851                let mut options = DatePickerOptions::new();
5852                options.use_material3 = true;
5853                prepare_date_picker(tester, &options);
5854                let theme = m3(&tester.cell.borrow());
5855
5856                let (color, shadow_color, surface_tint_color, elevation, shape, clip_behavior) =
5857                    tester.widget(dialog_material(tester), |material: &Material| {
5858                        (
5859                            material.color,
5860                            material.shadow_color,
5861                            material.surface_tint_color,
5862                            material.elevation,
5863                            material.shape.clone(),
5864                            material.clip_behavior,
5865                        )
5866                    });
5867                assert_eq!(color, Some(theme.color_scheme.surface_container_high()));
5868                assert_eq!(shadow_color, Some(Colors::TRANSPARENT));
5869                assert_eq!(surface_tint_color, Some(Colors::TRANSPARENT));
5870                assert_eq!(elevation, 6.0);
5871                assert_eq!(shape, Some(rounded(28.0)));
5872                assert_eq!(clip_behavior, waft_embedder::Clip::AntiAlias);
5873
5874                let dialog = tester.element(find::by_type::<Dialog>().at(0));
5875                let inset_padding = tester.widget(dialog, |dialog: &Dialog| dialog.inset_padding);
5876                assert_eq!(inset_padding, Some(EdgeInsets::symmetric(24.0, 16.0)));
5877            });
5878        }
5879
5880        #[test]
5881        fn material2_default_dialog_properties() {
5882            test_widgets(|tester| {
5883                prepare_date_picker(tester, &DatePickerOptions::new());
5884                let theme = m2(&tester.cell.borrow());
5885
5886                let (color, shadow_color, elevation, shape, clip_behavior) =
5887                    tester.widget(dialog_material(tester), |material: &Material| {
5888                        (
5889                            material.color,
5890                            material.shadow_color,
5891                            material.elevation,
5892                            material.shape.clone(),
5893                            material.clip_behavior,
5894                        )
5895                    });
5896                assert_eq!(color, Some(theme.color_scheme.surface()));
5897                assert_eq!(shadow_color, Some(theme.shadow_color));
5898                assert_eq!(elevation, 24.0);
5899                assert_eq!(shape, Some(rounded(4.0)));
5900                assert_eq!(clip_behavior, waft_embedder::Clip::AntiAlias);
5901
5902                let dialog = tester.element(find::by_type::<Dialog>().at(0));
5903                let inset_padding = tester.widget(dialog, |dialog: &Dialog| dialog.inset_padding);
5904                assert_eq!(inset_padding, Some(EdgeInsets::symmetric(24.0, 16.0)));
5905            });
5906        }
5907
5908        #[test]
5909        fn switching_to_input_mode_resets_input_error_state() {
5910            test_widgets(|tester| {
5911                prepare_date_picker(tester, &DatePickerOptions::new());
5912
5913                // Enter text input mode and type an invalid date to get error.
5914                tap_icon(tester, &Icons::edit());
5915                tester.enter_text(find::by_type::<EditableText>().at(0), "1234567");
5916                tester.tap(find::text("OK"));
5917                tester.pump_and_settle();
5918                assert!(has_text(tester, "Invalid format."));
5919
5920                // Toggle to calendar mode and then back to input mode
5921                tap_icon(tester, &Icons::calendar_today());
5922                tap_icon(tester, &Icons::edit());
5923                assert!(has_no_text(tester, "Invalid format."));
5924
5925                // Edit the text, the error should not be showing until ok is tapped
5926                tester.enter_text(find::by_type::<EditableText>().at(0), "1234567");
5927                tester.pump_and_settle();
5928                assert!(has_no_text(tester, "Invalid format."));
5929            });
5930        }
5931
5932        #[test]
5933        fn builder_parameter() {
5934            test_widgets(|tester| {
5935                let build_frame = |tester: &mut WidgetTester, text_direction: TextDirection| {
5936                    let mut show = Show::new();
5937                    show.builder = Some(directionality_builder(text_direction));
5938                    open_app(tester, true, "X", show);
5939                };
5940
5941                build_frame(tester, TextDirection::Ltr);
5942                tester.tap(find::text("X"));
5943                tester.pump_and_settle();
5944                let ltr_ok_right = tester.get_rect(find::text("OK")).right;
5945
5946                tester.tap(find::text("OK")); // Dismiss the dialog.
5947                tester.pump_and_settle();
5948
5949                build_frame(tester, TextDirection::Rtl);
5950                tester.tap(find::text("X"));
5951                tester.pump_and_settle();
5952
5953                // Verify that the time picker is being laid out RTL. We expect the left edge of the
5954                // 'OK' button in the RTL layout to match the gap between right edge of the 'OK'
5955                // button and the right edge of the 800 wide view.
5956                let rtl_ok_left = tester.get_rect(find::text("OK")).left;
5957                // Dart's `moreOrLessEquals`, at the f32 precision Valo lays out in.
5958                let expected = 800.0 - ltr_ok_right;
5959                assert!(
5960                    (rtl_ok_left - expected).abs() <= f64::from(f32::EPSILON) * expected.abs(),
5961                    "{rtl_ok_left} is not {expected}"
5962                );
5963            });
5964        }
5965
5966        #[test]
5967        fn barrier_is_dismissible_with_default_parameter() {
5968            test_widgets(|tester| {
5969                let mut show = Show::new();
5970                show.builder = Some(sized_box_builder());
5971                let observer = tester
5972                    .cell
5973                    .borrow_mut()
5974                    .create(DatePickerObserver::default());
5975                {
5976                    let app = tester.cell.borrow();
5977                    let home = Material::new()
5978                        .child(Center::new().child(Builder::new(move |_app, context| {
5979                            let show = show.clone();
5980                            ElevatedButton::new(
5981                                Some(Listener::new(move |app| drop(show.show(app, context)))),
5982                                Some(Text::new("X")),
5983                            )
5984                            .into_widget()
5985                        })))
5986                        .into_widget();
5987                    let root = crate::app::MaterialApp::new()
5988                        .theme(m3(&app))
5989                        .navigator_observers([
5990                            observer.erase::<waft_widgets::AnyNavigatorObserver>()
5991                        ])
5992                        .home(home)
5993                        .into_widget();
5994                    drop(app);
5995                    tester.pump_widget(root);
5996                }
5997
5998                // Open the dialog.
5999                let button = tester.element(find::by_type::<ElevatedButton>().at(0));
6000                let center = tester.get_center(button);
6001                tester.tap_at(center, 1);
6002                tester.pump_and_settle();
6003                assert_eq!(
6004                    tester.cell.borrow().get(&observer).date_picker_count.get(),
6005                    1
6006                );
6007
6008                // Tap on the barrier.
6009                tester.tap_at(Offset::new(10.0, 10.0), 1);
6010                tester.pump_and_settle();
6011                assert_eq!(
6012                    tester.cell.borrow().get(&observer).date_picker_count.get(),
6013                    0
6014                );
6015            });
6016        }
6017
6018        #[test]
6019        fn barrier_is_not_dismissible_with_barrier_dismissible_is_false() {
6020            test_widgets(|tester| {
6021                let mut show = Show::new();
6022                show.builder = Some(sized_box_builder());
6023                show.barrier_dismissible = false;
6024                let observer = tester
6025                    .cell
6026                    .borrow_mut()
6027                    .create(DatePickerObserver::default());
6028                {
6029                    let app = tester.cell.borrow();
6030                    let home = Material::new()
6031                        .child(Center::new().child(Builder::new(move |_app, context| {
6032                            let show = show.clone();
6033                            ElevatedButton::new(
6034                                Some(Listener::new(move |app| drop(show.show(app, context)))),
6035                                Some(Text::new("X")),
6036                            )
6037                            .into_widget()
6038                        })))
6039                        .into_widget();
6040                    let root = crate::app::MaterialApp::new()
6041                        .theme(m3(&app))
6042                        .navigator_observers([
6043                            observer.erase::<waft_widgets::AnyNavigatorObserver>()
6044                        ])
6045                        .home(home)
6046                        .into_widget();
6047                    drop(app);
6048                    tester.pump_widget(root);
6049                }
6050
6051                // Open the dialog.
6052                let button = tester.element(find::by_type::<ElevatedButton>().at(0));
6053                let center = tester.get_center(button);
6054                tester.tap_at(center, 1);
6055                tester.pump_and_settle();
6056                assert_eq!(
6057                    tester.cell.borrow().get(&observer).date_picker_count.get(),
6058                    1
6059                );
6060
6061                // Tap on the barrier, which shouldn't do anything this time.
6062                tester.tap_at(Offset::new(10.0, 10.0), 1);
6063                tester.pump_and_settle();
6064                assert_eq!(
6065                    tester.cell.borrow().get(&observer).date_picker_count.get(),
6066                    1
6067                );
6068            });
6069        }
6070
6071        fn last_modal_barrier<R>(
6072            tester: &WidgetTester,
6073            read: impl FnOnce(&ModalBarrier) -> R,
6074        ) -> R {
6075            let barrier = *find::by_type::<ModalBarrier>()
6076                .evaluate(tester)
6077                .last()
6078                .expect("a ModalBarrier");
6079            tester.widget(barrier, read)
6080        }
6081
6082        #[test]
6083        fn barrier_color() {
6084            test_widgets(|tester| {
6085                let mut show = Show::new();
6086                show.builder = Some(sized_box_builder());
6087                open_app(tester, true, "X", show.clone());
6088
6089                // Open the dialog.
6090                tester.tap(find::text("X"));
6091                tester.pump_and_settle();
6092                assert_eq!(
6093                    last_modal_barrier(tester, |barrier| barrier.color),
6094                    Some(Colors::BLACK54)
6095                );
6096
6097                // Dismiss the dialog.
6098                tester.tap_at(Offset::new(10.0, 10.0), 1);
6099
6100                show.barrier_color = Some(Colors::PINK.primary());
6101                open_app(tester, true, "X", show);
6102
6103                // Open the dialog.
6104                tester.tap(find::text("X"));
6105                tester.pump_and_settle();
6106                assert_eq!(
6107                    last_modal_barrier(tester, |barrier| barrier.color),
6108                    Some(Colors::PINK.primary())
6109                );
6110            });
6111        }
6112
6113        #[test]
6114        fn barrier_label() {
6115            test_widgets(|tester| {
6116                let mut show = Show::new();
6117                show.builder = Some(sized_box_builder());
6118                show.barrier_label = Some("Custom Label".to_string());
6119                open_app(tester, true, "X", show);
6120
6121                // Open the dialog.
6122                tester.tap(find::text("X"));
6123                tester.pump_and_settle();
6124                assert_eq!(
6125                    last_modal_barrier(tester, |barrier| barrier.semantics_label.clone()),
6126                    Some("Custom Label".to_string())
6127                );
6128            });
6129        }
6130
6131        #[test]
6132        fn uses_nested_navigator_if_use_root_navigator_is_false() {
6133            test_widgets(|tester| {
6134                let (root_observer, nested_observer) = {
6135                    let mut app = tester.cell.borrow_mut();
6136                    (
6137                        app.create(DatePickerObserver::default()),
6138                        app.create(DatePickerObserver::default()),
6139                    )
6140                };
6141                let root = {
6142                    let app = tester.cell.borrow();
6143                    crate::app::MaterialApp::new()
6144                        .theme(m3(&app))
6145                        .navigator_observers([
6146                            root_observer.erase::<waft_widgets::AnyNavigatorObserver>()
6147                        ])
6148                        .home(
6149                            waft_widgets::Navigator::new()
6150                                .observers([
6151                                    nested_observer.erase::<waft_widgets::AnyNavigatorObserver>()
6152                                ])
6153                                .on_generate_route(move |app, _settings| {
6154                                    let route = crate::page::MaterialPageRoute::new(
6155                                        app,
6156                                        Rc::new(move |_app, context| {
6157                                            let mut show = Show::new();
6158                                            show.builder = Some(sized_box_builder());
6159                                            show.use_root_navigator = false;
6160                                            ElevatedButton::new(
6161                                                Some(Listener::new(move |app| {
6162                                                    drop(show.show(app, context));
6163                                                })),
6164                                                Some(Text::new("Show Date Picker")),
6165                                            )
6166                                            .into_widget()
6167                                        }),
6168                                    );
6169                                    Some(route.erase())
6170                                }),
6171                        )
6172                        .into_widget()
6173                };
6174                tester.pump_widget(root);
6175
6176                // Open the dialog.
6177                let button = tester.element(find::by_type::<ElevatedButton>().at(0));
6178                let center = tester.get_center(button);
6179                tester.tap_at(center, 1);
6180
6181                let app = tester.cell.borrow();
6182                assert_eq!(app.get(&root_observer).date_picker_count.get(), 0);
6183                assert_eq!(app.get(&nested_observer).date_picker_count.get(), 1);
6184            });
6185        }
6186
6187        #[test]
6188        fn honors_dialog_theme_for_shape_and_elevation() {
6189            test_widgets(|tester| {
6190                // Test that the defaults work
6191                open_app(tester, false, "X", Show::new());
6192                tester.tap(find::text("X"));
6193                tester.pump_and_settle();
6194                let (shape, elevation) = tester
6195                    .widget(dialog_material(tester), |material: &Material| {
6196                        (material.shape.clone(), material.elevation)
6197                    });
6198                assert_eq!(shape, Some(rounded(4.0)));
6199                assert_eq!(elevation, 24.0);
6200
6201                // Test that it honors ThemeData.dialogTheme settings
6202                let custom_dialog_theme = crate::dialog_theme::DialogThemeData::new()
6203                    .shape(RoundedRectangleBorder::new(
6204                        BorderSide::NONE,
6205                        BorderRadiusGeometry::circular(40.0),
6206                    ))
6207                    .elevation(50.0);
6208                let theme = ThemeData::fallback(&tester.cell.borrow(), Some(false))
6209                    .copy_with()
6210                    .dialog_theme(custom_dialog_theme.clone())
6211                    .build();
6212                open_app_with_theme(tester, theme, "X", Show::new());
6213                tester.pump(); // start theme animation
6214                tester.pump_by(std::time::Duration::from_secs(5)); // end theme animation
6215                let (shape, elevation) = tester
6216                    .widget(dialog_material(tester), |material: &Material| {
6217                        (material.shape.clone(), material.elevation)
6218                    });
6219                assert_eq!(shape, custom_dialog_theme.shape.clone());
6220                assert_eq!(Some(elevation), custom_dialog_theme.elevation);
6221            });
6222        }
6223
6224        fn text_button_of(tester: &WidgetTester, text: &str) -> AnyElement {
6225            tester.element(
6226                find::ancestor(
6227                    find::text(text),
6228                    find::by_type::<crate::text_button::TextButton>(),
6229                )
6230                .first(),
6231            )
6232        }
6233
6234        fn animated_container(tester: &WidgetTester) -> AnyElement {
6235            tester.element(find::by_type::<waft_widgets::AnimatedContainer>().at(0))
6236        }
6237
6238        fn pump_icon_app(
6239            tester: &mut WidgetTester,
6240            material3: bool,
6241            initial_entry_mode: DatePickerEntryMode,
6242            switch_to_input_entry_mode_icon: Option<fn() -> Icon>,
6243            switch_to_calendar_entry_mode_icon: Option<fn() -> Icon>,
6244        ) {
6245            let mut show = Show::new();
6246            show.initial_entry_mode = initial_entry_mode;
6247            show.switch_to_input_entry_mode_icon = switch_to_input_entry_mode_icon;
6248            show.switch_to_calendar_entry_mode_icon = switch_to_calendar_entry_mode_icon;
6249            open_app(tester, material3, "Click X", show);
6250            tester.pump_and_settle();
6251            let button = tester.element(find::by_type::<ElevatedButton>().at(0));
6252            let center = tester.get_center(button);
6253            tester.tap_at(center, 1);
6254            tester.pump_and_settle();
6255        }
6256
6257        fn dismiss_with_ok(tester: &mut WidgetTester) {
6258            tester.tap(find::text("OK"));
6259            tester.pump_and_settle();
6260        }
6261
6262        #[test]
6263        fn honors_switch_to_input_entry_mode_icon() {
6264            test_widgets(|tester| {
6265                pump_icon_app(tester, false, DatePickerEntryMode::Calendar, None, None);
6266                assert_eq!(find::by_icon(&Icons::edit()).evaluate(tester).len(), 1);
6267                dismiss_with_ok(tester);
6268
6269                pump_icon_app(tester, true, DatePickerEntryMode::Calendar, None, None);
6270                assert_eq!(
6271                    find::by_icon(&Icons::edit_outlined())
6272                        .evaluate(tester)
6273                        .len(),
6274                    1
6275                );
6276                dismiss_with_ok(tester);
6277
6278                pump_icon_app(
6279                    tester,
6280                    false,
6281                    DatePickerEntryMode::Calendar,
6282                    Some(|| Icon::new(Some(Icons::keyboard()))),
6283                    None,
6284                );
6285                assert_eq!(find::by_icon(&Icons::keyboard()).evaluate(tester).len(), 1);
6286                dismiss_with_ok(tester);
6287            });
6288        }
6289
6290        #[test]
6291        fn honors_switch_to_calendar_entry_mode_icon() {
6292            test_widgets(|tester| {
6293                pump_icon_app(tester, false, DatePickerEntryMode::Input, None, None);
6294                assert_eq!(
6295                    find::by_icon(&Icons::calendar_today())
6296                        .evaluate(tester)
6297                        .len(),
6298                    1
6299                );
6300                dismiss_with_ok(tester);
6301
6302                pump_icon_app(tester, true, DatePickerEntryMode::Input, None, None);
6303                assert_eq!(
6304                    find::by_icon(&Icons::calendar_today())
6305                        .evaluate(tester)
6306                        .len(),
6307                    1
6308                );
6309                dismiss_with_ok(tester);
6310
6311                pump_icon_app(
6312                    tester,
6313                    false,
6314                    DatePickerEntryMode::Input,
6315                    None,
6316                    Some(|| Icon::new(Some(Icons::favorite()))),
6317                );
6318                assert_eq!(find::by_icon(&Icons::favorite()).evaluate(tester).len(), 1);
6319                dismiss_with_ok(tester);
6320            });
6321        }
6322
6323        fn ok_cancel_positions(tester: &WidgetTester) -> (f64, f64, f64) {
6324            (
6325                tester.get_rect(find::text("OK")).right,
6326                tester.get_rect(find::text("OK")).left,
6327                tester.get_rect(find::text("CANCEL")).right,
6328            )
6329        }
6330
6331        #[test]
6332        fn ok_cancel_button_layout() {
6333            test_widgets(|tester| {
6334                let build_frame = |tester: &mut WidgetTester, text_direction: TextDirection| {
6335                    let mut show = Show::new();
6336                    show.builder = Some(directionality_builder(text_direction));
6337                    let mut options = show;
6338                    options.initial_entry_mode = DatePickerEntryMode::Calendar;
6339                    open_app(tester, false, "X", options);
6340                };
6341                let show_and_read = |tester: &mut WidgetTester, text_direction: TextDirection| {
6342                    build_frame(tester, text_direction);
6343                    tester.tap(find::text("X"));
6344                    tester.pump_and_settle();
6345                    let positions = ok_cancel_positions(tester);
6346                    tester.tap(find::text("OK"));
6347                    tester.pump_and_settle();
6348                    positions
6349                };
6350
6351                // Default landscape layout.
6352                assert_eq!(
6353                    show_and_read(tester, TextDirection::Ltr),
6354                    (622.0, 594.0, 560.0)
6355                );
6356                assert_eq!(
6357                    show_and_read(tester, TextDirection::Rtl),
6358                    (206.0, 178.0, 324.0)
6359                );
6360
6361                // Portrait layout.
6362                tester.view().set_physical_size(Size::new(900.0, 1200.0));
6363                assert_eq!(
6364                    show_and_read(tester, TextDirection::Ltr),
6365                    (258.0, 230.0, 196.0)
6366                );
6367                assert_eq!(
6368                    show_and_read(tester, TextDirection::Rtl),
6369                    (70.0, 42.0, 188.0)
6370                );
6371            });
6372        }
6373
6374        fn month_button_present(tester: &WidgetTester, prefix: &str) -> bool {
6375            find::by_type::<crate::icon_button::IconButton>()
6376                .evaluate(tester)
6377                .into_iter()
6378                .any(|button| {
6379                    tester
6380                        .widget(button, |button: &crate::icon_button::IconButton| {
6381                            button.tooltip.clone()
6382                        })
6383                        .is_some_and(|tooltip| tooltip.starts_with(prefix))
6384                })
6385        }
6386
6387        fn tap_next_month(tester: &mut WidgetTester) {
6388            crate::calendar_date_picker::tests::tap_month_button(tester, "Next month");
6389            tester.pump_and_settle();
6390        }
6391
6392        fn tap_previous_month(tester: &mut WidgetTester) {
6393            crate::calendar_date_picker::tests::tap_month_button(tester, "Previous month");
6394            tester.pump_and_settle();
6395        }
6396
6397        /// Prepares the picker, runs `steps` and taps OK: what the picker completes with.
6398        fn pick(
6399            tester: &mut WidgetTester,
6400            options: DatePickerOptions,
6401            steps: impl FnOnce(&mut WidgetTester),
6402        ) -> Option<DateTime> {
6403            let result = prepare_date_picker(tester, &options);
6404            steps(tester);
6405            tester.tap(find::text("OK"));
6406            tester.pump_and_settle();
6407            picked_date(&result)
6408        }
6409
6410        fn prepared(
6411            tester: &mut WidgetTester,
6412            options: &DatePickerOptions,
6413            steps: impl FnOnce(&mut WidgetTester),
6414        ) {
6415            prepare_date_picker(tester, options);
6416            steps(tester);
6417        }
6418
6419        fn pump_zero(tester: &mut WidgetTester) {
6420            tester.pump();
6421        }
6422
6423        #[test]
6424        fn can_select_a_month() {
6425            test_widgets(|tester| {
6426                let date = pick(tester, DatePickerOptions::new(), |tester| {
6427                    tap_previous_month(tester);
6428                    tester.tap(find::text("25"));
6429                });
6430                assert_eq!(date, Some(local_date(2015, 12, 25)));
6431            });
6432        }
6433
6434        #[test]
6435        fn can_select_a_year() {
6436            test_widgets(|tester| {
6437                prepared(tester, &DatePickerOptions::new(), |tester| {
6438                    tester.tap(find::text("January 2016")); // Switch to year mode.
6439                    pump_zero(tester);
6440                    tester.tap(find::text("2018"));
6441                    pump_zero(tester);
6442                    expect(tester, &find::text("January 2018"), finds_one_widget());
6443                });
6444            });
6445        }
6446
6447        #[test]
6448        fn can_select_a_month_with_no_initial_date() {
6449            test_widgets(|tester| {
6450                let mut options = DatePickerOptions::new();
6451                options.initial_date = None;
6452                let date = pick(tester, options, |tester| {
6453                    tap_previous_month(tester);
6454                    tester.tap(find::text("25"));
6455                });
6456                assert_eq!(date, Some(local_date(2015, 12, 25)));
6457            });
6458        }
6459
6460        #[test]
6461        fn can_select_a_year_with_no_initial_date() {
6462            test_widgets(|tester| {
6463                let mut options = DatePickerOptions::new();
6464                options.initial_date = None;
6465                prepared(tester, &options, |tester| {
6466                    tester.tap(find::text("January 2016")); // Switch to year mode.
6467                    pump_zero(tester);
6468                    tester.tap(find::text("2018"));
6469                    pump_zero(tester);
6470                    expect(tester, &find::text("January 2018"), finds_one_widget());
6471                });
6472            });
6473        }
6474
6475        #[test]
6476        fn selecting_date_does_not_change_displayed_month() {
6477            test_widgets(|tester| {
6478                let mut options = DatePickerOptions::new();
6479                options.initial_date = Some(local_date(2020, 3, 15));
6480                prepared(tester, &options, |tester| {
6481                    tap_next_month(tester);
6482                    expect(tester, &find::text("April 2020"), finds_one_widget());
6483                    tester.tap(find::text("25"));
6484                    tester.pump_and_settle();
6485                    expect(tester, &find::text("April 2020"), finds_one_widget());
6486                    // There isn't a 31 in April so there shouldn't be one if it is showing April
6487                    expect(tester, &find::text("31"), finds_nothing());
6488                });
6489            });
6490        }
6491
6492        #[test]
6493        fn changing_year_does_change_selected_date() {
6494            test_widgets(|tester| {
6495                let date = pick(tester, DatePickerOptions::new(), |tester| {
6496                    tester.tap(find::text("January 2016"));
6497                    pump_zero(tester);
6498                    tester.tap(find::text("2018"));
6499                    pump_zero(tester);
6500                });
6501                assert_eq!(date, Some(local_date(2018, 1, 15)));
6502            });
6503        }
6504
6505        #[test]
6506        fn changing_year_does_not_change_the_month() {
6507            test_widgets(|tester| {
6508                prepared(tester, &DatePickerOptions::new(), |tester| {
6509                    tap_next_month(tester);
6510                    tap_next_month(tester);
6511                    tester.tap(find::text("March 2016"));
6512                    tester.pump_and_settle();
6513                    tester.tap(find::text("2018"));
6514                    tester.pump_and_settle();
6515                    expect(tester, &find::text("March 2018"), finds_one_widget());
6516                });
6517            });
6518        }
6519
6520        #[test]
6521        fn can_select_a_year_and_then_a_day() {
6522            test_widgets(|tester| {
6523                let date = pick(tester, DatePickerOptions::new(), |tester| {
6524                    tester.tap(find::text("January 2016")); // Switch to year mode.
6525                    pump_zero(tester);
6526                    tester.tap(find::text("2017"));
6527                    pump_zero(tester);
6528                    tester.tap(find::text("19"));
6529                });
6530                assert_eq!(date, Some(local_date(2017, 1, 19)));
6531            });
6532        }
6533
6534        #[test]
6535        fn current_year_is_visible_in_year_picker() {
6536            test_widgets(|tester| {
6537                prepared(tester, &DatePickerOptions::new(), |tester| {
6538                    tester.tap(find::text("January 2016")); // Switch to year mode.
6539                    pump_zero(tester);
6540                    expect(tester, &find::text("2016"), finds_one_widget());
6541                });
6542            });
6543        }
6544
6545        #[test]
6546        fn cannot_select_a_day_outside_bounds() {
6547            test_widgets(|tester| {
6548                let mut options = DatePickerOptions::new();
6549                let initial = local_date(2017, 1, 15);
6550                options.initial_date = Some(initial);
6551                options.first_date = initial;
6552                options.last_date = initial;
6553                let date = pick(tester, options, |tester| {
6554                    // Earlier than firstDate. Should be ignored.
6555                    tester.tap(find::text("10"));
6556                    // Later than lastDate. Should be ignored.
6557                    tester.tap(find::text("20"));
6558                });
6559                // We should still be on the initial date.
6560                assert_eq!(date, Some(initial));
6561            });
6562        }
6563
6564        #[test]
6565        fn cannot_select_a_month_past_last_date() {
6566            test_widgets(|tester| {
6567                let mut options = DatePickerOptions::new();
6568                options.initial_date = Some(local_date(2017, 1, 15));
6569                options.first_date = local_date(2017, 1, 15);
6570                options.last_date = local_date(2017, 2, 20);
6571                prepared(tester, &options, |tester| {
6572                    tap_next_month(tester);
6573                    // Shouldn't be possible to keep going into March.
6574                    assert!(!month_button_present(tester, "Next month"));
6575                });
6576            });
6577        }
6578
6579        #[test]
6580        fn cannot_select_a_month_before_first_date() {
6581            test_widgets(|tester| {
6582                let mut options = DatePickerOptions::new();
6583                options.initial_date = Some(local_date(2017, 1, 15));
6584                options.first_date = local_date(2016, 12, 10);
6585                options.last_date = local_date(2017, 1, 15);
6586                prepared(tester, &options, |tester| {
6587                    tap_previous_month(tester);
6588                    // Shouldn't be possible to keep going into November.
6589                    assert!(!month_button_present(tester, "Previous month"));
6590                });
6591            });
6592        }
6593
6594        #[test]
6595        fn cannot_select_disabled_year() {
6596            test_widgets(|tester| {
6597                let mut options = DatePickerOptions::new();
6598                options.initial_date = Some(local_date(2018, 7, 4));
6599                options.first_date = local_date(2018, 6, 9);
6600                options.last_date = local_date(2018, 12, 15);
6601                let date = pick(tester, options, |tester| {
6602                    tester.tap(find::text("July 2018")); // Switch to year mode.
6603                    tester.pump_and_settle();
6604                    tester.tap(find::text("2016")); // Disabled, doesn't change the year.
6605                    tester.pump_and_settle();
6606                });
6607                assert_eq!(date, Some(local_date(2018, 7, 4)));
6608            });
6609        }
6610
6611        #[test]
6612        fn selecting_first_date_year_respects_first_date() {
6613            test_widgets(|tester| {
6614                let mut options = DatePickerOptions::new();
6615                options.initial_date = Some(local_date(2018, 5, 4));
6616                options.first_date = local_date(2016, 6, 9);
6617                options.last_date = local_date(2019, 1, 15);
6618                prepared(tester, &options, |tester| {
6619                    tester.tap(find::text("May 2018"));
6620                    tester.pump_and_settle();
6621                    tester.tap(find::text("2016"));
6622                    tester.pump_and_settle();
6623                    // Month should be clamped to June as the range starts at June 2016
6624                    expect(tester, &find::text("June 2016"), finds_one_widget());
6625                });
6626            });
6627        }
6628
6629        #[test]
6630        fn selecting_last_date_year_respects_last_date() {
6631            test_widgets(|tester| {
6632                let mut options = DatePickerOptions::new();
6633                options.initial_date = Some(local_date(2018, 5, 4));
6634                options.first_date = local_date(2016, 6, 9);
6635                options.last_date = local_date(2019, 1, 15);
6636                prepared(tester, &options, |tester| {
6637                    tester.tap(find::text("May 2018"));
6638                    tester.pump_and_settle();
6639                    tester.tap(find::text("2019"));
6640                    tester.pump_and_settle();
6641                    // Month should be clamped to January as the range ends at January 2019
6642                    expect(tester, &find::text("January 2019"), finds_one_widget());
6643                });
6644            });
6645        }
6646
6647        #[test]
6648        fn can_select_initial_calendar_picker_mode() {
6649            test_widgets(|tester| {
6650                let mut options = DatePickerOptions::new();
6651                options.initial_date = Some(local_date(2014, 1, 15));
6652                options.initial_calendar_mode = DatePickerMode::Year;
6653                prepared(tester, &options, |tester| {
6654                    pump_zero(tester);
6655                    // 2018 wouldn't be available if the year picker wasn't showing.
6656                    // The initial current year is 2014.
6657                    tester.tap(find::text("2018"));
6658                    pump_zero(tester);
6659                    expect(tester, &find::text("January 2018"), finds_one_widget());
6660                });
6661            });
6662        }
6663
6664        /// Dart's `findDayGridMaterial`: what the Material all days paint on paints, found from an
6665        /// arbitrary day.
6666        fn day_grid_material_ops(tester: &WidgetTester) -> Vec<waft_embedder::valo::Op> {
6667            tester.nearest_material_ops(find::text("17").evaluate(tester)[0])
6668        }
6669
6670        /// Dart's `findDayDecoration(tester, day).color`.
6671        fn day_decoration_color(tester: &WidgetTester, day: &str) -> Option<waft_embedder::Color> {
6672            let ink = tester.element(
6673                find::ancestor(
6674                    find::text(day),
6675                    find::by_type::<crate::ink_decoration::Ink>(),
6676                )
6677                .first(),
6678            );
6679            tester.widget(ink, |ink: &crate::ink_decoration::Ink| {
6680                ink.decoration
6681                    .as_deref()
6682                    .and_then(|decoration| {
6683                        decoration
6684                            .as_any()
6685                            .downcast_ref::<waft_painting::ShapeDecoration>()
6686                    })
6687                    .and_then(|decoration| decoration.color.as_ref())
6688                    .map(|color| color.color())
6689            })
6690        }
6691
6692        fn pump_picker_with(tester: &mut WidgetTester, use_material3: bool) {
6693            let mut options = DatePickerOptions::new();
6694            options.use_material3 = use_material3;
6695            prepare_date_picker(tester, &options);
6696        }
6697
6698        fn theme_of(tester: &WidgetTester, use_material3: bool) -> ThemeData {
6699            if use_material3 {
6700                m3(&tester.cell.borrow())
6701            } else {
6702                m2(&tester.cell.borrow())
6703            }
6704        }
6705
6706        /// Asserts Dart's `paints..circle()..circle()[..circle()]..circle(color: overlay)`: today's
6707        /// outline, the selected day, (when pressed, the hover highlight,) then the overlay.
6708        fn assert_day_overlay(tester: &WidgetTester, pressed: bool, overlay: waft_embedder::Color) {
6709            let mut calls = vec![PaintCall::circle(None), PaintCall::circle(None)];
6710            if pressed {
6711                calls.push(PaintCall::circle(None));
6712            }
6713            calls.push(PaintCall::circle(Some(overlay)));
6714            assert!(
6715                paints(&day_grid_material_ops(tester), &calls).is_ok(),
6716                "the day grid's Material does not paint {calls:?}"
6717            );
6718        }
6719
6720        fn hover_day_30(tester: &mut WidgetTester) {
6721            let center = tester.get_center(find::text("30").evaluate(tester)[0]);
6722            let mut pointer = TestPointer::mouse(1, 1);
6723            tester.add_pointer(&mut pointer, Offset::ZERO);
6724            tester.move_to(&mut pointer, center, false);
6725            tester.pump_and_settle();
6726        }
6727
6728        fn press_day_30(tester: &mut WidgetTester) -> TestPointer {
6729            let center = tester.get_center(find::text("30").evaluate(tester)[0]);
6730            let mut pointer = TestPointer::mouse(1, 1);
6731            tester.add_pointer(&mut pointer, Offset::ZERO);
6732            tester.down(&mut pointer, center);
6733            tester.pump_and_settle();
6734            pointer
6735        }
6736
6737        fn select_day_30(tester: &mut WidgetTester, theme: &ThemeData) {
6738            tester.tap(find::text("30"));
6739            tester.pump_and_settle();
6740            assert_eq!(
6741                day_decoration_color(tester, "30"),
6742                Some(theme.color_scheme.primary())
6743            );
6744        }
6745
6746        #[test]
6747        fn current_date_is_highlighted() {
6748            test_widgets(|tester| {
6749                let mut options = DatePickerOptions::new();
6750                options.today = local_date(2016, 1, 2);
6751                prepare_date_picker(tester, &options);
6752                pump_zero(tester);
6753                let today_color = waft_embedder::Color::new(0xff2196f3); // default primary color
6754                // The current day should be painted with a circle outline.
6755                assert_paints(
6756                    &day_grid_material_ops(tester),
6757                    &[PaintCall::stroked_circle(today_color, 1.0)],
6758                );
6759            });
6760        }
6761
6762        #[allow(deprecated)]
6763        fn day_overlay_hovered(tester: &mut WidgetTester, use_material3: bool) {
6764            pump_picker_with(tester, use_material3);
6765            let theme = theme_of(tester, use_material3);
6766            hover_day_30(tester);
6767            assert_day_overlay(
6768                tester,
6769                false,
6770                theme.color_scheme.on_surface_variant().with_opacity(0.08),
6771            );
6772        }
6773
6774        #[allow(deprecated)]
6775        fn day_overlay_focused(tester: &mut WidgetTester, use_material3: bool, opacity: f64) {
6776            pump_picker_with(tester, use_material3);
6777            tester.set_highlight_strategy(waft_widgets::FocusHighlightStrategy::AlwaysTraditional);
6778            let theme = theme_of(tester, use_material3);
6779            // Navigate to the grid.
6780            tabs(tester, 4);
6781            // Navigate to day 30.
6782            for (physical, logical) in [
6783                (
6784                    PhysicalKeyboardKey::ARROW_DOWN,
6785                    LogicalKeyboardKey::ARROW_DOWN,
6786                ),
6787                (
6788                    PhysicalKeyboardKey::ARROW_DOWN,
6789                    LogicalKeyboardKey::ARROW_DOWN,
6790                ),
6791                (
6792                    PhysicalKeyboardKey::ARROW_RIGHT,
6793                    LogicalKeyboardKey::ARROW_RIGHT,
6794                ),
6795            ] {
6796                press(tester, physical, logical);
6797            }
6798            tester.pump_and_settle();
6799            assert_day_overlay(
6800                tester,
6801                false,
6802                theme
6803                    .color_scheme
6804                    .on_surface_variant()
6805                    .with_opacity(opacity),
6806            );
6807        }
6808
6809        #[allow(deprecated)]
6810        fn day_overlay_pressed(tester: &mut WidgetTester, use_material3: bool, opacity: f64) {
6811            pump_picker_with(tester, use_material3);
6812            let theme = theme_of(tester, use_material3);
6813            let pointer = press_day_30(tester);
6814            assert_day_overlay(
6815                tester,
6816                true,
6817                theme
6818                    .color_scheme
6819                    .on_surface_variant()
6820                    .with_opacity(opacity),
6821            );
6822            tester.up(&pointer);
6823        }
6824
6825        #[allow(deprecated)]
6826        fn day_overlay_selected_and_hovered(tester: &mut WidgetTester, use_material3: bool) {
6827            pump_picker_with(tester, use_material3);
6828            let theme = theme_of(tester, use_material3);
6829            select_day_30(tester, &theme);
6830            hover_day_30(tester);
6831            assert_day_overlay(
6832                tester,
6833                false,
6834                theme.color_scheme.on_primary().with_opacity(0.08),
6835            );
6836        }
6837
6838        #[allow(deprecated)]
6839        fn day_overlay_selected_and_focused(
6840            tester: &mut WidgetTester,
6841            use_material3: bool,
6842            opacity: f64,
6843        ) {
6844            pump_picker_with(tester, use_material3);
6845            tester.set_highlight_strategy(waft_widgets::FocusHighlightStrategy::AlwaysTraditional);
6846            let theme = theme_of(tester, use_material3);
6847            select_day_30(tester, &theme);
6848            // Navigate to the grid.
6849            tabs(tester, 4);
6850            tester.pump_and_settle();
6851            // Day 30 is selected and focused.
6852            assert_day_overlay(
6853                tester,
6854                false,
6855                theme.color_scheme.on_primary().with_opacity(opacity),
6856            );
6857        }
6858
6859        #[allow(deprecated)]
6860        fn day_overlay_selected_and_pressed(
6861            tester: &mut WidgetTester,
6862            use_material3: bool,
6863            opacity: f64,
6864        ) {
6865            pump_picker_with(tester, use_material3);
6866            let theme = theme_of(tester, use_material3);
6867            select_day_30(tester, &theme);
6868            let pointer = press_day_30(tester);
6869            assert_day_overlay(
6870                tester,
6871                true,
6872                theme.color_scheme.on_primary().with_opacity(opacity),
6873            );
6874            tester.up(&pointer);
6875        }
6876
6877        #[test]
6878        fn date_picker_day_overlay_color_resolves_hovered_state() {
6879            test_widgets(|tester| day_overlay_hovered(tester, true));
6880        }
6881
6882        #[test]
6883        fn date_picker_day_overlay_color_resolves_focused_state() {
6884            test_widgets(|tester| day_overlay_focused(tester, true, 0.10));
6885        }
6886
6887        #[test]
6888        fn date_picker_day_overlay_color_resolves_pressed_state() {
6889            test_widgets(|tester| day_overlay_pressed(tester, true, 0.10));
6890        }
6891
6892        // Regression test for https://github.com/flutter/flutter/issues/130586.
6893        #[test]
6894        fn date_picker_day_overlay_color_resolves_selected_and_hovered_state() {
6895            test_widgets(|tester| day_overlay_selected_and_hovered(tester, true));
6896        }
6897
6898        #[test]
6899        fn date_picker_day_overlay_color_resolves_selected_and_focused_state() {
6900            test_widgets(|tester| day_overlay_selected_and_focused(tester, true, 0.10));
6901        }
6902
6903        #[test]
6904        fn date_picker_day_overlay_color_resolves_selected_and_pressed_state() {
6905            test_widgets(|tester| day_overlay_selected_and_pressed(tester, true, 0.10));
6906        }
6907
6908        #[test]
6909        fn material2_date_picker_day_overlay_color_resolves_hovered_state() {
6910            test_widgets(|tester| day_overlay_hovered(tester, false));
6911        }
6912
6913        #[test]
6914        fn material2_date_picker_day_overlay_color_resolves_focused_state() {
6915            test_widgets(|tester| day_overlay_focused(tester, false, 0.12));
6916        }
6917
6918        #[test]
6919        fn material2_date_picker_day_overlay_color_resolves_pressed_state() {
6920            test_widgets(|tester| day_overlay_pressed(tester, false, 0.12));
6921        }
6922
6923        #[test]
6924        fn material2_date_picker_day_overlay_color_resolves_selected_and_hovered_state() {
6925            test_widgets(|tester| day_overlay_selected_and_hovered(tester, false));
6926        }
6927
6928        #[test]
6929        fn material2_date_picker_day_overlay_color_resolves_selected_and_focused_state() {
6930            test_widgets(|tester| day_overlay_selected_and_focused(tester, false, 0.12));
6931        }
6932
6933        #[test]
6934        fn material2_date_picker_day_overlay_color_resolves_selected_and_pressed_state() {
6935            test_widgets(|tester| day_overlay_selected_and_pressed(tester, false, 0.38));
6936        }
6937
6938        #[test]
6939        fn selecting_date_does_not_switch_picker_to_year_selection() {
6940            test_widgets(|tester| {
6941                let mut options = DatePickerOptions::new();
6942                options.initial_date = Some(local_date(2020, 5, 10));
6943                options.initial_calendar_mode = DatePickerMode::Year;
6944                prepared(tester, &options, |tester| {
6945                    pump_zero(tester);
6946                    tester.tap(find::text("2017"));
6947                    pump_zero(tester);
6948                    expect(tester, &find::text("May 2017"), finds_one_widget());
6949                    tester.tap(find::text("10"));
6950                    pump_zero(tester);
6951                    expect(tester, &find::text("May 2017"), finds_one_widget());
6952                    expect(tester, &find::text("2017"), finds_nothing());
6953                });
6954            });
6955        }
6956
6957        fn pump_dialog_m3(tester: &mut WidgetTester, dialog: DatePickerDialog) {
6958            let theme = m3(&tester.cell.borrow());
6959            tester.pump_widget(material_app(
6960                theme,
6961                Material::new().child(dialog).into_widget(),
6962            ));
6963        }
6964
6965        fn layout_dialog() -> DatePickerDialog {
6966            DatePickerDialog::new(local_date(2001, 1, 1), local_date(2031, 12, 31))
6967                .initial_date(local_date(2016, 1, 15))
6968        }
6969
6970        fn top_right(tester: &WidgetTester, element: AnyElement) -> Offset {
6971            let rect = tester.get_rect(element);
6972            Offset::new(rect.right, rect.top)
6973        }
6974
6975        #[test]
6976        fn default_calendar_mode_layout_landscape() {
6977            test_widgets(|tester| {
6978                tester.view().set_physical_size(Size::new(1920.0, 1080.0));
6979                pump_dialog_m3(tester, layout_dialog());
6980
6981                let help_text = tester.element(find::text("Select date"));
6982                let header_text = tester.element(find::text("Fri, Jan 15"));
6983                let sub_header_text = tester.element(find::text("January 2016"));
6984                expect(tester, &find::text("Cancel"), finds_one_widget());
6985                expect(tester, &find::text("OK"), finds_one_widget());
6986                let inset_padding = EdgeInsets::symmetric(24.0, 16.0);
6987
6988                // Test help text position.
6989                let container = animated_container(tester);
6990                let dialog_top_left = top_left(tester, container);
6991                let help_text_top_left = top_left(tester, help_text);
6992                assert_f32_equals(
6993                    help_text_top_left.dx(),
6994                    dialog_top_left.dx() + (inset_padding.horizontal() / 2.0),
6995                );
6996                assert_f32_equals(help_text_top_left.dy(), dialog_top_left.dy() + 16.0);
6997
6998                // Test header text position.
6999                let header_text_top_left = top_left(tester, header_text);
7000                let help_text_bottom_left = bottom_left(tester, help_text);
7001                assert_f32_equals(
7002                    header_text_top_left.dx(),
7003                    dialog_top_left.dx() + (inset_padding.horizontal() / 2.0),
7004                );
7005                assert_f32_equals(header_text_top_left.dy(), help_text_bottom_left.dy() + 16.0);
7006
7007                // Test switch button position.
7008                let switch_button = icon_button_of(tester, &Icons::edit_outlined());
7009                let switch_button_top_left = top_left(tester, switch_button);
7010                let switch_button_bottom_left = bottom_left(tester, switch_button);
7011                let header_text_bottom_left = bottom_left(tester, header_text);
7012                let dialog_bottom_left = bottom_left(tester, container);
7013                assert_f32_equals(switch_button_top_left.dx(), dialog_top_left.dx() + 8.0);
7014                assert_f32_equals(switch_button_top_left.dy(), header_text_bottom_left.dy());
7015                assert_f32_equals(switch_button_bottom_left.dx(), dialog_top_left.dx() + 8.0);
7016                assert_f32_equals(
7017                    switch_button_bottom_left.dy(),
7018                    dialog_bottom_left.dy() - 6.0,
7019                );
7020
7021                // Test vertical divider position.
7022                let divider =
7023                    tester.element(find::by_type::<crate::divider::VerticalDivider>().at(0));
7024                let divider_top_left = top_left(tester, divider);
7025                let header_text_top_right = top_right(tester, header_text);
7026                assert_f32_equals(divider_top_left.dx(), header_text_top_right.dx() + 16.0);
7027                assert_f32_equals(divider_top_left.dy(), dialog_top_left.dy());
7028
7029                // Test sub header text position.
7030                let sub_header_text_top_left = top_left(tester, sub_header_text);
7031                let divider_top_right = top_right(tester, divider);
7032                assert_f32_equals(sub_header_text_top_left.dx(), divider_top_right.dx() + 24.0);
7033                assert_f32_equals(sub_header_text_top_left.dy(), dialog_top_left.dy() + 16.0);
7034
7035                // Test sub header icon position.
7036                let sub_header_icon =
7037                    tester.element(find::by_icon(&Icons::arrow_drop_down()).first());
7038                let sub_header_icon_top_left = top_left(tester, sub_header_icon);
7039                let sub_header_text_top_right = top_right(tester, sub_header_text);
7040                assert_f32_equals(
7041                    sub_header_icon_top_left.dx(),
7042                    sub_header_text_top_right.dx(),
7043                );
7044                assert_f32_equals(sub_header_icon_top_left.dy(), dialog_top_left.dy() + 14.0);
7045
7046                // Test calendar page view position.
7047                let calendar_page_view =
7048                    tester.element(find::by_type::<waft_widgets::PageView>().at(0));
7049                let calendar_page_view_top_left = top_left(tester, calendar_page_view);
7050                let sub_header_text_bottom_left = bottom_left(tester, sub_header_text);
7051                assert_f32_equals(calendar_page_view_top_left.dx(), divider_top_right.dx());
7052                assert_f32_equals(
7053                    calendar_page_view_top_left.dy(),
7054                    sub_header_text_bottom_left.dy() + 16.0,
7055                );
7056
7057                // Test month navigation icons position.
7058                let previous_month_button = icon_button_of(tester, &Icons::chevron_left());
7059                let next_month_button = icon_button_of(tester, &Icons::chevron_right());
7060                let previous_month_button_top_right = top_right(tester, previous_month_button);
7061                let next_month_button_top_right = top_right(tester, next_month_button);
7062                let dialog_top_right = top_right(tester, container);
7063                assert_f32_equals(
7064                    next_month_button_top_right.dx(),
7065                    dialog_top_right.dx() - 4.0,
7066                );
7067                assert_f32_equals(
7068                    next_month_button_top_right.dy(),
7069                    dialog_top_right.dy() + 2.0,
7070                );
7071                assert_f32_equals(
7072                    previous_month_button_top_right.dx(),
7073                    next_month_button_top_right.dx() - 48.0,
7074                );
7075
7076                // Test action buttons position.
7077                let dialog_bottom_right = bottom_right(tester, container);
7078                let ok_button = text_button_of(tester, "OK");
7079                let cancel_button = text_button_of(tester, "Cancel");
7080                let ok_button_top_right = top_right(tester, ok_button);
7081                let cancel_button_top_right = top_right(tester, cancel_button);
7082                let calendar_page_view_bottom_right = bottom_right(tester, calendar_page_view);
7083                assert_f32_equals(ok_button_top_right.dx(), dialog_bottom_right.dx() - 8.0);
7084                assert_f32_equals(
7085                    ok_button_top_right.dy(),
7086                    calendar_page_view_bottom_right.dy() + 2.0,
7087                );
7088                let ok_button_top_left = top_left(tester, ok_button);
7089                assert_f32_equals(cancel_button_top_right.dx(), ok_button_top_left.dx() - 8.0);
7090            });
7091        }
7092
7093        #[test]
7094        fn default_calendar_mode_layout_portrait() {
7095            test_widgets(|tester| {
7096                tester.view().set_physical_size(Size::new(1070.0, 1770.0));
7097                pump_dialog_m3(tester, layout_dialog());
7098
7099                let help_text = tester.element(find::text("Select date"));
7100                let header_text = tester.element(find::text("Fri, Jan 15"));
7101                let sub_header_text = tester.element(find::text("January 2016"));
7102                expect(tester, &find::text("Cancel"), finds_one_widget());
7103                expect(tester, &find::text("OK"), finds_one_widget());
7104
7105                // Test help text position.
7106                let container = animated_container(tester);
7107                let dialog_top_left = top_left(tester, container);
7108                let help_text_top_left = top_left(tester, help_text);
7109                assert_f32_equals(help_text_top_left.dx(), dialog_top_left.dx() + 24.0);
7110                assert_f32_equals(help_text_top_left.dy(), dialog_top_left.dy() + 16.0);
7111
7112                // Test header text position
7113                let header_text_top_left = top_left(tester, header_text);
7114                let help_text_bottom_left = bottom_left(tester, help_text);
7115                assert_f32_equals(header_text_top_left.dx(), dialog_top_left.dx() + 24.0);
7116                assert_f32_equals(header_text_top_left.dy(), help_text_bottom_left.dy() + 28.0);
7117
7118                // Test switch button position.
7119                let switch_button = icon_button_of(tester, &Icons::edit_outlined());
7120                let switch_button_top_right = top_right(tester, switch_button);
7121                let dialog_top_right = top_right(tester, container);
7122                assert_f32_equals(switch_button_top_right.dx(), dialog_top_right.dx() - 12.0);
7123                assert_f32_equals(
7124                    switch_button_top_right.dy(),
7125                    header_text_top_left.dy() - 4.0,
7126                );
7127
7128                // Test horizontal divider position.
7129                let divider = tester.element(find::by_type::<crate::divider::Divider>().at(0));
7130                let divider_top_left = top_left(tester, divider);
7131                let header_text_bottom_left = bottom_left(tester, header_text);
7132                assert_f32_equals(divider_top_left.dx(), dialog_top_left.dx());
7133                assert_f32_equals(divider_top_left.dy(), header_text_bottom_left.dy() + 16.0);
7134
7135                // Test subHeaderText position.
7136                let sub_header_text_top_left = top_left(tester, sub_header_text);
7137                let divider_bottom_left = bottom_left(tester, divider);
7138                assert_f32_equals(sub_header_text_top_left.dx(), dialog_top_left.dx() + 24.0);
7139                assert_f32_equals(
7140                    sub_header_text_top_left.dy(),
7141                    divider_bottom_left.dy() + 16.0,
7142                );
7143
7144                // Test sub header icon position.
7145                let sub_header_icon =
7146                    tester.element(find::by_icon(&Icons::arrow_drop_down()).first());
7147                let sub_header_icon_top_left = top_left(tester, sub_header_icon);
7148                let sub_header_text_top_right = top_right(tester, sub_header_text);
7149                assert_f32_equals(
7150                    sub_header_icon_top_left.dx(),
7151                    sub_header_text_top_right.dx(),
7152                );
7153                assert_f32_equals(
7154                    sub_header_icon_top_left.dy(),
7155                    divider_bottom_left.dy() + 14.0,
7156                );
7157
7158                // Test month navigation icons position.
7159                let previous_month_button = icon_button_of(tester, &Icons::chevron_left());
7160                let next_month_button = icon_button_of(tester, &Icons::chevron_right());
7161                let previous_month_button_top_right = top_right(tester, previous_month_button);
7162                let next_month_button_top_right = top_right(tester, next_month_button);
7163                assert_f32_equals(
7164                    next_month_button_top_right.dx(),
7165                    dialog_top_right.dx() - 4.0,
7166                );
7167                assert_f32_equals(
7168                    next_month_button_top_right.dy(),
7169                    divider_bottom_left.dy() + 2.0,
7170                );
7171                assert_f32_equals(
7172                    previous_month_button_top_right.dx(),
7173                    next_month_button_top_right.dx() - 48.0,
7174                );
7175
7176                // Test calendar page view position.
7177                let calendar_page_view =
7178                    tester.element(find::by_type::<waft_widgets::PageView>().at(0));
7179                let calendar_page_view_top_left = top_left(tester, calendar_page_view);
7180                let sub_header_text_bottom_left = bottom_left(tester, sub_header_text);
7181                assert_f32_equals(calendar_page_view_top_left.dx(), dialog_top_left.dx());
7182                assert_f32_equals(
7183                    calendar_page_view_top_left.dy(),
7184                    sub_header_text_bottom_left.dy() + 16.0,
7185                );
7186
7187                // Test action buttons position.
7188                let dialog_bottom_right = bottom_right(tester, container);
7189                let ok_button = text_button_of(tester, "OK");
7190                let cancel_button = text_button_of(tester, "Cancel");
7191                let ok_button_top_right = top_right(tester, ok_button);
7192                let cancel_button_top_right = top_right(tester, cancel_button);
7193                let calendar_page_view_bottom_right = bottom_right(tester, calendar_page_view);
7194                let ok_button_top_left = top_left(tester, ok_button);
7195                assert_f32_equals(ok_button_top_right.dx(), dialog_bottom_right.dx() - 8.0);
7196                assert_f32_equals(
7197                    ok_button_top_right.dy(),
7198                    calendar_page_view_bottom_right.dy() + 2.0,
7199                );
7200                assert_f32_equals(cancel_button_top_right.dx(), ok_button_top_left.dx() - 8.0);
7201            });
7202        }
7203
7204        /// Dart's `TestCalendarDelegate` (a month of 21 or 28 days, the first on offset 1) and
7205        /// `_TestDateInputDelegate` (dates typed as `yyyymmdd`), each of which extends
7206        /// `GregorianCalendarDelegate`: everything they do not override forwards to it.
7207        #[derive(Debug)]
7208        pub(super) enum TestDelegate {
7209            Calendar,
7210            DateInput,
7211        }
7212
7213        impl CalendarDelegate for TestDelegate {
7214            fn now(&self, app: &App) -> DateTime {
7215                GregorianCalendarDelegate.now(app)
7216            }
7217
7218            fn date_only(&self, app: &App, date: &DateTime) -> DateTime {
7219                GregorianCalendarDelegate.date_only(app, date)
7220            }
7221
7222            fn month_delta(&self, app: &App, start_date: &DateTime, end_date: &DateTime) -> i32 {
7223                GregorianCalendarDelegate.month_delta(app, start_date, end_date)
7224            }
7225
7226            fn add_months_to_month_date(
7227                &self,
7228                app: &App,
7229                month_date: &DateTime,
7230                months_to_add: i32,
7231            ) -> DateTime {
7232                GregorianCalendarDelegate.add_months_to_month_date(app, month_date, months_to_add)
7233            }
7234
7235            fn add_days_to_date(&self, app: &App, date: &DateTime, days: i32) -> DateTime {
7236                GregorianCalendarDelegate.add_days_to_date(app, date, days)
7237            }
7238
7239            fn first_day_offset(
7240                &self,
7241                app: &App,
7242                year: i32,
7243                month: i32,
7244                localizations: &dyn MaterialLocalizations,
7245            ) -> i32 {
7246                match self {
7247                    TestDelegate::Calendar => 1,
7248                    TestDelegate::DateInput => {
7249                        GregorianCalendarDelegate.first_day_offset(app, year, month, localizations)
7250                    }
7251                }
7252            }
7253
7254            fn get_days_in_month(&self, year: i32, month: i32) -> i32 {
7255                match self {
7256                    TestDelegate::Calendar => {
7257                        if month % 2 == 0 {
7258                            21
7259                        } else {
7260                            28
7261                        }
7262                    }
7263                    TestDelegate::DateInput => {
7264                        GregorianCalendarDelegate.get_days_in_month(year, month)
7265                    }
7266                }
7267            }
7268
7269            fn get_month(&self, app: &App, year: i32, month: i32) -> DateTime {
7270                GregorianCalendarDelegate.get_month(app, year, month)
7271            }
7272
7273            fn get_day(&self, app: &App, year: i32, month: i32, day: i32) -> DateTime {
7274                GregorianCalendarDelegate.get_day(app, year, month, day)
7275            }
7276
7277            fn format_month_year(
7278                &self,
7279                app: &App,
7280                date: &DateTime,
7281                localizations: &dyn MaterialLocalizations,
7282            ) -> String {
7283                GregorianCalendarDelegate.format_month_year(app, date, localizations)
7284            }
7285
7286            fn format_medium_date(
7287                &self,
7288                app: &App,
7289                date: &DateTime,
7290                localizations: &dyn MaterialLocalizations,
7291            ) -> String {
7292                GregorianCalendarDelegate.format_medium_date(app, date, localizations)
7293            }
7294
7295            fn format_short_month_day(
7296                &self,
7297                app: &App,
7298                date: &DateTime,
7299                localizations: &dyn MaterialLocalizations,
7300            ) -> String {
7301                GregorianCalendarDelegate.format_short_month_day(app, date, localizations)
7302            }
7303
7304            fn format_short_date(
7305                &self,
7306                app: &App,
7307                date: &DateTime,
7308                localizations: &dyn MaterialLocalizations,
7309            ) -> String {
7310                GregorianCalendarDelegate.format_short_date(app, date, localizations)
7311            }
7312
7313            fn format_full_date(
7314                &self,
7315                app: &App,
7316                date: &DateTime,
7317                localizations: &dyn MaterialLocalizations,
7318            ) -> String {
7319                GregorianCalendarDelegate.format_full_date(app, date, localizations)
7320            }
7321
7322            fn format_compact_date(
7323                &self,
7324                app: &App,
7325                date: &DateTime,
7326                localizations: &dyn MaterialLocalizations,
7327            ) -> String {
7328                match self {
7329                    TestDelegate::Calendar => {
7330                        GregorianCalendarDelegate.format_compact_date(app, date, localizations)
7331                    }
7332                    TestDelegate::DateInput => {
7333                        format!(
7334                            "{:04}{:02}{:02}",
7335                            date.year(app),
7336                            date.month(app),
7337                            date.day(app)
7338                        )
7339                    }
7340                }
7341            }
7342
7343            fn parse_compact_date(
7344                &self,
7345                app: &App,
7346                input_string: Option<&str>,
7347                localizations: &dyn MaterialLocalizations,
7348            ) -> Option<DateTime> {
7349                match self {
7350                    TestDelegate::Calendar => GregorianCalendarDelegate.parse_compact_date(
7351                        app,
7352                        input_string,
7353                        localizations,
7354                    ),
7355                    TestDelegate::DateInput => {
7356                        let input = input_string.filter(|input| input.len() == 8)?;
7357                        let year: i32 = input.get(0..4)?.parse().ok()?;
7358                        let month: i32 = input.get(4..6)?.parse().ok()?;
7359                        let day: i32 = input.get(6..8)?.parse().ok()?;
7360                        let date = DateTime::new(app, year, month, day);
7361                        (date.year(app) == year && date.month(app) == month && date.day(app) == day)
7362                            .then_some(date)
7363                    }
7364                }
7365            }
7366
7367            fn date_help_text(&self, localizations: &dyn MaterialLocalizations) -> String {
7368                match self {
7369                    TestDelegate::Calendar => {
7370                        GregorianCalendarDelegate.date_help_text(localizations)
7371                    }
7372                    TestDelegate::DateInput => "yyyymmdd".to_string(),
7373                }
7374            }
7375
7376            fn keyboard_input_formatters(
7377                &self,
7378                _localizations: &dyn MaterialLocalizations,
7379            ) -> Option<Vec<waft_services::TextInputFormatterRef>> {
7380                match self {
7381                    TestDelegate::Calendar => None,
7382                    TestDelegate::DateInput => Some(vec![
7383                        waft_services::FilteringTextInputFormatter::digits_only(),
7384                        waft_services::TextInputFormatterRef(Rc::new(
7385                            waft_services::LengthLimitingTextInputFormatter::new(Some(8)),
7386                        )),
7387                    ]),
7388                }
7389            }
7390        }
7391
7392        #[test]
7393        fn keyboard_can_toggle_to_calendar_entry_mode() {
7394            test_widgets(|tester| {
7395                prepare_date_picker(tester, &DatePickerOptions::new());
7396                assert_eq!(text_field_count(tester), 0);
7397                // Navigate to the entry toggle button and activate it
7398                tabs(tester, 5);
7399                space(tester);
7400                tester.pump_and_settle();
7401                // Should be in the input mode
7402                assert_eq!(text_field_count(tester), 1);
7403            });
7404        }
7405
7406        #[test]
7407        fn keyboard_can_toggle_to_year_mode() {
7408            test_widgets(|tester| {
7409                prepare_date_picker(tester, &DatePickerOptions::new());
7410                expect(tester, &find::text("2016"), finds_nothing());
7411                // Navigate to the year selector and activate it
7412                tab(tester);
7413                space(tester);
7414                tester.pump_and_settle();
7415                // The years should be visible
7416                expect(tester, &find::text("2016"), finds_one_widget());
7417            });
7418        }
7419
7420        #[test]
7421        fn keyboard_can_navigate_next_previous_months() {
7422            test_widgets(|tester| {
7423                prepare_date_picker(tester, &DatePickerOptions::new());
7424                expect(tester, &find::text("January 2016"), finds_one_widget());
7425                // Navigate to the previous month button and activate it twice
7426                tabs(tester, 2);
7427                space(tester);
7428                tester.pump_and_settle();
7429                space(tester);
7430                tester.pump_and_settle();
7431                // Should be showing Nov 2015
7432                expect(tester, &find::text("November 2015"), finds_one_widget());
7433
7434                // Navigate to the next month button and activate it four times
7435                tab(tester);
7436                for _ in 0..4 {
7437                    space(tester);
7438                    tester.pump_and_settle();
7439                }
7440                // Should be on Mar 2016
7441                expect(tester, &find::text("March 2016"), finds_one_widget());
7442            });
7443        }
7444
7445        #[test]
7446        fn keyboard_can_navigate_date_grid_with_arrow_keys() {
7447            test_widgets(|tester| {
7448                let result = prepare_date_picker(tester, &DatePickerOptions::new());
7449                // Navigate to the grid
7450                tabs(tester, 4);
7451
7452                // Navigate from Jan 15 to Jan 18 with arrow keys
7453                arrows(
7454                    tester,
7455                    &[
7456                        Arrow::Left,
7457                        Arrow::Up,
7458                        Arrow::Left,
7459                        Arrow::Down,
7460                        Arrow::Down,
7461                        Arrow::Left,
7462                        Arrow::Left,
7463                    ],
7464                );
7465                tester.pump_and_settle();
7466
7467                // Activate it
7468                space(tester);
7469                tester.pump_and_settle();
7470
7471                // Navigate out of the grid and to the OK button
7472                tabs(tester, 3);
7473
7474                // Activate OK
7475                space(tester);
7476                tester.pump_and_settle();
7477
7478                // Should have selected Jan 18
7479                assert_eq!(picked_date(&result), Some(local_date(2016, 1, 18)));
7480            });
7481        }
7482
7483        #[test]
7484        fn keyboard_navigating_with_arrow_keys_scrolls_months() {
7485            test_widgets(|tester| {
7486                let result = prepare_date_picker(tester, &DatePickerOptions::new());
7487                // Navigate to the grid
7488                tabs(tester, 4);
7489                tester.pump_and_settle();
7490
7491                // Navigate from Jan 15 to Dec 31 with arrow keys
7492                arrows(tester, &[Arrow::Up, Arrow::Up, Arrow::Left]);
7493                tester.pump_and_settle();
7494
7495                // Should have scrolled to Dec 2015
7496                expect(tester, &find::text("December 2015"), finds_one_widget());
7497
7498                // Navigate from Dec 31 to Nov 26 with arrow keys
7499                arrows(tester, &[Arrow::Up; 5]);
7500                tester.pump_and_settle();
7501
7502                // Should have scrolled to Nov 2015
7503                expect(tester, &find::text("November 2015"), finds_one_widget());
7504
7505                // Activate it
7506                space(tester);
7507                tester.pump_and_settle();
7508
7509                // Navigate out of the grid and to the OK button
7510                tabs(tester, 3);
7511                tester.pump_and_settle();
7512
7513                // Activate OK
7514                space(tester);
7515                tester.pump_and_settle();
7516
7517                assert_eq!(picked_date(&result), Some(local_date(2015, 11, 26)));
7518            });
7519        }
7520
7521        #[test]
7522        fn keyboard_rtl_text_direction_reverses_the_horizontal_arrow_key_navigation() {
7523            test_widgets(|tester| {
7524                let mut options = DatePickerOptions::new();
7525                options.builder = Some(directionality_builder(TextDirection::Rtl));
7526                let result = prepare_date_picker(tester, &options);
7527                // Navigate to the grid
7528                tabs(tester, 4);
7529                tester.pump_and_settle();
7530
7531                // Navigate from Jan 15 to 19 with arrow keys
7532                arrows(
7533                    tester,
7534                    &[
7535                        Arrow::Right,
7536                        Arrow::Right,
7537                        Arrow::Right,
7538                        Arrow::Right,
7539                        Arrow::Down,
7540                        Arrow::Left,
7541                    ],
7542                );
7543                tester.pump_and_settle();
7544
7545                // Activate it
7546                space(tester);
7547                tester.pump_and_settle();
7548
7549                // Navigate out of the grid and to the OK button
7550                tabs(tester, 3);
7551                tester.pump_and_settle();
7552
7553                // Activate OK
7554                space(tester);
7555                tester.pump_and_settle();
7556
7557                assert_eq!(picked_date(&result), Some(local_date(2016, 1, 19)));
7558            });
7559        }
7560
7561        fn input_group_options() -> DatePickerOptions {
7562            let mut options = DatePickerOptions::new();
7563            options.first_date = local_date(2015, 1, 1);
7564            options.last_date = local_date(2017, 12, 31);
7565            options.initial_date = Some(local_date(2016, 1, 15));
7566            options.initial_entry_mode = DatePickerEntryMode::Input;
7567            options
7568        }
7569
7570        fn text_field_decoration(tester: &WidgetTester) -> crate::input_decorator::InputDecoration {
7571            let field = tester.element(find::by_type::<TextField>().at(0));
7572            tester.widget(field, |field: &TextField| {
7573                field.decoration.clone().expect("a decoration")
7574            })
7575        }
7576
7577        #[test]
7578        fn material3_input_mode_default_input_decoration() {
7579            test_widgets(|tester| {
7580                let mut options = input_group_options();
7581                options.use_material3 = true;
7582                prepare_date_picker(tester, &options);
7583                let decoration = text_field_decoration(tester);
7584                assert_eq!(
7585                    decoration.border,
7586                    Some(crate::input_border::InputBorderRef::new(
7587                        crate::input_border::OutlineInputBorder::default()
7588                    ))
7589                );
7590                assert_eq!(decoration.filled, Some(false));
7591                assert_eq!(decoration.hint_text.as_deref(), Some("mm/dd/yyyy"));
7592                assert_eq!(decoration.label_text.as_deref(), Some("Enter Date"));
7593                assert_eq!(decoration.error_text, None);
7594            });
7595        }
7596
7597        #[test]
7598        fn material2_input_mode_default_input_decoration() {
7599            test_widgets(|tester| {
7600                prepare_date_picker(tester, &input_group_options());
7601                let decoration = text_field_decoration(tester);
7602                assert_eq!(
7603                    decoration.border,
7604                    Some(crate::input_border::InputBorderRef::new(
7605                        crate::input_border::UnderlineInputBorder::default()
7606                    ))
7607                );
7608                assert_eq!(decoration.filled, Some(false));
7609                assert_eq!(decoration.hint_text.as_deref(), Some("mm/dd/yyyy"));
7610                assert_eq!(decoration.label_text.as_deref(), Some("Enter Date"));
7611                assert_eq!(decoration.error_text, None);
7612            });
7613        }
7614
7615        #[test]
7616        fn input_mode_keyboard_type_is_used() {
7617            test_widgets(|tester| {
7618                let mut options = input_group_options();
7619                options.keyboard_type = Some(TextInputType::TEXT);
7620                prepare_date_picker(tester, &options);
7621                let field = tester.element(find::by_type::<TextField>().at(0));
7622                let keyboard_type = tester.widget(field, |field: &TextField| field.keyboard_type);
7623                assert_eq!(keyboard_type, Some(TextInputType::TEXT));
7624            });
7625        }
7626
7627        #[test]
7628        fn input_mode_invalid_entered_text_shows_error_on_autovalidate() {
7629            test_widgets(|tester| {
7630                prepare_date_picker(tester, &input_group_options());
7631                tester.enter_text(find::by_type::<EditableText>().at(0), "");
7632
7633                // Enter some text to trigger autovalidate.
7634                tester.enter_text(find::by_type::<EditableText>().at(0), "xyz");
7635                tester.tap(find::text("OK"));
7636                tester.pump_and_settle();
7637
7638                // Invalid format validation error should be shown.
7639                expect(tester, &find::text("Invalid format."), finds_one_widget());
7640
7641                // Clear the text.
7642                tester.enter_text(find::by_type::<EditableText>().at(0), "");
7643
7644                // Enter an invalid date that is too long while autovalidate is still on.
7645                tester.enter_text(find::by_type::<EditableText>().at(0), "10/05/2023666777889");
7646                pump_zero(tester);
7647
7648                // Invalid format validation error should be shown.
7649                expect(tester, &find::text("Invalid format."), finds_one_widget());
7650            });
7651        }
7652
7653        #[test]
7654        fn landscape_input_only_date_picker_headers_use_headline_small_in_portrait() {
7655            test_widgets(|tester| {
7656                size_view(tester, Size::new(1070.0, 1770.0));
7657                let mut options = DatePickerOptions::new();
7658                options.initial_entry_mode = DatePickerEntryMode::Input;
7659                options.use_material3 = true;
7660                prepare_date_picker(tester, &options);
7661                assert_eq!(header_font_size(tester, "Fri, Jan 15"), Some(32.0));
7662                tester.tap(find::text("Cancel"));
7663                tester.pump_and_settle();
7664            });
7665        }
7666
7667        #[test]
7668        fn landscape_input_only_date_picker_headers_use_headline_small_in_landscape() {
7669            test_widgets(|tester| {
7670                size_view(tester, Size::new(1770.0, 1070.0));
7671                let mut options = DatePickerOptions::new();
7672                options.initial_entry_mode = DatePickerEntryMode::Input;
7673                options.use_material3 = true;
7674                prepare_date_picker(tester, &options);
7675                assert_eq!(header_font_size(tester, "Fri, Jan 15"), Some(24.0));
7676                tester.tap(find::text("Cancel"));
7677                tester.pump_and_settle();
7678            });
7679        }
7680
7681        /// A regression test for https://github.com/flutter/flutter/issues/131989.
7682        #[test]
7683        fn dialog_contents_do_not_overflow_when_resized_during_orientation_change() {
7684            test_widgets(|tester| {
7685                // Initial window size is wide for landscape mode.
7686                size_view(tester, WIDE_WINDOW_SIZE);
7687                let mut options = DatePickerOptions::new();
7688                options.use_material3 = true;
7689                prepare_date_picker(tester, &options);
7690                assert_eq!(
7691                    dialog_container_size(tester),
7692                    CALENDAR_LANDSCAPE_DIALOG_SIZE
7693                );
7694
7695                // Change window size to narrow for portrait mode.
7696                tester.view().set_physical_size(NARROW_WINDOW_SIZE);
7697                tester.pump();
7698                tester.pump_and_settle();
7699                assert_eq!(
7700                    dialog_container_size(tester),
7701                    CALENDAR_PORTRAIT_DIALOG_SIZE_M3
7702                );
7703            });
7704        }
7705
7706        /// A regression test for https://github.com/flutter/flutter/issues/140311.
7707        #[test]
7708        fn text_field_stays_visible_when_orientation_is_portrait_and_height_is_reduced() {
7709            test_widgets(|tester| {
7710                size_view(tester, Size::new(720.0, 1280.0));
7711                let mut options = DatePickerOptions::new();
7712                options.initial_entry_mode = DatePickerEntryMode::Input;
7713                options.use_material3 = true;
7714
7715                // Text field and header are visible by default.
7716                prepare_date_picker(tester, &options);
7717                expect(tester, &find::by_type::<TextField>(), finds_one_widget());
7718                expect(tester, &find::text("Select date"), finds_one_widget());
7719
7720                // Simulate the portait mode on a device with a small display when the virtual
7721                // keyboard is visible.
7722                tester.view().set_view_insets(waft_embedder::ViewPadding {
7723                    bottom: 1000.0,
7724                    ..waft_embedder::ViewPadding::ZERO
7725                });
7726                tester.pump_and_settle();
7727
7728                // Text field is visible and header is hidden.
7729                expect(tester, &find::by_type::<TextField>(), finds_one_widget());
7730                expect(tester, &find::text("Select date"), finds_nothing());
7731            });
7732        }
7733
7734        #[test]
7735        fn screen_configurations_show_and_close_the_picker_without_failing() {
7736            // Common screen size roughly based on a Pixel 1, and a small one based on a LG K130.
7737            for size in [
7738                Size::new(1070.0, 1770.0),
7739                Size::new(1770.0, 1070.0),
7740                Size::new(320.0, 521.0),
7741                Size::new(521.0, 320.0),
7742            ] {
7743                test_widgets(|tester| {
7744                    size_view(tester, size);
7745                    let result = prepare_date_picker(tester, &DatePickerOptions::new());
7746                    tester.tap(find::text("OK"));
7747                    tester.pump_and_settle();
7748                    assert_eq!(
7749                        picked_date(&result),
7750                        Some(local_date(2016, 1, 15)),
7751                        "{size:?}"
7752                    );
7753                });
7754            }
7755        }
7756        #[test]
7757        fn date_picker_dialog_with_updated_inset_padding() {
7758            test_widgets(|tester| {
7759                pump_dialog_m3(
7760                    tester,
7761                    layout_dialog().inset_padding(EdgeInsets::from_ltrb(10.0, 20.0, 30.0, 40.0)),
7762                );
7763                let dialog = tester.element(find::by_type::<Dialog>().at(0));
7764                let inset_padding = tester.widget(dialog, |dialog: &Dialog| dialog.inset_padding);
7765                assert_eq!(
7766                    inset_padding,
7767                    Some(EdgeInsets::from_ltrb(10.0, 20.0, 30.0, 40.0))
7768                );
7769            });
7770        }
7771
7772        #[test]
7773        fn date_picker_dialog_renders_at_zero_area() {
7774            test_widgets(|tester| {
7775                let theme = m3(&tester.cell.borrow());
7776                tester.pump_widget(material_app(
7777                    theme,
7778                    Center::new()
7779                        .child(SizedBox::shrink().child(DatePickerDialog::new(
7780                            local_date(2001, 1, 1),
7781                            local_date(2031, 12, 31),
7782                        )))
7783                        .into_widget(),
7784                ));
7785                let dialog = tester.element(find::by_type::<DatePickerDialog>().at(0));
7786                assert_eq!(tester.get_size(dialog), Size::new(0.0, 0.0));
7787            });
7788        }
7789
7790        fn last_day_text(tester: &WidgetTester) -> Option<String> {
7791            let inks = find::by_type::<crate::ink_decoration::Ink>().evaluate(tester);
7792            let day = find::by_type::<Text>()
7793                .evaluate(tester)
7794                .into_iter()
7795                .rfind(|text| {
7796                    tester
7797                        .ancestors(*text)
7798                        .iter()
7799                        .any(|ancestor| inks.contains(ancestor))
7800                })?;
7801            tester.widget(day, |text: &Text| text.data.clone())
7802        }
7803
7804        #[test]
7805        fn displays_calendar_based_on_the_calendar_delegate() {
7806            test_widgets(|tester| {
7807                pump_dialog_m3(
7808                    tester,
7809                    layout_dialog().calendar_delegate(Rc::new(TestDelegate::Calendar)),
7810                );
7811                let next_month_button = icon_button_of(tester, &Icons::chevron_right());
7812
7813                expect(tester, &find::text("January 2016"), finds_one_widget());
7814                assert_eq!(last_day_text(tester).as_deref(), Some("28"));
7815
7816                let center = tester.get_center(next_month_button);
7817                tester.tap_at(center, 1);
7818                tester.pump_and_settle();
7819                expect(tester, &find::text("February 2016"), finds_one_widget());
7820                assert_eq!(last_day_text(tester).as_deref(), Some("21"));
7821
7822                let center = tester.get_center(next_month_button);
7823                tester.tap_at(center, 1);
7824                tester.pump_and_settle();
7825                expect(tester, &find::text("March 2016"), finds_one_widget());
7826                assert_eq!(last_day_text(tester).as_deref(), Some("28"));
7827            });
7828        }
7829
7830        fn open_date_input_picker(tester: &mut WidgetTester) -> super::PickerResult {
7831            let result: super::PickerResult = Rc::default();
7832            let mut show = Show::new();
7833            show.initial_entry_mode = DatePickerEntryMode::Input;
7834            show.calendar_delegate = Rc::new(TestDelegate::DateInput);
7835            show.dates = Some((
7836                local_date(2016, 1, 15),
7837                local_date(2001, 1, 1),
7838                local_date(2031, 12, 31),
7839            ));
7840            show.result = Some(Rc::clone(&result));
7841            open_app(tester, false, "Open", show);
7842            tester.tap(find::text("Open"));
7843            tester.pump_and_settle();
7844            result
7845        }
7846
7847        #[test]
7848        fn date_text_input_formatter_applies_input_formatters_and_allows_text_entry_parsing() {
7849            test_widgets(|tester| {
7850                let result = open_date_input_picker(tester);
7851
7852                tester.enter_text(find::by_type::<EditableText>().at(0), "20240620");
7853                pump_zero(tester);
7854
7855                tester.tap(find::text("OK"));
7856                tester.pump_and_settle();
7857
7858                assert_eq!(picked_date(&result), Some(local_date(2024, 6, 20)));
7859            });
7860        }
7861
7862        #[test]
7863        fn date_text_input_formatter_filters_non_digit_input_via_input_formatters() {
7864            test_widgets(|tester| {
7865                open_date_input_picker(tester);
7866
7867                tester.enter_text(find::by_type::<EditableText>().at(0), "2024-06-20");
7868                pump_zero(tester);
7869
7870                // Verify that hyphens were removed by the formatter.
7871                assert_eq!(text_field_controller_text(tester), "20240620");
7872            });
7873        }
7874
7875        #[test]
7876        fn date_text_input_formatter_rejects_alphabetic_characters_via_input_formatters() {
7877            test_widgets(|tester| {
7878                open_date_input_picker(tester);
7879
7880                tester.enter_text(find::by_type::<EditableText>().at(0), "20ab24cd0620");
7881                pump_zero(tester);
7882
7883                // Only digits should remain in the controller.
7884                assert_eq!(text_field_controller_text(tester), "20240620");
7885            });
7886        }
7887    }
7888
7889    mod range {
7890        //! date_range_picker_test.dart: the range picker's layout, its dialog properties, the selection
7891        //! of a range, the validation of typed dates, the keyboard navigation and the calendar
7892        //! delegates.
7893
7894        use crate::test_support::local_date;
7895        use waft_widgets::testing::assert_f32_equals;
7896
7897        use std::rc::Rc;
7898
7899        use waft_embedder::{Size, TargetPlatform};
7900        use waft_foundation::{App, DateTime, Listener};
7901        use waft_painting::{
7902            BorderRadiusGeometry, BorderSide, EdgeInsets, RoundedRectangleBorder, ShapeBorderRef,
7903            TextDirection,
7904        };
7905        use waft_services::TextInputType;
7906        use waft_widgets::{AnyElement, BuildContext, Builder, Center, Icon, IntoWidget, Text};
7907
7908        use super::*;
7909        use super::{PickerResult, picked_range, range, size_view, tap_icon, text_field_count};
7910        use crate::colors::Colors;
7911        use crate::date::{DateTimeRange, GregorianCalendarDelegate};
7912        use crate::dialog::Dialog;
7913        use crate::elevated_button::ElevatedButton;
7914        use crate::icons::Icons;
7915        use crate::material::Material;
7916        use crate::test_support::{PaintInspection, material_app};
7917
7918        use crate::text_field::TextField;
7919        use crate::theme_data::ThemeData;
7920        use crate::tooltip::tests::{m2, m3};
7921        use waft_rendering::testing::{PaintCall, assert_paints};
7922
7923        /// The variables of date_range_picker_test.dart's `setUp`, and `preparePicker`'s arguments.
7924        #[derive(Clone)]
7925        struct Prepare {
7926            first_date: DateTime,
7927            last_date: DateTime,
7928            current_date: Option<DateTime>,
7929            initial_date_range: Option<DateTimeRange>,
7930            initial_entry_mode: DatePickerEntryMode,
7931            cancel_text: Option<String>,
7932            confirm_text: Option<String>,
7933            error_invalid_range_text: Option<String>,
7934            error_format_text: Option<String>,
7935            error_invalid_text: Option<String>,
7936            field_start_hint_text: Option<String>,
7937            field_end_hint_text: Option<String>,
7938            field_start_label_text: Option<String>,
7939            field_end_label_text: Option<String>,
7940            help_text: Option<String>,
7941            save_text: Option<String>,
7942            text_direction: TextDirection,
7943            use_material3: bool,
7944            selectable_day_predicate: Option<SelectableDayForRangePredicate>,
7945            calendar_delegate: Rc<dyn CalendarDelegate>,
7946            switch_to_input_entry_mode_icon: Option<fn() -> Icon>,
7947            switch_to_calendar_entry_mode_icon: Option<fn() -> Icon>,
7948        }
7949
7950        impl Prepare {
7951            fn new() -> Prepare {
7952                Prepare {
7953                    first_date: local_date(2015, 1, 1),
7954                    last_date: local_date(2016, 12, 31),
7955                    current_date: None,
7956                    initial_date_range: Some(range((2016, 1, 15), (2016, 1, 25))),
7957                    initial_entry_mode: DatePickerEntryMode::Calendar,
7958                    cancel_text: None,
7959                    confirm_text: None,
7960                    error_invalid_range_text: None,
7961                    error_format_text: None,
7962                    error_invalid_text: None,
7963                    field_start_hint_text: None,
7964                    field_end_hint_text: None,
7965                    field_start_label_text: None,
7966                    field_end_label_text: None,
7967                    help_text: None,
7968                    save_text: None,
7969                    text_direction: TextDirection::Ltr,
7970                    use_material3: false,
7971                    selectable_day_predicate: None,
7972                    calendar_delegate: Rc::new(GregorianCalendarDelegate),
7973                    switch_to_input_entry_mode_icon: None,
7974                    switch_to_calendar_entry_mode_icon: None,
7975                }
7976            }
7977
7978            /// The `setUp` of the 'Input mode' groups.
7979            fn input_mode() -> Prepare {
7980                let mut prepare = Prepare::new();
7981                prepare.first_date = local_date(2015, 1, 1);
7982                prepare.last_date = local_date(2017, 12, 31);
7983                prepare.initial_date_range = Some(range((2017, 1, 15), (2017, 1, 17)));
7984                prepare.initial_entry_mode = DatePickerEntryMode::Input;
7985                prepare
7986            }
7987
7988            fn show(&self, app: &mut App, context: BuildContext) -> CompleterFuture<RouteResult> {
7989                let text_direction = self.text_direction;
7990                let mut show = ShowDateRangePicker::new(self.first_date, self.last_date)
7991                    .initial_entry_mode(self.initial_entry_mode)
7992                    .keyboard_type(TextInputType::DATETIME)
7993                    .calendar_delegate(Rc::clone(&self.calendar_delegate));
7994                if let Some(initial_date_range) = self.initial_date_range {
7995                    show = show.initial_date_range(initial_date_range);
7996                }
7997                if let Some(current_date) = self.current_date {
7998                    show = show.current_date(current_date);
7999                }
8000                if let Some(help_text) = self.help_text.clone() {
8001                    show = show.help_text(help_text);
8002                }
8003                if let Some(cancel_text) = self.cancel_text.clone() {
8004                    show = show.cancel_text(cancel_text);
8005                }
8006                if let Some(confirm_text) = self.confirm_text.clone() {
8007                    show = show.confirm_text(confirm_text);
8008                }
8009                if let Some(save_text) = self.save_text.clone() {
8010                    show = show.save_text(save_text);
8011                }
8012                if let Some(error_format_text) = self.error_format_text.clone() {
8013                    show = show.error_format_text(error_format_text);
8014                }
8015                if let Some(error_invalid_text) = self.error_invalid_text.clone() {
8016                    show = show.error_invalid_text(error_invalid_text);
8017                }
8018                if let Some(error_invalid_range_text) = self.error_invalid_range_text.clone() {
8019                    show = show.error_invalid_range_text(error_invalid_range_text);
8020                }
8021                if let Some(field_start_hint_text) = self.field_start_hint_text.clone() {
8022                    show = show.field_start_hint_text(field_start_hint_text);
8023                }
8024                if let Some(field_end_hint_text) = self.field_end_hint_text.clone() {
8025                    show = show.field_end_hint_text(field_end_hint_text);
8026                }
8027                if let Some(field_start_label_text) = self.field_start_label_text.clone() {
8028                    show = show.field_start_label_text(field_start_label_text);
8029                }
8030                if let Some(field_end_label_text) = self.field_end_label_text.clone() {
8031                    show = show.field_end_label_text(field_end_label_text);
8032                }
8033                show = show.builder(Rc::new(move |_app, _context, child| {
8034                    waft_widgets::Directionality::new(
8035                        text_direction,
8036                        child.expect("a dialog child").clone(),
8037                    )
8038                    .into_widget()
8039                }));
8040                if let Some(icon) = self.switch_to_input_entry_mode_icon {
8041                    show = show.switch_to_input_entry_mode_icon(icon());
8042                }
8043                if let Some(icon) = self.switch_to_calendar_entry_mode_icon {
8044                    show = show.switch_to_calendar_entry_mode_icon(icon());
8045                }
8046                if let Some(predicate) = self.selectable_day_predicate.clone() {
8047                    show = show.selectable_day_predicate(predicate);
8048                }
8049                show.show(app, context)
8050            }
8051        }
8052
8053        /// Dart's `preparePicker`: an app with a button, tapped, that shows the date range picker.
8054        fn prepare_picker(tester: &mut WidgetTester, prepare: &Prepare) -> PickerResult {
8055            let theme = if prepare.use_material3 {
8056                m3(&tester.cell.borrow())
8057            } else {
8058                m2(&tester.cell.borrow())
8059            };
8060            prepare_picker_in(tester, prepare, theme)
8061        }
8062
8063        /// [`prepare_picker`] in an app of `theme`.
8064        fn prepare_picker_in(
8065            tester: &mut WidgetTester,
8066            prepare: &Prepare,
8067            theme: ThemeData,
8068        ) -> PickerResult {
8069            let result: PickerResult = Rc::default();
8070            let launcher = {
8071                let (prepare, result) = (prepare.clone(), Rc::clone(&result));
8072                Material::new()
8073                    .child(Builder::new(move |_app, context| {
8074                        let (prepare, result) = (prepare.clone(), Rc::clone(&result));
8075                        ElevatedButton::new(
8076                            Some(Listener::new(move |app| {
8077                                *result.borrow_mut() = Some(prepare.show(app, context));
8078                            })),
8079                            Some(Text::new("Go")),
8080                        )
8081                        .into_widget()
8082                    }))
8083                    .into_widget()
8084            };
8085            tester.pump_widget(material_app(theme, launcher));
8086            tester.tap(find::text("Go"));
8087            tester.pump_and_settle();
8088            result
8089        }
8090
8091        fn first_text(tester: &WidgetTester, text: &str) -> AnyElement {
8092            *find::text(text)
8093                .evaluate(tester)
8094                .first()
8095                .unwrap_or_else(|| panic!("a Text showing {text:?}"))
8096        }
8097
8098        fn tap_first(tester: &mut WidgetTester, text: &str) {
8099            let element = first_text(tester, text);
8100            let center = tester.get_center(element);
8101            tester.tap_at(center, 1);
8102        }
8103
8104        fn pick_range(
8105            tester: &mut WidgetTester,
8106            prepare: &Prepare,
8107            steps: impl FnOnce(&mut WidgetTester),
8108            action: &str,
8109        ) -> Option<DateTimeRange> {
8110            let result = prepare_picker(tester, prepare);
8111            steps(tester);
8112            tester.tap(find::text(action));
8113            tester.pump_and_settle();
8114            picked_range(&result)
8115        }
8116
8117        #[test]
8118        fn range_save_and_help_text_is_used_in_the_dialog() {
8119            test_widgets(|tester| {
8120                let mut prepare = Prepare::new();
8121                prepare.help_text = Some("help".to_string());
8122                prepare.save_text = Some("make it so".to_string());
8123                prepare_picker(tester, &prepare);
8124                expect(tester, &find::text("help"), finds_one_widget());
8125                expect(tester, &find::text("make it so"), finds_one_widget());
8126            });
8127        }
8128
8129        #[test]
8130        fn long_help_text_does_not_cutoff_the_save_button() {
8131            test_widgets(|tester| {
8132                let mut prepare = Prepare::new();
8133                let help_text = "long helpText".repeat(100);
8134                prepare.help_text = Some(help_text.clone());
8135                prepare.save_text = Some("make it so".to_string());
8136                prepare_picker(tester, &prepare);
8137                expect(tester, &find::text(&help_text), finds_one_widget());
8138                expect(tester, &find::text("make it so"), finds_one_widget());
8139            });
8140        }
8141
8142        #[test]
8143        fn material3_has_sentence_case_labels() {
8144            test_widgets(|tester| {
8145                let mut prepare = Prepare::new();
8146                prepare.use_material3 = true;
8147                prepare_picker(tester, &prepare);
8148                expect(tester, &find::text("Save"), finds_one_widget());
8149                expect(tester, &find::text("Select range"), finds_one_widget());
8150            });
8151        }
8152
8153        #[test]
8154        fn initial_date_is_the_default() {
8155            test_widgets(|tester| {
8156                let result = pick_range(tester, &Prepare::new(), |_tester| {}, "SAVE");
8157                assert_eq!(result, Some(range((2016, 1, 15), (2016, 1, 25))));
8158            });
8159        }
8160
8161        #[test]
8162        fn last_month_header_should_be_visible_if_last_date_is_selected() {
8163            test_widgets(|tester| {
8164                let mut prepare = Prepare::new();
8165                prepare.initial_date_range =
8166                    Some(DateTimeRange::new(prepare.last_date, prepare.last_date));
8167                prepare_picker(tester, &prepare);
8168                // December header should be showing, but no November
8169                expect(tester, &find::text("December 2016"), finds_one_widget());
8170                expect(tester, &find::text("November 2016"), finds_nothing());
8171            });
8172        }
8173
8174        #[test]
8175        fn first_month_header_should_be_visible_if_first_date_is_selected() {
8176            test_widgets(|tester| {
8177                let mut prepare = Prepare::new();
8178                prepare.initial_date_range =
8179                    Some(DateTimeRange::new(prepare.first_date, prepare.first_date));
8180                prepare_picker(tester, &prepare);
8181                // January and February headers should be showing, but no March
8182                expect(tester, &find::text("January 2015"), finds_one_widget());
8183                expect(tester, &find::text("February 2015"), finds_one_widget());
8184                expect(tester, &find::text("March 2015"), finds_nothing());
8185            });
8186        }
8187
8188        #[test]
8189        fn current_month_header_should_be_visible_if_no_date_is_selected() {
8190            test_widgets(|tester| {
8191                let mut prepare = Prepare::new();
8192                prepare.current_date = Some(local_date(2016, 9, 1));
8193                prepare.initial_date_range = None;
8194                prepare_picker(tester, &prepare);
8195                // September and October headers should be showing, but no August
8196                expect(tester, &find::text("September 2016"), finds_one_widget());
8197                expect(tester, &find::text("October 2016"), finds_one_widget());
8198                expect(tester, &find::text("August 2016"), finds_nothing());
8199            });
8200        }
8201
8202        #[test]
8203        fn can_cancel() {
8204            test_widgets(|tester| {
8205                let result = prepare_picker(tester, &Prepare::new());
8206                tap_icon(tester, &Icons::close());
8207                assert!(is_completed(&result));
8208                assert_eq!(picked_range(&result), None);
8209            });
8210        }
8211
8212        #[test]
8213        fn can_select_a_range() {
8214            test_widgets(|tester| {
8215                let result = pick_range(
8216                    tester,
8217                    &Prepare::new(),
8218                    |tester| {
8219                        tap_first(tester, "12");
8220                        tap_first(tester, "14");
8221                    },
8222                    "SAVE",
8223                );
8224                assert_eq!(result, Some(range((2016, 1, 12), (2016, 1, 14))));
8225            });
8226        }
8227
8228        #[test]
8229        fn tapping_earlier_date_resets_selected_range() {
8230            test_widgets(|tester| {
8231                let result = pick_range(
8232                    tester,
8233                    &Prepare::new(),
8234                    |tester| {
8235                        tap_first(tester, "12");
8236                        tap_first(tester, "11");
8237                        tap_first(tester, "15");
8238                    },
8239                    "SAVE",
8240                );
8241                assert_eq!(result, Some(range((2016, 1, 11), (2016, 1, 15))));
8242            });
8243        }
8244
8245        #[test]
8246        fn can_select_single_day_range() {
8247            test_widgets(|tester| {
8248                let result = pick_range(
8249                    tester,
8250                    &Prepare::new(),
8251                    |tester| {
8252                        tap_first(tester, "12");
8253                        tap_first(tester, "12");
8254                    },
8255                    "SAVE",
8256                );
8257                assert_eq!(result, Some(range((2016, 1, 12), (2016, 1, 12))));
8258            });
8259        }
8260
8261        #[test]
8262        fn cannot_select_a_day_outside_bounds() {
8263            test_widgets(|tester| {
8264                let mut prepare = Prepare::new();
8265                prepare.initial_date_range = Some(range((2017, 1, 13), (2017, 1, 15)));
8266                prepare.first_date = local_date(2017, 1, 12);
8267                prepare.last_date = local_date(2017, 1, 16);
8268                let result = pick_range(
8269                    tester,
8270                    &prepare,
8271                    |tester| {
8272                        // Earlier than firstDate. Should be ignored.
8273                        tester.tap(find::text("10"));
8274                        // Later than lastDate. Should be ignored.
8275                        tester.tap(find::text("20"));
8276                    },
8277                    "SAVE",
8278                );
8279                // We should still be on the initial date.
8280                assert_eq!(result, prepare.initial_date_range);
8281            });
8282        }
8283
8284        #[test]
8285        fn can_select_a_range_even_if_the_range_includes_non_selectable_days() {
8286            test_widgets(|tester| {
8287                let mut prepare = Prepare::new();
8288                prepare.selectable_day_predicate =
8289                    Some(Rc::new(|app, day, _, _| day.day(app) != 13));
8290                let result = pick_range(
8291                    tester,
8292                    &prepare,
8293                    |tester| {
8294                        tap_first(tester, "12");
8295                        tap_first(tester, "14");
8296                    },
8297                    "SAVE",
8298                );
8299                // The day 13 is not selectable, but the range is still valid.
8300                assert_eq!(result, Some(range((2016, 1, 12), (2016, 1, 14))));
8301            });
8302        }
8303
8304        #[test]
8305        fn cannot_select_a_day_inside_bounds_but_not_selectable() {
8306            test_widgets(|tester| {
8307                let mut prepare = Prepare::new();
8308                prepare.initial_date_range = Some(range((2017, 1, 13), (2017, 1, 14)));
8309                prepare.first_date = local_date(2017, 1, 12);
8310                prepare.last_date = local_date(2017, 1, 16);
8311                prepare.selectable_day_predicate =
8312                    Some(Rc::new(|app, day, _, _| day.day(app) != 15));
8313                let result = pick_range(
8314                    tester,
8315                    &prepare,
8316                    |tester| {
8317                        // Non-selectable date. Should be ignored.
8318                        tester.tap(find::text("15"));
8319                    },
8320                    "SAVE",
8321                );
8322                // We should still be on the initial date.
8323                assert_eq!(result, prepare.initial_date_range);
8324            });
8325        }
8326
8327        #[test]
8328        fn selectable_date_becoming_non_selectable_when_selected_start_day() {
8329            test_widgets(|tester| {
8330                let mut prepare = Prepare::new();
8331                prepare.selectable_day_predicate =
8332                    Some(Rc::new(|_app, day, selected_start, selected_end| {
8333                        if selected_end.is_none()
8334                            && let Some(selected_start) = selected_start
8335                        {
8336                            return day == selected_start || day.is_after(&selected_start);
8337                        }
8338                        true
8339                    }));
8340                let result = pick_range(
8341                    tester,
8342                    &prepare,
8343                    |tester| {
8344                        for day in ["12", "11", "14"] {
8345                            tap_first(tester, day);
8346                            tester.pump_and_settle();
8347                        }
8348                    },
8349                    "SAVE",
8350                );
8351                assert_eq!(result, Some(range((2016, 1, 12), (2016, 1, 14))));
8352            });
8353        }
8354
8355        #[test]
8356        fn selectable_day_predicate_should_be_called_with_the_selected_start_and_end_dates() {
8357            test_widgets(|tester| {
8358                let mut prepare = Prepare::new();
8359                prepare.initial_date_range = Some(range((2017, 1, 13), (2017, 1, 15)));
8360                prepare.first_date = local_date(2017, 1, 12);
8361                prepare.last_date = local_date(2017, 1, 16);
8362                let calls = Rc::new(std::cell::Cell::new(0));
8363                prepare.selectable_day_predicate = Some({
8364                    let calls = Rc::clone(&calls);
8365                    Rc::new(move |_app, _day, selected_start_date, selected_end_date| {
8366                        assert_eq!(selected_start_date, Some(local_date(2017, 1, 13)));
8367                        assert_eq!(selected_end_date, Some(local_date(2017, 1, 15)));
8368                        calls.set(calls.get() + 1);
8369                        true
8370                    })
8371                });
8372                prepare_picker(tester, &prepare);
8373                assert!(
8374                    calls.get() > 0,
8375                    "the predicate is asked about the days shown"
8376                );
8377            });
8378        }
8379
8380        #[test]
8381        fn can_switch_from_calendar_to_input_entry_mode() {
8382            test_widgets(|tester| {
8383                prepare_picker(tester, &Prepare::new());
8384                assert_eq!(field_count(tester), 0);
8385                tap_icon(tester, &Icons::edit());
8386                assert_eq!(field_count(tester), 2);
8387            });
8388        }
8389
8390        #[test]
8391        fn can_switch_from_input_to_calendar_entry_mode() {
8392            test_widgets(|tester| {
8393                let mut prepare = Prepare::new();
8394                prepare.initial_entry_mode = DatePickerEntryMode::Input;
8395                prepare_picker(tester, &prepare);
8396                assert_eq!(field_count(tester), 2);
8397                tap_icon(tester, &Icons::calendar_today());
8398                assert_eq!(field_count(tester), 0);
8399            });
8400        }
8401
8402        #[test]
8403        fn can_not_switch_out_of_calendar_only_mode() {
8404            test_widgets(|tester| {
8405                let mut prepare = Prepare::new();
8406                prepare.initial_entry_mode = DatePickerEntryMode::CalendarOnly;
8407                prepare_picker(tester, &prepare);
8408                assert_eq!(field_count(tester), 0);
8409                assert!(find::by_icon(&Icons::edit()).evaluate(tester).is_empty());
8410            });
8411        }
8412
8413        #[test]
8414        fn can_not_switch_out_of_input_only_mode() {
8415            test_widgets(|tester| {
8416                let mut prepare = Prepare::new();
8417                prepare.initial_entry_mode = DatePickerEntryMode::InputOnly;
8418                prepare_picker(tester, &prepare);
8419                assert_eq!(field_count(tester), 2);
8420                assert!(
8421                    find::by_icon(&Icons::calendar_today())
8422                        .evaluate(tester)
8423                        .is_empty()
8424                );
8425            });
8426        }
8427
8428        #[test]
8429        fn input_only_mode_should_validate_date() {
8430            test_widgets(|tester| {
8431                let mut prepare = Prepare::new();
8432                prepare.initial_entry_mode = DatePickerEntryMode::InputOnly;
8433                prepare.error_invalid_text = Some("oops".to_string());
8434                prepare_picker(tester, &prepare);
8435                enter_in(tester, 0, "08/08/2014");
8436                enter_in(tester, 1, "08/08/2014");
8437                expect(tester, &find::text("oops"), finds_nothing());
8438
8439                tester.tap(find::text("OK"));
8440                tester.pump_and_settle();
8441                expect(tester, &find::text("oops"), finds_n_widgets(2));
8442            });
8443        }
8444
8445        #[test]
8446        fn switching_to_input_mode_keeps_selected_date() {
8447            test_widgets(|tester| {
8448                let result = pick_range(
8449                    tester,
8450                    &Prepare::new(),
8451                    |tester| {
8452                        tap_first(tester, "12");
8453                        tap_first(tester, "14");
8454                        tap_icon(tester, &Icons::edit());
8455                    },
8456                    "OK",
8457                );
8458                assert_eq!(result, Some(range((2016, 1, 12), (2016, 1, 14))));
8459            });
8460        }
8461
8462        #[test]
8463        fn material3_default_layout_calendar_mode() {
8464            test_widgets(|tester| {
8465                let mut prepare = Prepare::new();
8466                prepare.use_material3 = true;
8467                prepare_picker(tester, &prepare);
8468
8469                let help_text = tester.element(find::text("Select range"));
8470                let first_date_header_text = tester.element(find::text("Jan 15"));
8471                let last_date_header_text = tester.element(find::text("Jan 25, 2016"));
8472                expect(tester, &find::text("Save"), finds_one_widget());
8473
8474                // Test the close button position.
8475                let close_button = tester.element(
8476                    find::ancestor(
8477                        find::by_type::<crate::icon_button::IconButton>().at(0),
8478                        find::by_type::<Center>(),
8479                    )
8480                    .first(),
8481                );
8482                let close_button_bottom_right = bottom_right(tester, close_button);
8483                let help_text_top_left = top_left(tester, help_text);
8484                assert_f32_equals(close_button_bottom_right.dx(), 56.0);
8485                assert_f32_equals(close_button_bottom_right.dy(), help_text_top_left.dy());
8486
8487                // Test the save and entry buttons position.
8488                let save_button_bottom_left = bottom_left(
8489                    tester,
8490                    tester.element(find::by_type::<crate::text_button::TextButton>().at(0)),
8491                );
8492                let entry_button_bottom_left =
8493                    bottom_left(tester, icon_button_of(tester, &Icons::edit_outlined()));
8494                assert_f32_equals(save_button_bottom_left.dx(), 711.6);
8495                assert_f32_equals(save_button_bottom_left.dy(), help_text_top_left.dy());
8496                assert_f32_equals(
8497                    entry_button_bottom_left.dx(),
8498                    save_button_bottom_left.dx() - 48.0,
8499                );
8500                assert_f32_equals(entry_button_bottom_left.dy(), help_text_top_left.dy());
8501
8502                // Test help text position.
8503                let help_text_bottom_left = bottom_left(tester, help_text);
8504                assert_f32_equals(help_text_bottom_left.dx(), 72.0);
8505                assert_f32_equals(
8506                    help_text_bottom_left.dy(),
8507                    close_button_bottom_right.dy() + 20.0,
8508                );
8509
8510                // Test the header position.
8511                let first_date_header_top_left = top_left(tester, first_date_header_text);
8512                let last_date_header_top_left = top_left(tester, last_date_header_text);
8513                assert_f32_equals(first_date_header_top_left.dx(), 72.0);
8514                assert_f32_equals(
8515                    first_date_header_top_left.dy(),
8516                    help_text_bottom_left.dy() + 8.0,
8517                );
8518                // Dart also asserts that the last date header starts 66.0 pixels after the first one
8519                // ends: the width of the `Text(' – ')` between them, three glyphs. Valo leaves the
8520                // trailing space out of a paragraph's max intrinsic width, so that assertion is
8521                // deferred (`PORTING.md`) until Valo counts it.
8522                assert_f32_equals(
8523                    last_date_header_top_left.dy(),
8524                    help_text_bottom_left.dy() + 8.0,
8525                );
8526
8527                // Test the day headers position.
8528                let day_headers_grid =
8529                    tester.element(find::by_type::<waft_widgets::GridView>().at(0));
8530                let day_headers_grid_top_left = top_left(tester, day_headers_grid);
8531                let first_date_header_bottom_left = bottom_left(tester, first_date_header_text);
8532                assert_f32_equals(day_headers_grid_top_left.dx(), (800.0 - 384.0) / 2.0);
8533                assert_f32_equals(
8534                    day_headers_grid_top_left.dy(),
8535                    first_date_header_bottom_left.dy() + 16.0,
8536                );
8537
8538                // Test the calendar custom scroll view position.
8539                let calendar_scroll_view =
8540                    tester.element(find::by_type::<waft_widgets::CustomScrollView>().at(0));
8541                let calendar_scroll_view_top_left = top_left(tester, calendar_scroll_view);
8542                let day_headers_grid_bottom_left = bottom_left(tester, day_headers_grid);
8543                assert_f32_equals(calendar_scroll_view_top_left.dx(), 0.0);
8544                assert_f32_equals(
8545                    calendar_scroll_view_top_left.dy(),
8546                    day_headers_grid_bottom_left.dy(),
8547                );
8548            });
8549        }
8550
8551        #[test]
8552        fn material2_default_layout_calendar_mode() {
8553            test_widgets(|tester| {
8554                prepare_picker(tester, &Prepare::new());
8555
8556                let help_text = tester.element(find::text("SELECT RANGE"));
8557                let first_date_header_text = tester.element(find::text("Jan 15"));
8558                let last_date_header_text = tester.element(find::text("Jan 25, 2016"));
8559                expect(tester, &find::text("SAVE"), finds_one_widget());
8560
8561                // Test the close button position.
8562                let close_button =
8563                    tester.element(find::by_type::<crate::action_buttons::CloseButton>().at(0));
8564                let close_button_bottom_right = bottom_right(tester, close_button);
8565                let help_text_top_left = top_left(tester, help_text);
8566                assert_f32_equals(close_button_bottom_right.dx(), 56.0);
8567                assert_f32_equals(
8568                    close_button_bottom_right.dy(),
8569                    help_text_top_left.dy() - 6.0,
8570                );
8571
8572                // Test the save and entry buttons position.
8573                let save_button_bottom_left = bottom_left(
8574                    tester,
8575                    tester.element(find::by_type::<crate::text_button::TextButton>().at(0)),
8576                );
8577                let entry_button_bottom_left =
8578                    bottom_left(tester, icon_button_of(tester, &Icons::edit()));
8579                assert_f32_equals(save_button_bottom_left.dx(), 800.0 - 80.0);
8580                assert_f32_equals(save_button_bottom_left.dy(), help_text_top_left.dy() - 6.0);
8581                assert_f32_equals(
8582                    entry_button_bottom_left.dx(),
8583                    save_button_bottom_left.dx() - 48.0,
8584                );
8585                assert_f32_equals(entry_button_bottom_left.dy(), help_text_top_left.dy() - 6.0);
8586
8587                // Test help text position.
8588                let help_text_bottom_left = bottom_left(tester, help_text);
8589                assert_f32_equals(help_text_bottom_left.dx(), 72.0);
8590                assert_f32_equals(
8591                    help_text_bottom_left.dy(),
8592                    close_button_bottom_right.dy() + 16.0,
8593                );
8594
8595                // Test the header position.
8596                let first_date_header_top_left = top_left(tester, first_date_header_text);
8597                let last_date_header_top_left = top_left(tester, last_date_header_text);
8598                assert_f32_equals(first_date_header_top_left.dx(), 72.0);
8599                assert_f32_equals(
8600                    first_date_header_top_left.dy(),
8601                    help_text_bottom_left.dy() + 8.0,
8602                );
8603                // Dart also asserts that the last date header starts 72.0 pixels after the first one
8604                // ends: the width of the `Text(' – ')` between them, three glyphs. Valo leaves the
8605                // trailing space out of a paragraph's max intrinsic width, so that assertion is
8606                // deferred (`PORTING.md`) until Valo counts it.
8607                assert_f32_equals(
8608                    last_date_header_top_left.dy(),
8609                    help_text_bottom_left.dy() + 8.0,
8610                );
8611
8612                // Test the day headers position.
8613                let day_headers_grid =
8614                    tester.element(find::by_type::<waft_widgets::GridView>().at(0));
8615                let day_headers_grid_top_left = top_left(tester, day_headers_grid);
8616                let first_date_header_bottom_left = bottom_left(tester, first_date_header_text);
8617                assert_f32_equals(day_headers_grid_top_left.dx(), (800.0 - 384.0) / 2.0);
8618                assert_f32_equals(
8619                    day_headers_grid_top_left.dy(),
8620                    first_date_header_bottom_left.dy() + 16.0,
8621                );
8622
8623                // Test the calendar custom scroll view position.
8624                let calendar_scroll_view =
8625                    tester.element(find::by_type::<waft_widgets::CustomScrollView>().at(0));
8626                let calendar_scroll_view_top_left = top_left(tester, calendar_scroll_view);
8627                let day_headers_grid_bottom_left = bottom_left(tester, day_headers_grid);
8628                assert_f32_equals(calendar_scroll_view_top_left.dx(), 0.0);
8629                assert_f32_equals(
8630                    calendar_scroll_view_top_left.dy(),
8631                    day_headers_grid_bottom_left.dy(),
8632                );
8633            });
8634        }
8635
8636        /// What the dialog's `Material` and `Dialog` say that the default-properties tests read.
8637        struct DialogProperties {
8638            color: Option<waft_embedder::Color>,
8639            shadow_color: Option<waft_embedder::Color>,
8640            surface_tint_color: Option<waft_embedder::Color>,
8641            elevation: f64,
8642            shape: Option<ShapeBorderRef>,
8643            clip_behavior: waft_embedder::Clip,
8644            inset_padding: Option<EdgeInsets>,
8645        }
8646
8647        fn dialog_properties(tester: &WidgetTester) -> DialogProperties {
8648            let mut properties = tester.widget(dialog_material(tester), |material: &Material| {
8649                DialogProperties {
8650                    color: material.color,
8651                    shadow_color: material.shadow_color,
8652                    surface_tint_color: material.surface_tint_color,
8653                    elevation: material.elevation,
8654                    shape: material.shape.clone(),
8655                    clip_behavior: material.clip_behavior,
8656                    inset_padding: None,
8657                }
8658            });
8659            let dialog = tester.element(find::by_type::<Dialog>().at(0));
8660            properties.inset_padding =
8661                tester.widget(dialog, |dialog: &Dialog| dialog.inset_padding);
8662            properties
8663        }
8664
8665        fn square_shape() -> ShapeBorderRef {
8666            ShapeBorderRef::new(RoundedRectangleBorder::default())
8667        }
8668
8669        #[test]
8670        fn material3_default_dialog_properties_calendar_mode() {
8671            test_widgets(|tester| {
8672                let mut prepare = Prepare::new();
8673                prepare.use_material3 = true;
8674                prepare_picker(tester, &prepare);
8675                let theme = m3(&tester.cell.borrow());
8676                let properties = dialog_properties(tester);
8677                assert_eq!(
8678                    properties.color,
8679                    Some(theme.color_scheme.surface_container_high())
8680                );
8681                assert_eq!(properties.shadow_color, Some(Colors::TRANSPARENT));
8682                assert_eq!(properties.surface_tint_color, Some(Colors::TRANSPARENT));
8683                assert_eq!(properties.elevation, 0.0);
8684                assert_eq!(properties.shape, Some(square_shape()));
8685                assert_eq!(properties.clip_behavior, waft_embedder::Clip::AntiAlias);
8686                assert_eq!(properties.inset_padding, Some(EdgeInsets::ZERO));
8687            });
8688        }
8689
8690        #[test]
8691        fn material2_default_dialog_properties_calendar_mode() {
8692            test_widgets(|tester| {
8693                prepare_picker(tester, &Prepare::new());
8694                let theme = m2(&tester.cell.borrow());
8695                let properties = dialog_properties(tester);
8696                assert_eq!(properties.color, Some(theme.color_scheme.surface()));
8697                assert_eq!(properties.shadow_color, Some(Colors::TRANSPARENT));
8698                assert_eq!(properties.surface_tint_color, Some(Colors::TRANSPARENT));
8699                assert_eq!(properties.elevation, 0.0);
8700                assert_eq!(properties.shape, Some(square_shape()));
8701                assert_eq!(properties.clip_behavior, waft_embedder::Clip::AntiAlias);
8702                assert_eq!(properties.inset_padding, Some(EdgeInsets::ZERO));
8703            });
8704        }
8705
8706        #[test]
8707        fn material3_default_dialog_properties_input_mode() {
8708            test_widgets(|tester| {
8709                let mut prepare = Prepare::input_mode();
8710                prepare.use_material3 = true;
8711                prepare_picker(tester, &prepare);
8712                let theme = m3(&tester.cell.borrow());
8713                let properties = dialog_properties(tester);
8714                assert_eq!(
8715                    properties.color,
8716                    Some(theme.color_scheme.surface_container_high())
8717                );
8718                assert_eq!(properties.shadow_color, Some(Colors::TRANSPARENT));
8719                assert_eq!(properties.surface_tint_color, Some(Colors::TRANSPARENT));
8720                assert_eq!(properties.elevation, 6.0);
8721                assert_eq!(properties.shape, Some(rounded(28.0)));
8722                assert_eq!(properties.clip_behavior, waft_embedder::Clip::AntiAlias);
8723                assert_eq!(
8724                    properties.inset_padding,
8725                    Some(EdgeInsets::symmetric(24.0, 16.0))
8726                );
8727            });
8728        }
8729
8730        #[test]
8731        fn material2_default_dialog_properties_input_mode() {
8732            test_widgets(|tester| {
8733                prepare_picker(tester, &Prepare::input_mode());
8734                let theme = m2(&tester.cell.borrow());
8735                let properties = dialog_properties(tester);
8736                assert_eq!(properties.color, Some(theme.color_scheme.surface()));
8737                assert_eq!(properties.shadow_color, Some(theme.shadow_color));
8738                assert_eq!(properties.surface_tint_color, None);
8739                assert_eq!(properties.elevation, 24.0);
8740                assert_eq!(properties.shape, Some(rounded(4.0)));
8741                assert_eq!(properties.clip_behavior, waft_embedder::Clip::AntiAlias);
8742                assert_eq!(
8743                    properties.inset_padding,
8744                    Some(EdgeInsets::symmetric(24.0, 16.0))
8745                );
8746            });
8747        }
8748
8749        #[test]
8750        fn material3_scaffold_and_app_bar_defaults() {
8751            test_widgets(|tester| {
8752                let mut prepare = Prepare::new();
8753                prepare.use_material3 = true;
8754                prepare_picker(tester, &prepare);
8755                let theme = m3(&tester.cell.borrow());
8756
8757                let scaffold = tester.element(find::by_type::<crate::scaffold::Scaffold>().at(0));
8758                let background_color = tester
8759                    .widget(scaffold, |scaffold: &crate::scaffold::Scaffold| {
8760                        scaffold.background_color
8761                    });
8762                assert_eq!(background_color, None);
8763
8764                let app_bar = tester.element(find::by_type::<crate::app_bar::AppBar>().at(0));
8765                let icon_theme = waft_widgets::IconThemeData::new()
8766                    .color(theme.color_scheme.on_surface_variant());
8767                let (app_bar_icon_theme, actions_icon_theme, elevation, scrolled_under, background) =
8768                    tester.widget(app_bar, |app_bar: &crate::app_bar::AppBar| {
8769                        (
8770                            app_bar.icon_theme.clone(),
8771                            app_bar.actions_icon_theme.clone(),
8772                            app_bar.elevation,
8773                            app_bar.scrolled_under_elevation,
8774                            app_bar.background_color.clone(),
8775                        )
8776                    });
8777                assert_eq!(app_bar_icon_theme, Some(icon_theme.clone()));
8778                assert_eq!(actions_icon_theme, Some(icon_theme));
8779                assert_eq!(elevation, Some(0.0));
8780                assert_eq!(scrolled_under, Some(0.0));
8781                assert_eq!(
8782                    background.map(|color| color.color()),
8783                    Some(Colors::TRANSPARENT)
8784                );
8785            });
8786        }
8787
8788        #[test]
8789        fn material2_scaffold_and_app_bar_defaults() {
8790            test_widgets(|tester| {
8791                prepare_picker(tester, &Prepare::new());
8792                let theme = m2(&tester.cell.borrow());
8793
8794                let scaffold = tester.element(find::by_type::<crate::scaffold::Scaffold>().at(0));
8795                let background_color = tester
8796                    .widget(scaffold, |scaffold: &crate::scaffold::Scaffold| {
8797                        scaffold.background_color
8798                    });
8799                assert_eq!(background_color, Some(theme.color_scheme.surface()));
8800
8801                let app_bar = tester.element(find::by_type::<crate::app_bar::AppBar>().at(0));
8802                let icon_theme =
8803                    waft_widgets::IconThemeData::new().color(theme.color_scheme.on_primary());
8804                let (app_bar_icon_theme, actions_icon_theme, elevation, scrolled_under, background) =
8805                    tester.widget(app_bar, |app_bar: &crate::app_bar::AppBar| {
8806                        (
8807                            app_bar.icon_theme.clone(),
8808                            app_bar.actions_icon_theme.clone(),
8809                            app_bar.elevation,
8810                            app_bar.scrolled_under_elevation,
8811                            app_bar.background_color.clone(),
8812                        )
8813                    });
8814                assert_eq!(app_bar_icon_theme, Some(icon_theme.clone()));
8815                assert_eq!(actions_icon_theme, Some(icon_theme));
8816                assert_eq!(elevation, None);
8817                assert_eq!(scrolled_under, None);
8818                assert_eq!(
8819                    background.map(|color| color.color()),
8820                    Some(theme.color_scheme.primary())
8821                );
8822            });
8823        }
8824
8825        fn field_count(tester: &WidgetTester) -> usize {
8826            text_field_count(tester)
8827        }
8828
8829        fn enter_in(tester: &mut WidgetTester, index: usize, text: &str) {
8830            tester.enter_text(find::by_type::<EditableText>().at(index), text);
8831        }
8832
8833        fn input_text_field_decoration(
8834            tester: &WidgetTester,
8835            index: usize,
8836        ) -> crate::input_decorator::InputDecoration {
8837            let field = tester.element(find::by_type::<TextField>().at(index));
8838            tester.widget(field, |field: &TextField| {
8839                field.decoration.clone().expect("a decoration")
8840            })
8841        }
8842
8843        #[test]
8844        fn material3_input_mode_default_input_decoration() {
8845            test_widgets(|tester| {
8846                let mut prepare = Prepare::input_mode();
8847                prepare.use_material3 = true;
8848                prepare_picker(tester, &prepare);
8849                for (index, label) in [(0, "Start Date"), (1, "End Date")] {
8850                    let decoration = input_text_field_decoration(tester, index);
8851                    assert_eq!(
8852                        decoration.border,
8853                        Some(crate::input_border::InputBorderRef::new(
8854                            crate::input_border::OutlineInputBorder::default()
8855                        ))
8856                    );
8857                    assert_eq!(decoration.filled, Some(false));
8858                    assert_eq!(decoration.hint_text.as_deref(), Some("mm/dd/yyyy"));
8859                    assert_eq!(decoration.label_text.as_deref(), Some(label));
8860                    assert_eq!(decoration.error_text, None);
8861                }
8862            });
8863        }
8864
8865        #[test]
8866        fn material2_input_mode_default_input_decoration() {
8867            test_widgets(|tester| {
8868                prepare_picker(tester, &Prepare::input_mode());
8869                for (index, label) in [(0, "Start Date"), (1, "End Date")] {
8870                    let decoration = input_text_field_decoration(tester, index);
8871                    assert_eq!(
8872                        decoration.border,
8873                        Some(crate::input_border::InputBorderRef::new(
8874                            crate::input_border::UnderlineInputBorder::default()
8875                        ))
8876                    );
8877                    assert_eq!(decoration.filled, Some(false));
8878                    assert_eq!(decoration.hint_text.as_deref(), Some("mm/dd/yyyy"));
8879                    assert_eq!(decoration.label_text.as_deref(), Some(label));
8880                    assert_eq!(decoration.error_text, None);
8881                }
8882            });
8883        }
8884
8885        #[test]
8886        fn input_mode_initial_entry_mode_is_used() {
8887            test_widgets(|tester| {
8888                prepare_picker(tester, &Prepare::input_mode());
8889                assert_eq!(field_count(tester), 2);
8890            });
8891        }
8892
8893        #[test]
8894        fn input_mode_all_custom_strings_are_used() {
8895            test_widgets(|tester| {
8896                let mut prepare = Prepare::input_mode();
8897                prepare.initial_date_range = None;
8898                prepare.cancel_text = Some("nope".to_string());
8899                prepare.confirm_text = Some("yep".to_string());
8900                prepare.field_start_hint_text = Some("hint1".to_string());
8901                prepare.field_end_hint_text = Some("hint2".to_string());
8902                prepare.field_start_label_text = Some("label1".to_string());
8903                prepare.field_end_label_text = Some("label2".to_string());
8904                prepare.help_text = Some("help".to_string());
8905                prepare_picker(tester, &prepare);
8906                for text in ["nope", "yep", "hint1", "hint2", "label1", "label2", "help"] {
8907                    assert_eq!(find::text(text).evaluate(tester).len(), 1, "{text}");
8908                }
8909            });
8910        }
8911
8912        #[test]
8913        fn input_mode_initial_date_range_is_the_default() {
8914            test_widgets(|tester| {
8915                let result = pick_range(tester, &Prepare::input_mode(), |_tester| {}, "OK");
8916                assert_eq!(result, Some(range((2017, 1, 15), (2017, 1, 17))));
8917            });
8918        }
8919
8920        #[test]
8921        fn input_mode_can_toggle_to_calendar_entry_mode() {
8922            test_widgets(|tester| {
8923                prepare_picker(tester, &Prepare::input_mode());
8924                assert_eq!(field_count(tester), 2);
8925                tap_icon(tester, &Icons::calendar_today());
8926                assert_eq!(field_count(tester), 0);
8927            });
8928        }
8929
8930        #[test]
8931        fn input_mode_toggle_to_calendar_mode_keeps_selected_date() {
8932            test_widgets(|tester| {
8933                let mut prepare = Prepare::input_mode();
8934                prepare.initial_date_range = None;
8935                let result = pick_range(
8936                    tester,
8937                    &prepare,
8938                    |tester| {
8939                        enter_in(tester, 0, "12/25/2016");
8940                        enter_in(tester, 1, "12/27/2016");
8941                        tap_icon(tester, &Icons::calendar_today());
8942                    },
8943                    "SAVE",
8944                );
8945                assert_eq!(result, Some(range((2016, 12, 25), (2016, 12, 27))));
8946            });
8947        }
8948
8949        #[test]
8950        fn input_mode_entered_text_returns_range() {
8951            test_widgets(|tester| {
8952                let mut prepare = Prepare::input_mode();
8953                prepare.initial_date_range = None;
8954                let result = pick_range(
8955                    tester,
8956                    &prepare,
8957                    |tester| {
8958                        enter_in(tester, 0, "12/25/2016");
8959                        enter_in(tester, 1, "12/27/2016");
8960                    },
8961                    "OK",
8962                );
8963                assert_eq!(result, Some(range((2016, 12, 25), (2016, 12, 27))));
8964            });
8965        }
8966
8967        fn range_error_case(
8968            tester: &mut WidgetTester,
8969            set: impl FnOnce(&mut Prepare),
8970            start: &str,
8971            end: &str,
8972            error: &str,
8973            expected_count: usize,
8974        ) {
8975            let mut prepare = Prepare::input_mode();
8976            prepare.initial_date_range = None;
8977            set(&mut prepare);
8978            prepare_picker(tester, &prepare);
8979            enter_in(tester, 0, start);
8980            enter_in(tester, 1, end);
8981            expect(tester, &find::text(error), finds_nothing());
8982
8983            tester.tap(find::text("OK"));
8984            tester.pump_and_settle();
8985            assert_eq!(find::text(error).evaluate(tester).len(), expected_count);
8986        }
8987
8988        #[test]
8989        fn input_mode_too_short_entered_text_shows_error() {
8990            test_widgets(|tester| {
8991                range_error_case(
8992                    tester,
8993                    |prepare| prepare.error_format_text = Some("oops".to_string()),
8994                    "12/25",
8995                    "12/25",
8996                    "oops",
8997                    2,
8998                );
8999            });
9000        }
9001
9002        #[test]
9003        fn input_mode_bad_format_entered_text_shows_error() {
9004            test_widgets(|tester| {
9005                range_error_case(
9006                    tester,
9007                    |prepare| prepare.error_format_text = Some("oops".to_string()),
9008                    "20202014",
9009                    "20212014",
9010                    "oops",
9011                    2,
9012                );
9013            });
9014        }
9015
9016        #[test]
9017        fn input_mode_invalid_entered_text_shows_error() {
9018            test_widgets(|tester| {
9019                range_error_case(
9020                    tester,
9021                    |prepare| prepare.error_invalid_text = Some("oops".to_string()),
9022                    "08/08/2014",
9023                    "08/08/2014",
9024                    "oops",
9025                    2,
9026                );
9027            });
9028        }
9029
9030        #[test]
9031        fn input_mode_end_before_start_date_shows_error() {
9032            test_widgets(|tester| {
9033                range_error_case(
9034                    tester,
9035                    |prepare| prepare.error_invalid_range_text = Some("oops".to_string()),
9036                    "12/27/2016",
9037                    "12/25/2016",
9038                    "oops",
9039                    1,
9040                );
9041            });
9042        }
9043
9044        #[test]
9045        fn input_mode_error_text_only_displayed_for_invalid_date() {
9046            test_widgets(|tester| {
9047                range_error_case(
9048                    tester,
9049                    |prepare| prepare.error_invalid_text = Some("oops".to_string()),
9050                    "12/27/2016",
9051                    "01/01/2018",
9052                    "oops",
9053                    1,
9054                );
9055            });
9056        }
9057
9058        #[test]
9059        fn input_mode_end_before_start_date_does_not_get_passed_to_calendar_mode() {
9060            test_widgets(|tester| {
9061                let mut prepare = Prepare::input_mode();
9062                prepare.initial_date_range = None;
9063                prepare_picker(tester, &prepare);
9064                enter_in(tester, 0, "12/27/2016");
9065                enter_in(tester, 1, "12/25/2016");
9066
9067                tap_icon(tester, &Icons::calendar_today());
9068                tester.tap(find::text("SAVE"));
9069                tester.pump_and_settle();
9070
9071                // Save button should be disabled, so dialog should still be up with the first date
9072                // selected, but no end date
9073                expect(tester, &find::text("Dec 27"), finds_one_widget());
9074                expect(tester, &find::text("End Date"), finds_one_widget());
9075            });
9076        }
9077
9078        #[test]
9079        fn input_decoration_theme_is_honored() {
9080            test_widgets(|tester| {
9081                let border = crate::input_border::InputBorderRef::none();
9082                let theme = ThemeData::builder()
9083                    .input_decoration_theme(
9084                        crate::input_decorator::InputDecorationThemeData::new()
9085                            .border(border.clone()),
9086                    )
9087                    .build(&tester.cell.borrow());
9088                prepare_picker_in(tester, &Prepare::input_mode(), theme);
9089
9090                // The start and the end date text fields.
9091                let painted =
9092                    crate::input_decorator::tests::common::borders_and_container_colors(tester);
9093                assert_eq!(painted.len(), 2);
9094                for (actual_border, container_color) in painted {
9095                    assert_eq!(actual_border, border);
9096                    assert_eq!(container_color, Colors::TRANSPARENT);
9097                }
9098            });
9099        }
9100
9101        fn toggled_calendar_texts(
9102            tester: &mut WidgetTester,
9103            set: impl FnOnce(&mut Prepare),
9104            start: &str,
9105            end: &str,
9106        ) {
9107            let mut prepare = Prepare::new();
9108            prepare.initial_entry_mode = DatePickerEntryMode::Input;
9109            set(&mut prepare);
9110            prepare_picker(tester, &prepare);
9111            enter_in(tester, 0, start);
9112            enter_in(tester, 1, end);
9113            tap_icon(tester, &Icons::calendar_today());
9114        }
9115
9116        #[test]
9117        fn toggle_from_input_entry_mode_validates_an_invalid_start_date() {
9118            test_widgets(|tester| {
9119                // Invalid start date should have neither a start nor end date selected in calendar
9120                // mode
9121                toggled_calendar_texts(tester, |_| {}, "12/27/1918", "12/25/2016");
9122                expect(tester, &find::text("Start Date"), finds_one_widget());
9123                expect(tester, &find::text("End Date"), finds_one_widget());
9124            });
9125        }
9126
9127        #[test]
9128        fn toggle_from_input_entry_mode_validates_a_non_selectable_start_date() {
9129            test_widgets(|tester| {
9130                // Even if start and end dates are selected, the start date is not selectable ending up
9131                // to no date selected at all in calendar mode.
9132                toggled_calendar_texts(
9133                    tester,
9134                    |prepare| {
9135                        prepare.selectable_day_predicate =
9136                            Some(Rc::new(|_app, day, _, _| day != local_date(2016, 12, 24)));
9137                    },
9138                    "12/24/2016",
9139                    "12/25/2016",
9140                );
9141                expect(tester, &find::text("Start Date"), finds_one_widget());
9142                expect(tester, &find::text("End Date"), finds_one_widget());
9143            });
9144        }
9145
9146        #[test]
9147        fn toggle_from_input_entry_mode_validates_an_invalid_end_date() {
9148            test_widgets(|tester| {
9149                // Invalid end date should only have a start date selected
9150                toggled_calendar_texts(tester, |_| {}, "12/24/2016", "12/25/2050");
9151                expect(tester, &find::text("Dec 24"), finds_one_widget());
9152                expect(tester, &find::text("End Date"), finds_one_widget());
9153            });
9154        }
9155
9156        #[test]
9157        fn toggle_from_input_entry_mode_validates_a_non_selectable_end_date() {
9158            test_widgets(|tester| {
9159                // The end date is not selectable, so only the start date should be selected.
9160                toggled_calendar_texts(
9161                    tester,
9162                    |prepare| {
9163                        prepare.selectable_day_predicate =
9164                            Some(Rc::new(|_app, day, _, _| day != local_date(2016, 12, 25)));
9165                    },
9166                    "12/24/2016",
9167                    "12/25/2016",
9168                );
9169                expect(tester, &find::text("Dec 24"), finds_one_widget());
9170                expect(tester, &find::text("End Date"), finds_one_widget());
9171            });
9172        }
9173
9174        #[test]
9175        fn toggle_from_input_entry_mode_validates_an_invalid_range() {
9176            test_widgets(|tester| {
9177                // Start date after end date should just use the start date
9178                toggled_calendar_texts(tester, |_| {}, "12/25/2016", "12/24/2016");
9179                expect(tester, &find::text("Dec 25"), finds_one_widget());
9180                expect(tester, &find::text("End Date"), finds_one_widget());
9181            });
9182        }
9183
9184        #[test]
9185        fn range_ok_cancel_button_layout() {
9186            test_widgets(|tester| {
9187                let show_ok_cancel_dialog =
9188                    |tester: &mut WidgetTester, text_direction: TextDirection| {
9189                        let mut prepare = Prepare::new();
9190                        prepare.first_date = local_date(2001, 1, 1);
9191                        prepare.last_date = local_date(2031, 12, 31);
9192                        prepare.initial_date_range = None;
9193                        prepare.text_direction = text_direction;
9194                        prepare_picker(tester, &prepare);
9195                        tap_icon(tester, &Icons::edit());
9196                    };
9197                let dismiss = |tester: &mut WidgetTester| {
9198                    tester.tap(find::text("CANCEL"));
9199                    tester.pump_and_settle();
9200                };
9201
9202                show_ok_cancel_dialog(tester, TextDirection::Ltr);
9203                assert_f32_equals(tester.get_rect(find::text("OK")).right, 622.0);
9204                assert_f32_equals(tester.get_rect(find::text("OK")).left, 594.0);
9205                assert_f32_equals(tester.get_rect(find::text("CANCEL")).right, 560.0);
9206                dismiss(tester);
9207
9208                show_ok_cancel_dialog(tester, TextDirection::Rtl);
9209                assert_f32_equals(tester.get_rect(find::text("OK")).right, 206.0);
9210                assert_f32_equals(tester.get_rect(find::text("OK")).left, 178.0);
9211                assert_f32_equals(tester.get_rect(find::text("CANCEL")).right, 324.0);
9212                dismiss(tester);
9213            });
9214        }
9215
9216        #[test]
9217        fn range_keyboard_can_toggle_to_input_entry_mode() {
9218            test_widgets(|tester| {
9219                prepare_picker(tester, &Prepare::new());
9220                assert_eq!(field_count(tester), 0);
9221                // Navigate to the entry toggle button and activate it
9222                tabs(tester, 2);
9223                space(tester);
9224                tester.pump_and_settle();
9225                // Should be in the input mode
9226                assert_eq!(field_count(tester), 2);
9227            });
9228        }
9229
9230        #[test]
9231        fn range_keyboard_can_navigate_date_grid_with_arrow_keys() {
9232            test_widgets(|tester| {
9233                let result = prepare_picker(tester, &Prepare::new());
9234                // Navigate to the grid
9235                tabs(tester, 4);
9236                tester.pump_and_settle();
9237
9238                // Navigate from Jan 15 to Jan 18 with arrow keys
9239                arrows(
9240                    tester,
9241                    &[
9242                        Arrow::Left,
9243                        Arrow::Up,
9244                        Arrow::Left,
9245                        Arrow::Down,
9246                        Arrow::Down,
9247                        Arrow::Left,
9248                        Arrow::Left,
9249                    ],
9250                );
9251                tester.pump_and_settle();
9252
9253                // Activate it to select the beginning of the range
9254                space(tester);
9255                tester.pump_and_settle();
9256
9257                // Navigate to Jan 29
9258                arrows(
9259                    tester,
9260                    &[
9261                        Arrow::Down,
9262                        Arrow::Right,
9263                        Arrow::Right,
9264                        Arrow::Right,
9265                        Arrow::Right,
9266                    ],
9267                );
9268                tester.pump_and_settle();
9269
9270                // Activate it to select the end of the range
9271                space(tester);
9272                tester.pump_and_settle();
9273
9274                // Navigate out of the grid and to the OK button
9275                tabs(tester, 3);
9276
9277                // Activate OK
9278                space(tester);
9279                tester.pump_and_settle();
9280
9281                // Should have selected Jan 18 - Jan 29
9282                assert_eq!(
9283                    picked_range(&result),
9284                    Some(range((2016, 1, 18), (2016, 1, 29)))
9285                );
9286            });
9287        }
9288
9289        #[test]
9290        fn range_keyboard_navigating_with_arrow_keys_scrolls_as_needed() {
9291            test_widgets(|tester| {
9292                let result = prepare_picker(tester, &Prepare::new());
9293                // Jan and Feb headers should be showing, but no March
9294                expect(tester, &find::text("January 2016"), finds_one_widget());
9295                expect(tester, &find::text("February 2016"), finds_one_widget());
9296                expect(tester, &find::text("March 2016"), finds_nothing());
9297
9298                // Navigate to the grid
9299                tabs(tester, 4);
9300
9301                // Navigate from Jan 15 to Jan 18 with arrow keys
9302                arrows(
9303                    tester,
9304                    &[
9305                        Arrow::Left,
9306                        Arrow::Left,
9307                        Arrow::Left,
9308                        Arrow::Left,
9309                        Arrow::Down,
9310                    ],
9311                );
9312                tester.pump_and_settle();
9313
9314                // Activate it to select the beginning of the range
9315                space(tester);
9316                tester.pump_and_settle();
9317
9318                // Navigate to Mar 17
9319                arrows(tester, &[Arrow::Down; 8]);
9320                arrows(tester, &[Arrow::Right; 3]);
9321                tester.pump_and_settle();
9322
9323                // Jan should have scrolled off, Mar should be visible
9324                expect(tester, &find::text("January 2016"), finds_nothing());
9325                expect(tester, &find::text("February 2016"), finds_one_widget());
9326                expect(tester, &find::text("March 2016"), finds_one_widget());
9327
9328                // Activate it to select the end of the range
9329                space(tester);
9330                tester.pump_and_settle();
9331
9332                // Navigate out of the grid and to the OK button
9333                tabs(tester, 3);
9334
9335                // Activate OK
9336                space(tester);
9337                tester.pump_and_settle();
9338
9339                // Should have selected Jan 18 - Mar 17
9340                assert_eq!(
9341                    picked_range(&result),
9342                    Some(range((2016, 1, 18), (2016, 3, 17)))
9343                );
9344            });
9345        }
9346
9347        #[test]
9348        fn range_keyboard_rtl_text_direction_reverses_the_horizontal_arrow_key_navigation() {
9349            test_widgets(|tester| {
9350                let mut prepare = Prepare::new();
9351                prepare.text_direction = TextDirection::Rtl;
9352                let result = prepare_picker(tester, &prepare);
9353                // Navigate to the grid
9354                tabs(tester, 4);
9355
9356                // Navigate from Jan 15 to 19 with arrow keys
9357                arrows(
9358                    tester,
9359                    &[
9360                        Arrow::Right,
9361                        Arrow::Right,
9362                        Arrow::Right,
9363                        Arrow::Right,
9364                        Arrow::Down,
9365                        Arrow::Left,
9366                    ],
9367                );
9368                tester.pump_and_settle();
9369
9370                // Activate it
9371                space(tester);
9372                tester.pump_and_settle();
9373
9374                // Navigate to Jan 21
9375                arrows(tester, &[Arrow::Left, Arrow::Left]);
9376                tester.pump_and_settle();
9377
9378                // Activate it
9379                space(tester);
9380                tester.pump_and_settle();
9381
9382                // Navigate out of the grid and to the OK button
9383                tabs(tester, 3);
9384
9385                // Activate OK
9386                space(tester);
9387                tester.pump_and_settle();
9388
9389                // Should have selected Jan 19 - Jan 21
9390                assert_eq!(
9391                    picked_range(&result),
9392                    Some(range((2016, 1, 19), (2016, 1, 21)))
9393                );
9394            });
9395        }
9396
9397        /// Records the haptic feedback the platform is asked for: Dart's `FeedbackTester`.
9398        #[derive(Default)]
9399        struct FeedbackTester {
9400            haptics: std::cell::RefCell<Vec<waft_embedder::HapticFeedbackType>>,
9401        }
9402
9403        impl waft_embedder::Haptics for FeedbackTester {
9404            fn feedback(&self, kind: waft_embedder::HapticFeedbackType) {
9405                self.haptics.borrow_mut().push(kind);
9406            }
9407        }
9408
9409        fn feedback_tester() -> (WidgetTester, Rc<FeedbackTester>) {
9410            let feedback = Rc::new(FeedbackTester::default());
9411            let platform = waft_test::TestPlatform::new()
9412                .on(TargetPlatform::Android)
9413                .with_haptics(Rc::clone(&feedback) as Rc<dyn waft_embedder::Haptics>);
9414            (WidgetTester::with_platform(platform), feedback)
9415        }
9416
9417        fn haptic_prepare() -> Prepare {
9418            let mut prepare = Prepare::new();
9419            prepare.initial_date_range = Some(range((2017, 1, 15), (2017, 1, 17)));
9420            prepare.first_date = local_date(2017, 1, 10);
9421            prepare.last_date = local_date(2018, 1, 20);
9422            prepare
9423        }
9424
9425        /// A regression test for https://github.com/flutter/flutter/issues/131989.
9426        #[test]
9427        fn dialog_contents_do_not_overflow_when_resized_from_landscape_to_portrait() {
9428            test_widgets(|tester| {
9429                // Initial window size is wide for landscape mode.
9430                size_view(tester, WIDE_WINDOW_SIZE);
9431                prepare_picker(tester, &Prepare::new());
9432
9433                // Change window size to narrow for portrait mode.
9434                tester.view().set_physical_size(NARROW_WINDOW_SIZE);
9435                tester.pump();
9436            });
9437        }
9438
9439        #[test]
9440        fn haptic_feedback_selecting_dates_vibrates() {
9441            test_widgets(|_| {
9442                let (mut feedback_tester, feedback) = feedback_tester();
9443                let tester = &mut feedback_tester;
9444                prepare_picker(tester, &haptic_prepare());
9445                let interval = std::time::Duration::from_millis(10);
9446                for (day, count) in [("10", 1), ("12", 2), ("14", 3)] {
9447                    tap_first(tester, day);
9448                    tester.pump_by(interval);
9449                    assert_eq!(feedback.haptics.borrow().len(), count, "after {day}");
9450                }
9451            });
9452        }
9453
9454        #[test]
9455        fn haptic_feedback_tapping_unselectable_date_does_not_vibrate() {
9456            test_widgets(|_| {
9457                let (mut feedback_tester, feedback) = feedback_tester();
9458                let tester = &mut feedback_tester;
9459                prepare_picker(tester, &haptic_prepare());
9460                tap_first(tester, "8");
9461                tester.pump_by(std::time::Duration::from_millis(10));
9462                assert_eq!(feedback.haptics.borrow().len(), 0);
9463            });
9464        }
9465
9466        #[test]
9467        fn range_picker_close_button_shape_should_be_square() {
9468            test_widgets(|tester| {
9469                let mut prepare = Prepare::new();
9470                prepare.use_material3 = true;
9471                prepare_picker(tester, &prepare);
9472                let theme = m3(&tester.cell.borrow());
9473                let button = icon_button_of(tester, &Icons::close());
9474                assert_eq!(tester.get_size(button), Size::new(48.0, 48.0));
9475
9476                // Test the close button overlay size is square.
9477                let center = tester.get_center(button);
9478                let mut pointer = TestPointer::mouse(1, 0);
9479                tester.add_pointer(&mut pointer, center);
9480                tester.move_to(&mut pointer, center, false);
9481                tester.pump_and_settle();
9482
9483                #[allow(deprecated)]
9484                let hover_color = theme.color_scheme.on_surface_variant().with_opacity(0.08);
9485                let render = tester.render_object(button);
9486                assert_paints(
9487                    &tester.painted_ops_deep(render),
9488                    &[PaintCall::rect_at(
9489                        waft_embedder::Rect::from_ltrb(0.0, 0.0, 40.0, 40.0),
9490                        Some(hover_color),
9491                    )],
9492                );
9493            });
9494        }
9495
9496        /// A regression test for https://github.com/flutter/flutter/issues/140311.
9497        #[test]
9498        fn range_text_fields_stay_visible_when_orientation_is_portrait_and_height_is_reduced() {
9499            test_widgets(|tester| {
9500                size_view(tester, Size::new(720.0, 1280.0));
9501                let mut prepare = Prepare::new();
9502                prepare.initial_entry_mode = DatePickerEntryMode::Input;
9503                prepare.use_material3 = true;
9504
9505                // Text fields and header are visible by default.
9506                prepare_picker(tester, &prepare);
9507                expect(tester, &find::by_type::<TextField>(), finds_n_widgets(2));
9508                expect(tester, &find::text("Select range"), finds_one_widget());
9509
9510                // Simulate the portait mode on a device with a small display when the virtual
9511                // keyboard is visible.
9512                tester.view().set_view_insets(waft_embedder::ViewPadding {
9513                    bottom: 1000.0,
9514                    ..waft_embedder::ViewPadding::ZERO
9515                });
9516                tester.pump_and_settle();
9517
9518                // Text fields are visible and header is hidden.
9519                expect(tester, &find::by_type::<TextField>(), finds_n_widgets(2));
9520                expect(tester, &find::text("Select range"), finds_nothing());
9521            });
9522        }
9523
9524        fn input_only_headline_font_size(tester: &mut WidgetTester, size: Size) -> Option<f64> {
9525            size_view(tester, size);
9526            let mut prepare = Prepare::new();
9527            prepare.initial_entry_mode = DatePickerEntryMode::Input;
9528            prepare.use_material3 = true;
9529            prepare_picker(tester, &prepare);
9530            let font_size = header_font_size(tester, "Jan 15 \u{2013} Jan 25, 2016");
9531            tester.tap(find::text("Cancel"));
9532            tester.pump_and_settle();
9533            font_size
9534        }
9535
9536        #[test]
9537        fn landscape_input_only_date_picker_headers_use_headline_small_in_portrait() {
9538            test_widgets(|tester| {
9539                assert_eq!(
9540                    input_only_headline_font_size(tester, Size::new(1070.0, 1770.0)),
9541                    Some(32.0)
9542                );
9543            });
9544        }
9545
9546        #[test]
9547        fn landscape_input_only_date_picker_headers_use_headline_small_in_landscape() {
9548            test_widgets(|tester| {
9549                assert_eq!(
9550                    input_only_headline_font_size(tester, Size::new(1770.0, 1070.0)),
9551                    Some(24.0)
9552                );
9553            });
9554        }
9555
9556        fn pump_icon_app(
9557            tester: &mut WidgetTester,
9558            use_material3: bool,
9559            initial_entry_mode: DatePickerEntryMode,
9560            switch_to_input_entry_mode_icon: Option<fn() -> Icon>,
9561            switch_to_calendar_entry_mode_icon: Option<fn() -> Icon>,
9562        ) {
9563            let mut prepare = Prepare::new();
9564            prepare.use_material3 = use_material3;
9565            prepare.first_date = local_date(2020, 1, 1);
9566            prepare.last_date = local_date(2030, 1, 1);
9567            prepare.initial_date_range = None;
9568            prepare.initial_entry_mode = initial_entry_mode;
9569            prepare.cancel_text = Some("CANCEL".to_string());
9570            prepare.switch_to_input_entry_mode_icon = switch_to_input_entry_mode_icon;
9571            prepare.switch_to_calendar_entry_mode_icon = switch_to_calendar_entry_mode_icon;
9572            prepare_picker(tester, &prepare);
9573        }
9574
9575        #[test]
9576        fn range_honors_switch_to_input_entry_mode_icon() {
9577            test_widgets(|tester| {
9578                pump_icon_app(tester, false, DatePickerEntryMode::Calendar, None, None);
9579                assert_eq!(find::by_icon(&Icons::edit()).evaluate(tester).len(), 1);
9580                tap_icon(tester, &Icons::close());
9581
9582                pump_icon_app(tester, true, DatePickerEntryMode::Calendar, None, None);
9583                assert_eq!(
9584                    find::by_icon(&Icons::edit_outlined())
9585                        .evaluate(tester)
9586                        .len(),
9587                    1
9588                );
9589                tap_icon(tester, &Icons::close());
9590
9591                pump_icon_app(
9592                    tester,
9593                    false,
9594                    DatePickerEntryMode::Calendar,
9595                    Some(|| Icon::new(Some(Icons::keyboard()))),
9596                    None,
9597                );
9598                assert_eq!(find::by_icon(&Icons::keyboard()).evaluate(tester).len(), 1);
9599                tap_icon(tester, &Icons::close());
9600            });
9601        }
9602
9603        #[test]
9604        fn range_honors_switch_to_calendar_entry_mode_icon() {
9605            test_widgets(|tester| {
9606                pump_icon_app(tester, false, DatePickerEntryMode::Input, None, None);
9607                assert_eq!(
9608                    find::by_icon(&Icons::calendar_today())
9609                        .evaluate(tester)
9610                        .len(),
9611                    1
9612                );
9613                tester.tap(find::text("CANCEL"));
9614                tester.pump_and_settle();
9615
9616                pump_icon_app(tester, true, DatePickerEntryMode::Input, None, None);
9617                assert_eq!(
9618                    find::by_icon(&Icons::calendar_today())
9619                        .evaluate(tester)
9620                        .len(),
9621                    1
9622                );
9623                tester.tap(find::text("CANCEL"));
9624                tester.pump_and_settle();
9625
9626                pump_icon_app(
9627                    tester,
9628                    false,
9629                    DatePickerEntryMode::Input,
9630                    None,
9631                    Some(|| Icon::new(Some(Icons::favorite()))),
9632                );
9633                assert_eq!(find::by_icon(&Icons::favorite()).evaluate(tester).len(), 1);
9634                tester.tap(find::text("CANCEL"));
9635                tester.pump_and_settle();
9636            });
9637        }
9638
9639        fn keyboard_type_of_shown_dialog(
9640            tester: &mut WidgetTester,
9641            keyboard_type: Option<TextInputType>,
9642        ) -> TextInputType {
9643            let (first_date, last_date) = dialog_first_last();
9644            let launcher = Material::new()
9645                .child(Builder::new(move |_app, context| {
9646                    // If no keyboardType, expect the default.
9647                    let keyboard_type = keyboard_type.unwrap_or(TextInputType::DATETIME);
9648                    ElevatedButton::new(
9649                        Some(Listener::new(move |app| {
9650                            drop(
9651                                ShowDateRangePicker::new(first_date, last_date)
9652                                    .initial_date_range(range((2016, 1, 15), (2016, 1, 25)))
9653                                    .initial_entry_mode(DatePickerEntryMode::Input)
9654                                    .keyboard_type(keyboard_type)
9655                                    .calendar_delegate(Rc::new(GregorianCalendarDelegate))
9656                                    .show(app, context),
9657                            );
9658                        })),
9659                        Some(Text::new("Go")),
9660                    )
9661                    .into_widget()
9662                }))
9663                .into_widget();
9664            let theme = m2(&tester.cell.borrow());
9665            tester.pump_widget(material_app(theme, launcher));
9666            tester.tap(find::text("Go"));
9667            tester.pump_and_settle();
9668            let dialog = tester.element(find::by_type::<DateRangePickerDialog>().at(0));
9669            tester.widget(dialog, |dialog: &DateRangePickerDialog| {
9670                dialog.keyboard_type
9671            })
9672        }
9673
9674        #[test]
9675        fn date_range_picker_takes_the_default_keyboard_type() {
9676            test_widgets(|tester| {
9677                assert_eq!(
9678                    keyboard_type_of_shown_dialog(tester, None),
9679                    TextInputType::DATETIME
9680                );
9681            });
9682        }
9683
9684        #[test]
9685        fn date_range_picker_takes_keyboard_type_email_address() {
9686            test_widgets(|tester| {
9687                assert_eq!(
9688                    keyboard_type_of_shown_dialog(tester, Some(TextInputType::EMAIL_ADDRESS)),
9689                    TextInputType::EMAIL_ADDRESS
9690                );
9691            });
9692        }
9693
9694        fn pump_range_dialog(tester: &mut WidgetTester, dialog: DateRangePickerDialog) {
9695            let theme = m3(&tester.cell.borrow());
9696            tester.pump_widget(material_app(
9697                theme,
9698                Material::new().child(dialog).into_widget(),
9699            ));
9700        }
9701
9702        fn dialog_first_last() -> (DateTime, DateTime) {
9703            (local_date(2015, 1, 1), local_date(2016, 12, 31))
9704        }
9705
9706        #[test]
9707        fn range_calendar_delegate_displays_calendar_based_on_the_calendar_delegate() {
9708            test_widgets(|tester| {
9709                let (first_date, last_date) = dialog_first_last();
9710                pump_range_dialog(
9711                    tester,
9712                    DateRangePickerDialog::new(first_date, last_date)
9713                        .initial_date_range(range((2016, 1, 15), (2016, 1, 25)))
9714                        .calendar_delegate(Rc::new(super::dialog::TestDelegate::Calendar)),
9715                );
9716
9717                // The month a header text titles: its nearest enclosing Column.
9718                let day_count = |month_year: &str| {
9719                    let month = find::ancestor(
9720                        find::text(month_year),
9721                        find::by_type::<waft_widgets::Column>(),
9722                    )
9723                    .first();
9724                    find::descendant(
9725                        find::descendant(month, find::by_type::<crate::ink_well::InkResponse>()),
9726                        find::by_type::<Text>(),
9727                    )
9728                    .evaluate(tester)
9729                    .len()
9730                };
9731                assert_eq!(day_count("January 2016"), 28);
9732                assert_eq!(day_count("February 2016"), 21);
9733            });
9734        }
9735
9736        /// The texts both `showDateRangePicker` delegate cases expect once each.
9737        fn assert_default_range_header(tester: &WidgetTester) {
9738            expect(tester, &find::text("Select range"), finds_one_widget());
9739            expect(tester, &find::text("Jan 15"), finds_one_widget());
9740            expect(tester, &find::text("Jan 25, 2016"), finds_one_widget());
9741            expect(tester, &find::text("Save"), finds_one_widget());
9742        }
9743
9744        #[test]
9745        fn show_date_range_picker_uses_gregorian_calendar_delegate_by_default() {
9746            test_widgets(|tester| {
9747                let mut prepare = Prepare::new();
9748                prepare.use_material3 = true;
9749                prepare_picker(tester, &prepare);
9750                assert_default_range_header(tester);
9751            });
9752        }
9753
9754        #[test]
9755        fn show_date_range_picker_using_custom_calendar_delegate_implementation() {
9756            test_widgets(|tester| {
9757                let mut prepare = Prepare::new();
9758                prepare.use_material3 = true;
9759                prepare.calendar_delegate = Rc::new(super::dialog::TestDelegate::Calendar);
9760                prepare_picker(tester, &prepare);
9761                assert_default_range_header(tester);
9762            });
9763        }
9764
9765        #[test]
9766        fn date_range_picker_dialog_does_not_crash_at_zero_area() {
9767            test_widgets(|tester| {
9768                let (first_date, last_date) = dialog_first_last();
9769                let theme = m3(&tester.cell.borrow());
9770                tester.pump_widget(material_app(
9771                    theme,
9772                    Center::new()
9773                        .child(
9774                            waft_widgets::SizedBox::shrink()
9775                                .child(DateRangePickerDialog::new(first_date, last_date)),
9776                        )
9777                        .into_widget(),
9778                ));
9779                let dialog = tester.element(find::by_type::<DateRangePickerDialog>().at(0));
9780                assert_eq!(tester.get_size(dialog), Size::new(0.0, 0.0));
9781            });
9782        }
9783
9784        #[test]
9785        fn local_input_decoration_theme_is_honored() {
9786            test_widgets(|tester| {
9787                let (first_date, last_date) = dialog_first_last();
9788                let theme = m3(&tester.cell.borrow());
9789                tester.pump_widget(material_app(
9790                    theme,
9791                    Center::new()
9792                        .child(
9793                            crate::input_decorator::InputDecorationTheme::new()
9794                                .with_data(
9795                                    crate::input_decorator::InputDecorationThemeData::new()
9796                                        .filled(true),
9797                                )
9798                                .child(
9799                                    DateRangePickerDialog::new(first_date, last_date)
9800                                        .with_current_date(local_date(2016, 1, 30))
9801                                        .initial_entry_mode(DatePickerEntryMode::InputOnly),
9802                                ),
9803                        )
9804                        .into_widget(),
9805                ));
9806                let start_date_decoration = input_text_field_decoration(tester, 0);
9807                assert_eq!(start_date_decoration.filled, Some(true));
9808            });
9809        }
9810
9811        #[test]
9812        fn date_range_picker_dialog_current_date_is_optional() {
9813            test_widgets(|tester| {
9814                let (first_date, last_date) = dialog_first_last();
9815                let theme = m3(&tester.cell.borrow());
9816                tester.pump_widget(material_app(
9817                    theme,
9818                    Center::new()
9819                        .child(
9820                            crate::input_decorator::InputDecorationTheme::new()
9821                                .with_data(
9822                                    crate::input_decorator::InputDecorationThemeData::new()
9823                                        .filled(true),
9824                                )
9825                                .child(
9826                                    DateRangePickerDialog::new(first_date, last_date)
9827                                        .initial_entry_mode(DatePickerEntryMode::InputOnly),
9828                                ),
9829                        )
9830                        .into_widget(),
9831                ));
9832                assert_eq!(field_count(tester), 2);
9833            });
9834        }
9835
9836        #[test]
9837        fn date_range_picker_respects_date_picker_theme_day_shape() {
9838            test_widgets(|tester| {
9839                let custom_shape = waft_painting::BeveledRectangleBorder::new(
9840                    BorderSide::NONE,
9841                    BorderRadiusGeometry::circular(10.0),
9842                );
9843                let theme = {
9844                    let app = tester.cell.borrow();
9845                    ThemeData::builder()
9846                        .date_picker_theme(
9847                            crate::date_picker_theme::DatePickerThemeData::new().day_shape(
9848                                <dyn waft_widgets::WidgetStateProperty<
9849                                        Option<waft_painting::OutlinedBorderRef>,
9850                                    >>::all(Some(
9851                                    waft_painting::OutlinedBorderRef::new(custom_shape),
9852                                )),
9853                            ),
9854                        )
9855                        .build(&app)
9856                };
9857                let mut prepare = Prepare::new();
9858                prepare.first_date = local_date(2023, 1, 1);
9859                prepare.last_date = local_date(2024, 1, 1);
9860                prepare.initial_date_range = Some(range((2023, 1, 15), (2023, 1, 20)));
9861                let launcher = Material::new()
9862                    .child(Builder::new(move |_app, context| {
9863                        let prepare = prepare.clone();
9864                        ElevatedButton::new(
9865                            Some(Listener::new(move |app| drop(prepare.show(app, context)))),
9866                            Some(Text::new("Open Picker")),
9867                        )
9868                        .into_widget()
9869                    }))
9870                    .into_widget();
9871                tester.pump_widget(material_app(theme, launcher));
9872                tester.tap(find::text("Open Picker"));
9873                tester.pump_and_settle();
9874
9875                let selected_day_text = first_text(tester, "15");
9876                let shapes: Vec<ShapeBorderRef> = tester
9877                    .ancestors(selected_day_text)
9878                    .into_iter()
9879                    .filter_map(|ancestor| {
9880                        let app = tester.cell.borrow();
9881                        let container = waft_widgets::downcast_widget::<waft_widgets::Container>(
9882                            &**ancestor.widget(&app),
9883                        )?;
9884                        container
9885                            .decoration
9886                            .as_deref()?
9887                            .as_any()
9888                            .downcast_ref::<waft_painting::ShapeDecoration>()
9889                            .map(|decoration| decoration.shape.clone())
9890                    })
9891                    .collect();
9892                assert_eq!(shapes.first(), Some(&ShapeBorderRef::new(custom_shape)));
9893            });
9894        }
9895    }
9896}