Skip to main content

waft_material/
input_date_picker_form_field.rs

1//! Flutter counterpart: material_ui's `input_date_picker_form_field.dart`.
2//!
3//! A text field that takes a date typed in the locale's compact format, validated against a
4//! date range, for the input mode of the date pickers.
5
6use std::fmt;
7use std::rc::Rc;
8
9use waft_embedder::{TextEditingValue, TextInputType, TextSelection};
10use waft_foundation::{App, DateTime, Handle, Ref, ValueChanged};
11use waft_scheduler::{FrameCallback, SchedulerBinding};
12use waft_widgets::{
13    BuildContext, FocusNodeRef, IntoWidget, KeyRef, SelectableDayPredicate, Semantics, State,
14    StateData, StatefulWidget, TextEditingController, TextEditingControllerLeaf, WidgetRef,
15};
16
17use crate::date::{CalendarDelegate, GregorianCalendarDelegate, is_day_before};
18use crate::input_border::{InputBorderRef, OutlineInputBorder, UnderlineInputBorder};
19use crate::input_decorator::{InputDecoration, InputDecorationTheme};
20use crate::material_localizations::MaterialLocalizations;
21use crate::text_form_field::TextFormField;
22use crate::theme::Theme;
23
24/// A [`TextFormField`] configured to accept and validate a date entered by a user.
25///
26/// When the field is saved or submitted, the text will be parsed into a [`DateTime`] according
27/// to the ambient locale's compact date format. If the input text doesn't parse into a date,
28/// the [`error_format_text`](Self::error_format_text) message will be displayed under the field.
29///
30/// [`first_date`](Self::first_date), [`last_date`](Self::last_date), and
31/// [`selectable_day_predicate`](Self::selectable_day_predicate) provide constraints on the
32/// dates that are valid. If the input date isn't in the date range or doesn't pass the given
33/// predicate, then the [`error_invalid_text`](Self::error_invalid_text) message will be
34/// displayed under the field.
35///
36/// In addition to validating the user input text, this widget can accept user input
37/// through the keyboard or other input methods, via the field's text editing; the date it
38/// shows is the [`initial_date`](Self::initial_date), formatted.
39///
40/// Requires a [`MaterialLocalizations`] and a [`Directionality`](waft_widgets::Directionality)
41/// ancestor.
42///
43/// See also:
44///
45///  * `showDatePicker`, which shows a dialog that contains a Material Design date picker which
46///    includes support for text entry of dates.
47pub struct InputDatePickerFormField {
48    pub key: Option<KeyRef>,
49
50    /// If provided, it will be used as the default value of the field.
51    pub initial_date: Option<DateTime>,
52
53    /// The earliest allowable [`DateTime`] that the user can input.
54    pub first_date: DateTime,
55
56    /// The latest allowable [`DateTime`] that the user can input.
57    pub last_date: DateTime,
58
59    /// An optional method to call when the user indicates they are done editing the text in
60    /// the field. Will only be called if the input represents a valid [`DateTime`].
61    pub on_date_submitted: Option<ValueChanged<DateTime>>,
62
63    /// An optional method to call with the final date when the form is saved via
64    /// `FormState::save`. Will only be called if the input represents a valid [`DateTime`].
65    pub on_date_saved: Option<ValueChanged<DateTime>>,
66
67    /// Function to provide full control over which [`DateTime`] can be selected.
68    pub selectable_day_predicate: Option<SelectableDayPredicate>,
69
70    /// The error text displayed if the entered date is not in the correct format.
71    pub error_format_text: Option<String>,
72
73    /// The error text displayed if the date is not valid.
74    ///
75    /// A date is not valid if it is earlier than [`first_date`](Self::first_date), later than
76    /// [`last_date`](Self::last_date), or doesn't pass the
77    /// [`selectable_day_predicate`](Self::selectable_day_predicate).
78    pub error_invalid_text: Option<String>,
79
80    /// The hint text displayed in the [`TextField`](crate::TextField).
81    ///
82    /// If this is null, it will default to the date format string. For example, 'mm/dd/yyyy'
83    /// for en_US.
84    pub field_hint_text: Option<String>,
85
86    /// The label text displayed in the [`TextField`](crate::TextField).
87    ///
88    /// If this is null, it will default to the words representing the date format string.
89    /// For example, 'Enter Date' for en_US.
90    pub field_label_text: Option<String>,
91
92    /// The keyboard type of the [`TextField`](crate::TextField).
93    ///
94    /// If this is null, it will default to [`TextInputType::DATETIME`].
95    pub keyboard_type: Option<TextInputType>,
96
97    /// Whether this field should focus itself if nothing else is already focused.
98    ///
99    /// If true, the keyboard will open as soon as this input obtains focus. Otherwise, the
100    /// keyboard is only shown after the user taps the text field.
101    ///
102    /// Defaults to false.
103    pub autofocus: bool,
104
105    /// Determines if an empty date would show [`error_format_text`](Self::error_format_text) or
106    /// not.
107    ///
108    /// Defaults to false.
109    ///
110    /// When [`autofocus`](Self::autofocus) is true and the date is empty, an error is not
111    /// shown.
112    pub accept_empty_date: bool,
113
114    /// Focus node of the field.
115    pub focus_node: Option<FocusNodeRef>,
116
117    /// The calendar system to use.
118    ///
119    /// Defaults to [`GregorianCalendarDelegate`].
120    pub calendar_delegate: Rc<dyn CalendarDelegate>,
121}
122
123impl InputDatePickerFormField {
124    /// Creates a [`TextFormField`] configured to accept and validate a date; Dart's optional
125    /// named arguments are the setters.
126    ///
127    /// If the optional [`initial_date`](Self::initial_date) is provided, then it will be used
128    /// to populate the text field. If the [`initial_date`](Self::initial_date) is outside of
129    /// the allowed range, it will be shown as the initial text, and an error will be shown.
130    pub fn new(first_date: DateTime, last_date: DateTime) -> InputDatePickerFormField {
131        InputDatePickerFormField {
132            key: None,
133            initial_date: None,
134            first_date,
135            last_date,
136            on_date_submitted: None,
137            on_date_saved: None,
138            selectable_day_predicate: None,
139            error_format_text: None,
140            error_invalid_text: None,
141            field_hint_text: None,
142            field_label_text: None,
143            keyboard_type: None,
144            autofocus: false,
145            accept_empty_date: false,
146            focus_node: None,
147            calendar_delegate: Rc::new(GregorianCalendarDelegate),
148        }
149    }
150
151    /// Dart's `initialDate` field, as its constructor fills it: the day of the date given.
152    pub fn effective_initial_date(&self, app: &App) -> Option<DateTime> {
153        self.initial_date
154            .map(|date| self.calendar_delegate.date_only(app, &date))
155    }
156
157    /// Dart's `firstDate` field, as its constructor fills it: the day of the date given.
158    pub fn effective_first_date(&self, app: &App) -> DateTime {
159        self.calendar_delegate.date_only(app, &self.first_date)
160    }
161
162    /// Dart's `lastDate` field, as its constructor fills it: the day of the date given.
163    pub fn effective_last_date(&self, app: &App) -> DateTime {
164        self.calendar_delegate.date_only(app, &self.last_date)
165    }
166
167    /// Dart's constructor assert that the initial day satisfies `selectableDayPredicate`, which
168    /// takes the day `date_only` makes, so it runs once the `App` is at hand.
169    fn debug_check_initial_date_is_selectable(&self, app: &App) {
170        debug_assert!(
171            self.selectable_day_predicate
172                .as_ref()
173                .is_none_or(|predicate| self
174                    .effective_initial_date(app)
175                    .is_none_or(|date| predicate(app, date))),
176            "Provided initialDate {:?} must satisfy provided selectableDayPredicate.",
177            self.effective_initial_date(app)
178        );
179    }
180
181    /// Dart `InputDatePickerFormField(key:)`.
182    pub fn key(mut self, key: KeyRef) -> InputDatePickerFormField {
183        self.key = Some(key);
184        self
185    }
186
187    /// Dart `InputDatePickerFormField(initialDate:)`.
188    pub fn initial_date(mut self, initial_date: DateTime) -> InputDatePickerFormField {
189        self.initial_date = Some(initial_date);
190        self
191    }
192
193    /// Dart `InputDatePickerFormField(onDateSubmitted:)`.
194    pub fn on_date_submitted(
195        mut self,
196        on_date_submitted: ValueChanged<DateTime>,
197    ) -> InputDatePickerFormField {
198        self.on_date_submitted = Some(on_date_submitted);
199        self
200    }
201
202    /// Dart `InputDatePickerFormField(onDateSaved:)`.
203    pub fn on_date_saved(
204        mut self,
205        on_date_saved: ValueChanged<DateTime>,
206    ) -> InputDatePickerFormField {
207        self.on_date_saved = Some(on_date_saved);
208        self
209    }
210
211    /// Dart `InputDatePickerFormField(selectableDayPredicate:)`.
212    pub fn selectable_day_predicate(
213        mut self,
214        selectable_day_predicate: SelectableDayPredicate,
215    ) -> InputDatePickerFormField {
216        self.selectable_day_predicate = Some(selectable_day_predicate);
217        self
218    }
219
220    /// Dart `InputDatePickerFormField(errorFormatText:)`.
221    pub fn error_format_text(
222        mut self,
223        error_format_text: impl Into<String>,
224    ) -> InputDatePickerFormField {
225        self.error_format_text = Some(error_format_text.into());
226        self
227    }
228
229    /// Dart `InputDatePickerFormField(errorInvalidText:)`.
230    pub fn error_invalid_text(
231        mut self,
232        error_invalid_text: impl Into<String>,
233    ) -> InputDatePickerFormField {
234        self.error_invalid_text = Some(error_invalid_text.into());
235        self
236    }
237
238    /// Dart `InputDatePickerFormField(fieldHintText:)`.
239    pub fn field_hint_text(
240        mut self,
241        field_hint_text: impl Into<String>,
242    ) -> InputDatePickerFormField {
243        self.field_hint_text = Some(field_hint_text.into());
244        self
245    }
246
247    /// Dart `InputDatePickerFormField(fieldLabelText:)`.
248    pub fn field_label_text(
249        mut self,
250        field_label_text: impl Into<String>,
251    ) -> InputDatePickerFormField {
252        self.field_label_text = Some(field_label_text.into());
253        self
254    }
255
256    /// Dart `InputDatePickerFormField(keyboardType:)`.
257    pub fn keyboard_type(mut self, keyboard_type: TextInputType) -> InputDatePickerFormField {
258        self.keyboard_type = Some(keyboard_type);
259        self
260    }
261
262    /// Dart `InputDatePickerFormField(autofocus:)`.
263    pub fn autofocus(mut self, autofocus: bool) -> InputDatePickerFormField {
264        self.autofocus = autofocus;
265        self
266    }
267
268    /// Dart `InputDatePickerFormField(acceptEmptyDate:)`.
269    pub fn accept_empty_date(mut self, accept_empty_date: bool) -> InputDatePickerFormField {
270        self.accept_empty_date = accept_empty_date;
271        self
272    }
273
274    /// Dart `InputDatePickerFormField(focusNode:)`.
275    pub fn focus_node(mut self, focus_node: FocusNodeRef) -> InputDatePickerFormField {
276        self.focus_node = Some(focus_node);
277        self
278    }
279
280    /// Dart `InputDatePickerFormField(calendarDelegate:)`.
281    pub fn calendar_delegate(
282        mut self,
283        calendar_delegate: Rc<dyn CalendarDelegate>,
284    ) -> InputDatePickerFormField {
285        self.calendar_delegate = calendar_delegate;
286        self
287    }
288}
289
290impl fmt::Debug for InputDatePickerFormField {
291    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
292        f.debug_struct("InputDatePickerFormField")
293            .field("initial_date", &self.initial_date)
294            .field("first_date", &self.first_date)
295            .field("last_date", &self.last_date)
296            .field("autofocus", &self.autofocus)
297            .field("accept_empty_date", &self.accept_empty_date)
298            .finish_non_exhaustive()
299    }
300}
301
302impl InputDatePickerFormField {
303    /// Dart's constructor asserts on the dates, by their days, which are read in the local time
304    /// zone: run in `init_state` and `did_update_widget`, for every widget the state is given,
305    /// since a constructor has no [`App`].
306    fn debug_check_dates(&self, app: &App) {
307        debug_assert!(
308            !is_day_before(app, &self.last_date, &self.first_date),
309            "lastDate {} must be on or after firstDate {}.",
310            self.last_date.to_string(app),
311            self.first_date.to_string(app)
312        );
313        debug_assert!(
314            self.initial_date
315                .is_none_or(|date| !is_day_before(app, &date, &self.first_date)),
316            "initialDate {:?} must be on or after firstDate {}.",
317            self.initial_date.map(|date| date.to_string(app)),
318            self.first_date.to_string(app)
319        );
320        debug_assert!(
321            self.initial_date
322                .is_none_or(|date| !is_day_before(app, &self.last_date, &date)),
323            "initialDate {:?} must be on or before lastDate {}.",
324            self.initial_date.map(|date| date.to_string(app)),
325            self.last_date.to_string(app)
326        );
327    }
328}
329
330impl StatefulWidget for InputDatePickerFormField {
331    type State = InputDatePickerFormFieldState;
332
333    fn key(&self) -> Option<&KeyRef> {
334        self.key.as_ref()
335    }
336
337    fn create_state(&self) -> InputDatePickerFormFieldState {
338        InputDatePickerFormFieldState {
339            state: StateData::new(),
340            controller: None,
341            selected_date: None,
342            input_text: None,
343            auto_selected: false,
344        }
345    }
346}
347
348/// Dart's `_InputDatePickerFormFieldState`.
349pub struct InputDatePickerFormFieldState {
350    state: StateData<InputDatePickerFormField>,
351    /// Created in `init_state`, because a state is created without the [`App`].
352    controller: Option<Ref<TextEditingController>>,
353    selected_date: Option<DateTime>,
354    input_text: Option<String>,
355    auto_selected: bool,
356}
357
358impl InputDatePickerFormFieldState {
359    fn controller(self: Handle<Self>, app: &App) -> Ref<TextEditingController> {
360        app.get(self)
361            .controller
362            .clone()
363            .expect("created in init_state")
364    }
365
366    fn update_value_for_selected_date(self: Handle<Self>, app: &mut App) {
367        let context = self.context(app);
368        let controller = self.controller(app).handle();
369        if let Some(selected_date) = app.get(self).selected_date {
370            let localizations = <dyn MaterialLocalizations>::of(app, context);
371            let widget = self.widget(app);
372            let autofocus = widget.autofocus;
373            let input_text =
374                widget
375                    .calendar_delegate
376                    .format_compact_date(app, &selected_date, &*localizations);
377            let mut text_editing_value = TextEditingValue::new().text(input_text.clone());
378            // Select the new text if we are auto focused and haven't selected the text before.
379            if autofocus && !app.get(self).auto_selected {
380                text_editing_value = text_editing_value.selection(TextSelection::new(
381                    0,
382                    input_text.encode_utf16().count() as i32,
383                ));
384                app.get_mut(self).auto_selected = true;
385            }
386            app.get_mut(self).input_text = Some(input_text);
387            controller.set_value(app, text_editing_value);
388        } else {
389            app.get_mut(self).input_text = Some(String::new());
390            controller.set_value(app, TextEditingValue::new().text(""));
391        }
392    }
393
394    fn parse_date(self: Handle<Self>, app: &mut App, text: Option<&str>) -> Option<DateTime> {
395        let context = self.context(app);
396        let localizations = <dyn MaterialLocalizations>::of(app, context);
397        self.widget(app)
398            .calendar_delegate
399            .parse_compact_date(app, text, &*localizations)
400    }
401
402    fn is_valid_acceptable_date(self: Handle<Self>, app: &App, date: Option<&DateTime>) -> bool {
403        let widget = self.widget(app);
404        date.is_some_and(|date| {
405            !date.is_before(&widget.effective_first_date(app))
406                && !date.is_after(&widget.effective_last_date(app))
407                && widget
408                    .selectable_day_predicate
409                    .as_ref()
410                    .is_none_or(|predicate| predicate(app, *date))
411        })
412    }
413
414    fn validate_date(self: Handle<Self>, app: &mut App, text: Option<&String>) -> Option<String> {
415        if text.is_none_or(|text| text.is_empty()) && self.widget(app).accept_empty_date {
416            return None;
417        }
418        let context = self.context(app);
419        let date = self.parse_date(app, text.map(String::as_str));
420        match date {
421            None => Some(
422                self.widget(app)
423                    .error_format_text
424                    .clone()
425                    .unwrap_or_else(|| {
426                        <dyn MaterialLocalizations>::of(app, context).invalid_date_format_label()
427                    }),
428            ),
429            Some(date) if !self.is_valid_acceptable_date(app, Some(&date)) => Some(
430                self.widget(app)
431                    .error_invalid_text
432                    .clone()
433                    .unwrap_or_else(|| {
434                        <dyn MaterialLocalizations>::of(app, context).date_out_of_range_label()
435                    }),
436            ),
437            Some(_) => None,
438        }
439    }
440
441    fn update_date(
442        self: Handle<Self>,
443        app: &mut App,
444        text: Option<&str>,
445        callback: Option<ValueChanged<DateTime>>,
446    ) {
447        let date = self.parse_date(app, text);
448        if self.is_valid_acceptable_date(app, date.as_ref()) {
449            app.get_mut(self).selected_date = date;
450            app.get_mut(self).input_text = text.map(str::to_owned);
451            if let (Some(callback), Some(date)) = (callback, date) {
452                callback(app, date);
453            }
454        }
455    }
456
457    fn handle_saved(self: Handle<Self>, app: &mut App, text: Option<String>) {
458        let callback = self.widget(app).on_date_saved.clone();
459        self.update_date(app, text.as_deref(), callback);
460    }
461
462    fn handle_submitted(self: Handle<Self>, app: &mut App, text: String) {
463        let callback = self.widget(app).on_date_submitted.clone();
464        self.update_date(app, Some(&text), callback);
465    }
466}
467
468impl State for InputDatePickerFormFieldState {
469    type Widget = InputDatePickerFormField;
470    waft_widgets::state_accessors!();
471
472    fn init_state(self: Handle<Self>, app: &mut App) {
473        self.widget(app).debug_check_dates(app);
474        self.widget(app).debug_check_initial_date_is_selectable(app);
475        let controller = TextEditingController::new(app);
476        let initial_date = self.widget(app).effective_initial_date(app);
477        let state = app.get_mut(self);
478        state.controller = Some(controller);
479        state.selected_date = initial_date;
480    }
481
482    fn dispose(self: Handle<Self>, app: &mut App) {
483        self.controller(app).handle().dispose(app);
484    }
485
486    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
487        self.update_value_for_selected_date(app);
488    }
489
490    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &InputDatePickerFormField) {
491        self.widget(app).debug_check_dates(app);
492        self.widget(app).debug_check_initial_date_is_selectable(app);
493        if self.widget(app).effective_initial_date(app) != old_widget.effective_initial_date(app) {
494            // Can't update the form field in the middle of a build, so do it next frame
495            SchedulerBinding::add_post_frame_callback(
496                app,
497                FrameCallback::new(move |app, _duration| {
498                    if !self.mounted(app) {
499                        return;
500                    }
501                    let initial_date = self.widget(app).effective_initial_date(app);
502                    app.get_mut(self).selected_date = initial_date;
503                    self.update_value_for_selected_date(app);
504                    self.set_state(app, |_| {});
505                }),
506                None,
507            );
508        }
509    }
510
511    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
512        let theme = Theme::of(app, context);
513        let use_material3 = theme.use_material3;
514        let localizations = <dyn MaterialLocalizations>::of(app, context);
515        let date_picker_theme = theme.date_picker_theme.clone();
516        let input_theme = InputDecorationTheme::of(app, context);
517        let effective_input_border = date_picker_theme
518            .input_decoration_theme
519            .as_ref()
520            .and_then(|theme| theme.border.clone())
521            .or_else(|| input_theme.border.clone())
522            .unwrap_or_else(|| {
523                if use_material3 {
524                    InputBorderRef::new(OutlineInputBorder::new())
525                } else {
526                    InputBorderRef::new(UnderlineInputBorder::new())
527                }
528            });
529
530        let widget = self.widget(app);
531        let delegate = widget.calendar_delegate.clone();
532        let hint_text = widget
533            .field_hint_text
534            .clone()
535            .unwrap_or_else(|| delegate.date_help_text(&*localizations));
536        let label_text = widget
537            .field_label_text
538            .clone()
539            .unwrap_or_else(|| localizations.date_input_label());
540        let keyboard_type = widget.keyboard_type.unwrap_or(TextInputType::DATETIME);
541        let autofocus = widget.autofocus;
542        let focus_node = widget.focus_node.clone();
543        let input_formatters = delegate.keyboard_input_formatters(&*localizations);
544        let controller = self.controller(app);
545
546        let mut merged = input_theme.merge(date_picker_theme.input_decoration_theme.as_ref());
547        merged.border = Some(effective_input_border);
548        let decoration = InputDecoration::new()
549            .hint_text(hint_text)
550            .label_text(label_text)
551            .apply_defaults(merged);
552
553        let mut field = TextFormField::new()
554            .decoration(Some(decoration))
555            .validator(move |app, text| self.validate_date(app, text))
556            .keyboard_type(keyboard_type)
557            .on_saved(move |app, text| self.handle_saved(app, text))
558            .on_field_submitted(move |app, text| self.handle_submitted(app, text))
559            .autofocus(autofocus)
560            .controller(controller.erase());
561        if let Some(focus_node) = focus_node {
562            field = field.focus_node(focus_node);
563        }
564        if let Some(input_formatters) = input_formatters {
565            field = field.input_formatters(input_formatters);
566        }
567        Semantics::new().container(true).child(field).into_widget()
568    }
569}
570
571impl fmt::Debug for InputDatePickerFormFieldState {
572    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
573        f.debug_struct("InputDatePickerFormFieldState")
574            .field("selected_date", &self.selected_date)
575            .field("input_text", &self.input_text)
576            .finish_non_exhaustive()
577    }
578}
579
580#[cfg(test)]
581mod tests {
582    use crate::test_support::local_date;
583    use std::cell::Cell;
584
585    use waft_embedder::TargetPlatform;
586    use waft_widgets::{FocusNode, Form, FormState, GlobalKey};
587
588    use waft_widgets::testing::{WidgetTester, expect, find, finds_one_widget, test_widgets};
589
590    use super::*;
591    use crate::date::{CalendarDelegate, GregorianCalendarDelegate};
592    use crate::input_decorator::InputDecorationThemeData;
593    use crate::material::Material;
594    use crate::material_localizations::MaterialLocalizations;
595    use crate::test_support::{PaintInspection, material_app};
596    use crate::text_field::TextField;
597    use crate::theme_data::ThemeData;
598    use waft_rendering::testing::{PaintCall, PaintedStyle, assert_paints, paints};
599
600    /// The options of Dart's test helper `inputDatePickerField(..)`.
601    #[derive(Clone, Default)]
602    struct FieldOptions {
603        initial_date: Option<DateTime>,
604        first_date: Option<DateTime>,
605        last_date: Option<DateTime>,
606        on_date_saved: Option<ValueChanged<DateTime>>,
607        selectable_day_predicate: Option<SelectableDayPredicate>,
608        error_format_text: Option<String>,
609        error_invalid_text: Option<String>,
610        accept_empty_date: bool,
611        form_key: Option<GlobalKey>,
612        focus_node: Option<FocusNodeRef>,
613        field_hint_text: Option<String>,
614        field_label_text: Option<String>,
615        theme: Option<ThemeData>,
616    }
617
618    fn input_date_picker_field(tester: &WidgetTester, options: FieldOptions) -> WidgetRef {
619        let mut field = InputDatePickerFormField::new(
620            options.first_date.unwrap_or(local_date(2001, 1, 1)),
621            options.last_date.unwrap_or(local_date(2031, 12, 31)),
622        )
623        .initial_date(options.initial_date.unwrap_or(local_date(2016, 1, 15)))
624        .accept_empty_date(options.accept_empty_date);
625        if let Some(on_date_saved) = options.on_date_saved {
626            field = field.on_date_saved(on_date_saved);
627        }
628        if let Some(predicate) = options.selectable_day_predicate {
629            field = field.selectable_day_predicate(predicate);
630        }
631        if let Some(text) = options.error_format_text {
632            field = field.error_format_text(text);
633        }
634        if let Some(text) = options.error_invalid_text {
635            field = field.error_invalid_text(text);
636        }
637        if let Some(focus_node) = options.focus_node {
638            field = field.focus_node(focus_node);
639        }
640        if let Some(text) = options.field_hint_text {
641            field = field.field_hint_text(text);
642        }
643        if let Some(text) = options.field_label_text {
644            field = field.field_label_text(text);
645        }
646        let mut form = Form::new(field);
647        if let Some(form_key) = options.form_key {
648            form = form.key(form_key.into());
649        }
650        let theme = options
651            .theme
652            .unwrap_or_else(|| crate::tooltip::tests::m3(&tester.cell.borrow()));
653        material_app(theme, Material::new().child(form).into_widget())
654    }
655
656    fn pump(tester: &mut WidgetTester, options: FieldOptions) {
657        let root = input_date_picker_field(tester, options);
658        tester.pump_widget(root);
659    }
660
661    fn text_field_element(tester: &WidgetTester) -> waft_widgets::AnyElement {
662        tester.element(find::by_type::<TextField>().at(0))
663    }
664
665    /// Dart's `textFieldController(tester).value.text`.
666    fn controller_text(tester: &WidgetTester) -> String {
667        let controller = tester.widget(text_field_element(tester), |field: &TextField| {
668            field.controller.clone().expect("a controller")
669        });
670        controller.text_value(&tester.cell.borrow()).to_owned()
671    }
672
673    /// Dart's `textFieldController(tester).text = text`.
674    fn set_controller_text(tester: &mut WidgetTester, text: &str) {
675        let controller = tester.widget(text_field_element(tester), |field: &TextField| {
676            field.controller.clone().expect("a controller")
677        });
678        controller.set_text(&mut tester.cell.borrow_mut(), text.to_owned());
679        tester.cell.checkpoint();
680    }
681
682    fn form_save(tester: &mut WidgetTester, form_key: &GlobalKey) {
683        let mut app = tester.cell.borrow_mut();
684        let form = form_key
685            .current_state::<FormState>(&app)
686            .expect("the form mounted");
687        form.save(&mut app);
688    }
689
690    fn form_validate(tester: &mut WidgetTester, form_key: &GlobalKey) -> bool {
691        let mut app = tester.cell.borrow_mut();
692        let form = form_key
693            .current_state::<FormState>(&app)
694            .expect("the form mounted");
695        form.validate(&mut app)
696    }
697
698    fn has_text(tester: &WidgetTester, text: &str) -> bool {
699        !find::text(text).evaluate(tester).is_empty()
700    }
701
702    fn saved() -> (Rc<Cell<Option<DateTime>>>, ValueChanged<DateTime>) {
703        let input_date = Rc::new(Cell::new(None));
704        let on_date_saved: ValueChanged<DateTime> = {
705            let input_date = Rc::clone(&input_date);
706            Rc::new(move |_app, date| input_date.set(Some(date)))
707        };
708        (input_date, on_date_saved)
709    }
710
711    #[test]
712    fn initial_date_is_the_default() {
713        test_widgets(|tester| {
714            let form_key = GlobalKey::new();
715            let initial_date = local_date(2016, 2, 21);
716            let (input_date, on_date_saved) = saved();
717            pump(
718                tester,
719                FieldOptions {
720                    initial_date: Some(initial_date),
721                    on_date_saved: Some(on_date_saved),
722                    form_key: Some(form_key.clone()),
723                    ..FieldOptions::default()
724                },
725            );
726            assert_eq!(controller_text(tester), "02/21/2016");
727            form_save(tester, &form_key);
728            assert_eq!(input_date.get(), Some(initial_date));
729        });
730    }
731
732    #[test]
733    fn changing_initial_date_is_reflected_in_text_value() {
734        test_widgets(|tester| {
735            pump(
736                tester,
737                FieldOptions {
738                    initial_date: Some(local_date(2016, 2, 21)),
739                    ..FieldOptions::default()
740                },
741            );
742            assert_eq!(controller_text(tester), "02/21/2016");
743
744            pump(
745                tester,
746                FieldOptions {
747                    initial_date: Some(local_date(2016, 2, 23)),
748                    ..FieldOptions::default()
749                },
750            );
751            tester.pump_and_settle();
752            assert_eq!(controller_text(tester), "02/23/2016");
753        });
754    }
755
756    #[test]
757    fn valid_date_entry() {
758        test_widgets(|tester| {
759            let form_key = GlobalKey::new();
760            let (input_date, on_date_saved) = saved();
761            pump(
762                tester,
763                FieldOptions {
764                    on_date_saved: Some(on_date_saved),
765                    form_key: Some(form_key.clone()),
766                    ..FieldOptions::default()
767                },
768            );
769
770            set_controller_text(tester, "02/21/2016");
771            form_save(tester, &form_key);
772            assert_eq!(input_date.get(), Some(local_date(2016, 2, 21)));
773        });
774    }
775
776    #[test]
777    fn invalid_text_entry_shows_error_format_text() {
778        test_widgets(|tester| {
779            let form_key = GlobalKey::new();
780            let (input_date, on_date_saved) = saved();
781            pump(
782                tester,
783                FieldOptions {
784                    on_date_saved: Some(Rc::clone(&on_date_saved)),
785                    form_key: Some(form_key.clone()),
786                    ..FieldOptions::default()
787                },
788            );
789            // Default errorFormat text
790            assert!(!has_text(tester, "Invalid format."));
791            tester.enter_text(find::by_type::<TextField>(), "foobar");
792            assert!(!form_validate(tester, &form_key));
793            tester.pump_and_settle();
794            assert_eq!(input_date.get(), None);
795            expect(tester, &find::text("Invalid format."), finds_one_widget());
796
797            // Change to a custom errorFormat text
798            pump(
799                tester,
800                FieldOptions {
801                    on_date_saved: Some(on_date_saved),
802                    error_format_text: Some("That is not a date.".to_owned()),
803                    form_key: Some(form_key.clone()),
804                    ..FieldOptions::default()
805                },
806            );
807            assert!(!form_validate(tester, &form_key));
808            tester.pump_and_settle();
809            assert!(!has_text(tester, "Invalid format."));
810            expect(
811                tester,
812                &find::text("That is not a date."),
813                finds_one_widget(),
814            );
815        });
816    }
817
818    #[test]
819    fn valid_text_entry_but_date_outside_first_or_last_date_shows_error_invalid_text() {
820        test_widgets(|tester| {
821            let form_key = GlobalKey::new();
822            let (input_date, on_date_saved) = saved();
823            pump(
824                tester,
825                FieldOptions {
826                    first_date: Some(local_date(1966, 2, 21)),
827                    last_date: Some(local_date(2040, 2, 23)),
828                    on_date_saved: Some(Rc::clone(&on_date_saved)),
829                    form_key: Some(form_key.clone()),
830                    ..FieldOptions::default()
831                },
832            );
833            // Default errorInvalid text
834            assert!(!has_text(tester, "Out of range."));
835            // Before first date
836            tester.enter_text(find::by_type::<TextField>(), "02/21/1950");
837            assert!(!form_validate(tester, &form_key));
838            tester.pump_and_settle();
839            assert_eq!(input_date.get(), None);
840            expect(tester, &find::text("Out of range."), finds_one_widget());
841            // After last date
842            tester.enter_text(find::by_type::<TextField>(), "02/23/2050");
843            assert!(!form_validate(tester, &form_key));
844            tester.pump_and_settle();
845            assert_eq!(input_date.get(), None);
846            expect(tester, &find::text("Out of range."), finds_one_widget());
847
848            pump(
849                tester,
850                FieldOptions {
851                    on_date_saved: Some(on_date_saved),
852                    error_invalid_text: Some("Not in given range.".to_owned()),
853                    form_key: Some(form_key.clone()),
854                    ..FieldOptions::default()
855                },
856            );
857            assert!(!form_validate(tester, &form_key));
858            tester.pump_and_settle();
859            assert!(!has_text(tester, "Out of range."));
860            expect(
861                tester,
862                &find::text("Not in given range."),
863                finds_one_widget(),
864            );
865        });
866    }
867
868    #[test]
869    fn selectable_day_predicate_will_be_used_to_show_error_invalid_if_date_is_not_selectable() {
870        test_widgets(|tester| {
871            let form_key = GlobalKey::new();
872            let (input_date, on_date_saved) = saved();
873            pump(
874                tester,
875                FieldOptions {
876                    initial_date: Some(local_date(2016, 1, 16)),
877                    on_date_saved: Some(on_date_saved),
878                    selectable_day_predicate: Some(Rc::new(|app: &App, date: DateTime| {
879                        date.day(app) % 2 == 0
880                    })),
881                    form_key: Some(form_key.clone()),
882                    ..FieldOptions::default()
883                },
884            );
885            // Default errorInvalid text
886            assert!(!has_text(tester, "Out of range."));
887            // Odd day shouldn't be valid
888            tester.enter_text(find::by_type::<TextField>(), "02/21/1966");
889            assert!(!form_validate(tester, &form_key));
890            tester.pump_and_settle();
891            assert_eq!(input_date.get(), None);
892            expect(tester, &find::text("Out of range."), finds_one_widget());
893            // Even day is valid
894            tester.enter_text(find::by_type::<TextField>(), "02/24/2030");
895            assert!(form_validate(tester, &form_key));
896            form_save(tester, &form_key);
897            tester.pump_and_settle();
898            assert_eq!(input_date.get(), Some(local_date(2030, 2, 24)));
899            assert!(!has_text(tester, "Out of range."));
900        });
901    }
902
903    #[test]
904    fn when_an_empty_date_is_entered_and_accept_empty_date_is_true_error_format_text_is_not_shown()
905    {
906        test_widgets(|tester| {
907            let form_key = GlobalKey::new();
908            pump(
909                tester,
910                FieldOptions {
911                    error_format_text: Some("That is not a date.".to_owned()),
912                    form_key: Some(form_key.clone()),
913                    accept_empty_date: true,
914                    ..FieldOptions::default()
915                },
916            );
917            tester.enter_text(find::by_type::<TextField>(), "");
918            tester.pump_and_settle();
919            form_validate(tester, &form_key);
920            tester.pump_and_settle();
921            assert!(!has_text(tester, "That is not a date."));
922        });
923    }
924
925    #[test]
926    fn when_an_empty_date_is_entered_and_accept_empty_date_is_false_error_format_text_is_shown() {
927        test_widgets(|tester| {
928            let form_key = GlobalKey::new();
929            pump(
930                tester,
931                FieldOptions {
932                    error_format_text: Some("That is not a date.".to_owned()),
933                    form_key: Some(form_key.clone()),
934                    ..FieldOptions::default()
935                },
936            );
937            tester.enter_text(find::by_type::<TextField>(), "");
938            tester.pump_and_settle();
939            form_validate(tester, &form_key);
940            tester.pump_and_settle();
941            expect(
942                tester,
943                &find::text("That is not a date."),
944                finds_one_widget(),
945            );
946        });
947    }
948
949    #[test]
950    fn focus_node_can_request_focus() {
951        test_widgets(|tester| {
952            let focus_node = FocusNode::new(&mut tester.cell.borrow_mut());
953            pump(
954                tester,
955                FieldOptions {
956                    focus_node: Some(focus_node.clone().into_erased()),
957                    ..FieldOptions::default()
958                },
959            );
960            let has_focus = |tester: &WidgetTester| {
961                use waft_widgets::FocusNodeLeaf;
962                focus_node.handle().has_focus(&mut tester.cell.borrow_mut())
963            };
964            assert!(!has_focus(tester));
965            {
966                use waft_widgets::FocusNodeLeaf;
967                focus_node
968                    .handle()
969                    .request_focus(&mut tester.cell.borrow_mut(), None);
970            }
971            tester.pump_and_settle();
972            assert!(has_focus(tester));
973            {
974                use waft_widgets::FocusNodeLeaf;
975                focus_node
976                    .handle()
977                    .as_node()
978                    .unfocus(&mut tester.cell.borrow_mut(), Default::default());
979            }
980            tester.pump_and_settle();
981            assert!(!has_focus(tester));
982        });
983    }
984
985    #[test]
986    fn input_date_picker_form_field_does_not_crash_at_zero_area() {
987        test_widgets(|tester| {
988            let field =
989                InputDatePickerFormField::new(local_date(2001, 1, 1), local_date(2031, 12, 31))
990                    .initial_date(local_date(2016, 1, 15));
991            let theme = ThemeData::builder().build(&tester.cell.borrow());
992            tester.pump_widget(material_app(
993                theme,
994                Material::new()
995                    .child(Form::new(waft_widgets::SizedBox::shrink().child(field)))
996                    .into_widget(),
997            ));
998            let _ = TargetPlatform::Android;
999        });
1000    }
1001
1002    /// Dart's `textOpacity(tester, text)`: the value of the first `FadeTransition` above `text`.
1003    fn text_opacity(tester: &WidgetTester, text: &str) -> f64 {
1004        let element = tester.element(find::text(text).first());
1005        let fade = tester
1006            .ancestors(element)
1007            .into_iter()
1008            .find(|ancestor| {
1009                let app = tester.cell.borrow();
1010                waft_widgets::downcast_widget::<waft_widgets::FadeTransition>(
1011                    &**ancestor.widget(&app),
1012                )
1013                .is_some()
1014            })
1015            .expect("a FadeTransition above the text");
1016        let opacity = tester.widget(fade, |fade: &waft_widgets::FadeTransition| {
1017            fade.opacity.clone()
1018        });
1019        opacity.value(&tester.cell.borrow())
1020    }
1021
1022    #[test]
1023    fn empty_field_shows_hint_text_when_focused() {
1024        test_widgets(|tester| {
1025            pump(tester, FieldOptions::default());
1026            // Focus on it
1027            let at = crate::chip::tests::center_of(tester, text_field_element(tester));
1028            tester.tap_at(at, 1);
1029            tester.pump_and_settle();
1030
1031            // Hint text should be invisible
1032            assert_eq!(text_opacity(tester, "mm/dd/yyyy"), 0.0);
1033            set_controller_text(tester, "");
1034            tester.pump_and_settle();
1035            // Hint text should be visible
1036            assert_eq!(text_opacity(tester, "mm/dd/yyyy"), 1.0);
1037
1038            // Change to a different hint text
1039            pump(
1040                tester,
1041                FieldOptions {
1042                    field_hint_text: Some("Enter some date".to_owned()),
1043                    ..FieldOptions::default()
1044                },
1045            );
1046            tester.pump_and_settle();
1047            assert!(!has_text(tester, "mm/dd/yyyy"));
1048            assert_eq!(text_opacity(tester, "Enter some date"), 1.0);
1049            tester.enter_text(find::by_type::<TextField>(), "foobar");
1050            tester.pump_and_settle();
1051            assert_eq!(text_opacity(tester, "Enter some date"), 0.0);
1052        });
1053    }
1054
1055    #[test]
1056    fn label_text() {
1057        test_widgets(|tester| {
1058            pump(tester, FieldOptions::default());
1059            // Default label
1060            expect(tester, &find::text("Enter Date"), finds_one_widget());
1061
1062            pump(
1063                tester,
1064                FieldOptions {
1065                    field_label_text: Some("Give me a date!".to_owned()),
1066                    ..FieldOptions::default()
1067                },
1068            );
1069            assert!(!has_text(tester, "Enter Date"));
1070            expect(tester, &find::text("Give me a date!"), finds_one_widget());
1071        });
1072    }
1073
1074    /// What the text field's subtree paints: Dart reads the `_InputBorderPainter` of the
1075    /// `_BorderContainer`, whose border is what `InputDecorator` draws.
1076    fn text_field_ops(tester: &WidgetTester) -> Vec<waft_embedder::valo::Op> {
1077        tester.painted_ops_deep(tester.render_object(text_field_element(tester)))
1078    }
1079
1080    /// The `drawPath` of a stroked border.
1081    fn stroked_border() -> PaintCall {
1082        PaintCall::Path {
1083            color: None,
1084            style: Some(PaintedStyle::Stroke(None)),
1085            includes: Vec::new(),
1086            excludes: Vec::new(),
1087        }
1088    }
1089
1090    #[test]
1091    fn theme_data_input_decoration_theme_is_honored() {
1092        test_widgets(|tester| {
1093            // The default theme draws the text field's outline.
1094            pump(tester, FieldOptions::default());
1095            tester.pump_and_settle();
1096            assert_paints(&text_field_ops(tester), &[stroked_border()]);
1097
1098            let theme = ThemeData::builder()
1099                .input_decoration_theme(
1100                    InputDecorationThemeData::new().border(InputBorderRef::none()),
1101                )
1102                .build(&tester.cell.borrow());
1103            pump(
1104                tester,
1105                FieldOptions {
1106                    theme: Some(theme),
1107                    ..FieldOptions::default()
1108                },
1109            );
1110            tester.pump_and_settle();
1111            // Border should match: none is drawn.
1112            assert!(paints(&text_field_ops(tester), &[stroked_border()]).is_err());
1113        });
1114    }
1115
1116    #[test]
1117    fn local_input_decoration_theme_is_honored() {
1118        test_widgets(|tester| {
1119            let field =
1120                InputDatePickerFormField::new(local_date(2025, 2, 1), local_date(2026, 5, 1));
1121            let theme = crate::tooltip::tests::m3(&tester.cell.borrow());
1122            tester.pump_widget(material_app(
1123                theme,
1124                Material::new()
1125                    .child(
1126                        waft_widgets::Center::new().child(
1127                            crate::input_decorator::InputDecorationTheme::new()
1128                                .with_data(InputDecorationThemeData::new().filled(true))
1129                                .child(field),
1130                        ),
1131                    )
1132                    .into_widget(),
1133            ));
1134
1135            let decoration = tester.widget(text_field_element(tester), |field: &TextField| {
1136                field.decoration.clone().expect("a decoration")
1137            });
1138            assert_eq!(decoration.filled, Some(true));
1139        });
1140    }
1141
1142    /// Dart's `TestCalendarDelegate extends GregorianCalendarDelegate`, overriding how a date is
1143    /// formatted and parsed; the rest forwards to the Gregorian delegate.
1144    #[derive(Debug)]
1145    struct TestCalendarDelegate;
1146
1147    impl CalendarDelegate for TestCalendarDelegate {
1148        fn now(&self, app: &App) -> DateTime {
1149            GregorianCalendarDelegate.now(app)
1150        }
1151        fn date_only(&self, app: &App, date: &DateTime) -> DateTime {
1152            GregorianCalendarDelegate.date_only(app, date)
1153        }
1154        fn month_delta(&self, app: &App, start_date: &DateTime, end_date: &DateTime) -> i32 {
1155            GregorianCalendarDelegate.month_delta(app, start_date, end_date)
1156        }
1157        fn add_months_to_month_date(
1158            &self,
1159            app: &App,
1160            month_date: &DateTime,
1161            months_to_add: i32,
1162        ) -> DateTime {
1163            GregorianCalendarDelegate.add_months_to_month_date(app, month_date, months_to_add)
1164        }
1165        fn add_days_to_date(&self, app: &App, date: &DateTime, days: i32) -> DateTime {
1166            GregorianCalendarDelegate.add_days_to_date(app, date, days)
1167        }
1168        fn first_day_offset(
1169            &self,
1170            app: &App,
1171            year: i32,
1172            month: i32,
1173            localizations: &dyn MaterialLocalizations,
1174        ) -> i32 {
1175            GregorianCalendarDelegate.first_day_offset(app, year, month, localizations)
1176        }
1177        fn get_days_in_month(&self, year: i32, month: i32) -> i32 {
1178            GregorianCalendarDelegate.get_days_in_month(year, month)
1179        }
1180        fn get_month(&self, app: &App, year: i32, month: i32) -> DateTime {
1181            GregorianCalendarDelegate.get_month(app, year, month)
1182        }
1183        fn get_day(&self, app: &App, year: i32, month: i32, day: i32) -> DateTime {
1184            GregorianCalendarDelegate.get_day(app, year, month, day)
1185        }
1186        fn format_month_year(
1187            &self,
1188            app: &App,
1189            date: &DateTime,
1190            localizations: &dyn MaterialLocalizations,
1191        ) -> String {
1192            GregorianCalendarDelegate.format_month_year(app, date, localizations)
1193        }
1194        fn format_medium_date(
1195            &self,
1196            app: &App,
1197            date: &DateTime,
1198            localizations: &dyn MaterialLocalizations,
1199        ) -> String {
1200            GregorianCalendarDelegate.format_medium_date(app, date, localizations)
1201        }
1202        fn format_short_month_day(
1203            &self,
1204            app: &App,
1205            date: &DateTime,
1206            localizations: &dyn MaterialLocalizations,
1207        ) -> String {
1208            GregorianCalendarDelegate.format_short_month_day(app, date, localizations)
1209        }
1210        fn format_short_date(
1211            &self,
1212            app: &App,
1213            date: &DateTime,
1214            localizations: &dyn MaterialLocalizations,
1215        ) -> String {
1216            GregorianCalendarDelegate.format_short_date(app, date, localizations)
1217        }
1218        fn format_full_date(
1219            &self,
1220            app: &App,
1221            date: &DateTime,
1222            localizations: &dyn MaterialLocalizations,
1223        ) -> String {
1224            GregorianCalendarDelegate.format_full_date(app, date, localizations)
1225        }
1226        fn format_compact_date(
1227            &self,
1228            app: &App,
1229            date: &DateTime,
1230            _localizations: &dyn MaterialLocalizations,
1231        ) -> String {
1232            format!("{}..{}..{}", date.year(app), date.month(app), date.day(app))
1233        }
1234        fn parse_compact_date(
1235            &self,
1236            app: &App,
1237            input_string: Option<&str>,
1238            _localizations: &dyn MaterialLocalizations,
1239        ) -> Option<DateTime> {
1240            let parts: Vec<&str> = input_string.expect("an input string").split("..").collect();
1241            if parts.len() != 3 {
1242                return None;
1243            }
1244            let number = |part: &str| part.parse::<i32>().unwrap_or(0);
1245            Some(DateTime::new(
1246                app,
1247                number(parts[0]),
1248                number(parts[1]),
1249                number(parts[2]),
1250            ))
1251        }
1252        fn date_help_text(&self, _localizations: &dyn MaterialLocalizations) -> String {
1253            "yyyy..mm..dd".to_owned()
1254        }
1255    }
1256
1257    #[test]
1258    fn displays_calendar_based_on_the_calendar_delegate() {
1259        test_widgets(|tester| {
1260            let selected_date = Rc::new(Cell::new(None));
1261            let field =
1262                InputDatePickerFormField::new(local_date(2025, 2, 1), local_date(2026, 5, 1))
1263                    .initial_date(local_date(2025, 2, 26))
1264                    .on_date_submitted({
1265                        let selected_date = Rc::clone(&selected_date);
1266                        Rc::new(move |_app, date| selected_date.set(Some(date)))
1267                    })
1268                    .calendar_delegate(Rc::new(TestCalendarDelegate));
1269            let theme = crate::tooltip::tests::m3(&tester.cell.borrow());
1270            tester.pump_widget(material_app(
1271                theme,
1272                Material::new().child(field).into_widget(),
1273            ));
1274
1275            assert_eq!(controller_text(tester), "2025..2..26");
1276            tester.enter_text(find::by_type::<TextField>(), "2025..3..10");
1277            tester
1278                .test_text_input()
1279                .receive_action(waft_services::TextInputAction::Done);
1280            tester.pump_and_settle();
1281            assert_eq!(selected_date.get(), Some(local_date(2025, 3, 10)));
1282            assert_eq!(controller_text(tester), "2025..3..10");
1283
1284            tester.enter_text(find::by_type::<TextField>(), "2025..4..21");
1285            tester
1286                .test_text_input()
1287                .receive_action(waft_services::TextInputAction::Done);
1288            tester.pump_and_settle();
1289            assert_eq!(selected_date.get(), Some(local_date(2025, 4, 21)));
1290        });
1291    }
1292}