Skip to main content

waft_widgets/widgets/
form.rs

1//! Flutter counterpart: `widgets/form.dart`.
2//!
3//! A [`Form`] groups the [`FormField`]s below it: each field's state registers with the form's
4//! [`FormState`] while it builds, and the form saves, resets and validates them together.
5//!
6//! [`FormField`] and [`FormFieldState`] are Dart classes that Material subclasses
7//! (`TextFormField`, `DropdownButtonFormField`, `DropdownMenuFormField`). A subclass is a leaf:
8//! its widget carries a [`FormFieldData`] and implements [`FormFieldLeaf`], its state carries a
9//! [`FormFieldStateData`] and implements [`FormFieldStateLeaf`], and the bodies Dart inherits
10//! are associated functions on [`FormFieldState`] that a leaf calls where Dart writes `super`.
11//! A form holds its fields erased, as [`DynamicFormFieldState`]s, Dart's
12//! `FormFieldState<dynamic>`, and a field's builder is handed its state as
13//! [`AnyFormFieldState`], Dart's `FormFieldState<T>`; both dispatch the virtuals to the leaf.
14
15use std::any::Any;
16use std::fmt::{self, Debug};
17use std::rc::Rc;
18
19use indexmap::IndexSet;
20use waft_embedder::{SemanticsRole, SemanticsValidationResult};
21use waft_foundation::{App, Handle, HandleId, OptionRetained, VoidCallback};
22use waft_scheduler::{FrameCallback, SchedulerBinding};
23use waft_services::RestorationBucket;
24
25use crate::framework::{
26    BuildContext, InheritedWidget, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
27};
28use crate::view::View;
29use crate::widgets::basic::Semantics;
30use crate::widgets::focus_manager::FocusNode;
31use crate::widgets::focus_manager::FocusNodeLeaf;
32use crate::widgets::focus_scope::Focus;
33use crate::widgets::navigator::RouteResult;
34use crate::widgets::pop_scope::PopScope;
35use crate::widgets::restoration::{RestorableProperty, RestorationMixin, RestorationMixinData};
36use crate::widgets::restoration_properties::{RestorableBool, RestorableStringN, RestorableValue};
37use crate::widgets::routes::PopInvokedWithResultCallback;
38use waft_foundation::Ref;
39
40// ---------------------------------------------------------------------------------------------
41// Form
42
43/// An optional container for grouping together multiple form field widgets (e.g. `TextField`
44/// widgets).
45///
46/// Each individual form field should be wrapped in a [`FormField`] widget, with the [`Form`]
47/// widget as a common ancestor of all of those. Call methods on [`FormState`] to save, reset, or
48/// validate each [`FormField`] that is a descendant of this [`Form`]. To obtain the
49/// [`FormState`], you may use [`Form::of`] with a context whose ancestor is the [`Form`], or pass
50/// a `GlobalKey` to the [`Form`] constructor and call `GlobalKey::current_state`.
51///
52/// See also:
53///
54///  * `GlobalKey`, a key that is unique across the entire app.
55///  * [`FormField`], a single form field widget that maintains the current state.
56///  * `TextFormField`, a convenience widget that wraps a `TextField` widget in a [`FormField`].
57pub struct Form {
58    /// See [`StatefulWidget::key`].
59    pub key: Option<KeyRef>,
60
61    /// The widget below this widget in the tree.
62    ///
63    /// This is the root of the widget hierarchy that contains this form.
64    pub child: WidgetRef,
65
66    /// When false, blocks the current route from being popped.
67    ///
68    /// See also:
69    ///
70    ///  * [`on_pop_invoked_with_result`](Self::on_pop_invoked_with_result), which also comes
71    ///    from [`PopScope`] and is often used in conjunction with this parameter.
72    ///  * [`PopScope::can_pop`], which is what [`Form`] delegates to internally.
73    pub can_pop: Option<bool>,
74
75    /// Called after a route pop was handled; see [`PopScope::on_pop_invoked_with_result`].
76    ///
77    /// See also:
78    ///
79    ///  * [`can_pop`](Self::can_pop), which also comes from [`PopScope`] and is often used in
80    ///    conjunction with this parameter.
81    ///  * [`PopScope::on_pop_invoked_with_result`], which is what [`Form`] delegates to
82    ///    internally.
83    pub on_pop_invoked_with_result: Option<PopInvokedWithResultCallback>,
84
85    /// Called when one of the form fields changes.
86    ///
87    /// In addition to this callback being invoked, all the form fields themselves will rebuild.
88    pub on_changed: Option<VoidCallback>,
89
90    /// Used to enable/disable form fields auto validation and update their error text.
91    ///
92    /// If [`AutovalidateMode::OnUserInteraction`], this form will only auto-validate after its
93    /// content changes. If [`AutovalidateMode::Always`], it will auto-validate even without user
94    /// interaction. If [`AutovalidateMode::Disabled`], auto-validation will be disabled.
95    ///
96    /// Defaults to [`AutovalidateMode::Disabled`].
97    pub autovalidate_mode: AutovalidateMode,
98}
99
100impl Form {
101    /// Creates a container for form fields.
102    #[cfg_attr(debug_assertions, track_caller)]
103    pub fn new<K>(child: impl IntoWidget<K>) -> Form {
104        Form {
105            key: None,
106            child: child.into_widget(),
107            can_pop: None,
108            on_pop_invoked_with_result: None,
109            on_changed: None,
110            autovalidate_mode: AutovalidateMode::Disabled,
111        }
112    }
113
114    /// Dart `Form(key:)`.
115    pub fn key(mut self, key: KeyRef) -> Form {
116        self.key = Some(key);
117        self
118    }
119
120    /// Dart `Form(canPop:)`.
121    pub fn can_pop(mut self, can_pop: bool) -> Form {
122        self.can_pop = Some(can_pop);
123        self
124    }
125
126    /// Dart `Form(onPopInvokedWithResult:)`.
127    pub fn on_pop_invoked_with_result(
128        mut self,
129        on_pop_invoked_with_result: PopInvokedWithResultCallback,
130    ) -> Form {
131        self.on_pop_invoked_with_result = Some(on_pop_invoked_with_result);
132        self
133    }
134
135    /// Dart `Form(onChanged:)`.
136    pub fn on_changed(mut self, on_changed: impl Fn(&mut App) + 'static) -> Form {
137        self.on_changed = Some(Rc::new(on_changed));
138        self
139    }
140
141    /// Dart `Form(autovalidateMode:)`.
142    pub fn autovalidate_mode(mut self, autovalidate_mode: AutovalidateMode) -> Form {
143        self.autovalidate_mode = autovalidate_mode;
144        self
145    }
146
147    /// Returns the [`FormState`] of the closest [`Form`] widget which encloses the given
148    /// context, or `None` if none is found.
149    ///
150    /// Calling this method will create a dependency on the closest [`Form`] in the `context`,
151    /// if there is one.
152    ///
153    /// See also:
154    ///
155    /// * [`Form::of`], which is similar to this method, but panics if no [`Form`] ancestor is
156    ///   found.
157    pub fn maybe_of(app: &mut App, context: BuildContext) -> Option<Handle<FormState>> {
158        context
159            .depend_on_inherited_widget_of_exact_type::<FormScope>(app)
160            .map(|scope| scope.form_state)
161    }
162
163    /// Returns the [`FormState`] of the closest [`Form`] widget which encloses the given
164    /// context.
165    ///
166    /// If no [`Form`] ancestor is found, this panics.
167    ///
168    /// Calling this method will create a dependency on the closest [`Form`] in the `context`.
169    ///
170    /// See also:
171    ///
172    /// * [`Form::maybe_of`], which is similar to this method, but returns `None` if no [`Form`]
173    ///   ancestor is found.
174    pub fn of(app: &mut App, context: BuildContext) -> Handle<FormState> {
175        let form_state = Form::maybe_of(app, context);
176        form_state.unwrap_or_else(|| {
177            panic!(
178                "Form.of() was called with a context that does not contain a Form widget.\n\
179                 No Form widget ancestor could be found starting from the context that was \
180                 passed to Form.of(). This can happen because you are using a widget that looks \
181                 for a Form ancestor, but no such ancestor exists.\n\
182                 The context used was:\n  {}",
183                context.widget(app).type_name()
184            )
185        })
186    }
187
188    /// Dart's `_callPopInvoked` tear-off, which the form hands its [`PopScope`].
189    fn call_pop_invoked(&self) -> PopInvokedWithResultCallback {
190        let on_pop_invoked_with_result = self.on_pop_invoked_with_result.clone();
191        Rc::new(move |app: &mut App, did_pop: bool, result: RouteResult| {
192            if let Some(on_pop_invoked_with_result) = &on_pop_invoked_with_result {
193                on_pop_invoked_with_result(app, did_pop, result);
194            }
195        })
196    }
197}
198
199impl Debug for Form {
200    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
201        f.debug_struct("Form")
202            .field("can_pop", &self.can_pop)
203            .field("autovalidate_mode", &self.autovalidate_mode)
204            .finish_non_exhaustive()
205    }
206}
207
208impl StatefulWidget for Form {
209    type State = FormState;
210
211    fn key(&self) -> Option<&KeyRef> {
212        self.key.as_ref()
213    }
214
215    fn create_state(&self) -> FormState {
216        FormState {
217            state: StateData::new(),
218            generation: 0,
219            has_interacted_by_user: false,
220            fields: IndexSet::new(),
221        }
222    }
223}
224
225/// State associated with a [`Form`] widget.
226///
227/// A [`FormState`] object can be used to [`save`](Self::save), [`reset`](Self::reset), and
228/// [`validate`](Self::validate) every [`FormField`] that is a descendant of the associated
229/// [`Form`].
230///
231/// Typically obtained via [`Form::of`].
232pub struct FormState {
233    state: StateData<Form>,
234    generation: i64,
235    has_interacted_by_user: bool,
236    fields: IndexSet<DynamicFormFieldState>,
237}
238
239impl FormState {
240    /// The [`FormFieldState`] objects that are currently registered with this [`Form`].
241    pub fn fields(self: Handle<Self>, app: &App) -> Vec<DynamicFormFieldState> {
242        app.get(self).fields.iter().copied().collect()
243    }
244
245    // Called when a form field has changed. This will cause all form fields
246    // to rebuild, useful if form fields have interdependencies.
247    fn field_did_change(self: Handle<Self>, app: &mut App) {
248        if let Some(on_changed) = self.widget(app).on_changed.clone() {
249            on_changed(app);
250        }
251
252        let fields = self.fields(app);
253        let has_interacted_by_user = fields
254            .into_iter()
255            .any(|field| field.has_interacted_by_user(app));
256        app.get_mut(self).has_interacted_by_user = has_interacted_by_user;
257
258        self.force_rebuild(app);
259    }
260
261    fn force_rebuild(self: Handle<Self>, app: &mut App) {
262        self.set_state(app, |state| {
263            state.generation += 1;
264        });
265    }
266
267    fn register(self: Handle<Self>, app: &mut App, field: DynamicFormFieldState) {
268        app.get_mut(self).fields.insert(field);
269    }
270
271    fn unregister(self: Handle<Self>, app: &mut App, field: DynamicFormFieldState) {
272        app.get_mut(self).fields.shift_remove(&field);
273    }
274
275    /// Saves every [`FormField`] that is a descendant of this [`Form`].
276    pub fn save(self: Handle<Self>, app: &mut App) {
277        for field in self.fields(app) {
278            field.save(app);
279        }
280    }
281
282    /// Resets every [`FormField`] that is a descendant of this [`Form`] back to its
283    /// [`FormFieldData::initial_value`].
284    ///
285    /// The [`Form::on_changed`] callback will be called.
286    ///
287    /// If the form's [`Form::autovalidate_mode`] property is [`AutovalidateMode::Always`], the
288    /// fields will all be revalidated after being reset.
289    pub fn reset(self: Handle<Self>, app: &mut App) {
290        for field in self.fields(app) {
291            field.reset(app);
292        }
293        app.get_mut(self).has_interacted_by_user = false;
294        self.field_did_change(app);
295    }
296
297    /// Clears the validation errors for all [`FormField`]s in this [`Form`] without resetting
298    /// their values.
299    ///
300    /// See also:
301    ///
302    ///  * [`FormFieldStateLeaf::clear_error`], which clears the error for a single form field.
303    pub fn clear_error(self: Handle<Self>, app: &mut App) {
304        for field in self.fields(app) {
305            field.clear_error_internal(app);
306        }
307        self.field_did_change(app);
308    }
309
310    /// Validates every [`FormField`] that is a descendant of this [`Form`], and returns true if
311    /// there are no errors.
312    ///
313    /// The form will rebuild to report the results.
314    ///
315    /// See also:
316    ///  * [`validate_granularly`](Self::validate_granularly), which also validates descendant
317    ///    [`FormField`]s, but instead returns a set of fields with errors.
318    pub fn validate(self: Handle<Self>, app: &mut App) -> bool {
319        app.get_mut(self).has_interacted_by_user = true;
320        self.force_rebuild(app);
321        self.validate_fields(app, None)
322    }
323
324    /// Validates every [`FormField`] that is a descendant of this [`Form`], and returns a set
325    /// of [`DynamicFormFieldState`] of the invalid field(s) only, if any.
326    ///
327    /// This method can be useful to highlight field(s) with errors.
328    ///
329    /// The form will rebuild to report the results.
330    ///
331    /// See also:
332    ///  * [`validate`](Self::validate), which also validates descendant [`FormField`]s, and
333    ///    return true if there are no errors.
334    pub fn validate_granularly(
335        self: Handle<Self>,
336        app: &mut App,
337    ) -> IndexSet<DynamicFormFieldState> {
338        let mut invalid_fields = IndexSet::new();
339        app.get_mut(self).has_interacted_by_user = true;
340        self.force_rebuild(app);
341        self.validate_fields(app, Some(&mut invalid_fields));
342        invalid_fields
343    }
344
345    /// Dart's `_validate`.
346    fn validate_fields(
347        self: Handle<Self>,
348        app: &mut App,
349        mut invalid_fields: Option<&mut IndexSet<DynamicFormFieldState>>,
350    ) -> bool {
351        let mut has_error = false;
352        let validate_on_focus_change =
353            self.widget(app).autovalidate_mode == AutovalidateMode::OnUnfocus;
354
355        for field in self.fields(app) {
356            let has_focus = field.focus_node(app).as_node().has_focus(app);
357
358            if !validate_on_focus_change || !has_focus || (validate_on_focus_change && has_focus) {
359                let is_field_valid = field.validate(app);
360                has_error |= !is_field_valid;
361                if let Some(invalid_fields) = invalid_fields.as_deref_mut()
362                    && !is_field_valid
363                {
364                    invalid_fields.insert(field);
365                }
366            }
367        }
368
369        !has_error
370    }
371}
372
373impl State for FormState {
374    type Widget = Form;
375    crate::state_accessors!();
376
377    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
378        let has_error = self
379            .fields(app)
380            .into_iter()
381            .any(|field| field.has_error(app));
382
383        match self.widget(app).autovalidate_mode {
384            AutovalidateMode::Always => {
385                self.validate_fields(app, None);
386            }
387            AutovalidateMode::OnUserInteraction => {
388                if app.get(self).has_interacted_by_user {
389                    self.validate_fields(app, None);
390                }
391            }
392            AutovalidateMode::OnUserInteractionIfError => {
393                if app.get(self).has_interacted_by_user && has_error {
394                    self.validate_fields(app, None);
395                }
396            }
397            AutovalidateMode::OnUnfocus | AutovalidateMode::Disabled => {}
398        }
399
400        let generation = app.get(self).generation;
401        let widget = self.widget(app);
402        let scope = FormScope {
403            form_state: self,
404            generation,
405            child: widget.child.clone(),
406        };
407        let form = if widget.can_pop.is_some() || widget.on_pop_invoked_with_result.is_some() {
408            PopScope::new(scope)
409                .can_pop(widget.can_pop.unwrap_or(true))
410                .on_pop_invoked_with_result(widget.call_pop_invoked())
411                .into_widget()
412        } else {
413            scope.into_widget()
414        };
415        Semantics::new()
416            .container(true)
417            .explicit_child_nodes(true)
418            .role(SemanticsRole::Form)
419            .child(form)
420            .into_widget()
421    }
422}
423
424/// Dart's `_FormScope`: hands a [`Form`]'s state to the fields below it, and rebuilds them
425/// each time a field changes.
426#[derive(Debug)]
427struct FormScope {
428    form_state: Handle<FormState>,
429
430    /// Incremented every time a form field has changed. This lets us know when to rebuild the
431    /// form.
432    generation: i64,
433
434    child: WidgetRef,
435}
436
437impl InheritedWidget for FormScope {
438    fn child(&self) -> &WidgetRef {
439        &self.child
440    }
441
442    fn update_should_notify(&self, old: &FormScope) -> bool {
443        self.generation != old.generation
444    }
445}
446
447// ---------------------------------------------------------------------------------------------
448// FormField
449
450/// Signature for validating a form field.
451///
452/// Returns an error string to display if the input is invalid, or `None` otherwise.
453///
454/// Used by [`FormFieldData::validator`].
455pub type FormFieldValidator<T> = Rc<dyn Fn(&mut App, Option<&T>) -> Option<String>>;
456
457/// Signature for a callback that builds an error widget.
458///
459/// See also:
460///
461///  * [`FormFieldData::error_builder`], which is of this type, and passes the result error
462///    given by `TextFormField.validator`.
463pub type FormFieldErrorBuilder = Rc<dyn Fn(&mut App, BuildContext, String) -> WidgetRef>;
464
465/// Signature for being notified when a form field changes value.
466///
467/// Used by [`FormFieldData::on_saved`].
468pub type FormFieldSetter<T> = Rc<dyn Fn(&mut App, Option<T>)>;
469
470/// Signature for building the widget representing the form field.
471///
472/// Used by [`FormFieldData::builder`].
473pub type FormFieldBuilder<T> = Rc<dyn Fn(&mut App, AnyFormFieldState<T>) -> WidgetRef>;
474
475/// The fields of Dart's `FormField<T>`, which [`FormField`] and its subclasses carry under the
476/// field `form_field`.
477pub struct FormFieldData<T: 'static> {
478    /// See [`StatefulWidget::key`].
479    pub key: Option<KeyRef>,
480
481    /// Function that returns the widget representing this form field.
482    ///
483    /// It is passed the form field state as input, containing the current value and validation
484    /// state of this field.
485    pub builder: FormFieldBuilder<T>,
486
487    /// An optional method to call with the final value when the form is saved via
488    /// [`FormState::save`].
489    pub on_saved: Option<FormFieldSetter<T>>,
490
491    /// An optional method to call when the form field is reset via
492    /// [`FormFieldStateLeaf::reset`].
493    pub on_reset: Option<VoidCallback>,
494
495    /// An optional property that forces the [`FormFieldState`] into an error state by directly
496    /// setting the [`FormFieldStateLeaf::error_text`] property without running the validator
497    /// function.
498    ///
499    /// When the [`force_error_text`](Self::force_error_text) property is provided, the
500    /// [`FormFieldStateLeaf::error_text`] will be set to the provided value, causing the form
501    /// field to be considered invalid and to display the error message specified.
502    ///
503    /// When [`validator`](Self::validator) is provided,
504    /// [`force_error_text`](Self::force_error_text) will override any error that it returns.
505    /// [`validator`](Self::validator) will not be called unless
506    /// [`force_error_text`](Self::force_error_text) is `None`.
507    pub force_error_text: Option<String>,
508
509    /// An optional method that validates an input. Returns an error string to display if the
510    /// input is invalid, or `None` otherwise.
511    ///
512    /// The returned value is exposed by the [`FormFieldStateLeaf::error_text`] property. The
513    /// `TextFormField` uses this to override the `InputDecoration.errorText` value.
514    ///
515    /// Alternating between error and normal state can cause the height of the `TextFormField`
516    /// to change if no other subtext decoration is set on the field. To create a field whose
517    /// height is fixed regardless of whether or not an error is displayed, either wrap the
518    /// `TextFormField` in a fixed height parent like `SizedBox`, or set the
519    /// `InputDecoration.helperText` parameter to a space.
520    pub validator: Option<FormFieldValidator<T>>,
521
522    /// Function that returns the widget representing the error to display.
523    ///
524    /// It is passed the form field validator error string as input. The resulting widget is
525    /// passed to `InputDecoration.error`.
526    ///
527    /// If `None`, the validator error string is passed to `InputDecoration.errorText`.
528    pub error_builder: Option<FormFieldErrorBuilder>,
529
530    /// An optional value to initialize the form field to, or `None` otherwise.
531    ///
532    /// The `initial_value` affects the form field's state in two cases:
533    /// 1. When the form field is first built, `initial_value` determines the field's initial
534    ///    state.
535    /// 2. When [`FormFieldStateLeaf::reset`] is called (either directly or by calling
536    ///    [`FormState::reset`]), the form field is reset to this `initial_value`.
537    pub initial_value: Option<T>,
538
539    /// Whether the form is able to receive user input.
540    ///
541    /// Defaults to true. If [`autovalidate_mode`](Self::autovalidate_mode) is not
542    /// [`AutovalidateMode::Disabled`], the field will be auto validated. Likewise, if this field
543    /// is false, the widget will not be validated regardless of
544    /// [`autovalidate_mode`](Self::autovalidate_mode).
545    pub enabled: bool,
546
547    /// Used to enable/disable this form field auto validation and update its error text.
548    ///
549    /// If [`AutovalidateMode::OnUserInteraction`], this FormField will only auto-validate after
550    /// its content changes. If [`AutovalidateMode::Always`], it will auto-validate even without
551    /// user interaction. If [`AutovalidateMode::Disabled`], auto-validation will be disabled.
552    ///
553    /// Defaults to [`AutovalidateMode::Disabled`].
554    pub autovalidate_mode: AutovalidateMode,
555
556    /// Restoration ID to save and restore the state of the form field.
557    ///
558    /// Setting the restoration ID to a non-`None` value results in whether or not the form field
559    /// validation persists.
560    ///
561    /// The state of this widget is persisted in a [`RestorationBucket`] claimed from the
562    /// surrounding `RestorationScope` using the provided restoration ID.
563    ///
564    /// See also:
565    ///
566    ///  * `RestorationManager`, which explains how state restoration works in Flutter.
567    pub restoration_id: Option<String>,
568}
569
570impl<T: 'static> FormFieldData<T> {
571    /// The fields of a form field built by `builder`, with Dart's defaults.
572    pub fn new(builder: FormFieldBuilder<T>) -> FormFieldData<T> {
573        FormFieldData {
574            key: None,
575            builder,
576            on_saved: None,
577            on_reset: None,
578            force_error_text: None,
579            validator: None,
580            error_builder: None,
581            initial_value: None,
582            enabled: true,
583            autovalidate_mode: AutovalidateMode::Disabled,
584            restoration_id: None,
585        }
586    }
587}
588
589impl<T: 'static> Debug for FormFieldData<T> {
590    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
591        f.debug_struct("FormField")
592            .field("force_error_text", &self.force_error_text)
593            .field("enabled", &self.enabled)
594            .field("autovalidate_mode", &self.autovalidate_mode)
595            .field("restoration_id", &self.restoration_id)
596            .finish_non_exhaustive()
597    }
598}
599
600/// The [`FormFieldData`] accessor a [`FormFieldLeaf`] implementor writes; the bag lives under
601/// the field `form_field`.
602#[macro_export]
603macro_rules! form_field_accessors {
604    () => {
605        fn form_field_data(&self) -> &$crate::FormFieldData<Self::Value> {
606            &self.form_field
607        }
608    };
609}
610
611/// The trait every form-field widget implements: [`FormField`] and its subclasses, such as
612/// `TextFormField`.
613///
614/// Its [`State`] is a [`FormFieldStateLeaf`].
615pub trait FormFieldLeaf: StatefulWidget {
616    /// Dart's `T` of `FormField<T>`.
617    type Value: Clone + 'static;
618
619    /// The [`FormFieldData`] bag ([`form_field_accessors!`](crate::form_field_accessors)).
620    fn form_field_data(&self) -> &FormFieldData<Self::Value>;
621}
622
623/// A single form field.
624///
625/// This widget maintains the current state of the form field, so that updates and validation
626/// errors are visually reflected in the UI.
627///
628/// When used inside a [`Form`], you can use methods on [`FormState`] to query or manipulate the
629/// form data as a whole. For example, calling [`FormState::save`] will invoke each
630/// [`FormField`]'s [`on_saved`](FormFieldData::on_saved) callback in turn.
631///
632/// Use a `GlobalKey` with [`FormField`] if you want to retrieve its current state, for example
633/// if you want one form field to depend on another.
634///
635/// A [`Form`] ancestor is not required. The [`Form`] allows one to save, reset, or validate
636/// multiple fields at once. To use without a [`Form`], pass a `GlobalKey` to the constructor
637/// and use `GlobalKey::current_state` to save or reset the form field.
638///
639/// See also:
640///
641///  * [`Form`], which is the widget that aggregates the form fields.
642///  * `TextField`, which is a commonly used form field for entering text.
643pub struct FormField<T: 'static> {
644    form_field: FormFieldData<T>,
645}
646
647impl<T: Clone + 'static> FormField<T> {
648    /// Creates a single form field.
649    pub fn new(
650        builder: impl Fn(&mut App, AnyFormFieldState<T>) -> WidgetRef + 'static,
651    ) -> FormField<T> {
652        FormField {
653            form_field: FormFieldData::new(Rc::new(builder)),
654        }
655    }
656
657    /// Dart `FormField(key:)`.
658    pub fn key(mut self, key: KeyRef) -> FormField<T> {
659        self.form_field.key = Some(key);
660        self
661    }
662
663    /// Dart `FormField(onSaved:)`.
664    pub fn on_saved(mut self, on_saved: impl Fn(&mut App, Option<T>) + 'static) -> FormField<T> {
665        self.form_field.on_saved = Some(Rc::new(on_saved));
666        self
667    }
668
669    /// Dart `FormField(onReset:)`.
670    pub fn on_reset(mut self, on_reset: impl Fn(&mut App) + 'static) -> FormField<T> {
671        self.form_field.on_reset = Some(Rc::new(on_reset));
672        self
673    }
674
675    /// Dart `FormField(forceErrorText:)`.
676    pub fn force_error_text(mut self, force_error_text: impl Into<String>) -> FormField<T> {
677        self.form_field.force_error_text = Some(force_error_text.into());
678        self
679    }
680
681    /// Dart `FormField(validator:)`.
682    pub fn validator(
683        mut self,
684        validator: impl Fn(&mut App, Option<&T>) -> Option<String> + 'static,
685    ) -> FormField<T> {
686        self.form_field.validator = Some(Rc::new(validator));
687        self
688    }
689
690    /// Dart `FormField(errorBuilder:)`.
691    pub fn error_builder(
692        mut self,
693        error_builder: impl Fn(&mut App, BuildContext, String) -> WidgetRef + 'static,
694    ) -> FormField<T> {
695        self.form_field.error_builder = Some(Rc::new(error_builder));
696        self
697    }
698
699    /// Dart `FormField(initialValue:)`.
700    pub fn initial_value(mut self, initial_value: T) -> FormField<T> {
701        self.form_field.initial_value = Some(initial_value);
702        self
703    }
704
705    /// Dart `FormField(enabled:)`.
706    pub fn enabled(mut self, enabled: bool) -> FormField<T> {
707        self.form_field.enabled = enabled;
708        self
709    }
710
711    /// Dart `FormField(autovalidateMode:)`.
712    pub fn autovalidate_mode(mut self, autovalidate_mode: AutovalidateMode) -> FormField<T> {
713        self.form_field.autovalidate_mode = autovalidate_mode;
714        self
715    }
716
717    /// Dart `FormField(restorationId:)`.
718    pub fn restoration_id(mut self, restoration_id: impl Into<String>) -> FormField<T> {
719        self.form_field.restoration_id = Some(restoration_id.into());
720        self
721    }
722}
723
724impl<T: 'static> Debug for FormField<T> {
725    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
726        self.form_field.fmt(f)
727    }
728}
729
730impl<T: Clone + 'static> FormFieldLeaf for FormField<T> {
731    type Value = T;
732    crate::form_field_accessors!();
733}
734
735impl<T: Clone + 'static> StatefulWidget for FormField<T> {
736    type State = FormFieldState<T>;
737
738    fn key(&self) -> Option<&KeyRef> {
739        self.form_field.key.as_ref()
740    }
741
742    fn create_state(&self) -> FormFieldState<T> {
743        FormFieldState {
744            state: StateData::new(),
745            restoration: RestorationMixinData::new(),
746            form_field_state: FormFieldStateData::new(&self.form_field),
747        }
748    }
749}
750
751// ---------------------------------------------------------------------------------------------
752// FormFieldState
753
754/// The value type of a form-field state: its widget's `T`.
755pub type FormFieldValue<S> = <<S as State>::Widget as FormFieldLeaf>::Value;
756
757/// The fields of Dart's `FormFieldState<T>`, which [`FormFieldState`] and its subclasses carry
758/// under the field `form_field_state`.
759///
760/// The restorable properties and the focus node need the [`App`], so
761/// [`FormFieldState::init_state`] creates them.
762pub struct FormFieldStateData<T> {
763    value: Option<T>,
764    error_text: Option<Ref<RestorableStringN>>,
765    has_interacted_by_user: Option<Ref<RestorableBool>>,
766    focus_node: Option<Ref<FocusNode>>,
767}
768
769impl<T: Clone + 'static> FormFieldStateData<T> {
770    /// The state of a field created for `widget`: Dart's `late T? _value = widget.initialValue`,
771    /// read when the state is created.
772    pub fn new(widget: &FormFieldData<T>) -> FormFieldStateData<T> {
773        FormFieldStateData {
774            value: widget.initial_value.clone(),
775            error_text: None,
776            has_interacted_by_user: None,
777            focus_node: None,
778        }
779    }
780
781    fn error_text_property(&self) -> Handle<RestorableStringN> {
782        self.error_text.handle().expect("created in init_state")
783    }
784
785    fn has_interacted_by_user_property(&self) -> Handle<RestorableBool> {
786        self.has_interacted_by_user
787            .handle()
788            .expect("created in init_state")
789    }
790
791    fn focus_node(&self) -> Handle<FocusNode> {
792        self.focus_node.handle().expect("created in init_state")
793    }
794}
795
796/// The [`FormFieldStateData`] accessors a [`FormFieldStateLeaf`] implementor writes; the bag
797/// lives under the field `form_field_state`.
798#[macro_export]
799macro_rules! form_field_state_accessors {
800    () => {
801        fn form_field_state_data(
802            self: ::waft_foundation::Handle<Self>,
803            app: &::waft_foundation::App,
804        ) -> &$crate::FormFieldStateData<$crate::FormFieldValue<Self>> {
805            &app.get(self).form_field_state
806        }
807
808        fn form_field_state_data_mut(
809            self: ::waft_foundation::Handle<Self>,
810            app: &mut ::waft_foundation::App,
811        ) -> &mut $crate::FormFieldStateData<$crate::FormFieldValue<Self>> {
812            &mut app.get_mut(self).form_field_state
813        }
814    };
815}
816
817/// The trait every form-field state implements: [`FormFieldState`] and its subclasses, such as
818/// `TextFormField`'s state.
819///
820/// The virtuals a subclass overrides are the members with a default body here; the shared
821/// bodies, and the lifecycle bodies a leaf's own [`State`] and [`RestorationMixin`] impls call,
822/// are associated functions on [`FormFieldState`], which an override calls where Dart writes
823/// `super.…`.
824pub trait FormFieldStateLeaf: RestorationMixin<Widget: FormFieldLeaf> {
825    /// Dart's `FormFieldState` fields, held under the field `form_field_state`
826    /// ([`form_field_state_accessors!`](crate::form_field_state_accessors)).
827    fn form_field_state_data(
828        self: Handle<Self>,
829        app: &App,
830    ) -> &FormFieldStateData<FormFieldValue<Self>>;
831
832    /// See [`form_field_state_data`](Self::form_field_state_data).
833    fn form_field_state_data_mut(
834        self: Handle<Self>,
835        app: &mut App,
836    ) -> &mut FormFieldStateData<FormFieldValue<Self>>;
837
838    /// The current value of the form field.
839    fn value(self: Handle<Self>, app: &App) -> Option<&FormFieldValue<Self>> {
840        self.form_field_state_data(app).value.as_ref()
841    }
842
843    /// The current validation error returned by the [`FormFieldData::validator`] callback, or
844    /// the manually provided error message using the [`FormFieldData::force_error_text`]
845    /// property.
846    ///
847    /// This property is automatically updated when [`validate`](Self::validate) is called and
848    /// the [`FormFieldData::validator`] callback is invoked, or If
849    /// [`FormFieldData::force_error_text`] is set directly to a non-`None` value.
850    fn error_text(self: Handle<Self>, app: &App) -> Option<String> {
851        let property = self.form_field_state_data(app).error_text_property();
852        RestorableValue::value(property, app).clone()
853    }
854
855    /// True if this field has any validation errors.
856    fn has_error(self: Handle<Self>, app: &App) -> bool {
857        let property = self.form_field_state_data(app).error_text_property();
858        RestorableValue::value(property, app).is_some()
859    }
860
861    /// Returns true if the user has modified the value of this field.
862    ///
863    /// This only updates to true once [`did_change`](Self::did_change) has been called and
864    /// resets to false when [`reset`](Self::reset) is called.
865    fn has_interacted_by_user(self: Handle<Self>, app: &App) -> bool {
866        let property = self
867            .form_field_state_data(app)
868            .has_interacted_by_user_property();
869        *RestorableValue::value(property, app)
870    }
871
872    /// True if the current value is valid.
873    ///
874    /// This will not set [`error_text`](Self::error_text) or [`has_error`](Self::has_error) and
875    /// it will not update error display.
876    ///
877    /// See also:
878    ///
879    ///  * [`validate`](Self::validate), which may update [`error_text`](Self::error_text) and
880    ///    [`has_error`](Self::has_error).
881    ///
882    ///  * [`FormFieldData::force_error_text`], which also may update
883    ///    [`error_text`](Self::error_text) and [`has_error`](Self::has_error).
884    fn is_valid(self: Handle<Self>, app: &mut App) -> bool {
885        let widget = self.widget(app).form_field_data();
886        if widget.force_error_text.is_some() {
887            return false;
888        }
889        let Some(validator) = widget.validator.clone() else {
890            return true;
891        };
892        let value = self.value(app).cloned();
893        validator(app, value.as_ref()).is_none()
894    }
895
896    /// Calls the [`FormField`]'s on_saved method with the current value.
897    fn save(self: Handle<Self>, app: &mut App) {
898        FormFieldState::save(self, app);
899    }
900
901    /// Resets the field to its initial value.
902    fn reset(self: Handle<Self>, app: &mut App) {
903        FormFieldState::reset(self, app);
904    }
905
906    /// Clears any visible validation error for this field without resetting the field's value.
907    ///
908    /// This sets [`error_text`](Self::error_text) to `None` and
909    /// [`has_interacted_by_user`](Self::has_interacted_by_user) to false.
910    ///
911    /// If [`AutovalidateMode::Always`] is used, the error may reappear immediately because the
912    /// field will trigger a new validation cycle during the next build.
913    /// See also:
914    ///
915    ///  * [`FormState::clear_error`], which clears errors across all fields in the form.
916    fn clear_error(self: Handle<Self>, app: &mut App) {
917        FormFieldState::clear_error(self, app);
918    }
919
920    /// Calls [`FormFieldData::validator`] to set the [`error_text`](Self::error_text) only if
921    /// [`FormFieldData::force_error_text`] is `None`. When
922    /// [`FormFieldData::force_error_text`] is not `None`, [`FormFieldData::validator`] will not
923    /// be called.
924    ///
925    /// Returns true if there were no errors.
926    /// See also:
927    ///
928    ///  * [`is_valid`](Self::is_valid), which passively gets the validity without setting
929    ///    [`error_text`](Self::error_text) or [`has_error`](Self::has_error).
930    fn validate(self: Handle<Self>, app: &mut App) -> bool {
931        FormFieldState::validate(self, app)
932    }
933
934    /// Updates this field's state to the new value. Useful for responding to child widget
935    /// changes, e.g. `Slider`'s `Slider.onChanged` argument.
936    ///
937    /// Triggers the [`Form::on_changed`] callback and, if [`Form::autovalidate_mode`] is
938    /// [`AutovalidateMode::Always`] or [`AutovalidateMode::OnUserInteraction`], revalidates all
939    /// the fields of the form.
940    fn did_change(self: Handle<Self>, app: &mut App, value: Option<FormFieldValue<Self>>) {
941        FormFieldState::did_change(self, app, value);
942    }
943
944    /// Sets the value associated with this form field.
945    ///
946    /// This method should only be called by subclasses that need to update the form field value
947    /// due to state changes identified during the widget build phase, when calling `set_state`
948    /// is prohibited. In all other cases, the value should be set by a call to
949    /// [`did_change`](Self::did_change), which ensures that `set_state` is called.
950    fn set_value(self: Handle<Self>, app: &mut App, value: Option<FormFieldValue<Self>>) {
951        self.form_field_state_data_mut(app).value = value;
952    }
953
954    /// This state as the erased [`AnyFormFieldState`]: what to pass where a Dart API takes a
955    /// `FormFieldState<T>`.
956    fn as_form_field_state(self: Handle<Self>) -> AnyFormFieldState<FormFieldValue<Self>> {
957        AnyFormFieldState {
958            id: self.id(),
959            vtable: const { &FormFieldStateVTable::<FormFieldValue<Self>>::of::<Self>() },
960        }
961    }
962
963    /// This state as the erased [`DynamicFormFieldState`]: what to pass where a Dart API takes
964    /// a `FormFieldState<dynamic>`.
965    fn as_dynamic_form_field_state(self: Handle<Self>) -> DynamicFormFieldState {
966        self.as_form_field_state().as_dynamic()
967    }
968}
969
970/// The current state of a [`FormField`]. Passed to the [`FormFieldBuilder`] method for use in
971/// constructing the form field's widget.
972///
973/// Its associated functions are the bodies Dart's `FormFieldState<T>` gives its subclasses:
974/// the virtuals' defaults, which an override calls where Dart writes `super.…`, and the
975/// lifecycle a subclass's [`State`] and [`RestorationMixin`] impls run at Dart's
976/// `super.initState()` and the rest.
977pub struct FormFieldState<T: Clone + 'static> {
978    state: StateData<FormField<T>>,
979    restoration: RestorationMixinData,
980    form_field_state: FormFieldStateData<T>,
981}
982
983impl<T: Clone + 'static> FormFieldState<T> {
984    /// See [`FormFieldStateLeaf::save`].
985    pub fn save<S: FormFieldStateLeaf<Widget: FormFieldLeaf<Value = T>>>(
986        this: Handle<S>,
987        app: &mut App,
988    ) {
989        if let Some(on_saved) = this.widget(app).form_field_data().on_saved.clone() {
990            let value = this.value(app).cloned();
991            on_saved(app, value);
992        }
993    }
994
995    /// See [`FormFieldStateLeaf::reset`].
996    pub fn reset<S: FormFieldStateLeaf<Widget: FormFieldLeaf<Value = T>>>(
997        this: Handle<S>,
998        app: &mut App,
999    ) {
1000        let initial_value = this.widget(app).form_field_data().initial_value.clone();
1001        this.form_field_state_data_mut(app).value = initial_value;
1002        clear_error_internal(this, app);
1003        this.set_state(app, |_state| {});
1004        if let Some(on_reset) = this.widget(app).form_field_data().on_reset.clone() {
1005            on_reset(app);
1006        }
1007        let context = this.context(app);
1008        if let Some(form) = Form::maybe_of(app, context) {
1009            form.field_did_change(app);
1010        }
1011    }
1012
1013    /// See [`FormFieldStateLeaf::clear_error`].
1014    pub fn clear_error<S: FormFieldStateLeaf<Widget: FormFieldLeaf<Value = T>>>(
1015        this: Handle<S>,
1016        app: &mut App,
1017    ) {
1018        clear_error_internal(this, app);
1019        this.set_state(app, |_state| {});
1020        let context = this.context(app);
1021        if let Some(form) = Form::maybe_of(app, context) {
1022            form.field_did_change(app);
1023        }
1024    }
1025
1026    /// See [`FormFieldStateLeaf::validate`].
1027    pub fn validate<S: FormFieldStateLeaf<Widget: FormFieldLeaf<Value = T>>>(
1028        this: Handle<S>,
1029        app: &mut App,
1030    ) -> bool {
1031        validate_field(this, app);
1032        this.set_state(app, |_state| {});
1033        !this.has_error(app)
1034    }
1035
1036    /// See [`FormFieldStateLeaf::did_change`].
1037    pub fn did_change<S: FormFieldStateLeaf<Widget: FormFieldLeaf<Value = T>>>(
1038        this: Handle<S>,
1039        app: &mut App,
1040        value: Option<T>,
1041    ) {
1042        this.form_field_state_data_mut(app).value = value;
1043        let has_interacted_by_user = this
1044            .form_field_state_data(app)
1045            .has_interacted_by_user_property();
1046        has_interacted_by_user.set_value(app, true);
1047        this.set_state(app, |_state| {});
1048        let context = this.context(app);
1049        if let Some(form) = Form::maybe_of(app, context) {
1050            form.field_did_change(app);
1051        }
1052    }
1053
1054    /// Dart's `FormFieldState.restorationId`.
1055    pub fn restoration_id<S: FormFieldStateLeaf<Widget: FormFieldLeaf<Value = T>>>(
1056        this: Handle<S>,
1057        app: &App,
1058    ) -> Option<&str> {
1059        this.widget(app).form_field_data().restoration_id.as_deref()
1060    }
1061
1062    /// Dart's `FormFieldState.restoreState`.
1063    pub fn restore_state<S: FormFieldStateLeaf<Widget: FormFieldLeaf<Value = T>>>(
1064        this: Handle<S>,
1065        app: &mut App,
1066        _old_bucket: Option<Handle<RestorationBucket>>,
1067        _initial_restore: bool,
1068    ) {
1069        let error_text = this.form_field_state_data(app).error_text_property();
1070        this.register_for_restoration(app, error_text.as_property(), "error_text");
1071        let has_interacted_by_user = this
1072            .form_field_state_data(app)
1073            .has_interacted_by_user_property();
1074        this.register_for_restoration(
1075            app,
1076            has_interacted_by_user.as_property(),
1077            "has_interacted_by_user",
1078        );
1079    }
1080
1081    /// Dart's `FormFieldState.deactivate`, run where the leaf's [`State::deactivate`] would call
1082    /// `super.deactivate()`.
1083    pub fn deactivate<S: FormFieldStateLeaf<Widget: FormFieldLeaf<Value = T>>>(
1084        this: Handle<S>,
1085        app: &mut App,
1086    ) {
1087        let context = this.context(app);
1088        if let Some(form) = Form::maybe_of(app, context) {
1089            form.unregister(app, this.as_dynamic_form_field_state());
1090        }
1091    }
1092
1093    /// Dart's `FormFieldState.initState`, with the field initializers Dart runs as the state is
1094    /// constructed.
1095    pub fn init_state<S: FormFieldStateLeaf<Widget: FormFieldLeaf<Value = T>>>(
1096        this: Handle<S>,
1097        app: &mut App,
1098    ) {
1099        let has_interacted_by_user = RestorableBool::new(app, false);
1100        let focus_node = FocusNode::new(app);
1101        let force_error_text = this.widget(app).form_field_data().force_error_text.clone();
1102        let error_text = RestorableStringN::new(app, force_error_text);
1103        let data = this.form_field_state_data_mut(app);
1104        data.has_interacted_by_user = Some(has_interacted_by_user);
1105        data.focus_node = Some(focus_node);
1106        data.error_text = Some(error_text);
1107    }
1108
1109    /// Dart's `FormFieldState.didUpdateWidget`.
1110    pub fn did_update_widget<S: FormFieldStateLeaf<Widget: FormFieldLeaf<Value = T>>>(
1111        this: Handle<S>,
1112        app: &mut App,
1113        old_widget: &S::Widget,
1114    ) {
1115        this.did_update_restoration_id(app);
1116        let force_error_text = this.widget(app).form_field_data().force_error_text.clone();
1117        if force_error_text != old_widget.form_field_data().force_error_text {
1118            let error_text = this.form_field_state_data(app).error_text_property();
1119            error_text.set_value(app, force_error_text);
1120        }
1121    }
1122
1123    /// Dart's `FormFieldState.didChangeDependencies`.
1124    pub fn did_change_dependencies<S: FormFieldStateLeaf<Widget: FormFieldLeaf<Value = T>>>(
1125        this: Handle<S>,
1126        app: &mut App,
1127    ) {
1128        this.did_change_dependencies_restoration(app);
1129        let context = this.context(app);
1130        let form = Form::maybe_of(app, context);
1131        match form.map(|form| form.widget(app).autovalidate_mode) {
1132            Some(AutovalidateMode::Always) => {
1133                let view = View::maybe_id_of(app, context);
1134                SchedulerBinding::add_post_frame_callback(
1135                    app,
1136                    FrameCallback::new(move |app, _time_stamp| {
1137                        // If the form is already validated, don't validate again.
1138                        if this.widget(app).form_field_data().enabled
1139                            && !this.has_error(app)
1140                            && !this.is_valid(app)
1141                        {
1142                            this.validate(app);
1143                        }
1144                    }),
1145                    view,
1146                );
1147            }
1148            Some(
1149                AutovalidateMode::OnUnfocus
1150                | AutovalidateMode::OnUserInteraction
1151                | AutovalidateMode::OnUserInteractionIfError
1152                | AutovalidateMode::Disabled,
1153            )
1154            | None => {}
1155        }
1156    }
1157
1158    /// Dart's `FormFieldState.dispose`.
1159    pub fn dispose<S: FormFieldStateLeaf<Widget: FormFieldLeaf<Value = T>>>(
1160        this: Handle<S>,
1161        app: &mut App,
1162    ) {
1163        let data = this.form_field_state_data(app);
1164        let (error_text, focus_node, has_interacted_by_user) = (
1165            data.error_text_property(),
1166            data.focus_node(),
1167            data.has_interacted_by_user_property(),
1168        );
1169        RestorableProperty::dispose(error_text, app);
1170        focus_node.as_node().dispose(app);
1171        RestorableProperty::dispose(has_interacted_by_user, app);
1172        this.dispose_restoration(app);
1173    }
1174
1175    /// Dart's `FormFieldState.build`.
1176    pub fn build<S: FormFieldStateLeaf<Widget: FormFieldLeaf<Value = T>>>(
1177        this: Handle<S>,
1178        app: &mut App,
1179        context: BuildContext,
1180    ) -> WidgetRef {
1181        let widget = this.widget(app).form_field_data();
1182        let (enabled, autovalidate_mode) = (widget.enabled, widget.autovalidate_mode);
1183        if enabled {
1184            match autovalidate_mode {
1185                AutovalidateMode::Always => {
1186                    validate_field(this, app);
1187                }
1188                AutovalidateMode::OnUserInteraction => {
1189                    if this.has_interacted_by_user(app) {
1190                        validate_field(this, app);
1191                    }
1192                }
1193                AutovalidateMode::OnUserInteractionIfError => {
1194                    if this.has_interacted_by_user(app) && this.has_error(app) {
1195                        validate_field(this, app);
1196                    }
1197                }
1198                AutovalidateMode::OnUnfocus | AutovalidateMode::Disabled => {}
1199            }
1200        }
1201
1202        if let Some(form) = Form::maybe_of(app, context) {
1203            form.register(app, this.as_dynamic_form_field_state());
1204        }
1205
1206        let builder = Rc::clone(&this.widget(app).form_field_data().builder);
1207        let validation_result = if this.has_error(app) {
1208            SemanticsValidationResult::Invalid
1209        } else {
1210            SemanticsValidationResult::Valid
1211        };
1212        let child = Semantics::new()
1213            .validation_result(validation_result)
1214            .child(builder(app, this.as_form_field_state()))
1215            .into_widget();
1216
1217        let form_autovalidate_mode =
1218            Form::maybe_of(app, context).map(|form| form.widget(app).autovalidate_mode);
1219        if form_autovalidate_mode == Some(AutovalidateMode::OnUnfocus)
1220            && autovalidate_mode != AutovalidateMode::Always
1221            || autovalidate_mode == AutovalidateMode::OnUnfocus
1222        {
1223            let focus_node = this
1224                .form_field_state_data(app)
1225                .focus_node
1226                .as_ref()
1227                .expect("created in init_state")
1228                .erase();
1229            return Focus::new(child)
1230                .can_request_focus(false)
1231                .skip_traversal(true)
1232                .on_focus_change(move |app, value| {
1233                    if !value {
1234                        validate_field(this, app);
1235                        this.set_state(app, |_state| {});
1236                    }
1237                })
1238                .focus_node(focus_node)
1239                .into_widget();
1240        }
1241
1242        child
1243    }
1244}
1245
1246/// Dart's private `_clearErrorInternal`.
1247fn clear_error_internal<S: FormFieldStateLeaf>(this: Handle<S>, app: &mut App) {
1248    let data = this.form_field_state_data(app);
1249    let (error_text, has_interacted_by_user) = (
1250        data.error_text_property(),
1251        data.has_interacted_by_user_property(),
1252    );
1253    error_text.set_value(app, None);
1254    has_interacted_by_user.set_value(app, false);
1255}
1256
1257/// Dart's private `FormFieldState._validate`.
1258fn validate_field<S: FormFieldStateLeaf>(this: Handle<S>, app: &mut App) {
1259    let error_text = this.form_field_state_data(app).error_text_property();
1260    let widget = this.widget(app).form_field_data();
1261    if let Some(force_error_text) = widget.force_error_text.clone() {
1262        error_text.set_value(app, Some(force_error_text));
1263        // Skip validating if error is forced.
1264        return;
1265    }
1266    if let Some(validator) = widget.validator.clone() {
1267        let value = this.value(app).cloned();
1268        let result = validator(app, value.as_ref());
1269        error_text.set_value(app, result);
1270    } else {
1271        error_text.set_value(app, None);
1272    }
1273}
1274
1275impl<T: Clone + 'static> FormFieldStateLeaf for FormFieldState<T> {
1276    crate::form_field_state_accessors!();
1277}
1278
1279impl<T: Clone + 'static> RestorationMixin for FormFieldState<T> {
1280    crate::restoration_mixin_accessors!();
1281
1282    fn restoration_id(self: Handle<Self>, app: &App) -> Option<&str> {
1283        FormFieldState::restoration_id(self, app)
1284    }
1285
1286    fn restore_state(
1287        self: Handle<Self>,
1288        app: &mut App,
1289        old_bucket: Option<Handle<RestorationBucket>>,
1290        initial_restore: bool,
1291    ) {
1292        FormFieldState::restore_state(self, app, old_bucket, initial_restore);
1293    }
1294}
1295
1296impl<T: Clone + 'static> State for FormFieldState<T> {
1297    type Widget = FormField<T>;
1298    crate::state_accessors!();
1299
1300    fn deactivate(self: Handle<Self>, app: &mut App) {
1301        FormFieldState::deactivate(self, app);
1302    }
1303
1304    fn init_state(self: Handle<Self>, app: &mut App) {
1305        FormFieldState::init_state(self, app);
1306    }
1307
1308    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &FormField<T>) {
1309        FormFieldState::did_update_widget(self, app, old_widget);
1310    }
1311
1312    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
1313        FormFieldState::did_change_dependencies(self, app);
1314    }
1315
1316    fn dispose(self: Handle<Self>, app: &mut App) {
1317        FormFieldState::dispose(self, app);
1318    }
1319
1320    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1321        FormFieldState::build(self, app, context)
1322    }
1323}
1324
1325// ---------------------------------------------------------------------------------------------
1326// The erased form-field states
1327
1328/// The typed handle for an erased id. Free: nothing is looked up; `get` checks the slot.
1329fn resolve<S: 'static>(id: HandleId) -> Handle<S> {
1330    Handle::from_id(id)
1331}
1332
1333/// The vtable of an erased [`DynamicFormFieldState`]: what does not name the value type.
1334struct DynamicFormFieldStateVTable {
1335    type_name: fn() -> &'static str,
1336    typed: fn() -> &'static dyn Any,
1337    value: fn(&App, HandleId) -> Option<&dyn Any>,
1338    context: fn(&App, HandleId) -> BuildContext,
1339    mounted: fn(&App, HandleId) -> bool,
1340    error_text: fn(&App, HandleId) -> Option<String>,
1341    has_error: fn(&App, HandleId) -> bool,
1342    has_interacted_by_user: fn(&App, HandleId) -> bool,
1343    is_valid: fn(&mut App, HandleId) -> bool,
1344    save: fn(&mut App, HandleId),
1345    reset: fn(&mut App, HandleId),
1346    clear_error: fn(&mut App, HandleId),
1347    validate: fn(&mut App, HandleId) -> bool,
1348    clear_error_internal: fn(&mut App, HandleId),
1349    focus_node: fn(&App, HandleId) -> Handle<FocusNode>,
1350}
1351
1352/// The vtable of an erased [`AnyFormFieldState`]: the members that name the value type, and the
1353/// [`DynamicFormFieldStateVTable`] of the same leaf.
1354struct FormFieldStateVTable<T: 'static> {
1355    dynamic: DynamicFormFieldStateVTable,
1356    value: fn(&App, HandleId) -> Option<&T>,
1357    did_change: fn(&mut App, HandleId, Option<T>),
1358}
1359
1360impl<T: Clone + 'static> FormFieldStateVTable<T> {
1361    const fn of<S: FormFieldStateLeaf<Widget: FormFieldLeaf<Value = T>>>() -> FormFieldStateVTable<T>
1362    {
1363        FormFieldStateVTable {
1364            dynamic: DynamicFormFieldStateVTable {
1365                type_name: std::any::type_name::<S>,
1366                typed: || const { &FormFieldStateVTable::<T>::of::<S>() } as &dyn Any,
1367                value: |app, id| S::value(resolve(id), app).map(|value| value as &dyn Any),
1368                context: |app, id| S::context(resolve(id), app),
1369                mounted: |app, id| S::mounted(resolve(id), app),
1370                error_text: |app, id| S::error_text(resolve(id), app),
1371                has_error: |app, id| S::has_error(resolve(id), app),
1372                has_interacted_by_user: |app, id| S::has_interacted_by_user(resolve(id), app),
1373                is_valid: |app, id| S::is_valid(resolve(id), app),
1374                save: |app, id| S::save(resolve(id), app),
1375                reset: |app, id| S::reset(resolve(id), app),
1376                clear_error: |app, id| S::clear_error(resolve(id), app),
1377                validate: |app, id| S::validate(resolve(id), app),
1378                clear_error_internal: |app, id| clear_error_internal::<S>(resolve(id), app),
1379                focus_node: |app, id| S::form_field_state_data(resolve(id), app).focus_node(),
1380            },
1381            value: |app, id| S::value(resolve(id), app),
1382            did_change: |app, id, value| S::did_change(resolve(id), app, value),
1383        }
1384    }
1385}
1386
1387/// Erased [`FormFieldStateLeaf`] whose value type is not known: what a field or parameter Dart
1388/// types as `FormFieldState<dynamic>` becomes, such as the fields a [`FormState`] holds.
1389///
1390/// Equality is Dart's `==` on an object reference.
1391#[derive(Clone, Copy)]
1392pub struct DynamicFormFieldState {
1393    id: HandleId,
1394    vtable: &'static DynamicFormFieldStateVTable,
1395}
1396
1397impl PartialEq for DynamicFormFieldState {
1398    fn eq(&self, other: &DynamicFormFieldState) -> bool {
1399        self.id == other.id
1400    }
1401}
1402
1403impl Eq for DynamicFormFieldState {}
1404
1405impl std::hash::Hash for DynamicFormFieldState {
1406    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1407        self.id.hash(state);
1408    }
1409}
1410
1411impl Debug for DynamicFormFieldState {
1412    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1413        write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
1414    }
1415}
1416
1417impl DynamicFormFieldState {
1418    /// The arena id behind this handle.
1419    pub fn id(self) -> HandleId {
1420        self.id
1421    }
1422
1423    /// The leaf state behind this handle, if it is an `S`: Dart's `field as S`.
1424    pub fn downcast<S: 'static>(self, app: &App) -> Option<Handle<S>> {
1425        app.handle::<S>(self.id)
1426    }
1427
1428    /// This field as a `FormFieldState<T>`, if its value type is `T`: Dart's
1429    /// `field is FormFieldState<T>`.
1430    pub fn typed<T: 'static>(self) -> Option<AnyFormFieldState<T>> {
1431        (self.vtable.typed)()
1432            .downcast_ref::<FormFieldStateVTable<T>>()
1433            .map(|vtable| AnyFormFieldState {
1434                id: self.id,
1435                vtable,
1436            })
1437    }
1438
1439    /// See [`FormFieldStateLeaf::value`].
1440    pub fn value(self, app: &App) -> Option<&dyn Any> {
1441        (self.vtable.value)(app, self.id)
1442    }
1443
1444    /// See [`State::context`].
1445    pub fn context(self, app: &App) -> BuildContext {
1446        (self.vtable.context)(app, self.id)
1447    }
1448
1449    /// See [`State::mounted`].
1450    pub fn mounted(self, app: &App) -> bool {
1451        (self.vtable.mounted)(app, self.id)
1452    }
1453
1454    /// See [`FormFieldStateLeaf::error_text`].
1455    pub fn error_text(self, app: &App) -> Option<String> {
1456        (self.vtable.error_text)(app, self.id)
1457    }
1458
1459    /// See [`FormFieldStateLeaf::has_error`].
1460    pub fn has_error(self, app: &App) -> bool {
1461        (self.vtable.has_error)(app, self.id)
1462    }
1463
1464    /// See [`FormFieldStateLeaf::has_interacted_by_user`].
1465    pub fn has_interacted_by_user(self, app: &App) -> bool {
1466        (self.vtable.has_interacted_by_user)(app, self.id)
1467    }
1468
1469    /// See [`FormFieldStateLeaf::is_valid`].
1470    pub fn is_valid(self, app: &mut App) -> bool {
1471        (self.vtable.is_valid)(app, self.id)
1472    }
1473
1474    /// See [`FormFieldStateLeaf::save`].
1475    pub fn save(self, app: &mut App) {
1476        (self.vtable.save)(app, self.id);
1477    }
1478
1479    /// See [`FormFieldStateLeaf::reset`].
1480    pub fn reset(self, app: &mut App) {
1481        (self.vtable.reset)(app, self.id);
1482    }
1483
1484    /// See [`FormFieldStateLeaf::clear_error`].
1485    pub fn clear_error(self, app: &mut App) {
1486        (self.vtable.clear_error)(app, self.id);
1487    }
1488
1489    /// See [`FormFieldStateLeaf::validate`].
1490    pub fn validate(self, app: &mut App) -> bool {
1491        (self.vtable.validate)(app, self.id)
1492    }
1493
1494    fn clear_error_internal(self, app: &mut App) {
1495        (self.vtable.clear_error_internal)(app, self.id);
1496    }
1497
1498    fn focus_node(self, app: &App) -> Handle<FocusNode> {
1499        (self.vtable.focus_node)(app, self.id)
1500    }
1501}
1502
1503/// Erased [`FormFieldStateLeaf`] with value type `T`: what a field or parameter Dart types as
1504/// `FormFieldState<T>` becomes, such as what a [`FormFieldBuilder`] is handed.
1505///
1506/// Equality is Dart's `==` on an object reference.
1507pub struct AnyFormFieldState<T: 'static> {
1508    id: HandleId,
1509    vtable: &'static FormFieldStateVTable<T>,
1510}
1511
1512impl<T: 'static> Clone for AnyFormFieldState<T> {
1513    fn clone(&self) -> AnyFormFieldState<T> {
1514        *self
1515    }
1516}
1517
1518impl<T: 'static> Copy for AnyFormFieldState<T> {}
1519
1520impl<T: 'static> PartialEq for AnyFormFieldState<T> {
1521    fn eq(&self, other: &AnyFormFieldState<T>) -> bool {
1522        self.id == other.id
1523    }
1524}
1525
1526impl<T: 'static> Eq for AnyFormFieldState<T> {}
1527
1528impl<T: 'static> Debug for AnyFormFieldState<T> {
1529    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1530        self.as_dynamic().fmt(f)
1531    }
1532}
1533
1534impl<T: 'static> AnyFormFieldState<T> {
1535    /// This field as a `FormFieldState<dynamic>`.
1536    pub fn as_dynamic(self) -> DynamicFormFieldState {
1537        DynamicFormFieldState {
1538            id: self.id,
1539            vtable: &self.vtable.dynamic,
1540        }
1541    }
1542
1543    /// The arena id behind this handle.
1544    pub fn id(self) -> HandleId {
1545        self.id
1546    }
1547
1548    /// The leaf state behind this handle, if it is an `S`: Dart's `field as S`.
1549    pub fn downcast<S: 'static>(self, app: &App) -> Option<Handle<S>> {
1550        app.handle::<S>(self.id)
1551    }
1552
1553    /// See [`FormFieldStateLeaf::value`].
1554    pub fn value(self, app: &App) -> Option<&T> {
1555        (self.vtable.value)(app, self.id)
1556    }
1557
1558    /// See [`FormFieldStateLeaf::did_change`].
1559    pub fn did_change(self, app: &mut App, value: Option<T>) {
1560        (self.vtable.did_change)(app, self.id, value);
1561    }
1562
1563    /// See [`State::context`].
1564    pub fn context(self, app: &App) -> BuildContext {
1565        self.as_dynamic().context(app)
1566    }
1567
1568    /// See [`State::mounted`].
1569    pub fn mounted(self, app: &App) -> bool {
1570        self.as_dynamic().mounted(app)
1571    }
1572
1573    /// See [`FormFieldStateLeaf::error_text`].
1574    pub fn error_text(self, app: &App) -> Option<String> {
1575        self.as_dynamic().error_text(app)
1576    }
1577
1578    /// See [`FormFieldStateLeaf::has_error`].
1579    pub fn has_error(self, app: &App) -> bool {
1580        self.as_dynamic().has_error(app)
1581    }
1582
1583    /// See [`FormFieldStateLeaf::has_interacted_by_user`].
1584    pub fn has_interacted_by_user(self, app: &App) -> bool {
1585        self.as_dynamic().has_interacted_by_user(app)
1586    }
1587
1588    /// See [`FormFieldStateLeaf::is_valid`].
1589    pub fn is_valid(self, app: &mut App) -> bool {
1590        self.as_dynamic().is_valid(app)
1591    }
1592
1593    /// See [`FormFieldStateLeaf::save`].
1594    pub fn save(self, app: &mut App) {
1595        self.as_dynamic().save(app);
1596    }
1597
1598    /// See [`FormFieldStateLeaf::reset`].
1599    pub fn reset(self, app: &mut App) {
1600        self.as_dynamic().reset(app);
1601    }
1602
1603    /// See [`FormFieldStateLeaf::clear_error`].
1604    pub fn clear_error(self, app: &mut App) {
1605        self.as_dynamic().clear_error(app);
1606    }
1607
1608    /// See [`FormFieldStateLeaf::validate`].
1609    pub fn validate(self, app: &mut App) -> bool {
1610        self.as_dynamic().validate(app)
1611    }
1612}
1613
1614// ---------------------------------------------------------------------------------------------
1615// AutovalidateMode
1616
1617/// Used to configure the auto validation of [`FormField`] and [`Form`] widgets.
1618#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1619pub enum AutovalidateMode {
1620    /// No auto validation will occur.
1621    Disabled,
1622
1623    /// Used to auto-validate [`Form`] and [`FormField`] even without user interaction.
1624    Always,
1625
1626    /// Used to auto-validate [`Form`] and [`FormField`] only after each user interaction.
1627    OnUserInteraction,
1628
1629    /// Used to auto-validate [`Form`] and [`FormField`] only after the field has lost focus.
1630    ///
1631    /// In order to validate all fields of a [`Form`] after the first time the user interacts
1632    /// with one, use [`Always`](Self::Always) instead.
1633    OnUnfocus,
1634
1635    /// Used to auto-validate [`Form`] and [`FormField`] after each user interaction, only if
1636    /// the field already has an error.
1637    ///
1638    /// This is useful for reducing unnecessary validation calls while still ensuring errors are
1639    /// re-checked when the user attempts to fix them.
1640    OnUserInteractionIfError,
1641}
1642
1643#[cfg(test)]
1644mod tests {
1645    use std::cell::{Cell, RefCell};
1646    use waft_foundation::OptionRetained;
1647    use waft_foundation::Ref;
1648
1649    use waft_embedder::{Size, TextDirection};
1650    use waft_foundation::{UniqueKey, ValueKey};
1651    use waft_services::RestorationMap;
1652
1653    use super::*;
1654    use crate::framework::GlobalKey;
1655    use crate::testing::{
1656        WidgetTester, expect, find, finds_n_widgets, finds_nothing, finds_one_widget, test_widgets,
1657    };
1658    use crate::widgets::basic::{Center, Column, Directionality, SizedBox, StatefulBuilder};
1659    use crate::widgets::focus_manager::{AnyFocusNode, FocusNodeRef};
1660    use crate::widgets::restoration::RootRestorationScope;
1661    use crate::widgets::scroll_view::ListView;
1662    use crate::widgets::text::Text;
1663
1664    /// Dart's `tester.pumpWidget(widget)` under the left-to-right `Directionality` the
1665    /// `MaterialApp` of Dart's cases gives it.
1666    fn pump_ltr(tester: &mut WidgetTester, widget: WidgetRef) {
1667        tester.pump_widget(Directionality::new(TextDirection::Ltr, widget));
1668    }
1669
1670    fn form_state(tester: &WidgetTester, key: &GlobalKey) -> Handle<FormState> {
1671        key.current_state::<FormState>(&tester.cell.borrow())
1672            .expect("the form is mounted")
1673    }
1674
1675    fn field_state<T: Clone + 'static>(
1676        tester: &WidgetTester,
1677        key: &GlobalKey,
1678    ) -> Handle<FormFieldState<T>> {
1679        key.current_state::<FormFieldState<T>>(&tester.cell.borrow())
1680            .expect("the field is mounted")
1681    }
1682
1683    /// `tester.enterText` on a field: the value its text field would hand `didChange`.
1684    fn enter_text(tester: &WidgetTester, key: &GlobalKey, text: &str) {
1685        let field = field_state::<String>(tester, key);
1686        field.did_change(&mut tester.cell.borrow_mut(), Some(text.to_string()));
1687    }
1688
1689    // ---- a minimal `TextFormField`: a `FormField<String>` showing its value and error ----
1690
1691    fn show_field(app: &mut App, field: AnyFormFieldState<String>) -> WidgetRef {
1692        let mut children =
1693            vec![Text::new(field.value(app).cloned().unwrap_or_default()).into_widget()];
1694        if let Some(error_text) = field.error_text(app) {
1695            children.push(Text::new(error_text).into_widget());
1696        }
1697        Column::new().children(children).into_widget()
1698    }
1699
1700    fn text_field(key: &GlobalKey) -> FormField<String> {
1701        FormField::new(show_field).key(key.clone().into())
1702    }
1703
1704    /// A field whose subtree takes the focus through `node`, as a text field's does on a tap.
1705    fn focusable_text_field(key: &GlobalKey, node: FocusNodeRef) -> FormField<String> {
1706        FormField::new(move |app, field| {
1707            Focus::new(show_field(app, field))
1708                .focus_node(node.clone())
1709                .into_widget()
1710        })
1711        .key(key.clone().into())
1712    }
1713
1714    fn error_text(value: Option<&String>) -> Option<String> {
1715        Some(format!(
1716            "{}/error",
1717            value.map(String::as_str).unwrap_or("null")
1718        ))
1719    }
1720
1721    #[test]
1722    fn on_saved_is_called_with_the_value_the_field_holds() {
1723        test_widgets(|tester| {
1724            let form_key = GlobalKey::new();
1725            let field_key = GlobalKey::new();
1726            let field_value = Rc::new(RefCell::new(None));
1727            let saved = Rc::clone(&field_value);
1728            pump_ltr(
1729                tester,
1730                Form::new(text_field(&field_key).on_saved(move |_app, value| {
1731                    *saved.borrow_mut() = value;
1732                }))
1733                .key(form_key.clone().into())
1734                .into_widget(),
1735            );
1736
1737            assert_eq!(*field_value.borrow(), None);
1738
1739            for test_value in ["Test", ""] {
1740                enter_text(tester, &field_key, test_value);
1741                let form = form_state(tester, &form_key);
1742                form.save(&mut tester.cell.borrow_mut());
1743                // Pumping is unnecessary because callback happens regardless of frames.
1744                assert_eq!(field_value.borrow().as_deref(), Some(test_value));
1745            }
1746        });
1747    }
1748
1749    #[test]
1750    fn on_reset_is_called_when_the_form_resets() {
1751        test_widgets(|tester| {
1752            let form_key = GlobalKey::new();
1753            let reset_called = Rc::new(Cell::new(false));
1754            let called = Rc::clone(&reset_called);
1755            pump_ltr(
1756                tester,
1757                Form::new(
1758                    FormField::<String>::new(|_app, _field| SizedBox::shrink().into_widget())
1759                        .on_reset(move |_app| called.set(true)),
1760                )
1761                .key(form_key.clone().into())
1762                .into_widget(),
1763            );
1764
1765            assert!(!reset_called.get());
1766
1767            let form = form_state(tester, &form_key);
1768            form.reset(&mut tester.cell.borrow_mut());
1769            tester.pump();
1770
1771            assert!(reset_called.get());
1772        });
1773    }
1774
1775    #[test]
1776    fn the_validator_sets_the_error_text_only_when_validate_is_called() {
1777        test_widgets(|tester| {
1778            let form_key = GlobalKey::new();
1779            let field_key = GlobalKey::new();
1780            let error_text = |value: Option<&String>| {
1781                Some(format!("{}/error", value.map(String::as_str).unwrap_or("")))
1782            };
1783            let builder = |autovalidate_mode| {
1784                Form::new(text_field(&field_key).validator(move |_app, value| error_text(value)))
1785                    .key(form_key.clone().into())
1786                    .autovalidate_mode(autovalidate_mode)
1787                    .into_widget()
1788            };
1789
1790            // Start off not autovalidating.
1791            pump_ltr(tester, builder(AutovalidateMode::Disabled));
1792
1793            for test_value in ["Test", ""] {
1794                let expected = error_text(Some(&test_value.to_string())).unwrap();
1795                let form = form_state(tester, &form_key);
1796                form.reset(&mut tester.cell.borrow_mut());
1797                pump_ltr(tester, builder(AutovalidateMode::Disabled));
1798                enter_text(tester, &field_key, test_value);
1799                tester.pump();
1800
1801                // We have to manually validate if we're not autovalidating.
1802                expect(tester, &find::text(&expected), finds_nothing());
1803                form.validate(&mut tester.cell.borrow_mut());
1804                tester.pump();
1805                expect(tester, &find::text(&expected), finds_one_widget());
1806
1807                // Try again with autovalidation. Should validate immediately.
1808                form.reset(&mut tester.cell.borrow_mut());
1809                pump_ltr(tester, builder(AutovalidateMode::Always));
1810                enter_text(tester, &field_key, test_value);
1811                tester.pump();
1812
1813                expect(tester, &find::text(&expected), finds_one_widget());
1814            }
1815        });
1816    }
1817
1818    fn valid_string_validator(value: Option<&String>) -> Option<String> {
1819        (value.map(String::as_str) != Some("Valid string")).then(|| "Error text".to_string())
1820    }
1821
1822    #[test]
1823    fn is_valid_is_true_for_fields_that_are_valid() {
1824        test_widgets(|tester| {
1825            let field_key1 = GlobalKey::new();
1826            let field_key2 = GlobalKey::new();
1827            let field = |key: &GlobalKey| {
1828                text_field(key)
1829                    .initial_value("Valid string".to_string())
1830                    .validator(|_app, value| valid_string_validator(value))
1831                    .autovalidate_mode(AutovalidateMode::Always)
1832                    .into_widget()
1833            };
1834            pump_ltr(
1835                tester,
1836                Form::new(ListView::new().children([field(&field_key1), field(&field_key2)]))
1837                    .into_widget(),
1838            );
1839
1840            let (field1, field2) = (
1841                field_state::<String>(tester, &field_key1),
1842                field_state::<String>(tester, &field_key2),
1843            );
1844            assert!(field1.is_valid(&mut tester.cell.borrow_mut()));
1845            assert!(field2.is_valid(&mut tester.cell.borrow_mut()));
1846        });
1847    }
1848
1849    #[test]
1850    fn is_valid_is_false_for_an_invalid_field_and_does_not_change_its_error_display() {
1851        test_widgets(|tester| {
1852            let field_key1 = GlobalKey::new();
1853            let field_key2 = GlobalKey::new();
1854            let field = |key: &GlobalKey, initial_value: &str| {
1855                text_field(key)
1856                    .initial_value(initial_value.to_string())
1857                    .validator(|_app, value| valid_string_validator(value))
1858                    .autovalidate_mode(AutovalidateMode::Disabled)
1859                    .into_widget()
1860            };
1861            pump_ltr(
1862                tester,
1863                Form::new(
1864                    ListView::new()
1865                        .children([field(&field_key1, "Valid string"), field(&field_key2, "")]),
1866                )
1867                .into_widget(),
1868            );
1869
1870            let (field1, field2) = (
1871                field_state::<String>(tester, &field_key1),
1872                field_state::<String>(tester, &field_key2),
1873            );
1874            assert!(field1.is_valid(&mut tester.cell.borrow_mut()));
1875            assert!(!field2.is_valid(&mut tester.cell.borrow_mut()));
1876            assert!(!field2.has_error(&tester.cell.borrow_mut()));
1877        });
1878    }
1879
1880    #[test]
1881    fn validate_granularly_returns_a_set_of_all_and_only_the_invalid_fields() {
1882        test_widgets(|tester| {
1883            let form_key = GlobalKey::new();
1884            let valid_fields_key = UniqueKey::new();
1885            let invalid_fields_key = UniqueKey::new();
1886            let field = |key: UniqueKey, initial_value: &str| {
1887                FormField::new(show_field)
1888                    .key(key.into())
1889                    .initial_value(initial_value.to_string())
1890                    .validator(|_app, value| valid_string_validator(value))
1891                    .autovalidate_mode(AutovalidateMode::Disabled)
1892                    .into_widget()
1893            };
1894            pump_ltr(
1895                tester,
1896                Form::new(ListView::new().children([
1897                    field(valid_fields_key, "Valid string"),
1898                    field(invalid_fields_key, "Invalid string"),
1899                    field(invalid_fields_key, "Invalid string"),
1900                ]))
1901                .key(form_key.clone().into())
1902                .into_widget(),
1903            );
1904
1905            let form = form_state(tester, &form_key);
1906            let validation_result = form.validate_granularly(&mut tester.cell.borrow_mut());
1907
1908            let app = tester.cell.borrow_mut();
1909            let with_key = |key: UniqueKey| {
1910                let key = KeyRef::from(key);
1911                validation_result
1912                    .iter()
1913                    .filter(|field| field.context(&app).widget(&app).key() == Some(&key))
1914                    .count()
1915            };
1916            assert_eq!(validation_result.len(), 2);
1917            assert_eq!(with_key(invalid_fields_key), 2);
1918            assert_eq!(with_key(valid_fields_key), 0);
1919        });
1920    }
1921
1922    #[test]
1923    fn multiple_fields_communicate() {
1924        test_widgets(|tester| {
1925            let form_key = GlobalKey::new();
1926            let field_key = GlobalKey::new();
1927            let second_key = GlobalKey::new();
1928            let read_key = field_key.clone();
1929            // Input 2's validator depends on a input 1's value.
1930            let builder = || {
1931                let read_key = read_key.clone();
1932                Form::new(
1933                    ListView::new().children([
1934                        text_field(&field_key).into_widget(),
1935                        text_field(&second_key)
1936                            .validator(move |app, _input| {
1937                                let field = read_key
1938                                    .current_state::<FormFieldState<String>>(app)
1939                                    .expect("the first field is mounted");
1940                                Some(format!(
1941                                    "{}/error",
1942                                    field.value(app).cloned().unwrap_or_default()
1943                                ))
1944                            })
1945                            .into_widget(),
1946                    ]),
1947                )
1948                .key(form_key.clone().into())
1949                .autovalidate_mode(AutovalidateMode::Always)
1950                .into_widget()
1951            };
1952            pump_ltr(tester, builder());
1953
1954            for test_value in ["Test", ""] {
1955                enter_text(tester, &field_key, test_value);
1956                tester.pump();
1957
1958                // Check for a new Text widget with our error text.
1959                expect(
1960                    tester,
1961                    &find::text(&format!("{test_value}/error")),
1962                    finds_one_widget(),
1963                );
1964            }
1965        });
1966    }
1967
1968    #[test]
1969    fn removing_a_field_from_the_tree_does_not_crash_the_form() {
1970        test_widgets(|tester| {
1971            let form_key = GlobalKey::new();
1972            let field_key = GlobalKey::new();
1973            let field_value = Rc::new(RefCell::new(None::<String>));
1974            let builder = |remove: bool| {
1975                let saved = Rc::clone(&field_value);
1976                let child = if remove {
1977                    SizedBox::new().into_widget()
1978                } else {
1979                    text_field(&field_key)
1980                        .on_saved(move |_app, value| *saved.borrow_mut() = value)
1981                        .validator(|_app, value| {
1982                            value
1983                                .is_some_and(|value| !value.is_empty())
1984                                .then(|| "yes".to_string())
1985                        })
1986                        .into_widget()
1987                };
1988                Form::new(child).key(form_key.clone().into()).into_widget()
1989            };
1990
1991            pump_ltr(tester, builder(false));
1992            let form = form_state(tester, &form_key);
1993
1994            assert_eq!(*field_value.borrow(), None);
1995            assert!(form.validate(&mut tester.cell.borrow_mut()));
1996
1997            enter_text(tester, &field_key, "Test");
1998            pump_ltr(tester, builder(false));
1999
2000            // Form wasn't saved yet.
2001            assert_eq!(*field_value.borrow(), None);
2002            assert!(!form.validate(&mut tester.cell.borrow_mut()));
2003
2004            form.save(&mut tester.cell.borrow_mut());
2005
2006            // Now fieldValue is saved.
2007            assert_eq!(field_value.borrow().as_deref(), Some("Test"));
2008            assert!(!form.validate(&mut tester.cell.borrow_mut()));
2009
2010            // Now remove the field with an error.
2011            pump_ltr(tester, builder(true));
2012
2013            // Reset the form. Should not crash.
2014            form.reset(&mut tester.cell.borrow_mut());
2015            form.save(&mut tester.cell.borrow_mut());
2016            assert!(form.validate(&mut tester.cell.borrow_mut()));
2017        });
2018    }
2019
2020    /// A lone field, no form above it, that records its state as its builder is handed it.
2021    fn recording_field(
2022        recorded: &Rc<Cell<Option<AnyFormFieldState<String>>>>,
2023        show_error: bool,
2024    ) -> FormField<String> {
2025        let recorded = Rc::clone(recorded);
2026        FormField::new(move |app, field| {
2027            recorded.set(Some(field));
2028            let mut children = vec![SizedBox::new().into_widget()];
2029            if show_error && let Some(error_text) = field.error_text(app) {
2030                children.push(Text::new(error_text).into_widget());
2031            }
2032            Column::new().children(children).into_widget()
2033        })
2034    }
2035
2036    fn required(value: Option<&String>) -> Option<String> {
2037        value
2038            .is_none_or(|value| value.is_empty())
2039            .then(|| "Required".to_string())
2040    }
2041
2042    #[test]
2043    fn a_field_does_not_autovalidate_before_its_value_changes_on_user_interaction() {
2044        test_widgets(|tester| {
2045            let recorded = Rc::new(Cell::new(None));
2046            pump_ltr(
2047                tester,
2048                recording_field(&recorded, true)
2049                    .initial_value("foo".to_string())
2050                    .autovalidate_mode(AutovalidateMode::OnUserInteraction)
2051                    .validator(|_app, value| error_text(value))
2052                    .into_widget(),
2053            );
2054            let field = recorded.get().expect("built");
2055            // The form field has no error.
2056            assert!(!field.has_error(&tester.cell.borrow_mut()));
2057            // No error widget is visible.
2058            expect(tester, &find::text("foo/error"), finds_nothing());
2059        });
2060    }
2061
2062    #[test]
2063    fn a_field_does_not_autovalidate_before_its_value_changes_on_user_interaction_if_error() {
2064        test_widgets(|tester| {
2065            let recorded = Rc::new(Cell::new(None));
2066            pump_ltr(
2067                tester,
2068                recording_field(&recorded, true)
2069                    .initial_value("foo".to_string())
2070                    .autovalidate_mode(AutovalidateMode::OnUserInteractionIfError)
2071                    .validator(|_app, value| required(value))
2072                    .into_widget(),
2073            );
2074            let field = recorded.get().expect("built");
2075            // The form field has no error.
2076            assert!(!field.has_error(&tester.cell.borrow_mut()));
2077            // No "Required" error is visible.
2078            expect(tester, &find::text("Required"), finds_nothing());
2079        });
2080    }
2081
2082    #[test]
2083    fn a_field_with_an_empty_value_does_not_autovalidate_before_it_changes_on_user_interaction_if_error()
2084     {
2085        test_widgets(|tester| {
2086            let recorded = Rc::new(Cell::new(None));
2087            pump_ltr(
2088                tester,
2089                recording_field(&recorded, true)
2090                    .autovalidate_mode(AutovalidateMode::OnUserInteractionIfError)
2091                    .validator(|_app, value| required(value))
2092                    .into_widget(),
2093            );
2094            let field = recorded.get().expect("built");
2095
2096            assert!(!field.has_error(&tester.cell.borrow_mut()));
2097            expect(tester, &find::text("Required"), finds_nothing());
2098            assert_eq!(field.error_text(&tester.cell.borrow_mut()), None);
2099
2100            field.validate(&mut tester.cell.borrow_mut());
2101            tester.pump();
2102
2103            assert!(field.has_error(&tester.cell.borrow_mut()));
2104            expect(tester, &find::text("Required"), finds_one_widget());
2105        });
2106    }
2107
2108    #[test]
2109    fn a_field_autovalidates_before_its_value_changes_when_its_mode_is_always() {
2110        test_widgets(|tester| {
2111            let recorded = Rc::new(Cell::new(None));
2112            pump_ltr(
2113                tester,
2114                recording_field(&recorded, false)
2115                    .initial_value("foo".to_string())
2116                    .autovalidate_mode(AutovalidateMode::Always)
2117                    .validator(|_app, value| error_text(value))
2118                    .into_widget(),
2119            );
2120            let field = recorded.get().expect("built");
2121            assert!(field.has_error(&tester.cell.borrow_mut()));
2122        });
2123    }
2124
2125    fn error_slash(value: Option<&String>) -> Option<String> {
2126        Some(format!(
2127            "error/{}",
2128            value.map(String::as_str).unwrap_or("null")
2129        ))
2130    }
2131
2132    #[test]
2133    fn a_form_autovalidates_its_fields_only_after_one_changes_on_user_interaction() {
2134        test_widgets(|tester| {
2135            let keys = [GlobalKey::new(), GlobalKey::new(), GlobalKey::new()];
2136            let builder = || {
2137                Form::new(Column::new().children(keys.iter().map(|key| {
2138                    text_field(key)
2139                        .initial_value("foo".to_string())
2140                        .validator(|_app, value| error_slash(value))
2141                        .into_widget()
2142                })))
2143                .autovalidate_mode(AutovalidateMode::OnUserInteraction)
2144                .into_widget()
2145            };
2146
2147            // Makes sure the Form widget won't auto-validate the form fields
2148            // after rebuilds if there is not user interaction.
2149            pump_ltr(tester, builder());
2150            pump_ltr(tester, builder());
2151
2152            // We expect no validation error text being shown.
2153            expect(tester, &find::text("error/foo"), finds_nothing());
2154
2155            // Set a empty string into the first form field to
2156            // trigger the fields validators.
2157            enter_text(tester, &keys[0], "");
2158            tester.pump();
2159
2160            // Now we expect the errors to be shown for the first Text Field and
2161            // for the next two form fields that have their contents unchanged.
2162            expect(tester, &find::text("error/"), finds_one_widget());
2163            expect(tester, &find::text("error/foo"), finds_n_widgets(2));
2164        });
2165    }
2166
2167    #[test]
2168    fn a_form_autovalidates_its_fields_before_any_changes_when_its_mode_is_always() {
2169        test_widgets(|tester| {
2170            let field_key = GlobalKey::new();
2171            let builder = || {
2172                Form::new(
2173                    text_field(&field_key)
2174                        // A `TextFormField` without an initial value holds an empty string.
2175                        .initial_value(String::new())
2176                        .validator(|_app, value| error_slash(value)),
2177                )
2178                .autovalidate_mode(AutovalidateMode::Always)
2179                .into_widget()
2180            };
2181
2182            // The issue only happens on the second build so we
2183            // need to rebuild the tree twice.
2184            pump_ltr(tester, builder());
2185            pump_ltr(tester, builder());
2186
2187            // We expect validation error text being shown.
2188            expect(tester, &find::text("error/"), finds_one_widget());
2189        });
2190    }
2191
2192    #[test]
2193    fn form_reset_clears_errors_and_autovalidates_again_only_on_the_next_user_interaction() {
2194        test_widgets(|tester| {
2195            let form_key = GlobalKey::new();
2196            let field_key = GlobalKey::new();
2197            pump_ltr(
2198                tester,
2199                Form::new(
2200                    text_field(&field_key)
2201                        .initial_value("foo".to_string())
2202                        .validator(|_app, value| error_text(value)),
2203                )
2204                .key(form_key.clone().into())
2205                .autovalidate_mode(AutovalidateMode::OnUserInteraction)
2206                .into_widget(),
2207            );
2208
2209            // No error text is visible yet.
2210            expect(tester, &find::text("foo/error"), finds_nothing());
2211
2212            enter_text(tester, &field_key, "bar");
2213            tester.pump();
2214            tester.pump();
2215            expect(tester, &find::text("bar/error"), finds_one_widget());
2216
2217            // Resetting the form state should remove the error text.
2218            let form = form_state(tester, &form_key);
2219            form.reset(&mut tester.cell.borrow_mut());
2220            tester.pump();
2221            expect(tester, &find::text("bar/error"), finds_nothing());
2222        });
2223    }
2224
2225    #[test]
2226    fn a_form_on_user_interaction_if_error_revalidates_only_once_an_error_exists() {
2227        test_widgets(|tester| {
2228            let form_key = GlobalKey::new();
2229            let field_key = GlobalKey::new();
2230            pump_ltr(
2231                tester,
2232                Form::new(
2233                    text_field(&field_key)
2234                        .initial_value("foo".to_string())
2235                        .validator(|_app, value| required(value)),
2236                )
2237                .key(form_key.clone().into())
2238                .autovalidate_mode(AutovalidateMode::OnUserInteractionIfError)
2239                .into_widget(),
2240            );
2241            let form = form_state(tester, &form_key);
2242
2243            // No error text is visible yet. (Initial valid state).
2244            expect(tester, &find::text("Required"), finds_nothing());
2245
2246            // User types valid input 'bar' → autovalidate is disabled → still no error.
2247            enter_text(tester, &field_key, "bar");
2248            tester.pump();
2249            expect(tester, &find::text("Required"), finds_nothing());
2250
2251            // Clear the input (invalid).
2252            enter_text(tester, &field_key, "");
2253            tester.pump();
2254
2255            // Manually submit form to show the initial error (AutovalidateMode is now active).
2256            form.validate(&mut tester.cell.borrow_mut());
2257            expect(tester, &find::text("Required"), finds_nothing());
2258            tester.pump();
2259
2260            // Verify error is shown.
2261            expect(tester, &find::text("Required"), finds_one_widget());
2262
2263            // Now user interacts again with valid text ('baz') → validation auto-runs and clears
2264            // the error.
2265            enter_text(tester, &field_key, "baz");
2266            tester.pump();
2267            expect(tester, &find::text("Required"), finds_nothing());
2268
2269            // Check the behavior of a manual validate when the text is already valid.
2270            // This should *confirm* the error is cleared, not re-introduce it.
2271            form.validate(&mut tester.cell.borrow_mut());
2272            tester.pump();
2273            expect(tester, &find::text("Required"), finds_nothing());
2274
2275            // Resetting should clear form (already cleared, but a safety check).
2276            enter_text(tester, &field_key, "");
2277            form.reset(&mut tester.cell.borrow_mut());
2278            tester.pump();
2279            expect(tester, &find::text("Required"), finds_nothing());
2280        });
2281    }
2282
2283    #[test]
2284    fn has_interacted_by_user_is_false_while_the_input_has_not_changed() {
2285        test_widgets(|tester| {
2286            let field_key = GlobalKey::new();
2287            pump_ltr(tester, text_field(&field_key).into_widget());
2288
2289            let field = field_state::<String>(tester, &field_key);
2290            assert!(!field.has_interacted_by_user(&tester.cell.borrow_mut()));
2291        });
2292    }
2293
2294    #[test]
2295    fn has_interacted_by_user_is_true_after_the_input_changed() {
2296        test_widgets(|tester| {
2297            let field_key = GlobalKey::new();
2298            pump_ltr(tester, text_field(&field_key).into_widget());
2299            let field = field_state::<String>(tester, &field_key);
2300
2301            // initially, the field has not been interacted with
2302            assert!(!field.has_interacted_by_user(&tester.cell.borrow_mut()));
2303
2304            // after entering text, the field has been interacted with
2305            enter_text(tester, &field_key, "foo");
2306            assert!(field.has_interacted_by_user(&tester.cell.borrow_mut()));
2307        });
2308    }
2309
2310    #[test]
2311    fn has_interacted_by_user_is_false_after_the_field_is_reset() {
2312        test_widgets(|tester| {
2313            let field_key = GlobalKey::new();
2314            pump_ltr(tester, text_field(&field_key).into_widget());
2315            let field = field_state::<String>(tester, &field_key);
2316
2317            // initially, the field has not been interacted with
2318            assert!(!field.has_interacted_by_user(&tester.cell.borrow_mut()));
2319
2320            // after entering text, the field has been interacted with
2321            enter_text(tester, &field_key, "foo");
2322            assert!(field.has_interacted_by_user(&tester.cell.borrow_mut()));
2323
2324            // after resetting the field, it has not been interacted with again
2325            field.reset(&mut tester.cell.borrow_mut());
2326            assert!(!field.has_interacted_by_user(&tester.cell.borrow_mut()));
2327        });
2328    }
2329
2330    #[test]
2331    fn force_error_text_forces_an_error_state_from_the_first_build() {
2332        test_widgets(|tester| {
2333            let field_key = GlobalKey::new();
2334            pump_ltr(
2335                tester,
2336                Form::new(text_field(&field_key).force_error_text("Forcing error."))
2337                    .autovalidate_mode(AutovalidateMode::Disabled)
2338                    .into_widget(),
2339            );
2340            expect(tester, &find::text("Forcing error."), finds_one_widget());
2341        });
2342    }
2343
2344    #[test]
2345    fn validate_is_false_with_a_force_error_text_even_when_the_validator_finds_no_error() {
2346        test_widgets(|tester| {
2347            let form_key = GlobalKey::new();
2348            let field_key = GlobalKey::new();
2349            pump_ltr(
2350                tester,
2351                Form::new(
2352                    text_field(&field_key)
2353                        .force_error_text("Forcing error")
2354                        .validator(|_app, _value| None),
2355                )
2356                .key(form_key.clone().into())
2357                .into_widget(),
2358            );
2359
2360            expect(tester, &find::text("Forcing error"), finds_one_widget());
2361            let form = form_state(tester, &form_key);
2362            let is_valid = form.validate(&mut tester.cell.borrow_mut());
2363            assert!(!is_valid);
2364
2365            tester.pump();
2366            expect(tester, &find::text("Forcing error"), finds_one_widget());
2367        });
2368    }
2369
2370    #[test]
2371    fn force_error_text_forces_an_error_state_only_once_it_is_set() {
2372        test_widgets(|tester| {
2373            let form_key = GlobalKey::new();
2374            let field_key = GlobalKey::new();
2375            let builder = |force_error_text: Option<&str>| {
2376                let mut field = text_field(&field_key);
2377                if let Some(force_error_text) = force_error_text {
2378                    field = field.force_error_text(force_error_text);
2379                }
2380                Form::new(field)
2381                    .key(form_key.clone().into())
2382                    .autovalidate_mode(AutovalidateMode::Disabled)
2383                    .into_widget()
2384            };
2385
2386            pump_ltr(tester, builder(None));
2387            let form = form_state(tester, &form_key);
2388            let is_valid = form.validate(&mut tester.cell.borrow_mut());
2389            assert!(is_valid);
2390            expect(tester, &find::text("Forcing Error Text"), finds_nothing());
2391            pump_ltr(tester, builder(Some("Forcing Error Text")));
2392            expect(
2393                tester,
2394                &find::text("Forcing Error Text"),
2395                finds_one_widget(),
2396            );
2397        });
2398    }
2399
2400    #[test]
2401    fn the_validator_is_not_called_while_a_force_error_text_is_given() {
2402        test_widgets(|tester| {
2403            let form_key = GlobalKey::new();
2404            let field_key = GlobalKey::new();
2405            let force_error_text = "Forcing error.";
2406            let validator_error_text =
2407                "this error should not appear as we override it with forceErrorText";
2408            let did_call_validator = Rc::new(Cell::new(false));
2409            let builder = |autovalidate_mode| {
2410                let called = Rc::clone(&did_call_validator);
2411                Form::new(
2412                    text_field(&field_key)
2413                        .force_error_text(force_error_text)
2414                        .validator(move |_app, _value| {
2415                            called.set(true);
2416                            Some(validator_error_text.to_string())
2417                        }),
2418                )
2419                .key(form_key.clone().into())
2420                .autovalidate_mode(autovalidate_mode)
2421                .into_widget()
2422            };
2423
2424            // Start off not autovalidating.
2425            pump_ltr(tester, builder(AutovalidateMode::Disabled));
2426            expect(tester, &find::text(force_error_text), finds_one_widget());
2427            expect(tester, &find::text(validator_error_text), finds_nothing());
2428
2429            let form = form_state(tester, &form_key);
2430            form.reset(&mut tester.cell.borrow_mut());
2431            tester.pump();
2432            expect(tester, &find::text(force_error_text), finds_nothing());
2433            expect(tester, &find::text(validator_error_text), finds_nothing());
2434
2435            // We have to manually validate if we're not autovalidating.
2436            form.validate(&mut tester.cell.borrow_mut());
2437            tester.pump();
2438
2439            assert!(!did_call_validator.get());
2440            expect(tester, &find::text(force_error_text), finds_one_widget());
2441            expect(tester, &find::text(validator_error_text), finds_nothing());
2442
2443            // Try again with autovalidation. Should validate immediately.
2444            pump_ltr(tester, builder(AutovalidateMode::Always));
2445
2446            assert!(!did_call_validator.get());
2447            expect(tester, &find::text(force_error_text), finds_one_widget());
2448            expect(tester, &find::text(validator_error_text), finds_nothing());
2449        });
2450    }
2451
2452    #[test]
2453    fn removing_the_validator_takes_its_error_text_away() {
2454        test_widgets(|tester| {
2455            let form_key = GlobalKey::new();
2456            let field_key = GlobalKey::new();
2457            let use_validator = Rc::new(Cell::new(false));
2458            let set_state = Rc::new(RefCell::new(None));
2459            let builder = {
2460                let (form_key, field_key) = (form_key.clone(), field_key.clone());
2461                let (use_validator, set_state) = (Rc::clone(&use_validator), Rc::clone(&set_state));
2462                StatefulBuilder::new(move |_app, _context, setter| {
2463                    *set_state.borrow_mut() = Some(setter);
2464                    let mut field = text_field(&field_key);
2465                    if use_validator.get() {
2466                        field = field.validator(|_app, value| {
2467                            value
2468                                .is_none_or(|value| value.is_empty())
2469                                .then(|| "test_error".to_string())
2470                        });
2471                    }
2472                    Form::new(field).key(form_key.clone().into()).into_widget()
2473                })
2474            };
2475            pump_ltr(tester, builder.into_widget());
2476            let form = form_state(tester, &form_key);
2477            let set_use_validator = |tester: &mut WidgetTester, value: bool| {
2478                let setter = set_state.borrow().clone().expect("built");
2479                let use_validator = Rc::clone(&use_validator);
2480                setter(&mut tester.cell.borrow_mut(), &mut move |_app| {
2481                    use_validator.set(value)
2482                });
2483                tester.pump();
2484            };
2485
2486            // Start with no validator.
2487            enter_text(tester, &field_key, "");
2488            tester.pump();
2489            form.validate(&mut tester.cell.borrow_mut());
2490            tester.pump();
2491            expect(tester, &find::text("test_error"), finds_nothing());
2492
2493            // Now use the validator.
2494            set_use_validator(tester, true);
2495            form.validate(&mut tester.cell.borrow_mut());
2496            tester.pump();
2497            expect(tester, &find::text("test_error"), finds_one_widget());
2498
2499            // Remove the validator again and expect the error to disappear.
2500            set_use_validator(tester, false);
2501            form.validate(&mut tester.cell.borrow_mut());
2502            tester.pump();
2503            expect(tester, &find::text("test_error"), finds_nothing());
2504        });
2505    }
2506
2507    /// `tester.tap` on a text field: its subtree takes the primary focus.
2508    fn focus(tester: &mut WidgetTester, node: AnyFocusNode) {
2509        node.request_focus(&mut tester.cell.borrow_mut(), None);
2510        tester.pump();
2511        tester.pump();
2512    }
2513
2514    #[test]
2515    fn a_form_on_unfocus_validates_a_field_as_it_loses_the_focus() {
2516        test_widgets(|tester| {
2517            let (key1, key2) = (GlobalKey::new(), GlobalKey::new());
2518            let (node1, node2): (FocusNodeRef, FocusNodeRef) = {
2519                let mut app = tester.cell.borrow_mut();
2520                (
2521                    FocusNode::new(&mut app).into_erased(),
2522                    FocusNode::new(&mut app).into_erased(),
2523                )
2524            };
2525            let field = |key: &GlobalKey, node| {
2526                focusable_text_field(key, node)
2527                    .initial_value("bar".to_string())
2528                    .validator(|_app, value| error_text(value))
2529                    .into_widget()
2530            };
2531            pump_ltr(
2532                tester,
2533                Form::new(
2534                    Column::new()
2535                        .children([field(&key1, node1.clone()), field(&key2, node2.clone())]),
2536                )
2537                .autovalidate_mode(AutovalidateMode::OnUnfocus)
2538                .into_widget(),
2539            );
2540
2541            // No error text is visible yet.
2542            expect(tester, &find::text("foo/error"), finds_nothing());
2543
2544            // Enter text in the first TextFormField.
2545            focus(tester, node1.handle());
2546            enter_text(tester, &key1, "foo");
2547            tester.pump();
2548
2549            // No error text is visible yet.
2550            expect(tester, &find::text("foo/error"), finds_nothing());
2551
2552            // Tap on the second TextFormField to trigger validation.
2553            // This should trigger validation for the first TextFormField as well.
2554            focus(tester, node2.handle());
2555
2556            // Verify that the error text is displayed for the first TextFormField.
2557            expect(tester, &find::text("foo/error"), finds_one_widget());
2558            expect(tester, &find::text("bar/error"), finds_nothing());
2559
2560            // Tap on the first TextFormField to trigger validation.
2561            focus(tester, node1.handle());
2562
2563            // Verify that the both error texts are displayed.
2564            expect(tester, &find::text("foo/error"), finds_one_widget());
2565            expect(tester, &find::text("bar/error"), finds_one_widget());
2566        });
2567    }
2568
2569    #[test]
2570    fn a_field_mode_of_its_own_wins_over_the_form_on_unfocus() {
2571        test_widgets(|tester| {
2572            let (key1, key2) = (GlobalKey::new(), GlobalKey::new());
2573            let (node1, node2): (FocusNodeRef, FocusNodeRef) = {
2574                let mut app = tester.cell.borrow_mut();
2575                (
2576                    FocusNode::new(&mut app).into_erased(),
2577                    FocusNode::new(&mut app).into_erased(),
2578                )
2579            };
2580            pump_ltr(
2581                tester,
2582                Form::new(
2583                    Column::new().children([
2584                        focusable_text_field(&key1, node1.clone())
2585                            .autovalidate_mode(AutovalidateMode::Always)
2586                            .initial_value("foo".to_string())
2587                            .validator(|_app, value| error_text(value))
2588                            .into_widget(),
2589                        focusable_text_field(&key2, node2.clone())
2590                            .autovalidate_mode(AutovalidateMode::Disabled)
2591                            .initial_value("bar".to_string())
2592                            .validator(|_app, value| error_text(value))
2593                            .into_widget(),
2594                    ]),
2595                )
2596                .autovalidate_mode(AutovalidateMode::OnUnfocus)
2597                .into_widget(),
2598            );
2599
2600            // Verify that the error text is displayed for the first TextFormField.
2601            expect(tester, &find::text("foo/error"), finds_one_widget());
2602
2603            // Enter text in the TextFormField.
2604            focus(tester, node1.handle());
2605            enter_text(tester, &key1, "foo");
2606            tester.pump();
2607
2608            // Click in the second TextFormField to trigger validation.
2609            focus(tester, node2.handle());
2610
2611            // No error text is visible yet for the second TextFormField.
2612            expect(tester, &find::text("bar/error"), finds_nothing());
2613
2614            // Now click in the first TextFormField to trigger validation for the second
2615            // TextFormField.
2616            focus(tester, node1.handle());
2617
2618            // Verify that the error text is displayed for the second TextFormField.
2619            expect(tester, &find::text("bar/error"), finds_one_widget());
2620        });
2621    }
2622
2623    #[test]
2624    fn a_form_on_unfocus_validates_every_field_when_validated_by_hand() {
2625        test_widgets(|tester| {
2626            let form_key = GlobalKey::new();
2627            let (key1, key2) = (GlobalKey::new(), GlobalKey::new());
2628            let (node1, node2): (FocusNodeRef, FocusNodeRef) = {
2629                let mut app = tester.cell.borrow_mut();
2630                (
2631                    FocusNode::new(&mut app).into_erased(),
2632                    FocusNode::new(&mut app).into_erased(),
2633                )
2634            };
2635            pump_ltr(
2636                tester,
2637                Form::new(
2638                    Column::new().children([
2639                        focusable_text_field(&key1, node1.clone())
2640                            .initial_value("foo".to_string())
2641                            .validator(|_app, value| error_text(value))
2642                            .into_widget(),
2643                        focusable_text_field(&key2, node2.clone())
2644                            .initial_value("bar".to_string())
2645                            .validator(|_app, value| error_text(value))
2646                            .into_widget(),
2647                    ]),
2648                )
2649                .key(form_key.clone().into())
2650                .autovalidate_mode(AutovalidateMode::OnUnfocus)
2651                .into_widget(),
2652            );
2653
2654            // Focus on the first field.
2655            focus(tester, node1.handle());
2656
2657            // Check no error messages are displayed initially.
2658            expect(tester, &find::text("foo/error"), finds_nothing());
2659            expect(tester, &find::text("bar/error"), finds_nothing());
2660
2661            // Validate all fields manually using FormState.
2662            let form = form_state(tester, &form_key);
2663            assert!(!form.validate(&mut tester.cell.borrow_mut()));
2664            tester.pump();
2665
2666            // Check error messages are displayed.
2667            expect(tester, &find::text("foo/error"), finds_one_widget());
2668            expect(tester, &find::text("bar/error"), finds_one_widget());
2669        });
2670    }
2671
2672    #[test]
2673    fn a_form_always_validates_its_fields_at_the_second_frame() {
2674        test_widgets(|tester| {
2675            let (key1, key2) = (GlobalKey::new(), GlobalKey::new());
2676            pump_ltr(
2677                tester,
2678                Form::new(
2679                    Column::new().children([
2680                        text_field(&key1)
2681                            .initial_value("foo".to_string())
2682                            .validator(|_app, value| error_text(value))
2683                            .into_widget(),
2684                        text_field(&key2)
2685                            .initial_value("bar".to_string())
2686                            .validator(|_app, value| error_text(value))
2687                            .into_widget(),
2688                    ]),
2689                )
2690                .autovalidate_mode(AutovalidateMode::Always)
2691                .into_widget(),
2692            );
2693
2694            // The validation happens in a post frame callback, so the error
2695            // doesn't show up until the second frame.
2696            expect(tester, &find::text("foo/error"), finds_nothing());
2697            expect(tester, &find::text("bar/error"), finds_nothing());
2698
2699            tester.pump();
2700
2701            // The error shows up on the second frame.
2702            expect(tester, &find::text("foo/error"), finds_one_widget());
2703            expect(tester, &find::text("bar/error"), finds_one_widget());
2704        });
2705    }
2706
2707    /// `Text('X')`: a box that would be bigger than zero, which zero constraints squeeze.
2708    fn sized_text() -> WidgetRef {
2709        Text::new("X").into_widget()
2710    }
2711
2712    #[test]
2713    fn a_form_does_not_crash_at_zero_area() {
2714        test_widgets(|tester| {
2715            pump_ltr(
2716                tester,
2717                Center::new()
2718                    .child(SizedBox::shrink().child(Form::new(sized_text())))
2719                    .into_widget(),
2720            );
2721            assert_eq!(tester.get_size(find::by_type::<Form>()), Size::ZERO);
2722        });
2723    }
2724
2725    #[test]
2726    fn a_form_field_does_not_crash_at_zero_area() {
2727        test_widgets(|tester| {
2728            pump_ltr(
2729                tester,
2730                Center::new()
2731                    .child(
2732                        SizedBox::shrink()
2733                            .child(FormField::<String>::new(|_app, _field| sized_text())),
2734                    )
2735                    .into_widget(),
2736            );
2737            assert_eq!(
2738                tester.get_size(find::by_type::<FormField<String>>()),
2739                Size::ZERO
2740            );
2741        });
2742    }
2743
2744    #[test]
2745    fn clear_error_clears_the_error_and_keeps_the_value() {
2746        test_widgets(|tester| {
2747            let field_key = GlobalKey::new();
2748            pump_ltr(
2749                tester,
2750                Form::new(
2751                    text_field(&field_key)
2752                        .initial_value("foo".to_string())
2753                        .validator(|_app, value| error_text(value)),
2754                )
2755                .into_widget(),
2756            );
2757            let field = field_state::<String>(tester, &field_key);
2758
2759            field.validate(&mut tester.cell.borrow_mut());
2760            tester.pump();
2761            expect(tester, &find::text("foo/error"), finds_one_widget());
2762
2763            field.clear_error(&mut tester.cell.borrow_mut());
2764            tester.pump();
2765
2766            expect(tester, &find::text("foo/error"), finds_nothing());
2767
2768            // Value is preserved.
2769            expect(tester, &find::text("foo"), finds_one_widget());
2770        });
2771    }
2772
2773    #[test]
2774    fn clear_error_on_the_form_clears_every_field_error() {
2775        test_widgets(|tester| {
2776            let form_key = GlobalKey::new();
2777            let (key1, key2) = (GlobalKey::new(), GlobalKey::new());
2778            pump_ltr(
2779                tester,
2780                Form::new(
2781                    Column::new().children([
2782                        text_field(&key1)
2783                            .initial_value("foo".to_string())
2784                            .validator(|_app, value| error_text(value))
2785                            .into_widget(),
2786                        text_field(&key2)
2787                            .initial_value("bar".to_string())
2788                            .validator(|_app, value| error_text(value))
2789                            .into_widget(),
2790                    ]),
2791                )
2792                .key(form_key.clone().into())
2793                .into_widget(),
2794            );
2795            let form = form_state(tester, &form_key);
2796
2797            form.validate(&mut tester.cell.borrow_mut());
2798            tester.pump();
2799
2800            expect(tester, &find::text("foo/error"), finds_one_widget());
2801            expect(tester, &find::text("bar/error"), finds_one_widget());
2802
2803            form.clear_error(&mut tester.cell.borrow_mut());
2804            tester.pump();
2805
2806            expect(tester, &find::text("foo/error"), finds_nothing());
2807            expect(tester, &find::text("bar/error"), finds_nothing());
2808            expect(tester, &find::text("foo"), finds_one_widget());
2809            expect(tester, &find::text("bar"), finds_one_widget());
2810        });
2811    }
2812
2813    #[test]
2814    fn fields_exposes_every_registered_field_state_with_its_value() {
2815        test_widgets(|tester| {
2816            let form_key = GlobalKey::new();
2817            let (key1, key2) = (GlobalKey::new(), GlobalKey::new());
2818            pump_ltr(
2819                tester,
2820                Form::new(
2821                    Column::new().children([
2822                        text_field(&key1)
2823                            .initial_value("A".to_string())
2824                            .into_widget(),
2825                        text_field(&key2)
2826                            .initial_value("B".to_string())
2827                            .into_widget(),
2828                    ]),
2829                )
2830                .key(form_key.clone().into())
2831                .into_widget(),
2832            );
2833
2834            let form = form_state(tester, &form_key);
2835            let app = tester.cell.borrow_mut();
2836            let fields = form.fields(&app);
2837            assert_eq!(fields.len(), 2);
2838            let values: Vec<&String> = fields
2839                .iter()
2840                .map(|field| {
2841                    field
2842                        .value(&app)
2843                        .and_then(|value| value.downcast_ref::<String>())
2844                        .unwrap()
2845                })
2846                .collect();
2847            assert!(values.contains(&&"A".to_string()));
2848            assert!(values.contains(&&"B".to_string()));
2849        });
2850    }
2851
2852    #[test]
2853    fn fields_reports_every_field_invalid_after_validation_errors() {
2854        test_widgets(|tester| {
2855            let form_key = GlobalKey::new();
2856            let (key1, key2) = (GlobalKey::new(), GlobalKey::new());
2857            pump_ltr(
2858                tester,
2859                Form::new(
2860                    Column::new().children([
2861                        text_field(&key1)
2862                            .initial_value("foo".to_string())
2863                            .validator(|_app, value| error_text(value))
2864                            .into_widget(),
2865                        text_field(&key2)
2866                            .initial_value("bar".to_string())
2867                            .validator(|_app, value| error_text(value))
2868                            .into_widget(),
2869                    ]),
2870                )
2871                .key(form_key.clone().into())
2872                .into_widget(),
2873            );
2874            let form = form_state(tester, &form_key);
2875
2876            form.validate(&mut tester.cell.borrow_mut());
2877            tester.pump();
2878
2879            expect(tester, &find::text("foo/error"), finds_one_widget());
2880            expect(tester, &find::text("bar/error"), finds_one_widget());
2881
2882            let mut app = tester.cell.borrow_mut();
2883            let fields = form.fields(&app);
2884
2885            // Expect all fields to be invalid.
2886            assert!(fields.into_iter().all(|field| !field.is_valid(&mut app)));
2887        });
2888    }
2889
2890    #[test]
2891    fn is_valid_evaluates_validity_without_updating_the_error_display() {
2892        test_widgets(|tester| {
2893            let form_key = GlobalKey::new();
2894            let field_key = GlobalKey::new();
2895            pump_ltr(
2896                tester,
2897                Form::new(
2898                    text_field(&field_key)
2899                        .initial_value("foo".to_string())
2900                        .validator(|_app, value| error_text(value)),
2901                )
2902                .key(form_key.clone().into())
2903                .into_widget(),
2904            );
2905
2906            let form = form_state(tester, &form_key);
2907            let fields = form.fields(&tester.cell.borrow_mut());
2908            assert_eq!(fields.len(), 1);
2909            let field = fields[0];
2910
2911            assert!(!field.is_valid(&mut tester.cell.borrow_mut()));
2912
2913            // No error UI should be shown.
2914            expect(tester, &find::text("foo/error"), finds_nothing());
2915            assert!(!field.has_error(&tester.cell.borrow_mut()));
2916        });
2917    }
2918
2919    #[test]
2920    fn fields_collects_and_updates_the_values_of_fields_of_every_type() {
2921        test_widgets(|tester| {
2922            let form_key = GlobalKey::new();
2923            let keyed = |name: &str| KeyRef::from(ValueKey::new(name.to_string()));
2924            pump_ltr(
2925                tester,
2926                Form::new(
2927                    Column::new().children([
2928                        FormField::new(show_field)
2929                            .key(keyed("name"))
2930                            .initial_value("Name".to_string())
2931                            .into_widget(),
2932                        FormField::new(show_field)
2933                            .key(keyed("email"))
2934                            .initial_value("Email".to_string())
2935                            .into_widget(),
2936                        FormField::<i64>::new(|_app, _field| SizedBox::shrink().into_widget())
2937                            .key(keyed("age"))
2938                            .initial_value(18)
2939                            .into_widget(),
2940                    ]),
2941                )
2942                .key(form_key.clone().into())
2943                .into_widget(),
2944            );
2945            let form = form_state(tester, &form_key);
2946
2947            let collect_data = |tester: &WidgetTester| {
2948                let app = tester.cell.borrow_mut();
2949                let mut data = Vec::new();
2950                for field in form.fields(&app) {
2951                    let key = field.context(&app).widget(&app).key().cloned();
2952                    let value = field.value(&app).expect("every field holds a value");
2953                    let value = value
2954                        .downcast_ref::<String>()
2955                        .cloned()
2956                        .or_else(|| value.downcast_ref::<i64>().map(i64::to_string))
2957                        .expect("a String or an i64");
2958                    data.push((key.expect("every field is keyed"), value));
2959                }
2960                data
2961            };
2962
2963            assert_eq!(
2964                collect_data(tester),
2965                [
2966                    (keyed("name"), "Name".to_string()),
2967                    (keyed("email"), "Email".to_string()),
2968                    (keyed("age"), "18".to_string()),
2969                ]
2970            );
2971
2972            let field = |tester: &WidgetTester, name: &str| {
2973                let app = tester.cell.borrow_mut();
2974                form.fields(&app)
2975                    .into_iter()
2976                    .find(|field| field.context(&app).widget(&app).key() == Some(&keyed(name)))
2977                    .expect("a field keyed so")
2978            };
2979            let name = field(tester, "name")
2980                .typed::<String>()
2981                .expect("a String field");
2982            let email = field(tester, "email")
2983                .typed::<String>()
2984                .expect("a String field");
2985            let age = field(tester, "age").typed::<i64>().expect("an i64 field");
2986            assert!(field(tester, "age").typed::<String>().is_none());
2987
2988            name.did_change(&mut tester.cell.borrow_mut(), Some("New Name".to_string()));
2989            email.did_change(
2990                &mut tester.cell.borrow_mut(),
2991                Some("new@email.com".to_string()),
2992            );
2993            age.did_change(&mut tester.cell.borrow_mut(), Some(30));
2994
2995            tester.pump();
2996
2997            assert_eq!(
2998                collect_data(tester),
2999                [
3000                    (keyed("name"), "New Name".to_string()),
3001                    (keyed("email"), "new@email.com".to_string()),
3002                    (keyed("age"), "30".to_string()),
3003                ]
3004            );
3005        });
3006    }
3007
3008    // ---- restoration, through a field that restores its value as `TextFormField` does ----
3009
3010    /// A [`FormField`] subclass whose state also restores its value, as `TextFormField`'s
3011    /// restorable controller does.
3012    struct RestorableTextField {
3013        form_field: FormFieldData<String>,
3014    }
3015
3016    impl Debug for RestorableTextField {
3017        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3018            self.form_field.fmt(f)
3019        }
3020    }
3021
3022    impl FormFieldLeaf for RestorableTextField {
3023        type Value = String;
3024        crate::form_field_accessors!();
3025    }
3026
3027    impl StatefulWidget for RestorableTextField {
3028        type State = RestorableTextFieldState;
3029
3030        fn key(&self) -> Option<&KeyRef> {
3031            self.form_field.key.as_ref()
3032        }
3033
3034        fn create_state(&self) -> RestorableTextFieldState {
3035            RestorableTextFieldState {
3036                state: StateData::new(),
3037                restoration: RestorationMixinData::new(),
3038                form_field_state: FormFieldStateData::new(&self.form_field),
3039                text: None,
3040            }
3041        }
3042    }
3043
3044    struct RestorableTextFieldState {
3045        state: StateData<RestorableTextField>,
3046        restoration: RestorationMixinData,
3047        form_field_state: FormFieldStateData<String>,
3048        text: Option<Ref<RestorableStringN>>,
3049    }
3050
3051    impl RestorableTextFieldState {
3052        fn text(self: Handle<Self>, app: &App) -> Handle<RestorableStringN> {
3053            app.get(self).text.handle().expect("created in init_state")
3054        }
3055    }
3056
3057    impl FormFieldStateLeaf for RestorableTextFieldState {
3058        crate::form_field_state_accessors!();
3059
3060        fn did_change(self: Handle<Self>, app: &mut App, value: Option<String>) {
3061            FormFieldState::did_change(self, app, value.clone());
3062            self.text(app).set_value(app, value);
3063        }
3064
3065        fn reset(self: Handle<Self>, app: &mut App) {
3066            let initial_value = self.widget(app).form_field.initial_value.clone();
3067            self.text(app).set_value(app, initial_value);
3068            FormFieldState::reset(self, app);
3069        }
3070    }
3071
3072    impl RestorationMixin for RestorableTextFieldState {
3073        crate::restoration_mixin_accessors!();
3074
3075        fn restoration_id(self: Handle<Self>, app: &App) -> Option<&str> {
3076            FormFieldState::restoration_id(self, app)
3077        }
3078
3079        fn restore_state(
3080            self: Handle<Self>,
3081            app: &mut App,
3082            old_bucket: Option<Handle<RestorationBucket>>,
3083            initial_restore: bool,
3084        ) {
3085            FormFieldState::restore_state(self, app, old_bucket, initial_restore);
3086            let text = self.text(app);
3087            self.register_for_restoration(app, text.as_property(), "text");
3088            let value = RestorableValue::value(text, app).clone();
3089            self.set_value(app, value);
3090        }
3091    }
3092
3093    impl State for RestorableTextFieldState {
3094        type Widget = RestorableTextField;
3095        crate::state_accessors!();
3096
3097        fn deactivate(self: Handle<Self>, app: &mut App) {
3098            FormFieldState::deactivate(self, app);
3099        }
3100
3101        fn init_state(self: Handle<Self>, app: &mut App) {
3102            FormFieldState::init_state(self, app);
3103            let initial_value = self.widget(app).form_field.initial_value.clone();
3104            let text = RestorableStringN::new(app, initial_value);
3105            app.get_mut(self).text = Some(text);
3106        }
3107
3108        fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &RestorableTextField) {
3109            FormFieldState::did_update_widget(self, app, old_widget);
3110        }
3111
3112        fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
3113            FormFieldState::did_change_dependencies(self, app);
3114        }
3115
3116        fn dispose(self: Handle<Self>, app: &mut App) {
3117            let text = self.text(app);
3118            RestorableProperty::dispose(text, app);
3119            FormFieldState::dispose(self, app);
3120        }
3121
3122        fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
3123            FormFieldState::build(self, app, context)
3124        }
3125    }
3126
3127    #[test]
3128    fn a_lone_field_restores_its_error_text_on_user_interaction() {
3129        let field_key = GlobalKey::new();
3130        let builder = || {
3131            let mut form_field = FormFieldData::new(Rc::new(show_field));
3132            form_field.key = Some(field_key.clone().into());
3133            form_field.autovalidate_mode = AutovalidateMode::OnUserInteraction;
3134            form_field.restoration_id = Some("text_form_field".to_string());
3135            form_field.initial_value = Some("foo".to_string());
3136            form_field.validator = Some(Rc::new(|_app, value| error_text(value)));
3137            RootRestorationScope::new(Some("app".to_string()), RestorableTextField { form_field })
3138                .into_widget()
3139        };
3140        let restart_and_restore = |data: Option<RestorationMap>| {
3141            let mut tester = WidgetTester::restoring(data);
3142            pump_ltr(&mut tester, builder());
3143            tester
3144        };
3145
3146        let mut tester = WidgetTester::restoring(None);
3147        pump_ltr(&mut tester, builder());
3148
3149        // No error text is visible yet.
3150        expect(&tester, &find::text("foo/error"), finds_nothing());
3151
3152        let field = key_state::<RestorableTextFieldState>(&tester, &field_key);
3153        field.did_change(&mut tester.cell.borrow_mut(), Some("bar".to_string()));
3154        tester.pump();
3155        tester.pump();
3156        expect(&tester, &find::text("bar/error"), finds_one_widget());
3157
3158        let data = tester.restoration_data();
3159        let mut tester = restart_and_restore(data.clone());
3160        // Error text should be present after restart and restore.
3161        expect(&tester, &find::text("bar/error"), finds_one_widget());
3162
3163        // Resetting the form state should remove the error text.
3164        let field = key_state::<RestorableTextFieldState>(&tester, &field_key);
3165        field.reset(&mut tester.cell.borrow_mut());
3166        tester.pump();
3167        tester.pump();
3168        expect(&tester, &find::text("bar/error"), finds_nothing());
3169        let tester = restart_and_restore(tester.restoration_data());
3170        // Error text should still be removed after restart and restore.
3171        expect(&tester, &find::text("bar/error"), finds_nothing());
3172
3173        let tester = restart_and_restore(data);
3174        expect(&tester, &find::text("bar/error"), finds_one_widget());
3175    }
3176
3177    fn key_state<S: State>(tester: &WidgetTester, key: &GlobalKey) -> Handle<S> {
3178        key.current_state::<S>(&tester.cell.borrow())
3179            .expect("the field is mounted")
3180    }
3181
3182    #[test]
3183    fn a_form_with_can_pop_wraps_its_fields_in_a_pop_scope() {
3184        test_widgets(|tester| {
3185            pump_ltr(
3186                tester,
3187                Form::new(SizedBox::shrink()).can_pop(false).into_widget(),
3188            );
3189            expect(tester, &find::by_type::<PopScope>(), finds_one_widget());
3190            tester.widget(find::by_type::<PopScope>(), |scope: &PopScope| {
3191                assert!(!scope.can_pop);
3192            });
3193
3194            pump_ltr(tester, Form::new(SizedBox::shrink()).into_widget());
3195            expect(tester, &find::by_type::<PopScope>(), finds_nothing());
3196        });
3197    }
3198}